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/main
|
<repo_name>ElMargaritox/ElSoldado---Laboratorio<file_sep>/ElSoldado/Models/Soldado.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElSoldado.Models
{
public class Soldado
{
public Soldado() { }
public virtual void RecogerArma(Arma arma)
{
_arma = arma;
}
public void DejarArma()
{
Console.WriteLine("Has Dejado El Arma: {0}", _arma.Nombre);
_arma = null;
}
public virtual void Disparar() { }
public void VerArma()
{
Console.WriteLine("El Arma Que Tienes En La Mano Es: {0}", _arma.Nombre);
}
public bool TieneArma()
{
Console.Clear();
if (_arma == null)
{
Console.WriteLine("No posees Ningun Arma");
}
else
{
return true;
}
return false;
}
public void Menu()
{
bool salir = false;
do
{
Console.WriteLine("-== Bienvenido al campo de entrenamiento, Soldado ==-");
Console.WriteLine("¿Que Desea Hacer?");
Console.WriteLine(" 1 - Recoger Arma");
Console.WriteLine(" 2 - Dejar Arma");
Console.WriteLine(" 3 - Disparar");
Console.WriteLine(" 4 - Ver Arma En Uso");
Console.WriteLine(" 5 - Salir");
int.TryParse(Console.ReadLine(), out int opcion);
switch (opcion)
{
case 1:
Console.Clear();
SeleccionarArma(salir);
break;
case 2:
Console.Clear();
if (TieneArma())
{
DejarArma();
}
break;
case 3:
if (TieneArma())
{
Console.WriteLine("Has Disparado El Arma: {0}", _arma.Nombre); Disparar();
}
break;
case 4:
if (TieneArma())
{
VerArma();
}
break;
case 5:
salir = true;
break;
}
} while (!salir);
}
public void SeleccionarArma(bool salir)
{
do
{
Console.WriteLine("1 - Revolver");
Console.WriteLine("2 - Rifle");
Console.WriteLine("3 - Escopeta");
Console.WriteLine("4 - Volver");
int.TryParse(Console.ReadLine(), out int opcion);
switch (opcion)
{
case 1:
_arma = new Revolver(); RecogerArma(_arma); salir = true;
break;
case 2:
_arma = new Rifle(); RecogerArma(_arma); salir = true;
break;
case 3:
_arma = new Escopeta(); RecogerArma(_arma); salir = true;
break;
case 4:
salir = true;
return;
}
Console.Clear();
Console.WriteLine("Has Seleccionado: {0}", _arma.Nombre);
} while (!salir);
}
private Arma _arma;
}
}
<file_sep>/ElSoldado/Models/Rifle.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElSoldado.Models
{
public class Rifle : Arma
{
public Rifle()
{
Nombre = "Rifle";
Balas = 5;
}
public override void Disparar()
{
Console.WriteLine("El Sonido De Disparo Es: PUM!");
}
}
}
<file_sep>/ElSoldado/Models/Arma.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElSoldado.Models
{
public class Arma : Soldado
{
public string Nombre;
public int Balas;
}
}
<file_sep>/ElSoldado/Models/Escopeta.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElSoldado.Models
{
public class Escopeta : Arma
{
public Escopeta()
{
Nombre = "Escopeta";
Balas = 8;
}
public override void Disparar()
{
Console.WriteLine("El Sonido De Disparo Es: PAWN!");
}
}
}
<file_sep>/ElSoldado/Program.cs
using ElSoldado.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElSoldado
{
class Program
{
static void Main(string[] args)
{
Soldado menu = new Soldado();
menu.Menu();
}
}
}
<file_sep>/ElSoldado/Models/Revolver.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElSoldado.Models
{
public class Revolver : Arma
{
public Revolver()
{
Nombre = "Revolver";
Balas = 6;
}
public override void Disparar()
{
Console.WriteLine("El Sonido De Disparo Es: Piu Piu");
}
}
}
|
75c5e48d114701130cbe9121a50206de6125bd3a
|
[
"C#"
] | 6 |
C#
|
ElMargaritox/ElSoldado---Laboratorio
|
349c369d80b6b930d1be0d963d6423a0a8928d45
|
8faa374d5b42a9caad5830c7841e9aeaa6e7f3fa
|
refs/heads/master
|
<file_sep>from django.http import HttpResponse
from django.shortcuts import render
def home_view(request, *args, **kwargs):
return render(request, "home.html", {})
def contact_view(request, *args, **kwargs):
return render(request, "contact.html", {})
def about_view(request,*args, **kwargs):
my_context = {
"my_text": "This is about us",
"my_number": 123,
"this_is_true": True,
"my_list": [21, 12, 34, "Abc"]
}
return render(request, "about.html", my_context)
def social_view(request,*args, **kwargs):
return render(request, "social.html", {})
<file_sep><!DOCTYPE html>
{% load render_bundle from webpack_loader %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Coding using Django</title>
</head>
<body>
<div id="app">
{% include 'nav.html' %}
{% block content %}
{% endblock %}
</div>
{% render_bundle 'main' %}
</body>
</html>
|
5e1f89837091815bbae843744785e696801b761d
|
[
"Python",
"HTML"
] | 2 |
Python
|
waihiga/Django-project
|
7d52bc592bb6bcbb05343d283214873eb68fc8c8
|
a37bf409c432e7edfbbd243cb297a0d604534072
|
refs/heads/master
|
<repo_name>pprett/zipline<file_sep>/zipline/sources/__init__.py
from zipline.sources.data_frame_source import DataFrameSource
from zipline.sources.test_source import SpecificEquityTrades
__all__ = [
'DataFrameSource',
'SpecificEquityTrades'
]
<file_sep>/etc/requirements_dev.txt
ipython==0.13.1
# Testing
nose==1.2.1
# Fetching sample data
requests==0.14.2
# Linting
flake8==1.6.2
# Documentation Conversion
pyandoc==0.0.1
<file_sep>/zipline/utils/tradingcalendar.py
#
# Copyright 2012 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytz
from datetime import datetime
from dateutil import rrule
from zipline.utils.date_utils import utcnow
start = datetime(2002, 1, 1, tzinfo=pytz.utc)
end = utcnow()
non_trading_rules = []
weekends = rrule.rrule(
rrule.YEARLY,
byweekday=(rrule.SA, rrule.SU),
cache=True,
dtstart=start,
until=end
)
non_trading_rules.append(weekends)
new_years = rrule.rrule(
rrule.MONTHLY,
byyearday=1,
cache=True,
dtstart=start,
until=end
)
non_trading_rules.append(new_years)
mlk_day = rrule.rrule(
rrule.MONTHLY,
bymonth=1,
byweekday=(rrule.MO(+3)),
cache=True,
dtstart=start,
until=end
)
non_trading_rules.append(mlk_day)
presidents_day = rrule.rrule(
rrule.MONTHLY,
bymonth=2,
byweekday=(rrule.MO(3)),
cache=True,
dtstart=start,
until=end
)
non_trading_rules.append(presidents_day)
good_friday = rrule.rrule(
rrule.DAILY,
byeaster=-2,
cache=True,
dtstart=start,
until=end
)
non_trading_rules.append(good_friday)
memorial_day = rrule.rrule(
rrule.MONTHLY,
bymonth=5,
byweekday=(rrule.MO(-1)),
cache=True,
dtstart=start,
until=end
)
non_trading_rules.append(memorial_day)
july_4th = rrule.rrule(
rrule.MONTHLY,
bymonth=7,
bymonthday=4,
cache=True,
dtstart=start,
until=end
)
non_trading_rules.append(july_4th)
labor_day = rrule.rrule(
rrule.MONTHLY,
bymonth=9,
byweekday=(rrule.MO(1)),
cache=True,
dtstart=start,
until=end
)
non_trading_rules.append(labor_day)
thanksgiving = rrule.rrule(
rrule.MONTHLY,
bymonth=11,
byweekday=(rrule.TH(-1)),
cache=True,
dtstart=start,
until=end
)
non_trading_rules.append(thanksgiving)
christmas = rrule.rrule(
rrule.MONTHLY,
bymonth=12,
bymonthday=25,
cache=True,
dtstart=start,
until=end
)
non_trading_rules.append(christmas)
non_trading_ruleset = rrule.rruleset()
for rule in non_trading_rules:
non_trading_ruleset.rrule(rule)
non_trading_days = non_trading_ruleset.between(start, end, inc=True)
<file_sep>/etc/requirements.txt
msgpack-python==0.2.2
iso8601==0.1.4
# Logging
Logbook==0.4
blist==1.3.4
# Scientific Libraries
pytz==2012h
numpy==1.6.2
Cython==0.17.2
pandas==0.9.1
python-dateutil==2.1
six==1.2.0
<file_sep>/zipline/protocol.py
#
# Copyright 2012 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from utils.protocol_utils import Enum
# Datasource type should completely determine the other fields of a
# message with its type.
DATASOURCE_TYPE = Enum(
'AS_TRADED_EQUITY',
'MERGER',
'SPLIT',
'DIVIDEND',
'TRADE',
'EMPTY',
'DONE'
)
|
31cb6f868ec4ce2411d4f57efb85ec93d159d2c6
|
[
"Python",
"Text"
] | 5 |
Python
|
pprett/zipline
|
803a0cee5c35274944be2ae5ecc453d11f88ad56
|
4b8aa2830b533eae05be36f417f831455edbe3cf
|
refs/heads/master
|
<file_sep>#include "stdio.h"
#include "stdlib.h"
#define M 20 /*预定义图的最大顶点数*/
#include "string.h"
typedef struct node
{ //边表结点
int adjvex; //邻接点
struct node *next;
} edgenode;
typedef struct vnode
{ //头节点类型
char vertex; //顶点信息
edgenode *firstedge; //邻接表表头指针
} vertexnode;
typedef struct
{ //邻接表类型
vertexnode adjlist[M]; //存放头节点的顺序表
int n, e; //图的顶点数与边数
} linkedgraph;
int visited[M];
void createwithfile(linkedgraph *g, char *filename, int c) //c = 0表示创建无向图
{
int i, j, k;
edgenode *s;
FILE *fp;
fp = fopen(filename, "r");
if (fp)
{
fscanf(fp, "%d%d", &g->n, &g->e); //读入顶点数与边数
for (i = 0; i < g->n; i++)
{
fscanf(fp, "%d", &g->adjlist[i].vertex); //读入顶点信息
g->adjlist[i].firstedge = NULL; //边表置为空表
}
for (k = 0; k < g->e; k++) //循环e次建立边表
{
fscanf(fp, "%d%d", &i, &j); //读入无序对(i,j)
s = (edgenode *)malloc(sizeof(edgenode));
s->adjvex = j; //邻接点序号为j
s->next = g->adjlist[i].firstedge;
g->adjlist[i].firstedge = s; //将新节点*s插入顶点Vi的边表头部
if (c == 0)
{
s = (edgenode *)malloc(sizeof(edgenode));
s->adjvex = i; //邻接点序号为i
s->next = g->adjlist[j].firstedge; //将新节点*s插入顶点Vj的边表头部
g->adjlist[j].firstedge = s;
}
}
fclose(fp);
}
else
g->n = 0; ///文件打开失败
}
linkedgraph *create(int c) //c = 0表示创建无向图
{
linkedgraph *g;
g = (linkedgraph *)malloc(sizeof(linkedgraph));
int i, j, k;
edgenode *s;
printf("输入结点数和边数:\n");
scanf("%d%d", &g->n, &g->e); //读入顶点数与边数
printf("输入结点值:\n");
getchar();
for (i = 0; i < g->n; i++)
{
scanf("%c", &g->adjlist[i].vertex); //读入顶点信息
getchar();
g->adjlist[i].firstedge = NULL; //边表置为空表
}
if (c == 0)
printf("输入无序对:\n");
else
printf("输入有序对:\n");
for (k = 0; k < g->e; k++) //循环e次建立边表
{
scanf("%d%d", &i, &j); //读入无序对(i,j)
s = (edgenode *)malloc(sizeof(edgenode));
s->adjvex = j; //邻接点序号为j
s->next = g->adjlist[i].firstedge;
g->adjlist[i].firstedge = s; //将新节点*s插入顶点Vi的边表头部
if (c == 0)
{
s = (edgenode *)malloc(sizeof(edgenode));
s->adjvex = i; //邻接点序号为i
s->next = g->adjlist[j].firstedge; //将新节点*s插入顶点Vj的边表头部
g->adjlist[j].firstedge = s;
}
}
return g;
}
void dfs(linkedgraph *g, int i)
{
edgenode *p;
printf("visit vertex:%c \n", g->adjlist[i].vertex); //访问顶点i
visited[i] = 1;
p = g->adjlist[i].firstedge;
while (p) //从p的邻接点出发进行深度优先搜索
{
if (!visited[p->adjvex])
dfs(g, p->adjvex);
p = p->next;
}
}
void dfstraverse(linkedgraph *g)
{
int i;
for (i = 0; i < g->n; i++)
visited[i] = 0;
for (i = 0; i < g->n; i++)
if (!visited[i])
dfs(g, i);
}
void bfs(linkedgraph *g, int i)
{
int j;
edgenode *p;
int queue[M], front, rear; //创建一个队列
front = rear = 0; //初始化空队列
printf("%c ", g->adjlist[i].vertex); //访问根节点
visited[i] = 1;
queue[rear++] = i; //被访问结点进队
while (rear > front)
{
j = queue[front++]; //出队
p = g->adjlist[j].firstedge;
while (p)
{
if (visited[p->adjvex] == 0)
{
printf("%c ", g->adjlist[p->adjvex].vertex);
queue[rear++] = p->adjvex;
visited[p->adjvex] = 1;
}
p = p->next;
}
}
}
int bfstraverse(linkedgraph *g)
{
int i, count = 0;
for (i = 0; i < g->n; i++)
visited[i] = 0;
for (i = 0; i < g->n; i++)
if (!visited[i]) //vi未被访问过
{
printf("\n");
count++;
bfs(g, i);
}
return count;
}
int main()
{
linkedgraph *h;
h = create(0);
printf("深度遍历:\n");
dfstraverse(h);
printf("广度遍历:\n");
int count = bfstraverse(h);
printf("\n此图的连通分量为:\n");
printf("%d\n", count);
return 0;
}<file_sep># 图的遍历
+ 推荐一个数据可视化的网站[visualgo](https://visualgo.net/zh),可以更好理解这个图的遍历
## 深度优先遍历
### 1.1 无向图的深度优先遍历
它的思想:
+ 初始状态,图中的所有顶点均未被访问过,先从某个顶点V出发,然后依次访问每个没有被访问过的邻接点,直至图中所有和V路径相通的顶点均被访问到。
+ 此时若还有没有访问到的顶点,则选另一个未被访问过的顶点作为起始点,重复以上过程,直至图中所有顶点均被访问到
<font size = 4>下面以"无向图"为实例,对深度遍历进行演示</font>
<div align="center">
|||
|:--:|:--:|
|||
</div>
<font size = 3>对上面的无向图进行深度优先遍历</font>
+ 首先访问根节点c0
+ 在刚问了源点c0之后,选择C0的第一个邻接点c1
+ 因为C1没有被访问过,接着从c1出发进行访问,由上面图的邻接表可得出,c1的第一个邻接点c0已经被访问过,因此下一步就会访问c1的第二个邻接点c3
+ 接着从c3出发进行搜索并进行访问,指导所有结点均被访问过
+ 由此得到的顶点序列为: c0->c1->c3->c4->c5->c2
<div align="center">
<font size = 3>上面图的邻接表</font>

</div>
代码
```c
void dfs(linkedgraph *g,int i)
{
edgenode *p;
printf("visit vertex:%c \n",g->adjlist[i].vertex); //访问顶点i
visited[i] = 1;
p = g->adjlist[i].firstedge;
while(p) //从p的邻接点出发进行深度优先搜索
{
if(!visited[p->adjvex])
dfs(g,p->adjvex);
p = p->next;
}
}
void dfstraverse(linkedgraph *g)
{
int i;
for(i = 0;i < g->n;i ++)
visited[i] = 0; //初始化标志数组
for(i = 0;i < g->n;i ++)
if(!visited[i]) //vi没有被访问过
dfs(g,i);
}
```
## 广度优先遍历
### 1.1 无向图的深度优先遍历
它的思想是:
+ 从图中某顶点v出发,在访问了v之后依次访问v的各个未曾访问过的邻接点,然后分别从这些邻接点出发依次访问它们的邻接点
+ 使得“先被访问的顶点的邻接点先于后被访问的顶点的邻接点被访问,直至图中所有已被访问的顶点的邻接点都被访问到。
+ 如果此时图中尚有顶点未被访问,则需要另选一个未曾被访问过的顶点作为新的起始点,重复上述过程,直至图中所有顶点都被访问到为止。
<div align="center">
|||
|:--:|:--:|
|||
</div>
+ 第1步:访问A。
+ 第2步:依次访问C,D,F。
+ 在访问了A之后,接下来访问A的邻接点。前面已经说过,在本文实现中,顶点ABCDEFG按照顺序存储的,C在"D和F"的前面。
+ 因此,先访问C。再访问完C之后,再依次访问D,F。
+ 第3步:依次访问B,G。
在第2步访问完C,D,F之后,再依次访问它们的邻接点。首先访问C的邻接点B,再访问F的邻接点G。
+ 第4步:访问E。
在第3步访问完B,G之后,再依次访问它们的邻接点。只有G有邻接点E,因此访问G的邻接点E。
<font size= 4>因此访问顺序是:A -> C -> D -> F -> B -> G -> E</font>
<font size = 5>代码:</font>
```c
void bfs(linkedgraph *g,int i)
{
int j;
edgenode *p;
int queue[M],front,rear; //创建一个队列
front = rear = 0; //初始化空队列
printf("%c ",g->adjlist[i].vertex); //访问根节点
visited[i] = 1;
queue[rear ++] = i; //被访问结点进队
while(rear > front)
{
j = queue[front ++]; //出队
p = g->adjlist[j].firstedge;
while(p) //广度优先遍历邻接表
{
if(visited[p->adjvex] == 0)
{
printf("%c ",g->adjlist[p->adjvex].vertex);
queue[rear ++] = p->adjvex;
visited[p->adjvex] = 1;
}
p = p->next;
}
}
}
int bfstraverse(linkedgraph *g)
{
int i,count = 0;
for(i = 0;i < g->n;i ++)
visited[i] = 0; //初始化标志数组
for(i = 0;i < g->n;i ++)
if(!visited[i]) //vi未被访问过
{
printf("\n");
count ++; //连通分量数加1
bfs(g,i);
}
return count;
}
```
<font size = 4>如有问题,不妨提个pr?</div>
<file_sep># 17070047班数据结构课程
+ ## 线性表及其顺序储存
+ ## 线性表的链式存储
+ ## 字符串、数组和特殊矩阵
+ ## 递归
+ ## 树形结构
+ ## 二叉树
+ ## 图
+ [图的创建及遍历](https://github.com/17070047/CodeStructureCourse/blob/master/%E5%9B%BE/%E5%9B%BE%E7%9A%84%E9%81%8D%E5%8E%86.md)
+ ## 检索
+ ## 内排序
+ ## 数据结构实验
|
b4998a3558ef7391e309c6a5caa9b49043bd3a12
|
[
"Markdown",
"C++"
] | 3 |
C++
|
kklll/CodeStructureCourse
|
8cc7e69d7944790f2f0bb722fedd0c632ba0671b
|
b6c73a95628d29797f752ba482f299551567478d
|
refs/heads/master
|
<file_sep>[package]
name = "consistent-rs"
description = "Consistent hash package for Rust"
version = "0.1.1"
documentation = "https://docs.rs/consistent-rs/0.1.1/consistent_rs/"
homepage = "https://github.com/DavidCai1993/consistent"
authors = ["<NAME> <<EMAIL>>"]
readme = "README.md"
repository = "https://github.com/DavidCai1993/consistent"
keywords = ["consistent", "hash-ring"]
categories = ["algorithms"]
license = "MIT"
[dependencies]
crc = "1.4.0"
<file_sep># consistent
[](https://travis-ci.org/DavidCai1993/consistent)
Consistent hash package for Rust.
### Installation
```toml
[dependencies]
consistent_rs = "0.1.1"
```
### Documentation
See: https://docs.rs/consistent-rs/0.1.1/consistent_rs/
### Example
```rust
let mut consistant = Consistant::default();
consistant.add("cacheA");
consistant.add("cacheB");
consistant.add("cacheC");
println!("david => {:?}", consistant.get("david"));
println!("james => {:?}", consistant.get("james"));
println!("kelly => {:?}", consistant.get("kelly"));
```
<file_sep>//! Consistent hash package for Rust.
extern crate crc;
mod consistant;
pub use consistant::*;
<file_sep>use std::default::Default;
use std::rc::Rc;
use std::iter::Iterator;
use std::collections::hash_map::HashMap;
use std::sync::RwLock;
use crc::crc32::checksum_ieee;
/// Consistant holds the information of the hash ring.
#[derive(Debug)]
pub struct Consistant {
pub replicas_num: usize,
circle: HashMap<u32, Rc<String>>,
members: HashMap<Rc<String>, ()>,
sorted_keys: Vec<u32>,
lock: RwLock<()>,
}
impl Default for Consistant {
fn default() -> Consistant {
Consistant {
replicas_num: 20,
circle: HashMap::new(),
members: HashMap::new(),
sorted_keys: Vec::new(),
lock: RwLock::new(()),
}
}
}
impl Consistant {
/// Crete a new instance of Consistant.
pub fn new(replicas_num: usize) -> Self {
Consistant {
replicas_num: replicas_num,
circle: HashMap::new(),
members: HashMap::new(),
sorted_keys: Vec::new(),
lock: RwLock::new(()),
}
}
/// Get the count of added elements.
pub fn count(&self) -> usize {
let _ = self.lock.read().expect("rLock");
self.members.len()
}
/// Add an elment to the hash ring.
pub fn add<S: Into<String>>(&mut self, element: S) {
let _ = self.lock.write().expect("wLock");
let s = &Rc::new(element.into());
if self.contains(s) {
return;
}
for i in 0..self.replicas_num {
let sum = checksum_ieee(Self::generate_element_name(s, i).as_bytes());
self.circle.insert(sum, s.clone());
self.sorted_keys.push(sum)
}
self.members.insert(s.clone(), ());
self.sorted_keys.sort();
}
/// Get the cloeset element's name to the given "name".
pub fn get<S: Into<String>>(&self, name: S) -> Option<String> {
let _ = self.lock.read().expect("rLock");
if self.circle.len() == 0 {
return None;
}
let key = self.sorted_keys[self.get_key_index(checksum_ieee(name.into().as_bytes()))];
Some(self.get_i_from_circle(key))
}
/// Get the N cloeset elements' names to the given "name".
pub fn get_n<S: Into<String>>(&self, name: S, n: usize) -> Option<Vec<String>> {
let _ = self.lock.read().expect("rLock");
if n == 0 || self.circle.len() == 0 {
return None;
}
let count = if self.count() > n { n } else { self.count() };
let mut start = self.get_key_index(checksum_ieee(name.into().as_bytes()));
let mut element = self.get_i_from_circle(self.sorted_keys[start]);
let mut res = Vec::with_capacity(count);
res.push(element);
loop {
start = start + 1;
if start >= self.sorted_keys.len() {
start = 0;
}
element = self.get_i_from_circle(self.sorted_keys[start]);
if !res.contains(&element) {
res.push(element)
}
if res.len() == count {
break;
}
}
Some(res)
}
/// Remove the given element.
pub fn remove<S: Into<String>>(&mut self, name: S) {
let _ = self.lock.write().expect("wLock");
let s = &Rc::new(name.into());
if !self.contains(s) {
return;
}
for i in 0..self.replicas_num {
let sum = &checksum_ieee(Self::generate_element_name(s, i).as_bytes());
self.circle.remove(sum);
match self.sorted_keys.iter().position(|key| key.eq(sum)) {
Some(index) => self.sorted_keys.remove(index),
None => unreachable!(),
};
}
self.members.remove(s);
}
#[inline]
fn get_i_from_circle(&self, i: u32) -> String {
match self.circle.get(&i) {
Some(rc) => (**rc).clone(),
None => unreachable!(),
}
}
#[inline]
fn contains(&self, name: &Rc<String>) -> bool {
self.members.contains_key(name)
}
#[inline]
fn get_key_index(&self, sum: u32) -> usize {
let iter = (&self.sorted_keys).into_iter();
for (i, key) in iter.enumerate() {
if sum < *key {
return i;
}
}
0
}
#[inline]
fn generate_element_name(element: &str, i: usize) -> String {
String::from(element) + &i.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default() {
let consistant = Consistant::default();
assert_eq!(consistant.replicas_num, 20);
assert_eq!(consistant.circle.len(), 0);
assert_eq!(consistant.sorted_keys.len(), 0);
}
#[test]
fn test_new() {
let consistant = Consistant::new(30);
assert_eq!(consistant.replicas_num, 30);
assert_eq!(consistant.circle.len(), 0);
assert_eq!(consistant.sorted_keys.len(), 0);
}
#[test]
fn test_count() {
let mut consistant = Consistant::default();
consistant.add("cacheA");
consistant.add("cacheB");
consistant.add("cacheC");
assert_eq!(consistant.count(), 3);
}
#[test]
fn test_add() {
let mut consistant = Consistant::default();
consistant.add("cacheA");
consistant.add("cacheB");
consistant.add("cacheC");
assert_eq!(consistant.circle.len(), 3 * consistant.replicas_num);
assert_eq!(consistant.sorted_keys.len(), 3 * consistant.replicas_num);
}
#[test]
fn test_contains() {
let mut consistant = Consistant::default();
consistant.add("cacheA");
assert_eq!(consistant.contains(&Rc::new(String::from("cacheA"))), true);
assert_eq!(consistant.contains(&Rc::new(String::from("cacheB"))), false);
assert_eq!(consistant.contains(&Rc::new(String::from("CachEa"))), false);
}
#[test]
fn test_get() {
let mut consistant = Consistant::default();
consistant.add("cacheA");
consistant.add("cacheB");
consistant.add("cacheC");
assert_eq!(consistant.get("david").unwrap(),
consistant.get("david").unwrap());
assert_eq!(consistant.get("kally").unwrap(),
consistant.get("kally").unwrap());
assert_eq!(consistant.get("jason").unwrap(),
consistant.get("jason").unwrap());
}
#[test]
fn test_get_n() {
let mut consistant = Consistant::default();
consistant.add("cacheA");
consistant.add("cacheB");
consistant.add("cacheC");
let res = consistant.get_n("david", 3).unwrap();
assert_eq!(res.len(), 3);
consistant.remove("cacheA");
let res2 = consistant.get_n("david", 3).unwrap();
assert_eq!(res2.len(), 2);
}
#[test]
fn test_remove() {
let mut consistant = Consistant::default();
consistant.add("cacheA");
consistant.add("cacheB");
consistant.add("cacheC");
consistant.remove("cacheC");
assert_eq!(consistant.count(), 2);
assert!(consistant.get("david").unwrap() != String::from("cacheC"));
assert!(consistant.get("kally").unwrap() != String::from("cacheC"));
assert!(consistant.get("jason").unwrap() != String::from("cacheC"));
}
}
|
f0fc12593cafe032e2ab3a1ef43f1ded5e8228c9
|
[
"TOML",
"Rust",
"Markdown"
] | 4 |
TOML
|
DavidCai1111/consistent
|
ad3bf1413d72ac6b3bd0b0e1d4587ce4419cfa0b
|
ca1cd8fc409aab8b7b02fe4d43dce40b17bb40f6
|
refs/heads/master
|
<repo_name>zhiruisong02/lab3<file_sep>/main.py
# Author: <NAME> <EMAIL>
# Collaborator: <NAME> <EMAIL>
# Collaborator: <NAME> <EMAIL>
# Collaborator: <NAME> <EMAIL>
def sum_n(n):
if n==0:
return n
else:
return n+sum_n(n-1)
def print_n(s,n):
if n==0:
return
else:
print(s)
print_n(s,n-1)
def run():
n = input ("Enter an int: ")
n = int(n)
n1 = sum_n(n)
print(f"sum is {n1}.")
s = input("Enter a string: ")
s = print_n(s,n)
if __name__=="__main__":
run()
|
6dbe21676479a7563f5ef73515da010b78ab2756
|
[
"Python"
] | 1 |
Python
|
zhiruisong02/lab3
|
38a425a762a9ab8503940ec38e561206055a818a
|
7e99c03d7983ae0ecfe48f8d14985bdd31fd4396
|
refs/heads/master
|
<repo_name>kepeter/DemoData<file_sep>/DAL/Data.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
namespace DemoData
{
public class Data
{
private static Random _Random = new Random( );
private static CultureInfo _CultureInfo;
private static int _SID = 0;
private static Stack<int> _SIDStack = new Stack<int>( );
private static string _BaseName = string.Format( @"{0}\culture\{{0}}\{{1}}.json", Path.GetDirectoryName( System.Reflection.Assembly.GetEntryAssembly( ).Location ) );
private static string _MissingResource = "###There is no resource '{0}' in culture '{1}'!";
private static Dictionary<string, Dictionary<string, string[ ]>> _Resources = new Dictionary<string, Dictionary<string, string[ ]>>( );
public static void Reset ( string Culture )
{
_CultureInfo = string.IsNullOrEmpty( Culture ) ? CultureInfo.GetCultureInfo( "en" ) : CultureInfo.GetCultureInfo( Culture );
_SID = 0;
}
public static void PushSID ( )
{
_SIDStack.Push( _SID );
_SID = 0;
}
public static void PopSID ( )
{
_SID = _SIDStack.Pop( );
}
#region Pure randoms
public static string Sign ( )
{
return ( _Random.Next( -1, 2 ) > 0 ? string.Empty : "-" );
}
public static string Number ( int MinLength = 0, int MaxLength = 0 )
{
if ( MaxLength == 0 )
{
MaxLength = MinLength;
MinLength = 0;
}
return (
Convert.ToString(
_Random.Next(
Convert.ToInt32( "1".PadRight( MinLength, '0' ) ),
Convert.ToInt32( "1".PadRight( MaxLength + 1, '0' ) )
)
)
);
}
public static string Range ( int Min = 0, int Max = 0 )
{
if ( Max == 0 )
{
Max = Min;
Min = 0;
}
return ( Convert.ToString( _Random.Next( Min, Max + 1 ) ) );
}
public static string Guid ( )
{
return ( System.Guid.NewGuid( ).ToString( ) );
}
public static string Alpha ( int MinLength = 0, int MaxLength = 0 )
{
if ( MaxLength == 0 )
{
MaxLength = MinLength;
MinLength = 1;
}
int nLength = _Random.Next( MinLength, MaxLength + 1 );
string szChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string szResult = new string(
Enumerable.Repeat( szChars, nLength )
.Select( szArray => szArray[_Random.Next( szArray.Length )] )
.ToArray( ) );
return ( szResult );
}
public static string Ip4 ( )
{
return ( Convert.ToString( string.Format( "{0}.{1}.{2}.{3}",
_Random.Next( 1, 255 ),
_Random.Next( 0, 256 ),
_Random.Next( 0, 256 ),
_Random.Next( 0, 256 ) ) ) );
}
public static string Ip6 ( )
{
return ( Convert.ToString( string.Format( "{0:X}:{1:X}:{2:X}:{3:X}:{4:X}:{5:X}:{6:X}:{7:X}",
_Random.Next( 1, Int16.MaxValue + 1 ),
_Random.Next( 0, Int16.MaxValue + 1 ),
_Random.Next( 0, Int16.MaxValue + 1 ),
_Random.Next( 0, Int16.MaxValue + 1 ),
_Random.Next( 0, Int16.MaxValue + 1 ),
_Random.Next( 0, Int16.MaxValue + 1 ),
_Random.Next( 0, Int16.MaxValue + 1 ),
_Random.Next( 0, Int16.MaxValue + 1 ) ) ) );
}
public static string Latitude ( bool Formated = false )
{
if ( Formated )
{
return ( string.Format( "{0}° {1}'", _Random.Next( -90, 90 ), _Random.Next( 0, 60 ) ) );
}
else
{
return ( string.Format( "{0}.{1}", _Random.Next( -90, 90 ), _Random.Next( 0, 100 ) ) );
}
}
public static string Longitude ( bool Formated = false )
{
if ( Formated )
{
return ( string.Format( "{0}° {1}'", _Random.Next( -180, 180 ), _Random.Next( 0, 60 ) ) );
}
else
{
return ( string.Format( "{0}.{1}", _Random.Next( -180, 180 ), _Random.Next( 0, 100 ) ) );
}
}
public static string Date ( int MaxYear = 9999 )
{
int nYear = _Random.Next( 1900, Math.Max( 2000, MaxYear ) + 1 );
int nMonth = _Random.Next( 1, 13 );
int nDay = _Random.Next( 1, DateTime.DaysInMonth( nYear, nMonth ) + 1 );
DateTime oDate = new DateTime( nYear, nMonth, nDay );
return ( oDate.ToString( _CultureInfo.DateTimeFormat.ShortDatePattern ) );
}
public static string Time ( )
{
DateTime oDate = new DateTime( 1, 1, 1, _Random.Next( 0, 24 ), _Random.Next( 0, 60 ), 0 );
return ( oDate.ToString( _CultureInfo.DateTimeFormat.ShortTimePattern ) );
}
public static string Datetime ( int MaxYear = 9999 )
{
return ( string.Format( "{0} {1}", Date( MaxYear ), Time( ) ) );
}
public static string Sid ( )
{
return ( Convert.ToString( ++_SID ) );
}
#endregion
#region Resource handling
public static string Resource ( string Name )
{
if ( LoadResource( Name ) )
{
return ( _Resources[_CultureInfo.Name][Name][_Random.Next( _Resources[_CultureInfo.Name][Name].Length )] );
}
return ( string.Format( _MissingResource, Name, _CultureInfo.Name ) );
}
private static bool LoadResource ( string Name )
{
if ( !File.Exists( string.Format( _BaseName, _CultureInfo.Name, Name ) ) )
{
return ( false );
}
else
{
if ( !_Resources.ContainsKey( _CultureInfo.Name ) )
{
_Resources[_CultureInfo.Name] = new Dictionary<string, string[ ]>( );
}
if ( !_Resources[_CultureInfo.Name].ContainsKey( Name ) )
{
_Resources[_CultureInfo.Name][Name] = JsonConvert.DeserializeObject<string[ ]>(
System.IO.File.ReadAllText( string.Format( _BaseName, _CultureInfo.Name, Name ) )
);
}
}
return ( true );
}
#endregion
}
}
<file_sep>/DemoData/Command.cs
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.CSharp;
using Newtonsoft.Json;
using static DemoData.Command.CommandList;
namespace DemoData
{
public class Command
{
#pragma warning disable CS0649
internal struct CommandList
{
public enum Format
{
CSV,
JSON,
}
public struct Column
{
public string Name;
public string Func;
}
public struct Relation
{
public string Parent;
public string Child;
}
public struct Table
{
public string Name;
public int Rows;
public Relation[ ] Relations;
public Table[ ] ChildTables;
public Column[ ] Columns;
}
public bool Compile;
public Format Output;
public Table[ ] Tables;
}
#pragma warning restore CS0649
private static void WriteTable ( Table Table, StringBuilder Code, List<string> TableName, string Culture )
{
Dictionary<string, string> oProperties = new Dictionary<string, string>( );
bool bNeedNext = false;
Code.AppendLine( string.Format( "public class {0} {{", Table.Name ) );
List<string> oLines = new List<string>( );
TableName.Add( Table.Name );
foreach ( Column oColumn in Table.Columns )
{
Relation[ ] oRelations = Table.Relations?.Where( oRelation => oRelation.Child == oColumn.Name ).ToArray( );
if ( oRelations?.Length == 1 )
{
oLines.Add( string.Format( "{{\"{0}\", Parent[\"{1}\"].Value<string>()}},", Helpers.TextInfo.ToTitleCase( oColumn.Name ), Helpers.TextInfo.ToTitleCase( oRelations[0].Parent ) ) );
continue;
}
else if ( oRelations?.Length > 1 )
{
Console.WriteLine( string.Format( "WARNING: More then one relation for the same column ({0}) in tabel ({1})! Ignored...", oColumn.Name, Table.Name ) );
}
List<string> oFunc = new List<string>( );
int nIndex = 0;
string szFinalFormat = oColumn.Func;
Match oMatch = Helpers.Resource.Match( oColumn.Func );
while ( oMatch.Success )
{
bNeedNext = true;
string szKey = Helpers.TextInfo.ToTitleCase( Helpers.Replace( Helpers.SquareToNothingRegex, Helpers.SquareToNothing, oMatch.Value ) );
if ( !oProperties.ContainsKey( szKey ) )
{
oProperties.Add( szKey, string.Format( "Resource({0})", Helpers.Replace( Helpers.SquareToQuoteRegex, Helpers.SquareToQuote, oMatch.Value ) ) );
Code.AppendLine( string.Format( "private static dynamic {0};", szKey ) );
}
oFunc.Add( szKey );
szFinalFormat = szFinalFormat.Replace( oMatch.Value, string.Format( "{{{0}}}", nIndex++ ) );
oMatch = oMatch.NextMatch( );
}
oMatch = Helpers.Function.Match( oColumn.Func );
while ( oMatch.Success )
{
oFunc.Add( string.Format( "Data{0}.{1}", Culture, Helpers.TextInfo.ToTitleCase( string.Format( "{0}", oMatch.Value.Replace( "<", "" ).Replace( ">", "" ) ) ) ) );
szFinalFormat = szFinalFormat.Replace( oMatch.Value, string.Format( "{{{0}}}", nIndex++ ) );
oMatch = oMatch.NextMatch( );
}
if ( nIndex > 0 )
{
oLines.Add( string.Format( "{{\"{0}\", string.Format(\"{1}\", {2})}},", Helpers.TextInfo.ToTitleCase( oColumn.Name ), szFinalFormat, string.Join( ", ", oFunc.ToArray( ) ) ) );
}
else
{
oLines.Add( string.Format( "{{\"{0}\", \"{1}\"}},", Helpers.TextInfo.ToTitleCase( oColumn.Name ), szFinalFormat ) );
}
}
if ( bNeedNext )
{
Code.AppendLine( "private static void Next() {" );
foreach ( KeyValuePair<string, string> oProperty in oProperties )
{
Code.AppendLine( string.Format( "{0} = Data{1}.{2};", oProperty.Key, Culture, oProperty.Value ) );
}
Code.AppendLine( "}" );
}
Code.AppendLine( "private static JObject Record( JObject Parent = null ) {" );
if ( bNeedNext )
{
Code.AppendLine( "Next();" );
}
string szObject = string.Join( Environment.NewLine, oLines.ToArray( ) );
szObject = string.Format( "return( new JObject {{{0}}} );", szObject );
Code.AppendLine( szObject );
Code.AppendLine( "}" );
Code.AppendLine( "public static void LoadData ( Dictionary<string, Stack> Storage, JObject Parent = null ) {" );
Code.AppendLine( "Data.PushSID();" );
Code.AppendLine( string.Format( "for (int i = 0; i < {0}; i++ ) {{", Table.Rows ) );
Code.AppendLine( string.Format( "Storage[\"{0}\"].Push( Record( Parent ) );", Table.Name ) );
foreach ( Table oChild in Table.ChildTables ?? Enumerable.Empty<Table>( ) )
{
Code.AppendLine( string.Format( "{0}.LoadData( Storage, ( JObject )Storage[\"{1}\"].Peek( ) );", oChild.Name, Table.Name ) );
}
Code.AppendLine( "}" );
Code.AppendLine( "Data.PopSID();" );
Code.AppendLine( "}" );
Code.AppendLine( "}" );
foreach ( Table oChild in Table.ChildTables ?? Enumerable.Empty<Table>( ) )
{
WriteTable( oChild, Code, TableName, Culture );
}
}
public static bool Execute ( string CommandFile, string Culture )
{
StringBuilder oCode = new StringBuilder( );
List<string> oTableNames = new List<string>( );
string szFile = string.Format( @"{0}\{1}", Helpers.Root, CommandFile );
if ( !File.Exists( szFile ) )
{
Console.WriteLine( "ERROR: Can not find command file!" );
return ( false );
}
string szJson = File.ReadAllText( szFile ).ToLower( );
CommandList oCommand = JsonConvert.DeserializeObject<CommandList>( szJson );
if ( oCommand.Compile )
{
if ( !Compiler.Compile( Culture ) )
{
return ( false );
}
}
oCode.AppendLine( "using System;" );
oCode.AppendLine( "using System.Collections;" );
oCode.AppendLine( "using System.Collections.Generic;" );
oCode.AppendLine( "using Newtonsoft.Json.Linq;" );
oCode.AppendLine( "namespace DemoData {" );
foreach ( Table oTable in oCommand.Tables )
{
WriteTable( oTable, oCode, oTableNames, Culture );
}
oCode.AppendLine( "public class Execute {" );
oCode.AppendLine( "public static void Run() {" );
oCode.AppendLine( "Dictionary<string, Stack> oStorage = new Dictionary<string, Stack>( );" );
oCode.AppendLine( string.Format( "Data.Reset( \"{0}\" );", Culture ) );
foreach ( string szTable in oTableNames )
{
oCode.AppendLine( string.Format( "oStorage.Add( \"{0}\", new Stack( ) );", szTable ) );
}
foreach ( Table oTable in oCommand.Tables )
{
oCode.AppendLine( string.Format( "{0}.LoadData( oStorage );", oTable.Name ) );
}
oCode.AppendLine( "foreach ( KeyValuePair<string, Stack> oTable in oStorage ) {" );
oCode.AppendLine( string.Format( "Export.SetOutput( string.Format( @\"C:\\Users\\peter\\Source\\Repos\\demodata\\DemoData\\bin\\Debug\\results\\{{0}}.{0}\", oTable.Key ) );", oCommand.Output ) );
oCode.AppendLine( "Export.ToCsv(Array.ConvertAll(oTable.Value.ToArray(), oItem => (JObject)oItem));" );
oCode.AppendLine( "Export.RestoreOutput( );" );
oCode.AppendLine( "}" );
oCode.AppendLine( "}" );
oCode.AppendLine( "}" );
oCode.AppendLine( "}" );
string szCode = oCode.ToString( );
CSharpCodeProvider oCodeProvider = new CSharpCodeProvider( );
CompilerParameters oParameters = new CompilerParameters( );
oParameters.ReferencedAssemblies.Add( "System.dll" );
oParameters.ReferencedAssemblies.Add( "System.Core.dll" );
oParameters.ReferencedAssemblies.Add( "Microsoft.CSharp.dll" );
oParameters.ReferencedAssemblies.Add( "Newtonsoft.Json.dll" );
oParameters.ReferencedAssemblies.Add( "Data.dll" );
oParameters.ReferencedAssemblies.Add( "Export.dll" );
oParameters.ReferencedAssemblies.Add( string.Format( "Data{0}.dll", Culture ) );
oParameters.GenerateInMemory = true;
oParameters.GenerateExecutable = false;
oParameters.MainClass = "Execute";
CompilerResults oResults = oCodeProvider.CompileAssemblyFromSource( oParameters, szCode );
if ( oResults.Errors.HasErrors )
{
Console.WriteLine( "There were some errors:" );
foreach ( CompilerError oError in oResults.Errors )
{
Console.WriteLine( String.Format( " ({0}): {1}, at ({2}, {3})", oError.ErrorNumber, oError.ErrorText, oError.Line, oError.Column ) );
}
Helpers.Dump( szCode );
return ( false );
}
var oType = oResults.CompiledAssembly.GetType( "DemoData.Execute" );
if ( oType == null )
{
Console.WriteLine( "ERROR: Compiled Assembly does not contain a class for Execute..." );
return ( false );
}
oType.GetMethod( "Run" ).Invoke( null, null );
Console.WriteLine( " ...done..." );
return ( true );
}
}
}
<file_sep>/DemoData/Compiler.cs
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.CSharp;
using Newtonsoft.Json;
using static DemoData.Compiler.Culture;
namespace DemoData
{
public class Compiler
{
#pragma warning disable CS0649
internal struct Culture
{
public struct Function
{
public string Name;
public string Func;
}
public string Inherit;
public Function[ ] Local;
}
#pragma warning restore CS0649
public static bool Compile ( string Culture )
{
string szFile = string.Format( @"{0}\{1}\func.json", Helpers.CultureRoot, Culture );
if ( !File.Exists( szFile ) )
{
Console.WriteLine( "ERROR: Can not find functions definitions file..." );
return ( false );
}
Culture oCustom = JsonConvert.DeserializeObject<Culture>( File.ReadAllText( szFile ).ToLower( ) );
StringBuilder oCode = new StringBuilder( );
oCode.AppendLine( "using System.Linq;" );
oCode.AppendLine( "namespace DemoData {" );
oCode.AppendLine( string.Format( "public class Data{0} : Data{1} {{", Culture, oCustom.Inherit ) );
foreach ( Function oCustomFunction in oCustom.Local )
{
List<string> oFunc = new List<string>( );
int nIndex = 0;
string szFinalFormat = oCustomFunction.Func;
Match oMatch = Helpers.Resource.Match( oCustomFunction.Func );
while ( oMatch.Success )
{
oFunc.Add( string.Format( "Resource({0})", Helpers.Replace( Helpers.SquareToQuoteRegex, Helpers.SquareToQuote, oMatch.Value ) ) );
szFinalFormat = szFinalFormat.Replace( oMatch.Value, string.Format( "{{{0}}}", nIndex++ ) );
oMatch = oMatch.NextMatch( );
}
oMatch = Helpers.Function.Match( szFinalFormat );
while ( oMatch.Success )
{
oFunc.Add( Helpers.TextInfo.ToTitleCase( string.Format( "{0}", Helpers.Replace( Helpers.AngleToNothingRegex, Helpers.AngleToNothing, oMatch.Value ) ) ) );
szFinalFormat = szFinalFormat.Replace( oMatch.Value, string.Format( "{{{0}}}", nIndex++ ) );
oMatch = oMatch.NextMatch( );
}
string szResult = string.Format( "return( \"{0}\" );", szFinalFormat );
if ( nIndex > 0 )
{
szResult = string.Format( "return( string.Format( \"{0}\", {1} ) );", szFinalFormat, string.Join( ", ", oFunc.ToArray( ) ) );
}
oCode.AppendLine( string.Format( "public static dynamic {0} () {{", Helpers.TextInfo.ToTitleCase( oCustomFunction.Name ) ) );
oCode.AppendLine( szResult );
oCode.AppendLine( "}" );
}
oCode.AppendLine( "}" );
oCode.AppendLine( "}" );
string szCode = oCode.ToString( );
CSharpCodeProvider oCodeProvider = new CSharpCodeProvider( );
CompilerParameters oParameters = new CompilerParameters( );
oParameters.ReferencedAssemblies.Add( "System.Core.dll" );
oParameters.ReferencedAssemblies.Add( string.Format( "Data{0}.dll", oCustom.Inherit ) );
oParameters.GenerateInMemory = false;
oParameters.GenerateExecutable = false;
oParameters.OutputAssembly = string.Format( "Data{0}.dll", Culture );
oParameters.MainClass = string.Format( "Data{0}", Culture );
CompilerResults oResults = oCodeProvider.CompileAssemblyFromSource( oParameters, szCode );
if ( oResults.Errors.HasErrors )
{
Console.WriteLine( "There were some errors:" );
foreach ( CompilerError oError in oResults.Errors )
{
Console.WriteLine( String.Format( " ({0}): {1}, at ({2}, {3})", oError.ErrorNumber, oError.ErrorText, oError.Line, oError.Column ) );
}
Helpers.Dump( szCode );
return ( false );
}
else
{
Console.WriteLine( " ...done..." );
return ( true );
}
}
}
}
<file_sep>/DemoData/Helpers.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace DemoData
{
public class Helpers
{
public static Dictionary<string, string> SquareToQuote = new Dictionary<string, string> { { "[", "\"" }, { "]", "\"" } };
public static Dictionary<string, string> SquareToNothing = new Dictionary<string, string> { { "[", string.Empty }, { "]", string.Empty } };
public static Dictionary<string, string> AngleToNothing = new Dictionary<string, string> { { "<", string.Empty }, { ">", string.Empty } };
public static Regex SquareToQuoteRegex = new Regex( "(" + string.Join( "|", SquareToQuote.Keys.Select( Regex.Escape ) ) + ")" );
public static Regex SquareToNothingRegex = new Regex( "(" + string.Join( "|", SquareToNothing.Keys.Select( Regex.Escape ) ) + ")" );
public static Regex AngleToNothingRegex = new Regex( "(" + string.Join( "|", AngleToNothing.Keys.Select( Regex.Escape ) ) + ")" );
public struct Commands
{
public static string List = "-list";
public static string Compile = "-comp";
public static string Command = "-cmd";
}
public static string Root = Path.GetDirectoryName( Assembly.GetEntryAssembly( ).Location );
public static string CultureRoot = string.Format( @"{0}\Culture", Root );
public static string[ ] Cultures = Directory.GetDirectories( Helpers.CultureRoot );
public static TextInfo TextInfo = new CultureInfo( "en", false ).TextInfo;
public static Regex Resource = new Regex( @"\[(.*?)\]" );
public static Regex Function = new Regex( @"\<(.*?)\>" );
public static void Dump ( string Code )
{
string[ ] szLines = Code.Split( new string[ ] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries );
int nLine = 1;
int nTabs = 1;
Console.WriteLine( );
foreach ( string szLine in szLines )
{
if ( szLine.StartsWith( "}" ) )
{
nTabs--;
}
Console.WriteLine( string.Format( "{0:D4}{2}{1}", nLine, szLine, new string( ' ', nTabs * 2 ) ) );
if ( szLine.EndsWith( "{" ) )
{
nTabs++;
}
nLine++;
}
}
public static string Replace ( Regex Condition, Dictionary<string, string> ReplaceList, string Value )
{
return ( Condition.Replace( Value, oMatch => ReplaceList[oMatch.Value] ) );
}
}
}
<file_sep>/Export/Export.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace DemoData
{
public class Export
{
private static TextWriter _StandardOutput = Console.Out;
public static void SetOutput ( string Out )
{
Directory.CreateDirectory( Path.GetDirectoryName( Out ) );
Console.Out.Flush( );
Console.SetOut( new StreamWriter( Out ) );
}
public static void RestoreOutput ( )
{
Console.Out.Flush( );
Console.SetOut( _StandardOutput );
}
public static void ToJson ( JObject[ ] Set )
{
Console.WriteLine( JsonConvert.SerializeObject( Set ) );
}
public static void ToCsv ( JObject[ ] Set )
{
StringBuilder oSB = new StringBuilder( );
DataTable oData = JsonConvert.DeserializeObject<DataTable>( JsonConvert.SerializeObject( Set ) );
IEnumerable<string> szColumns = oData.Columns.Cast<DataColumn>( ).Select( oColumn => oColumn.ColumnName );
oSB.AppendLine( string.Join( ",", szColumns ) );
foreach ( DataRow oRow in oData.Rows )
{
IEnumerable<string> szValues = oRow.ItemArray.Select( szValue => string.Format( "\"{0}\"", szValue.ToString( ) ) );
oSB.AppendLine( string.Join( ",", szValues ) );
}
Console.WriteLine( oSB.ToString( ) );
}
}
}
<file_sep>/DemoData/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace DemoData
{
class Program
{
static void Main ( string[ ] args )
{
List<string> oArgs = args.ToList( );
int nIndex;
PrintHeader( );
if ( ( oArgs.Count( ) == 0 ) ||
( !oArgs.Contains( Helpers.Commands.List ) &&
!oArgs.Contains( Helpers.Commands.Compile ) &&
!oArgs.Contains( Helpers.Commands.Command ) ) )
{
PrintHelp( );
return;
}
if ( oArgs.Contains( Helpers.Commands.List ) )
{
Console.WriteLine( "Listing cultures..." );
if ( Helpers.Cultures.Length > 0 )
{
foreach ( string szCulture in Helpers.Cultures )
{
DirectoryInfo oDir = new DirectoryInfo( szCulture );
Console.WriteLine( );
Console.WriteLine( string.Format( " {0}", oDir.Name ) );
Console.WriteLine( string.Format( " Functions definitions file is {0}...", File.Exists( Path.Combine( oDir.FullName, "func.json" ) ) ? "presented" : "missing" ) );
Console.WriteLine( " Resources:" );
foreach ( FileInfo oFile in oDir.GetFiles( ) )
{
if ( !oFile.Name.ToLower( ).Equals( "func.json" ) )
{
Console.WriteLine( string.Format( " {0}", oFile.Name.Replace( oFile.Extension, string.Empty ) ) );
}
}
}
}
else
{
Console.WriteLine( " ...none found..." );
}
}
if ( oArgs.Contains( Helpers.Commands.Compile ) )
{
nIndex = oArgs.IndexOf( Helpers.Commands.Compile ) + 1;
if ( oArgs.Count > nIndex )
{
string szCulture = oArgs[nIndex];
Console.WriteLine( );
Console.WriteLine( string.Format( "Compiling culture '{0}'...", szCulture ) );
if ( !Compiler.Compile( szCulture ) )
{
return;
}
}
else
{
Console.WriteLine( "ERROR. Missing culture..." );
return;
}
}
if ( oArgs.Contains( Helpers.Commands.Command ) )
{
nIndex = oArgs.IndexOf( Helpers.Commands.Command ) + 2;
if ( oArgs.Count > nIndex )
{
string szCommandFile = oArgs[nIndex - 1];
string szCulture = oArgs[nIndex];
Console.WriteLine( string.Format( "Executing command from '{0}', using culture '{1}'...", szCommandFile, szCulture ) );
if ( !Command.Execute( szCommandFile, szCulture ) )
{
return;
}
}
else
{
Console.WriteLine( "ERROR. Missing command file and/or culture..." );
return;
}
}
}
static void PrintHeader ( )
{
Console.WriteLine( "DemoData" );
Console.WriteLine( string.Format( " Version: {0}", Assembly.GetEntryAssembly( ).GetName( ).Version.ToString( ) ) );
Console.WriteLine( );
}
static void PrintHelp ( )
{
Console.WriteLine( "USAGE:" );
Console.WriteLine( " DemoData -list | -comp {culture} | -cmd {file} {culture}" );
Console.WriteLine( );
Console.WriteLine( "Where:" );
Console.WriteLine( " -list Lists all the cultures currently exists," );
Console.WriteLine( " including their resources" );
Console.WriteLine( " -comp {culture} Compiles the specified 'culture'" );
Console.WriteLine( " -cmd {file} {culture} Runs the commands in 'file' using 'culture'" );
Console.WriteLine( );
Console.WriteLine( "Details: https://www.codeproject.com/Articles/1198666/Demo-data" );
}
}
}
|
4fef8bdedd3e764a52fd6a155fe7930f08893112
|
[
"C#"
] | 6 |
C#
|
kepeter/DemoData
|
9cc5e06dc4ca391cc9e531d65b63d4a54a1ca7c8
|
ff9e7b89269e9de814182fc73d8e9cea2d2503f6
|
refs/heads/master
|
<file_sep>//
// config.h
// PokerAnalysis
//
// Created by <NAME> on 12-11-26.
// Copyright (c) 2012年 <NAME>. All rights reserved.
//
#ifndef PokerAnalysis_config_h
#define PokerAnalysis_config_h
#define PREFLOP 1
#define POSTFLOP 2
#define TURN 3
#define RIVER 4
#define LIMP 1
#define RAISE 2
#define FOLD 3
#define BB_CHECK 4
#define CHECK_RAISE 5
#define RE_RAISE 6
#define CALL_FOLD 7
#define CHECK_FOLD 8
#define RAISE_FOLD 9
#define THREE_BET 10
#define FOUR_BET 11
#define CALL 12
#define CHECK 13
#define ALL_IN 14
#define SB 1
#define BB 2
#define UTG 3
#define MP 4
#define CO 5
#define BTN 6
//typedef struct player_info;
#define TOTAL_PLAYERS 9
#define DEAD 0
#define ALIVE 1
#define MEMBER_SET 1
#define MEMBER_ANALYSIS 2
#endif
<file_sep>PokerAnalysis
=============
For Poker player
|
02777df29365fb0a7d63cc1ac518d412c3e913b6
|
[
"Markdown",
"C"
] | 2 |
C
|
stupidma/PokerAnalysis
|
2be7c5a29b1cc7c952df433f92862f675b4194d6
|
b68aa026de763114ac9be72abb27e85df098bd37
|
refs/heads/master
|
<repo_name>hardeepamritsar/react-native-fetch-offline<file_sep>/README.md
<p align="center"><a href="https://travis-ci.org/hardeepamritsar/react-native-fetch-offline"><img src="https://api.travis-ci.org/hardeepamritsar/react-native-fetch-offline.svg?branch=master"/></a></p>
# react-native-fetch-offline
Returns fetch object with cached data if user is offline
## Installation
```
npm install --save react-native-fetch-offline # with npm
yarn add react-native-fetch-offline # with yarn
```
Link react-native-internet-reachability
```
react-native link react-native-internet-reachability
```
## How it works
<p align="center"><a href="https://i.imgur.com/X5X9FFq.png"><img src="https://i.imgur.com/X5X9FFq.png"/></a></p>
## How to use
```javascript
import FetchOffline, { cacheReponse } from 'react-native-fetch-offline';
const requestOptions = {
method: 'GET',
offline: {
defaultResponse: {
data: {
myKey: 'myValue',
}
},
},
};
FetchOffline('http://www.domain.com/api', requestOptions)
.catch(err => get(err, 'message', 'Default error message'))
.then(response => response.json()
.then((body) => {
cacheReponse(requestOptions.url, fetchOptions, body); // if you want to cache response (to be returened for future calls while being offline)
return body;
}));
```
<file_sep>/src/index.js
import { AsyncStorage } from 'react-native';
import hash from 'object-hash';
import _ from 'lodash';
import omit from 'lodash/omit';
import Network from 'react-native-internet-reachability';
export default async function FetchOffline(url, options, ignoredRoutesForCacheKey) {
const reachabilityTimeout = options.reachabilityTimeout ? options.reachabilityTimeout : 5000;
const reachabilityDomain = options.reachabilityDomain ? options.reachabilityDomain : '8.8.8.8';
const isReachable = await Network.isReachable(reachabilityTimeout, reachabilityDomain);
if (isReachable) {
return fetch(url, options);
} else {
return getDataFromCache(url, options, ignoredRoutesForCacheKey);
}
}
async function getDataFromCache(url, options, ignoredRoutesForCacheKey) {
const data = await getFailCaseResponse(url, options, ignoredRoutesForCacheKey);
if (data) {
return new Promise((resolve) => {
resolve({
ok: true,
json() {
return Promise.resolve(data);
},
});
});
}
return Promise.reject(new Error('No Internet'));
}
export async function getFailCaseResponse(url, options, ignoredRoutesForCacheKey) {
const key = genrateKeyFor(url, options, ignoredRoutesForCacheKey);
let data = await AsyncStorage.getItem(key);
if (data) {
data = JSON.parse(data);
} else {
data = getDefaultResponseFromOptions(options);
}
if(data){
data.fallbackResponse=true;
}
return data;
}
export function isResponseFromOnline(result){
if (result && result.fallbackResponse) {
return false;
} else {
return true;
}
}
export function cacheReponse(url, options, responseBody, ignoredRoutesForCacheKey) {
const key = genrateKeyFor(url, options, ignoredRoutesForCacheKey);
AsyncStorage.setItem(key, JSON.stringify(responseBody));
}
function getDefaultResponseFromOptions(options) {
if (options.offline && options.offline.defaultResponse) {
return options.offline.defaultResponse;
}
return null;
}
function genrateKeyFor(url, options, ignoredRoutesForCacheKey) {
const providedOtions = omit(options, ['offline']);
for (var key in ignoredRoutesForCacheKey) {
_.set(providedOtions, key, ignoredRoutesForCacheKey[key]);
}
return `options:${hash(providedOtions)} url:${url}}`;
}
<file_sep>/src/index.test.js
import { AsyncStorage } from 'react-native';
import Network from 'react-native-internet-reachability';
import omit from 'lodash/omit';
import hash from 'object-hash';
import FetchOffline, { cacheReponse } from './index';
jest.mock('react-native-internet-reachability', () => ({
isReachable: jest.fn(),
}));
jest.mock('react-native', () => ({
AsyncStorage: {
getItem: jest.fn(),
setItem: jest.fn(),
},
}));
global.fetch = jest.fn();
const requestOptions = {
url: 'http://example.com',
method: 'GET',
body: {
bacon: 'baconbaconbacon',
},
headers: {
BreakfastFoods: 'AreTheBest',
},
offline: {
defaultResponse: {
offlineData: 'Response from options',
},
},
};
describe('Test FetchOffline function', () => {
it('it should return default data from options', async () => {
Network.isReachable.mockImplementation(() => false);
AsyncStorage.getItem.mockImplementation(() => Promise.resolve(null));
const response = await FetchOffline(requestOptions.url, requestOptions)
.then(responseObj => responseObj.json()
.then(body => body));
expect(response.offlineData).toBe('Response from options');
});
it('it should return default data from asyncStorage', async () => {
Network.isReachable.mockImplementation(() => false);
AsyncStorage.getItem.mockImplementation(() => Promise.resolve(JSON.stringify({ offlineData: 'Response from asyncStorage' })));
const response = await FetchOffline(requestOptions.url, requestOptions)
.then(responseObj => responseObj.json()
.then(body => body));
expect(response.offlineData).toBe('Response from asyncStorage');
});
it('it should return default data from Fetch', async () => {
Network.isReachable.mockImplementation(() => true);
fetch.mockImplementation(() => new Promise((resolve) => {
resolve({
ok: true,
json() {
return Promise.resolve({ offlineData: 'Response from fetch' });
},
});
}));
const response = await FetchOffline(requestOptions.url, requestOptions)
.then(responseObj => responseObj.json()
.then(body => body));
expect(response.offlineData).toBe('Response from fetch');
});
});
describe('Test cacheReponse function', () => {
it('it should call AsyncStorage.setItem with provided key avlue', async () => {
AsyncStorage.setItem.mockImplementation(() => {});
cacheReponse(requestOptions.url, requestOptions, requestOptions.offline);
const providedOtions = omit(requestOptions, ['offline']);
const key = `options:${hash(providedOtions)} url:${requestOptions.url}}`;
expect(AsyncStorage.setItem.mock.calls[0][0]).toBe(key);
expect(AsyncStorage.setItem.mock.calls[0][1]).toBe(JSON.stringify(requestOptions.offline));
expect(AsyncStorage.setItem.mock.calls.length).toBe(1);
});
});
|
81de7fd60e0d8dbff64e125a57e30629e3fb1fdc
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
hardeepamritsar/react-native-fetch-offline
|
683f93e450bc76689ba8f09c1543ef88f8aba40c
|
ca03264a49101dddbcfcdf5c46b91a274789f52f
|
refs/heads/master
|
<file_sep>//
// CreationViewController.swift
// Flashcards
//
// Created by <NAME> on 3/3/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class CreationViewController: UIViewController {
var flashcardController: ViewController!
var initialQuestion: String?
var initialAnswer: String?
var initialIncorrect1: String?
var initialIncorrect2: String?
@IBOutlet var questionText: UITextField!
@IBOutlet var answerText: UITextField!
@IBOutlet var incorrectOption1: UITextField!
@IBOutlet var incorrectOption2: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
questionText.text = initialQuestion
answerText.text = initialAnswer
incorrectOption1.text = initialIncorrect1
incorrectOption2.text = initialIncorrect2
}
@IBAction func didTapOnCancel(_ sender: Any) {
if flashcardController.flashcardToBeDeleted != nil{
flashcardController.flashcards.append(flashcardController.flashcardToBeDeleted)
}
dismiss(animated: true)
}
@IBAction func didTapOnDone(_ sender: Any) {
if questionText.text==nil || questionText.text!.isEmpty
|| answerText.text==nil || answerText.text!.isEmpty
|| incorrectOption1.text==nil || incorrectOption1.text!.isEmpty
|| incorrectOption2.text==nil || incorrectOption2.text!.isEmpty {
let missingTextAlert = UIAlertController(title: "Missing Text", message: "You need to enter a question and three answer choices.", preferredStyle: .alert)
let OKAlert = UIAlertAction(title: "Ok", style: .default)
missingTextAlert.addAction(OKAlert)
present(missingTextAlert, animated: true)
} else {
flashcardController.updateFlashcard(q: questionText.text!,
a: answerText.text!,
i1: incorrectOption1.text!,
i2: incorrectOption2.text!,
isExisting: initialQuestion != nil)
dismiss(animated: true)}
}
// MARK: - Navigation
/*
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
let navigationController = segue.destination as! UINavigationController
let creationController = navigationController.topViewController as! CreationViewController
CreationViewController.flashcardController = self
}
*/
}
<file_sep>//
// ViewController.swift
// Flashcards
//
// Created by <NAME> on 2/8/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
struct Flashcard {
var question: String!
var answer: String!
var incorrect1: String!
var incorrect2: String!
}
class ViewController: UIViewController {
var creationController = CreationViewController.self
@IBOutlet weak var answerLabel: UILabel!
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet var prevButton: UIButton!
@IBOutlet var nextButton: UIButton!
@IBOutlet var card: UIView!
@IBOutlet var opt1: UIButton!
@IBOutlet var opt2: UIButton!
@IBOutlet var opt3: UIButton!
@IBOutlet var deleteButton: UIButton! = nil
var correctButton: UIButton!
var flashcardToBeDeleted: Flashcard!
var flashcards = [Flashcard]()
var currentIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
card.layer.cornerRadius=20.0
answerLabel.layer.cornerRadius=20.0
answerLabel.clipsToBounds=true
questionLabel.layer.cornerRadius=20.0
questionLabel.clipsToBounds=true
card.layer.shadowRadius=15.0
card.layer.shadowOpacity=0.2
opt1.layer.cornerRadius=20.0
opt1.layer.borderWidth=3.0
opt1.layer.borderColor=#colorLiteral(red: 0.2572371662, green: 0.7545303702, blue: 0.9694395661, alpha: 1)
opt2.layer.cornerRadius=20.0
opt2.layer.borderWidth=3.0
opt2.layer.borderColor=#colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)
opt3.layer.cornerRadius=20.0
opt3.layer.borderWidth=3.0
opt3.layer.borderColor=#colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)
card.sizeToFit()
readSavedFlashcards()
if flashcards.count==0{
currentIndex=0
flashcards.append(Flashcard(question: "This is a sample flashcard.", answer: "Option 1", incorrect1: "Option 2", incorrect2: "Option 3"))
updateFlashcard(q: "This is a sample flashcard.", a: "Option 1", i1: "Option 2", i2: "Option 3", isExisting: true)
} else {
updateLabels()
updatePrevNextButtons()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
card.alpha = 0.0
card.transform = CGAffineTransform.identity.scaledBy(x: 0.75, y: 0.75)
UIView.animate(withDuration: 0.6, delay: 0.5, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: [], animations: {
self.card.alpha = 1
self.card.transform = CGAffineTransform.identity
})
}
@IBAction func didTapOnFlashcard(_ sender: Any) {
flipFlashcard()
}
func flipFlashcard(){
UIView.transition(with: card, duration: 0.3, options: .transitionFlipFromRight, animations: {
self.questionLabel.isHidden = !self.questionLabel.isHidden
})
}
@IBAction func didTapOpt1(_ sender: Any) {
if opt1==correctButton{
flipFlashcard()
} else {
opt1.isHidden=true
questionLabel.isHidden=false
}
}
@IBAction func didTapOpt2(_ sender: Any) {
if opt2==correctButton{
flipFlashcard()
} else {
opt2.isHidden=true
questionLabel.isHidden=false
}
}
@IBAction func didTapOpt3(_ sender: Any) {
if opt3==correctButton{
flipFlashcard()
} else {
opt3.isHidden=true
questionLabel.isHidden=false
}
}
func updateFlashcard(q: String, a: String, i1: String, i2: String, isExisting: Bool) {
let flashcardV = Flashcard(question: q, answer: a, incorrect1: i1, incorrect2: i2)
if isExisting{
flashcards[currentIndex]=flashcardV
} else {
flashcards.append(flashcardV)
currentIndex = flashcards.count-1
}
updatePrevNextButtons()
updateLabels()
saveAllFlashcardsToDisk()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let navigationController = segue.destination as! UINavigationController
let creationController = navigationController.topViewController as! CreationViewController
creationController.flashcardController = self
if segue.identifier=="EditSegue" {
creationController.initialQuestion = questionLabel.text
creationController.initialAnswer = answerLabel.text
creationController.initialIncorrect1 = opt2.titleLabel!.text
creationController.initialIncorrect2 = opt3.titleLabel!.text
}
}
@IBAction func didTapOnNext(_ sender: Any) {
currentIndex+=1
updatePrevNextButtons()
animateCardOutLeft()
}
func animateCardOutLeft(){
UIView.animate(withDuration: 0.2, animations: {
self.card.transform = CGAffineTransform.identity.translatedBy(x: -400.0, y: 0.0)
}, completion: { finished in
self.updateLabels()
self.animateCardInFromRight()
})
}
func animateCardInFromRight(){
card.transform = CGAffineTransform.identity.translatedBy(x: 400.0, y: 0.0)
UIView.animate(withDuration: 0.2){
self.card.transform = CGAffineTransform.identity
}
}
@IBAction func didTapOnPrev(_ sender: Any) {
currentIndex-=1
updatePrevNextButtons()
animateCardOutRight()
}
func animateCardOutRight(){
UIView.animate(withDuration: 0.2, animations: {
self.card.transform = CGAffineTransform.identity.translatedBy(x: 400.0, y: 0.0)
}, completion: { finished in
self.updateLabels()
self.animateCardInFromLeft()
})
}
func animateCardInFromLeft(){
card.transform = CGAffineTransform.identity.translatedBy(x: -400.0, y: 0.0)
UIView.animate(withDuration: 0.2){
self.card.transform = CGAffineTransform.identity
}
}
func updatePrevNextButtons(){
if currentIndex==flashcards.count-1{
nextButton.isEnabled=false
} else {
nextButton.isEnabled=true
}
if currentIndex==0{
prevButton.isEnabled=false
} else {
prevButton.isEnabled=true
}
}
func updateLabels(){
opt1.isHidden=false
opt2.isHidden=false
opt3.isHidden=false
answerLabel.text = flashcards[currentIndex].answer
questionLabel.text = flashcards[currentIndex].question
let currentFlashcard = flashcards[currentIndex]
let buttons = [opt1, opt2, opt3].shuffled()
let answers = [currentFlashcard.answer, currentFlashcard.incorrect2, currentFlashcard.incorrect1].shuffled()
for (button, answer) in zip(buttons, answers){
button?.setTitle(answer, for: .normal)
if answer == currentFlashcard.answer {
correctButton=button
}
}
self.questionLabel.isHidden=false
}
@IBAction func didTapOnDelete(_ sender: Any) {
let alert = UIAlertController(title: "Delete Flashcard", message: "Are you sure you want to delete this flashcard?", preferredStyle: .actionSheet)
let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { action in
self.deleteCurrentFlashcard()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alert.addAction(deleteAction)
alert.addAction(cancelAction)
present(alert, animated: true)
}
func deleteCurrentFlashcard(){
flashcardToBeDeleted = flashcards[currentIndex]
flashcards.remove(at: currentIndex)
if currentIndex>flashcards.count-1{
currentIndex = flashcards.count-1
}
if currentIndex<0{
currentIndex=0
performSegue(withIdentifier: "creationSegue", sender: self)
return
}
updateLabels()
updatePrevNextButtons()
saveAllFlashcardsToDisk()
}
func saveAllFlashcardsToDisk(){
let dictionaryArray = flashcards.map { (card) -> [String: String] in
return ["question": card.question!, "answer": card.answer!, "incorrect1": card.incorrect1!, "incorrect2": card.incorrect2!]
}
UserDefaults.standard.set(dictionaryArray, forKey: "flashcards")
print("Flashcards saved to UserDefaults!")
}
func readSavedFlashcards(){
if let dictionaryArray = UserDefaults.standard.array(forKey: "flashcards") as? [[String: String]] {
let savedCards = dictionaryArray.map { dictionary -> Flashcard in return Flashcard(question: dictionary["question"], answer: dictionary["answer"], incorrect1: dictionary["incorrect1"], incorrect2: dictionary["incorrect2"])
}
flashcards.append(contentsOf: savedCards)
}
}
}
|
c936691db11f08b5f613ed84ba407f036842e78e
|
[
"Swift"
] | 2 |
Swift
|
petershelley/Flashcards
|
6d97785ce4c2eb421377c7cb7195905a9d005453
|
a9d21281ba510ed90e5e6926d440fca6c47a679a
|
refs/heads/master
|
<repo_name>madhura-raverkar/Python-Programs<file_sep>/evenodd.py
#whether given no is even or odd
a= int(input("enter no"))
if(a%2==0):
print("the given no is even")
else:
print("the given no is odd")
<file_sep>/for1.py
list = [1,2,3,4,5]
print (list)
for a in list:
print (a)
<file_sep>/palindrome1.py
str ="NITIN"
print(str)
list2 = list.reverse(str)
print (list2)
<file_sep>/number.py
a = 2
b= 3.5
c= 3.14j
print (a)
print (b)
print (c)
<file_sep>/Arithmetic.py
a= 30
b= 60
c= 0
c = a+b
print ("sum = ", c)
c = a-b
print ("substraction = ", c)
c = a*b
print ("multiplication = ", c)
c = a/b
print ("division = ", c)
|
0731659c0ceb44305e8c3987265ec7db620f61c3
|
[
"Python"
] | 5 |
Python
|
madhura-raverkar/Python-Programs
|
35b2d407efeb63125cdf79d43205d4a5188bba4f
|
7b6d58bd68851c04339e7ea6e7f8b3440e961516
|
refs/heads/master
|
<repo_name>marcosmarcon/Oracle-and-Grafana-integration<file_sep>/Configuration/oracle_conection.py
import cx_Oracle
class OracleConnection:
def connect(self):
uid = "user id"
pwd = "<PASSWORD>"
sid = "string connection"
self.connection = cx_Oracle.connect(uid, pwd, sid)
def open_cursor(self):
self.cursor = self.connection.cursor()
def execute_cursor(self, sql):
self.cursor.execute(sql)
def close_cursor(self):
self.cursor.close()
def close_connection(self):
self.connection.close()
<file_sep>/query/anonymous_block.py
from Configuration.oracle_conection import OracleConnection
def example_1():
sql_results = []
ora_conn = OracleConnection()
ora_conn.connect()
ora_conn.open_cursor()
ora_conn.cursor.callproc("dbms_output.enable")
ora_conn.execute_cursor('''DECLARE
TEST NUMBER;
BEGIN
FOR DATA IN (
SELECT Field_1, Field_2
FROM Table_1
WHERE 1=1
)LOOP
DBMS_OUTPUT.PUT_LINE (DATA.Field_1 || DATA.Field_2) ;
END LOOP;
END;
''')
# perform loop to fetch the text that was added by PL/SQL
textVar = ora_conn.cursor.var(str)
statusVar = ora_conn.cursor.var(int)
sql_return = ''
while True:
ora_conn.cursor.callproc("dbms_output.get_line", (textVar, statusVar))
if statusVar.getvalue() != 0:
break
sql_return += textVar.getvalue()
return (sql_return)<file_sep>/Configuration/influx.py
from influxdb import InfluxDBClient
class InfluxConnection:
points = []
def __init__(self):
self.points = []
self.host = "host"
self.port = "port"
self.username = "user"
self.password = "<PASSWORD>"
self.database = "base"
self.client = InfluxDBClient(self.host, self.port, self.username, self.password, self.database)
def drop_current_measurement(self, measurement):
self.client.query("DROP MEASUREMENT """ + measurement + """""")
def append_point(self, point):
self.points.append(point)
def write_points(self):
self.client.write_points(self.points)
def clean_points(self):
self.points = []<file_sep>/README.md
<!-- PROJECT LOGO -->
<h1 align="center">
Oracle and Grafana integration without plugins
</h1>
<!-- PROJECT SHIELDS -->
[![MIT License][license-shield]][license-url]
[![LinkedIn][linkedin-shield]][linkedin-url]
<p>
Project to integrate the Oracle database with Grafana without using plugins. <br>
</p>
<p>
Simple execution like 1, 2, 3
</p>
1. Build your Oracle query<br>
2. Python script to execute the Oracle query and put the result inside Influx<br>
3. Grafana reads Influx data<br>
<!-- TABLE OF CONTENTS -->
## Table of Contents
* [Technologies](#technologies)
* [Getting Started](#getting-started)
* [Installation](#installation)
* [Contributing](#contributing)
* [License](#license)
* [Contact](#contact)
<!-- ABOUT THE PROJECT -->
## Technologies
* [Python](https://www.python.org/) <img src="https://github.com/marcosmarcon/Oracle-and-Grafana-integration/blob/master/images/python.svg" alt="Logo" width="30" height="30">
* [InfluxDB](https://www.influxdata.com/) <img src="https://github.com/marcosmarcon/Oracle-and-Grafana-integration/blob/master/images/influx.svg" alt="Logo" width="30" height="30">
* [Grafana](https://grafana.com/) <img src="https://github.com/marcosmarcon/Oracle-and-Grafana-integration/blob/master/images/grafana.svg" alt="Logo" width="30" height="30">
<!-- GETTING STARTED -->
## Getting Started
First it is necessary to install Python and Python library cx_Oracle.
### Installation
1. Clone the repo
```sh
git clone https://github.com/marcosmarcon/Oracle-and-Grafana-integration
```
2. Install packages
```sh
python -m pip install cx_Oracle --upgrade pip
```
<!-- CONTRIBUTING -->
## Contributing
1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/Feature`)
3. Commit your Changes (`git commit -m 'Add some Feature'`)
4. Push to the Branch (`git push origin feature/Feature`)
5. Open a Pull Request
<!-- LICENSE -->
## License
Distributed under the MIT License. See `LICENSE` for more information.
<!-- CONTACT -->
## Contact
Project Link: [https://github.com/marcosmarcon/Oracle-and-Grafana-integration](https://github.com/marcosmarcon/Oracle-and-Grafana-integration)
Linkedin: [https://www.linkedin.com/in/marcos-marcon-048a7855/](https://www.linkedin.com/in/marcos-marcon-048a7855/)
<!-- MARKDOWN LINKS & IMAGES -->
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
[license-shield]: https://img.shields.io/badge/License-MIT-blue.svg
[license-url]: https://opensource.org/licenses/MIT
[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=flat-square&logo=linkedin&colorB=555
[linkedin-url]: linkedin.com/in/marcos-marcon-048a7855
<file_sep>/query/query.py
def query():
sql = '''SELECT Field_1 FROM Table_1 '''
return sql<file_sep>/Service/app.py
from Configuration.influx import InfluxConnection
from Configuration.oracle_conection import OracleConnection
from query.anonymous_block import example_1
from query.query import query
def example_anonymous_block():
return_example_1 = example_1()
save_influx_anonymous_block(return_example_1)
def example_query():
return_example_2 = query()
save_influx_query(return_example_2)
def save_influx_anonymous_block(return_example_1):
data_1 = return_example_1[1:9]
data_2 = return_example_1[9:]
point = {
"measurement": "measurement_1",
"fields": {
"data_1": data_1,
"data_2": data_2
},
}
save = InfluxConnection()
save.append_point(point)
save.write_points()
def save_influx_query( return_example_2):
point = {
"measurement": "measurement_2",
"fields": {
"data_1": return_example_2
},
}
save = InfluxConnection()
save.append_point(point)
save.write_points()
|
fa0b84a8b0cc71543c260684149b684de16a083f
|
[
"Markdown",
"Python"
] | 6 |
Python
|
marcosmarcon/Oracle-and-Grafana-integration
|
0a7f47a940a72b281a9ff04285c222be99516829
|
bfc74f4f49ff861cd9d8a65aec27567aaaaa1a18
|
refs/heads/master
|
<repo_name>hoonto/scuttlebutt<file_sep>/util.js
exports.createId =
function () {
return [1,1,1].map(function () {
return Math.random().toString(16).substring(2).toUpperCase()
}).join('')
}
exports.filter = function (update, sources) {
var ts = update[1]
var source = update[2]
return (!sources || !sources[source] || sources[source] < ts)
}
|
aabcd9092a168022b6c3ee0cc32ab6929c671c67
|
[
"JavaScript"
] | 1 |
JavaScript
|
hoonto/scuttlebutt
|
662063b53fb75a3689d0a2d8f565431b44b30abb
|
f0c941e84fe2f848be8425528e44464384ac5650
|
refs/heads/master
|
<repo_name>iamthiago/ProgrammingAssignment2<file_sep>/cachematrix.R
## This function stores the inverse of a matrix
makeCacheMatrix <- function(x = matrix()) {
inv = NULL
## if a new matrix is given, override x
set = function(y) {
x <<- y
inv <<- NULL
}
get = function() x
setinv = function(inverse) inv <<- inverse
getinv = function() inv
list(set=set, get=get, setinv=setinv, getinv=getinv)
}
## Inverting a matrix can be a expensive computation
## Calculate the inverse and store it in the object
cacheSolve <- function(x, ...) {
## Get the inverse if any
inv = x$getinv()
# if the object has already calculate the inverse, return it
if (!is.null(inv)){
# get it from the cache and skips the computation.
message("getting cached data")
return(inv)
}
# otherwise get the matrix from the object and calculate it!
inv = solve(x$get(), ...)
# now store the value in the object for further look up
x$setinv(inv)
return(inv)
}
|
96ad740e1de0a5dde3a7da4c121b8232e4a82529
|
[
"R"
] | 1 |
R
|
iamthiago/ProgrammingAssignment2
|
d698e3ff28b14023a671612f15d2b7acf425e9c3
|
d25e404dba519a51b69b7a0078ffe5395e8f6d23
|
refs/heads/master
|
<repo_name>NEPTUNE-GTR/Python-web-server<file_sep>/README.md
# Python-web-server
###
- A python web server implemented using TCP stream sockets
- The server will listen for connections that come to a specific host and port number.
- This web server supports GET and POST methods, the sending of cookies, and the execution of server side scripts (including CGI scripts).
- This server has some error handling capabilities but they are limited.
<file_sep>/testServer.py
#!/usr/bin/env python
import subprocess, sys, os, time
from socket import * # get socket constructor and constants
class Server:
#------------------------------------------------------------------------------------------------#
def __init__(self):
self.myHost = gethostname()
self.myPort = 15001
self.addr = (self.myHost, self.myPort)
self.directory = 'public_html'
#------------------------------------------------------------------------------------------------#
def startServer(self):
self.sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP/IP socket object
try:
self.sockobj.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.sockobj.bind(self.addr)
print("Server initalizaed on: %s, and port: %d") %(self.myHost, self.myPort)
except error as err:
print ("socket creation giving error: %s") %(err)
sys.exit(1)
self.waitForConnections()
#------------------------------------------------------------------------------------------------#
def generateHeaders(self, code, type):
header = ''
if (code == 200):
header = 'HTTP/1.1 200 OK\n'
elif(code == 404):
header = 'HTTP/1.1 404 Not Found\n'
if (type == 'html' or type == 'cgi'):
header += 'Content-Type: text/html\n\n'
elif (type == 'css'):
header += "HTTP/1.1 200 OK\nContent-Type: text/css\n\n"
return header
#------------------------------------------------------------------------------------------------#
def waitForConnections(self):
self.sockobj.listen(10)
while True:
print ("Listening for new connection")
responseContent = ''
responseHeaders = ''
connection, address = self.sockobj.accept()
#connection.settimeout(45)
print('Server connected by', address[0])
data = connection.recv(4096)
if not data: break
string = bytes.decode(data)
requestMethod = string.split(' ')[0]
print("METHOD IS: {m}".format(m=requestMethod))
print("REQUEST BODY IS:\n**************************\n {b}".format(b=string))
print("**************************")
print("REQUEST PAGE IS:\n**************************\n {b}".format(b=string.split(' ')[1]))
print("**************************")
#///////////////////////////////////HANDLING GET COMMANDS\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#
if requestMethod == 'GET':
print("Serving http GET request")
fileRequested = string.split(' ')[1]
fileRequested = fileRequested.split('?')
string = ''
if (len(fileRequested) > 1): string = fileRequested[1]
fileRequested = fileRequested[0]
if(fileRequested == '/'): fileRequested = 'index.html'
print ("Serving web page: {b}".format(b=fileRequested))
fileRequested = fileRequested.strip('/')
try:
fileHander = open(fileRequested,'rb')
responseContent = fileHander.read() # read file content
fileHander.close()
if (fileRequested.endswith(".html")): responseHeaders = self.generateHeaders(200, 'html')
elif (fileRequested.endswith(".css")): responseHeaders = self.generateHeaders(200, 'css')
elif (fileRequested.endswith(".cgi")):
responseHeaders = self.generateHeaders(200, 'cgi')
responseContent = ''
if(len(string) > 1): os.environ['QUERY_STRING'] = string
proc = subprocess.Popen(fileRequested, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out = proc.communicate(input = None)
responseContent = out[0]
if(len(responseContent.split('Content-type: text/html\n')[0]) > 0):
cookie = responseContent.split('Content-type: text/html\n')[0]
cookie = cookie.split(':')[1]
os.environ['HTTP_COOKIE'] = cookie
responseContent = responseContent.split('Content-type: text/html\n')[1]
except Exception as e: #in case file was not found, generate 404 page
print ("Warning, file not found. Serving response code 404\n", e)
responseHeaders = self.generateHeaders( 404, 'html')
responseContent = b"""
<html>
<body>
<img style="display:block;" width="100%" height="100%" src="https://tincan.co.uk/sites/default/files/styles/banner_image_tincan/public/images/Blog-404-01.png?itok=G8jyKL7k" />
</body>
</html>"""
serverResponse = str(responseHeaders) + str(responseContent)
connection.send(serverResponse)
#///////////////////////////////////HANDLING POST COMMANDS\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#
elif requestMethod == 'POST':
print("Serving http POST request")
fileRequested = string.split(' ')[1]
string = string.split('\n')
#if there is a cookie
if (string[-1].find('&') != -1):
string = string[-1]
part1 = string.split('&')[0]
part1 = part1.split('=')[1]
part2 = string.split('&')[1]
part2 = part2.split('=')[1]
cookie = part1 + '=' + part2
os.environ['HTTP_COOKIE'] = cookie
if(fileRequested == '/'): fileRequested = 'index.html'
print ("Serving web page: {b}".format(b=fileRequested))
fileRequested = fileRequested.strip('/')
try:
fileHander = open(fileRequested,'rb')
responseContent = fileHander.read() # read file content
fileHander.close()
if (fileRequested.endswith(".html")): responseHeaders = self.generateHeaders(200, 'html')
elif (fileRequested.endswith(".css")): responseHeaders = self.generateHeaders(200, 'css')
elif (fileRequested.endswith(".cgi")):
responseHeaders = self.generateHeaders(200, 'cgi')
if (string[-1].find('&') != -1):
#Sending the query string to stdin of cgi
out = subprocess.Popen(fileRequested, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate(input = string[-1])
else:
#else no query string to send
out = subprocess.Popen(fileRequested, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate(input = None)
responseContent = out[0]
responseContent = responseContent.split('Content-type: text/html\n')[1]
except Exception as e: #in case file was not found, generate 404 page
print ("Warning, file not found. Serving response code 404\n", e)
responseHeaders = self.generateHeaders( 404, 'html')
responseContent = b"""
<html>
<body>
<img style="display:block;" width="100%" height="100%" src="https://tincan.co.uk/sites/default/files/styles/banner_image_tincan/public/images/Blog-404-01.png?itok=G8jyKL7k" />
</body>
</html>"""
serverResponse = str(responseHeaders) + str(responseContent)
connection.send(serverResponse)
else:
responseHeaders = self.generateHeaders( 404, 'html')
responseContent = b"""
<html>
<body>
<p>unsupported HTTP method</p>
</body>
</html>"""
print("Unsupported HTTP request method:", requestMethod)
serverResponse = str(responseHeaders) + str(responseContent)
connection.send(serverResponse)
connection.close()
#------------------------------------------------------------------------------------------------#
#---------------------------------End of server class--------------------------------------------#
print ("*****Starting HTTP/1.1 web server*****")
serv = Server()
serv.startServer()
|
afa14f8f3b619ffa5e4d16cf572ca317d550f081
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
NEPTUNE-GTR/Python-web-server
|
0b29b216fa98f6cbe763346bf4821349071e7e55
|
86967d37d2e81ca4d753842afb4458de708506b9
|
refs/heads/master
|
<file_sep>import styled from "styled-components";
export const Container = styled.div`
width: 100vw;
.hide {
display: none;
}
`;
export const Content = styled.section`
display: flex;
flex-direction: column;
width: 100%;
color: #ffe;
`;
export const MateriasContainer = styled.div`
width: 100%;
display: flex;
padding: 20px;
`;
export const MateriaWrapper = styled.div`
max-width: 1200px;
padding: 20px;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
align-items: center;
`;
export const MateriaBox = styled.div`
margin: 0 20px;
padding: 5px;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
width: 510px;
img {
width: 510px;
height: 337px;
}
h3 {
font-weight: bold;
margin: 15px 0;
}
p {
}
`;
export const EbookContainer = styled.div`
width: 100%;
display: flex;
padding: 20px;
background: var(--color-secondary-orange-1);
`;
export const EbookWrapper = styled.div`
max-width: 1200px;
width: 100%;
padding: 20px;
margin: 0 auto;
display: flex;
flex-direction: column;
flex-wrap: wrap;
justify-content: space-around;
align-items: center;
`;
export const EbookImage = styled.div`
flex-basis: 50%;
max-width: 400px;
padding: 20px;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
align-items: center;
align-self: flex-start;
img {
width: 240px;
margin-top: -150px;
}
`;
export const EbookActionArea = styled.div`
max-width: 400px;
flex-basis: 50%;
padding: 20px;
flex-direction: column;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
align-items: center;
color: #fff;
h3 {
font-size: 20px;
margin-bottom: 15px;
}
a {
display: flex;
text-decoration: none !important;
justify-content: center;
align-items: center;
width: 181px;
height: 41px;
background: #fff;
color: #3c3c3c !important;
}
a:visited {
color: inherit;
text-decoration: none;
}
`;
export const SubscriptionContainer = styled.div`
width: 100%;
max-width: 1050px;
background: var(--color-primary-blue-1);
`;
export const LeadContainer = styled.div`
width: 100%;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
`;
export const LeadForm = styled.form`
margin-top: 30px;
max-width: 1200px;
height: 145px;
width: 100%;
padding: 20px;
margin: 0 auto;
display: flex;
justify-content: space-around;
align-items: center;
background: var(--color-primary-blue-1);
strong {
color: #fff;
font-weight: bold;
font-size: 22px;
line-height: 26px;
}
p {
color: #fff;
font-size: 16px;
line-height: 19px;
}
input.nome {
width: 220px;
height: 40px;
padding-left: 22px;
}
input.email {
width: 340px;
height: 40px;
padding-left: 22px;
}
button {
background: var(--color-secondary-orange-1);
width: 160px;
height: 41px;
border: none;
color: #fff;
}
`;
// post (refatorar isso se der tempo)
export const PostContainer = styled.div`
max-width: 1200px;
width: 100%;
padding: 20px;
margin: 0 auto;
display: flex;
flex-direction: column;
flex-wrap: wrap;
justify-content: center;
align-items: center;
h1 {
color: #4d4d4d;
margin-bottom: 30px;
}
p {
font-family: "Open Sans";
font-size: 16px;
line-height: 22px;
text-align: justify;
}
`;
export const JumbotronContainer = styled.div`
color: #fff;
padding: 20px;
height: 240px;
width: 100%;
background: var(--color-primary-blue-2);
margin: 0 auto;
display: flex;
flex-direction: column;
flex-wrap: wrap;
justify-content: center;
align-items: center;
line-height: 26px;
margin-bottom: 30px;
h1 {
font-style: normal;
font-weight: normal;
margin: 30px;
}
h3 {
font-style: normal;
font-weight: normal;
}
`;
export const BannerContainer = styled.div`
width: 100%;
display: flex;
padding: 20px;
`;
export const BannerWrapper = styled.div`
max-width: 1200px;
width: 100%;
padding: 20px;
margin: 0 auto;
display: flex;
flex-direction: column;
flex-wrap: wrap;
justify-content: space-around;
align-items: center;
`;
export const EbookContent = styled.div`
max-width: 1200px;
width: 100%;
padding: 20px;
margin: 0 auto;
display: flex;
align-items: flex-end;
flex-wrap: wrap-reverse;
`;
export const EbookDescription = styled.div`
width: 510px;
height: 600px;
padding: 10px;
display: flex;
flex-direction: column;
img {
width: 100%;
}
h3 {
font-weight: bold;
margin: 15px 0;
}
p {
margin: 15px 0;
}
`;
export const EbookForm = styled.div`
display: flex;
flex-direction: column;
max-width: 400px;
flex-wrap: initial;
height: 450px;
background: var(--color-primary-blue-1);
justify-content: space-between;
`;
export const EbookFormHeader = styled.div`
background: var(--color-secondary-orange-1);
color: #fff;
/*width: 500px;*/
text-align: center;
padding: 20px;
p {
margin: 15px 0;
}
`;
export const EbookFormBody = styled.div`
display: flex;
height: 500px;
/*width: 510px;*/
flex-direction: column;
justify-content: flex-start;
align-items: center;
padding: 20px;
color: #fff;
flex-shrink: 1;
input {
width: 100%;
margin: 10px 0;
height: 40px;
padding-left: 22px;
flex-shrink: 1;
}
button {
background: var(--color-secondary-orange-1);
width: 100%;
height: 41px;
border: none;
color: #fff;
margin: 10px 0;
flex-shrink: 1;
}
p {
}
`;
<file_sep>import firebase from "firebase/app";
import "firebase/database";
import "firebase/storage";
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "blog-fcam.firebaseapp.com",
databaseURL: "https://blog-fcam.firebaseio.com",
projectId: "blog-fcam",
storageBucket: "blog-fcam.appspot.com",
messagingSenderId: "301059358640",
appId: "1:301059358640:web:5a72db5bd7eb6ab2"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export const database = firebase.database();
export const storage = firebase.storage();
<file_sep>import React from "react";
// import { Container } from './styles';
const Auth = () => <div>Login</div>;
export default Auth;
<file_sep>export const b2cDomain = [
"gmail.com"
,"yahoo.com"
,"hotmail.com"
,"aol.com"
,"hotmail.co.uk"
,"hotmail.fr"
,"msn.com"
,"yahoo.fr"
,"wanadoo.fr"
,"orange.fr"
,"comcast.net"
,"yahoo.co.uk"
,"yahoo.com.br"
,"yahoo.co.in"
,"live.com"
,"rediffmail.com"
,"free.fr"
,"gmx.de"
,"web.de"
,"yandex.ru"
,"ymail.com"
,"libero.it"
,"outlook.com"
,"uol.com.br"
,"bol.com.br"
,"mail.ru"
,"cox.net"
,"hotmail.it"
,"sbcglobal.net"
,"sfr.fr"
,"live.fr"
,"verizon.net"
,"live.co.uk"
,"googlemail.com"
,"yahoo.es"
,"ig.com.br"
,"live.nl"
,"bigpond.com"
,"terra.com.br"
,"yahoo.it"
,"neuf.fr"
,"yahoo.de"
,"alice.it"
,"rocketmail.com"
,"att.net"
,"laposte.net"
,"facebook.com"
,"bellsouth.net"
,"yahoo.in"
,"hotmail.es"
,"charter.net"
,"yahoo.ca"
,"yahoo.com.au"
,"rambler.ru"
,"hotmail.de"
,"tiscali.it"
,"shaw.ca"
,"yahoo.co.jp"
,"sky.com"
,"earthlink.net"
,"optonline.net"
,"freenet.de"
,"t-online.de"
,"aliceadsl.fr"
,"virgilio.it"
,"home.nl"
,"qq.com"
,"telenet.be"
,"me.com"
,"yahoo.com.ar"
,"tiscali.co.uk"
,"yahoo.com.mx"
,"voila.fr"
,"gmx.net"
,"mail.com"
,"planet.nl"
,"tin.it"
,"live.it"
,"ntlworld.com"
,"arcor.de"
,"yahoo.co.id"
,"frontiernet.net"
,"hetnet.nl"
,"live.com.au"
,"yahoo.com.sg"
,"zonnet.nl"
,"club-internet.fr"
,"juno.com"
,"optusnet.com.au"
,"blueyonder.co.uk"
,"bluewin.ch"
,"skynet.be"
,"sympatico.ca"
,"windstream.net"
,"mac.com"
,"centurytel.net"
,"chello.nl"
,"live.ca"
,"aim.com"
,"bigpond.net.au"
]<file_sep>import styled from "styled-components";
export const Container = styled.div`
width: 100%;
height: 450px;
display: flex;
justify-content: center;
align-items: center;
position: relative;
`;
export const DestaqueTextWrapper = styled.div`
width: 420px;
height: 337px;
background: url("https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/hand-holding-white-light-bulb-with-crumpled-paper-balls-gray-background_23-2147873532.png?alt=media&token=9d8e9560-<KEY>25-549f4b5a<PASSWORD>");
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
`;
export const DestaqueImageWrapper = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
padding: 10px;
font-size: 20px;
width: 420px;
color: #fff;
height: 212px;
background: var(--color-primary-blue-1);
position: relative;
left: 50px;
`;
<file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "96f74be528327ecbfffade0aabb86635",
"url": "/index.html"
},
{
"revision": "cbaaa505b736572231d3",
"url": "/static/js/2.fb11a511.chunk.js"
},
{
"revision": "deedfa26ba58e7cf2719",
"url": "/static/js/main.2362b5e7.chunk.js"
},
{
"revision": "42ac5946195a7306e2a5",
"url": "/static/js/runtime~main.a8a9905a.js"
}
]);<file_sep>import styled from "styled-components";
export const HeaderBlog = styled.div`
/*Menu*/
background: var(--color-secondary-orange-1);
.menu {
height: 60px;
max-width: 1050px;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
}
.menu a {
color: white;
}
.menu-logo a {
font-weight: bold;
text-decoration: none;
}
.menu-nav {
height: 60px;
display: flex;
}
.menu-nav ul {
display: flex;
flex-wrap: wrap;
list-style: none;
}
.menu-nav a {
font-size: 1.25em;
display: block;
padding: 10px;
text-decoration: none;
}
.menu-nav a:hover {
text-decoration: underline;
text-decoration-color: #fff;
}
`;
export const HeaderContainer = styled.div`
width: 100%;
height: 100%;
max-width: 1440px;
display: flex;
align-items: center;
/* justify-content: space-around; */
`;
export const SubscriptionContainer = styled.div`
background: var(--color-primary-blue-1);
`;
export const HeaderLogo = styled.div`
background: var(--color-primary-blue-0);
/* border: 1px solid #000000;
display: flex;
justify-content: center;
font-size: 28px;
align-items: center;
width: 122px;
height: 56px;
color: #000000; */
`;
<file_sep>import React, { Component, Fragment } from "react";
import Helmet from "react-helmet";
import { database } from "../../config/firebase";
import { Container, PostContainer, LeadContainer, LeadForm } from "./styles";
import { b2cDomain } from "../../consts/b2c_array";
import Header from "../../components/Header";
export default class Post extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
nome: "",
loading: false,
posts: [],
post: "",
teste: "",
slug: this.props.match.params.slug
};
}
async componentWillMount() {
this.state.posts = await JSON.parse(
localStorage.getItem("@Okrnapratica:posts")
);
this.state.post = await this.getPostRequest();
console.log(this.state.post);
}
async getPostRequest() {
this.state.posts = await this.state.posts.filter(Boolean);
let res = await this.state.posts.filter(it =>
new RegExp(this.state.slug || "", "i").test(it.slug)
);
console.log(res, "res[0]");
this.state.post = res[0];
return res[0];
}
async findMyIp() {
const ip = await fetch("http://httpbin.org/ip");
const dataIp = await ip.json();
return dataIp.origin.split(",")[0];
}
handleInputChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = async e => {
e.preventDefault();
let { email, nome, ip, tipo, data_hora } = this.state; //
const address = email.split("@").pop();
ip = await this.findMyIp();
tipo = b2cDomain.some(d => d === address) ? "b2c" : "b2b";
data_hora = `${new Date()
.toISOString()
.slice(0, 10)} ${new Date().toLocaleTimeString()}`;
const id = database.ref().push().key;
const leads = {};
leads["leads/" + id] = {
email: email,
nome: nome,
ip: ip,
tipo: tipo,
data_hora: data_hora
};
database.ref().update(leads);
alert("Email cadastrado");
};
render() {
const { email, nome } = this.state;
console.log(this.state, "post render");
const { post } = this.state;
console.log(post);
return (
<Fragment>
<Helmet>
<title>Sobre - React Router com Helmet</title>
<meta name="description" content={post.meta_descript} />
<meta name="keywords" content={post.meta_kw} />
</Helmet>
<Header />
<Container>
<PostContainer>
<h1>{post.Titulo}</h1>
<p>{post.texto}</p>
{/* <p>{this.state.post.Titulo}</p>
<p>{this.state.post.texto}</p> */}
</PostContainer>
<LeadContainer>
<LeadForm onSubmit={this.handleSubmit} type="post">
<div>
<strong>Entre para a lista!</strong>
<p>
Receba conteúdos exclusivos e<br /> com prioridade.
</p>
</div>
<input
className="nome"
name="nome"
id="nome"
placeholder="Qual o seu nome? "
type="text"
value={nome}
onChange={this.handleInputChange}
/>
<input
name="email"
className="email"
id="email"
type="text"
value={email}
placeholder="Qual o seu melhor e-mail?"
onChange={this.handleInputChange}
/>
<button type="submit">Cadastrar</button>
</LeadForm>
</LeadContainer>
</Container>
</Fragment>
);
}
}
<file_sep>import React from "react";
import { Link } from "react-router-dom";
import logo from "../../img/logo_okr.png";
import { HeaderBlog, HeaderLogo } from "./styles";
const Header = () => (
<HeaderBlog>
<div className="menu">
<div className="menu-logo">
<Link to="/">
<HeaderLogo>
<img src={logo} alt="logo okr na prática" />
</HeaderLogo>
</Link>
</div>
<nav className="menu-nav">
<ul>
<li>
<Link to="/materias">Matérias</Link>
</li>
<li>
<Link to="/ebook">E-book</Link>
</li>
</ul>
</nav>
</div>
</HeaderBlog>
);
export default Header;
<file_sep>import React, { Component, Fragment } from "react";
import DownloadLink from "react-download-link";
import { database } from "../../config/firebase";
import { Link } from "react-router-dom";
import {
Container,
LeadForm,
MateriasContainer,
MateriaBox,
MateriaWrapper,
LeadContainer,
EbookContainer,
EbookWrapper,
EbookImage,
EbookActionArea
} from "./styles";
import { b2cDomain } from "../../consts/b2c_array";
import Header from "../../components/Header";
import Destaque from "../../components/Destaque";
import Materia from "../../components/Materia";
class Main extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
nome: "",
ip: "",
tipo: "",
posts: [],
data_hora: ""
};
console.log(props, "");
}
handleInputChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
componentDidMount = async () => {
const posts = await database.ref("posts");
posts.on("value", async snapshot => {
let p = await snapshot.val();
this.setState({
posts: p
});
this.getPosts();
});
};
getPosts = async () => {
await localStorage.setItem(
"@Okrnapratica:posts",
JSON.stringify([...this.state.posts])
);
console.log(this.state);
};
async findMyIp() {
const ip = await fetch("http://httpbin.org/ip");
const dataIp = await ip.json();
return dataIp.origin.split(",")[0];
}
handleSubmit = async e => {
e.preventDefault();
let { email, nome, ip, tipo, data_hora } = this.state; //
const address = email.split("@").pop();
ip = await this.findMyIp();
tipo = b2cDomain.some(d => d === address) ? "b2c" : "b2b";
data_hora = `${new Date()
.toISOString()
.slice(0, 10)} ${new Date().toLocaleTimeString()}`;
const id = database.ref().push().key;
const leads = {};
leads["leads/" + id] = {
email: email,
nome: nome,
ip: ip,
tipo: tipo,
data_hora: data_hora
};
database.ref().update(leads);
alert("Email cadastrado");
};
render() {
const { email, nome } = this.state; //, ip, tipo, data_hora
return (
<Fragment>
<Header />
<Container>
<Destaque />
<MateriasContainer>
<MateriaWrapper>
<MateriaBox>
<img
src="https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/connected-circle.png?alt=media&token=<PASSWORD>"
alt=""
/>
<h3>8 Benefícios de OKR</h3>
<p>
<Link to="/post/blog/okr-beneficios">
A metodologia possui vários benefícios na implementação e na
execução dentro da empresa, bem como flexibilidade, modelo
não-tradicional e não-sistemático.{" "}
</Link>
</p>
</MateriaBox>
<MateriaBox>
<img
src="https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/photo-1522881451255-f59ad836fdfb%20(1).png?alt=media&token=<PASSWORD>"
alt=""
/>
<h3> OKR na prática</h3>
<p>
<Link to="/post/blog/okr-beneficios">
Lorem ipsum dolor sit, amet consectetur adipisicing elit.
Ipsam rem enim natus nihil illum est, hic similique quos
quia excepturi consequuntur veritatis doloribus asperiores
cum, alias a non sunt sequi.
</Link>
</p>
</MateriaBox>
</MateriaWrapper>
</MateriasContainer>
<EbookContainer>
<EbookWrapper>
<EbookActionArea>
<h3>Baixe nosso Ebook agora!</h3>
<DownloadLink
filename="gs://blog-fcam.appspot.com/eBook OKR.pdf"
exportFile={() => "My cached data"}
>
Baixar
</DownloadLink>
</EbookActionArea>
<EbookImage>
<img
src="https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/eBook%20OKR.png?alt=media&token=<PASSWORD>"
alt=""
/>
</EbookImage>
</EbookWrapper>
</EbookContainer>
<MateriasContainer>
<MateriaWrapper>
<MateriaBox>
<img
src="https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/photo-1535231540604-72e8fbaf8cdb.png?alt=media&token=<PASSWORD>"
alt=""
/>
<h3>Ciclos para execução do OKR</h3>
<p>
<Link to="/post/blog/okr-ciclos-de-execucao">
Lorem ipsum dolor sit, amet consectetur adipisicing elit.
Ipsam rem enim natus nihil illum est, hic similique quos
quia excepturi consequuntur veritatis doloribus asperiores
cum, alias a non sunt sequi.
</Link>
</p>
</MateriaBox>
<MateriaBox>
<img
src="https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/error-404-note-is-written-white-sticker-that-hangs-with-clothespin-rope_76080-189.png?alt=media&token=<PASSWORD>"
alt=""
/>
<h3>Erros comuns no OKR </h3>
<p>
<Link to="/post/blog/okr-erros-comuns">
A gente sabe que criar estratégias para uma empresa não é
uma tarefa fácil Muitos gestores e suas equipes não têm
alcançado o potencial máximo desta metodologia Para
conseguir extrair o máximo desta ferramenta selecionamos os
erros mais comuns durante a estruturação do OKR que você
deve evitar!
</Link>
</p>
</MateriaBox>
</MateriaWrapper>
</MateriasContainer>
<LeadContainer>
<LeadForm onSubmit={this.handleSubmit} type="post">
<div>
<strong>Entre para a lista!</strong>
<p>
Receba conteúdos exclusivos e<br /> com prioridade.
</p>
</div>
<input
className="nome"
name="nome"
id="nome"
placeholder="Qual o seu nome? "
type="text"
value={nome}
onChange={this.handleInputChange}
/>
<input
name="email"
className="email"
id="email"
type="text"
value={email}
placeholder="Qual o seu melhor e-mail?"
onChange={this.handleInputChange}
/>
<button type="submit">Cadastrar</button>
</LeadForm>
</LeadContainer>
</Container>
</Fragment>
);
}
}
export default Main;
<file_sep>import React from "react";
import { Container, DestaqueImageWrapper, DestaqueTextWrapper } from "./styles";
const Destaque = () => (
<Container>
<DestaqueImageWrapper>
<h1>O que é OKR</h1>
<p>
<a href="/post/blog/o-que-e-okr">
Conheça o novo modelo de gestão criado pelo Google que ajuda à
alavancar os resultados da sua empresa e tornar sua equipe mais eficaz
</a>
</p>
</DestaqueImageWrapper>
<DestaqueTextWrapper />
</Container>
);
export default Destaque;
<file_sep>import { createGlobalStyle } from "styled-components";
const Colors = createGlobalStyle`
:root {
--color-primary-blue-0: #00a7b0;
--color-primary-blue-1: #009BA3;
--color-primary-blue-2: #005257;
--color-secondary-blue-0: #09649C;
--color-secondary-blue-1: #085B8E;
--color-secondary-blue-2: #074B75;
--color-secondary-rust-0: #BA3C13;
--color-secondary-rust-1: #AD3811;
--color-secondary-rust-2: #6E240B;
--color-secondary-orange-0: #FF794D;
--color-secondary-orange-1: #FA6432;
--color-secondary-orange-2: #C75028;
--color-primary-gray-0: #F9FAFC ;
--color-primary-gray-1: #EFF2F7;
--color-primary-gray-2: #E5E9F2;
--color-secondary-gray-0: #777382;
--color-secondary-gray-1: #63606C;
--color-secondary-gray-2: #4E4E56;
}
`;
export default Colors;
<file_sep>import React, { Component, Fragment } from "react";
import Helmet from "react-helmet";
import { database } from "../../config/firebase";
import ReactHtmlParser from "react-html-parser";
import {
Container,
PostContainer,
LeadContainer,
LeadForm,
SpinnerContainer
} from "./styles";
import Header from "../../components/Header";
import Loading from "../../components/Loading";
export default class CicloPost extends Component {
render() {
return (
<div>
{this.state.isLoading ? (
<Fragment>
<Header />
<SpinnerContainer>
<Loading />
</SpinnerContainer>
</Fragment>
) : (
<Fragment>
<Helmet>
<title>Sobre - React Router com Helmet</title>
<meta name="description" content={this.state.meta_descript} />
<meta name="keywords" content={this.state.meta_kw} />
</Helmet>
<Header />
<Container>
<PostContainer>
<PostContainer>
<h1>{this.state.post.Titulo}</h1>
<h3>{this.state.post.subtitulo}</h3>
<p>
<img src={this.state.post.imagem} alt="" />
</p>
<p>{ReactHtmlParser(this.state.post.texto)}</p>
</PostContainer>
</PostContainer>
</Container>
</Fragment>
)}
</div>
);
}
}
<file_sep>import React, { Fragment, Component } from "react";
import { toast } from "react-toastify";
import { b2cDomain } from "../../consts/b2c_array";
import { database, storage } from "../../config/firebase";
import ValidationContract from "../../validators/fluent-validator";
import {
Container,
JumbotronContainer,
EbookContent,
EbookDescription,
EbookForm,
EbookFormHeader,
EbookFormBody
} from "./styles";
import Header from "../../components/Header";
class Ebook extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
nome: "",
ip: "",
tipo: "",
posts: [],
data_hora: ""
};
console.log(props, "");
}
async getPostRequest() {
this.state.posts = await this.state.posts.filter(Boolean);
let res = await this.state.posts.filter(it =>
new RegExp(this.state.slug || "", "i").test(it.slug)
);
console.log(res, "res[0]");
this.state.post = res[0];
return res[0];
}
async findMyIp() {
debugger;
const ipRequest = await fetch("https://api.ipify.org/?format=json").then(
response => response.json()
);
return ipRequest.ip;
}
// Start file download.
handleSubmit = async e => {
e.preventDefault();
let { email, nome, ip, tipo, data_hora } = this.state;
let contract = new ValidationContract();
contract.hasMinLen(nome, 3, "Erro ao cadastrar nome");
contract.isEmail(email, 3, "O email não está no formato correto");
if (!contract.isValid()) {
toast.error("Ops... falha ao cadastrar contato", {
position: toast.POSITION.TOP_RIGHT
});
return false;
}
try {
//
const address = email.split("@").pop();
ip = await this.findMyIp();
tipo = b2cDomain.some(d => d === address) ? "b2c" : "b2b";
data_hora = `${new Date()
.toISOString()
.slice(0, 10)} ${new Date().toLocaleTimeString()}`;
const id = database.ref().push().key;
const leads = {};
leads["leads/" + id] = {
email: email,
nome: nome,
ip: ip,
tipo: tipo,
data_hora: data_hora
};
toast.success("Contato cadastrado !", {
position: toast.POSITION.TOP_RIGHT
});
database.ref().update(leads);
var ebookRef = storage.ref("eBook OKR.pdf");
const linkEbook = await ebookRef.getDownloadURL().then(url => url);
this.download(linkEbook, "book");
} catch (error) {
console.log(error);
}
};
download(dataUrl, filename) {
// Construct the 'a' element
var link = document.createElement("a");
link.download = filename;
link.target = "_blank";
link.href = dataUrl;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
handleInputChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
render() {
const { email, nome } = this.state;
return (
<Fragment>
<Header />
<Container>
<JumbotronContainer>
<h1>O Guia Definitivo do OKR </h1>
<h3>
Tudo o que você precisa saber para utilizar esse metodologia para
alcançar seus resultados{" "}
</h3>
</JumbotronContainer>
<EbookContent>
<EbookDescription>
<img
src="https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/eBook%20OKR.png?alt=media&token=<PASSWORD>"
alt=""
/>
<h3>
Descubra como a Google, Amazon, LinkedIn e Spotify tornaram-se
autoridade com a metodologia OKR
</h3>
<p>
Aprenda a importância da flexibilidade e rapidez da gestão
eficiente e os indicadores chave para a prática da metodologia
OKR.
</p>
<h3>
Conheça os benefícios e proteja-se contra os erros comuns na
implementação
</h3>
<p>
Veja neste eBook verá quais são as recomendações e objetivos
para você conseguir ter uma gestão sólida e eficiente e
estratégica com foco nos resultados. Também contará com: -
Tópicos abordados de forma mais dinâmica e direta - Cases
práticos - E muito mais!
</p>
</EbookDescription>
<EbookForm>
<EbookFormHeader>
<h3>
Faça o <strong>download grátis</strong> aqui!
</h3>
<p>Basta preencher o formulário abaixo</p>
</EbookFormHeader>
<EbookFormBody>
<form onSubmit={this.handleSubmit} type="post">
<input
className="nome"
name="nome"
id="nome"
required
placeholder="Qual o seu nome? "
type="text"
value={nome}
onChange={this.handleInputChange}
/>
<input
name="email"
required
className="email"
id="email"
type="text"
value={email}
placeholder="Qual o seu melhor e-mail?"
onChange={this.handleInputChange}
/>
<button type="submit">Cadastrar</button>
</form>
<p>
Ao realizar o download você também está autorizando a OKR na
prática a enviar conteúdos sobre a metodologia de seu
interesse. Respeitamos a sua privacidade e não fazemos spam,
confira nossa política.
</p>
</EbookFormBody>
</EbookForm>
</EbookContent>
</Container>
</Fragment>
);
}
}
export default Ebook;
<file_sep>import React, { Component, Fragment } from "react";
import Helmet from "react-helmet";
import Button from "react-bootstrap/Button";
import { database } from "../../config/firebase";
import ReactHtmlParser from "react-html-parser";
import {
Container,
PostContainer,
LeadContainer,
LeadForm,
SpinnerContainer
} from "./styles";
import { b2cDomain } from "../../consts/b2c_array";
import Header from "../../components/Header";
import Loading from "../../components/Loading";
export default class Post extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
nome: "",
isLoading: true,
posts: [],
post: "",
teste: "",
slug: this.props.match.params.slug
};
}
async componentDidMount() {
const posts = await database.ref("posts");
posts.on("value", async snapshot => {
let p = await snapshot.val();
this.setState({
posts: p
});
const teste = await this.getPostRequest();
this.setState({
post: teste,
isLoading: false
});
});
}
async getPostRequest() {
this.state.posts = await this.state.posts.filter(Boolean);
let res = await this.state.posts.filter(it =>
new RegExp(this.state.slug || "", "i").test(it.slug)
);
this.state.post = res[0];
this.state.isLoading = true;
return res[0];
}
async findMyIp() {
const ip = await fetch("http://httpbin.org/ip");
const dataIp = await ip.json();
return dataIp.origin.split(",")[0];
}
handleInputChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = async e => {
e.preventDefault();
let { email, nome, ip, tipo, data_hora } = this.state; //
const address = email.split("@").pop();
ip = await this.findMyIp();
tipo = b2cDomain.some(d => d === address) ? "b2c" : "b2b";
data_hora = `${new Date()
.toISOString()
.slice(0, 10)} ${new Date().toLocaleTimeString()}`;
const id = database.ref().push().key;
const leads = {};
leads["leads/" + id] = {
email: email,
nome: nome,
ip: ip,
tipo: tipo,
data_hora: data_hora
};
database.ref().update(leads);
alert("Email cadastrado");
};
render() {
const { email, nome } = this.state;
return (
<div>
{this.state.isLoading ? (
<Fragment>
<Header />
<SpinnerContainer>
<Loading />
</SpinnerContainer>
</Fragment>
) : (
<Fragment>
<Helmet>
<title>Sobre - React Router com Helmet</title>
<meta name="description" content={this.state.meta_descript} />
<meta name="keywords" content={this.state.meta_kw} />
</Helmet>
<Header />
<Container>
<PostContainer>
<PostContainer>
<h1>{this.state.post.Titulo}</h1>
<h3>{this.state.post.subtitulo}</h3>
<p>
<img src={this.state.post.imagem} alt="" />
</p>
<p>{ReactHtmlParser(this.state.post.texto)}</p>
</PostContainer>
</PostContainer>
</Container>
</Fragment>
)}
</div>
);
}
}
<file_sep>import styled from "styled-components";
export const HeaderDate = styled.p`
font-style: normal;
font-weight: normal;
font-size: 12px;
line-height: 16px;
`
export const TitleBlog = styled.p`
font-family: Roboto;
font-style: normal;
font-weight: normal;
font-size: 26px;
line-height: 30px;
`
export const SubTitleBlog= styled.p`
font-family: Open Sans;
font-style: normal;
font-weight: normal;
font-size: 18px;
line-height: 25px;
color: #C4C4C4;
`
export const Container = styled.div`
width: 100%;
height: 60px;
display: flex;
background: #E5E5E5;
flex-direction: column;
padding-left: 194px;
`;
<file_sep>import React, { Component, Fragment } from "react";
import { database, storage } from "../../config/firebase";
import { toast } from "react-toastify";
import ValidationContract from "../../validators/fluent-validator";
import { Link } from "react-router-dom";
import {
Container,
LeadForm,
MateriasContainer,
MateriaBox,
MateriaWrapper,
LeadContainer,
EbookContainer,
EbookWrapper,
EbookImage,
EbookActionArea
} from "./styles";
import { b2cDomain } from "../../consts/b2c_array";
import Header from "../../components/Header";
import Destaque from "../../components/Destaque";
class Main extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
nome: "",
ip: "",
tipo: "",
posts: [],
data_hora: ""
};
console.log(props, "");
}
handleInputChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
componentDidMount = async () => {
const posts = await database.ref("posts");
posts.on("value", async snapshot => {
let p = await snapshot.val();
this.setState({
posts: p
});
this.getPosts();
});
};
getPosts = async () => {
await localStorage.setItem(
"@Okrnapratica:posts",
JSON.stringify([...this.state.posts])
);
console.log(this.state);
};
async findMyIp() {
const ipRequest = await fetch("https://api.ipify.org/?format=json").then(
response => response.json()
);
return ipRequest.ip;
}
handleSubmit = async e => {
e.preventDefault();
let { email, nome, ip, tipo, data_hora } = this.state;
let contract = new ValidationContract();
contract.hasMinLen(nome, 3, "Erro ao cadastrar nome");
contract.isEmail(email, 3, "O email não está no formato correto");
if (!contract.isValid()) {
toast.error("Ops... falha ao cadastrar contato", {
position: toast.POSITION.TOP_RIGHT
});
return false;
}
try {
//
const address = email.split("@").pop();
ip = await this.findMyIp();
tipo = b2cDomain.some(d => d === address) ? "b2c" : "b2b";
data_hora = `${new Date()
.toISOString()
.slice(0, 10)} ${new Date().toLocaleTimeString()}`;
const id = database.ref().push().key;
const leads = {};
leads["leads/" + id] = {
email: email,
nome: nome,
ip: ip,
tipo: tipo,
data_hora: data_hora
};
toast.success("Contato cadastrado !", {
position: toast.POSITION.TOP_RIGHT
});
database.ref().update(leads);
var ebookRef = storage.ref("eBook OKR.pdf");
const linkEbook = await ebookRef.getDownloadURL().then(url => url);
this.download(linkEbook, "book");
} catch (error) {
console.log(error);
}
};
render() {
const { email, nome } = this.state; //, ip, tipo, data_hora
return (
<Fragment>
<Header />
<Container>
<Destaque />
<MateriasContainer>
<MateriaWrapper>
<MateriaBox>
<img
src="https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/connected-circle.png?alt=media&token=<PASSWORD>"
alt=""
/>
<h3>8 Benefícios de OKR</h3>
<p>
<Link to="/materias/okr-beneficios">
A metodologia possui vários benefícios na implementação e na
execução dentro da empresa, bem como flexibilidade, modelo
não-tradicional e não-sistemático.{" "}
</Link>
</p>
<small>18/06/2018</small>
</MateriaBox>
<MateriaBox>
<img
src="https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/photo-1522881451255-f59ad836fdfb%20(1).png?alt=media&token=<PASSWORD>"
alt=""
/>
<h3> OKR na prática</h3>
<p>
<Link to="/materias/okr-beneficios">
A busca por ferramentas e metodologias para uma gestão
eficiente pode trazer uma lista imensa de opções disponíveis
no mercado. Mas, para tornar a produtividade da equipe
eficaz e alavancar o negócio, é fundamental ter na manga um
modelo de gestão para ser aplicado com facilidade.
</Link>
</p>
<small>18/06/2018</small>
</MateriaBox>
</MateriaWrapper>
</MateriasContainer>
<EbookContainer>
<EbookWrapper>
<EbookActionArea>
<h3>Baixe nosso Ebook agora!</h3>
<Link to="/">baixar</Link>
</EbookActionArea>
<EbookImage>
<img
src="https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/eBook%20OKR.png?alt=media&token=<PASSWORD>"
alt=""
/>
</EbookImage>
</EbookWrapper>
</EbookContainer>
<MateriasContainer>
<MateriaWrapper>
<MateriaBox>
<img
src="https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/photo-1535231540604-72e8fbaf8cdb.png?alt=media&token=<PASSWORD>"
alt=""
/>
<h3>Ciclos para execução do OKR</h3>
<p>
<Link to="/materias/okr-ciclos-de-execucao">
Sabemos que o OKR é uma metodologia muito legal, mas também
sabemos que não é algo tão simples de colocar ela para
funcionar, portanto queremos aqui mostrar de uma forma bem
simples.
</Link>
</p>
<small>18/06/2018</small>
</MateriaBox>
<MateriaBox>
<img
src="https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/error-404-note-is-written-white-sticker-that-hangs-with-clothespin-rope_76080-189.png?alt=media&token=<PASSWORD>"
alt=""
/>
<h3>Erros comuns no OKR </h3>
<p>
<Link to="/materias/okr-erros-comuns">
A gente sabe que criar estratégias para uma empresa não é
uma tarefa fácil Muitos gestores e suas equipes não têm
alcançado o potencial máximo desta metodologia Para
conseguir extrair o máximo desta ferramenta selecionamos os
erros mais comuns durante a estruturação do OKR que você
deve evitar!
</Link>
</p>
<small>18/06/2018</small>
</MateriaBox>
</MateriaWrapper>
</MateriasContainer>
<LeadContainer>
<LeadForm onSubmit={this.handleSubmit} type="post">
<div>
<strong>Entre para a lista!</strong>
<p>
Receba conteúdos exclusivos e<br /> com prioridade.
</p>
</div>
<input
className="nome"
name="nome"
id="nome"
placeholder="Qual o seu nome? "
type="text"
value={nome}
onChange={this.handleInputChange}
/>
<input
name="email"
className="email"
id="email"
type="text"
value={email}
placeholder="Qual o seu melhor e-mail?"
onChange={this.handleInputChange}
/>
<button type="submit">Cadastrar</button>
</LeadForm>
</LeadContainer>
<MateriasContainer>
<MateriaWrapper>
<MateriaBox>
<img
src="https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/photo-1535231540604-72e8fbaf8cdb.png?alt=media&token=<PASSWORD>"
alt=""
/>
<h3>Ciclos para execução do OKR</h3>
<p>
<Link to="/materias/okr-ciclos-de-execucao">
Sabemos que o OKR é uma metodologia muito legal, mas também
sabemos que não é algo tão simples de colocar ela para
funcionar, portanto queremos aqui mostrar de uma forma bem
simples.
</Link>
</p>
<small>18/06/2018</small>
</MateriaBox>
<MateriaBox>
<img
src="https://firebasestorage.googleapis.com/v0/b/blog-fcam.appspot.com/o/error-404-note-is-written-white-sticker-that-hangs-with-clothespin-rope_76080-189.png?alt=media&token=<PASSWORD>"
alt=""
/>
<h3>Erros comuns no OKR </h3>
<p>
<Link to="/materias/okr-erros-comuns">
A gente sabe que criar estratégias para uma empresa não é
uma tarefa fácil Muitos gestores e suas equipes não têm
alcançado o potencial máximo desta metodologia Para
conseguir extrair o máximo desta ferramenta selecionamos os
erros mais comuns durante a estruturação do OKR que você
deve evitar!
</Link>
</p>
<small>18/06/2018</small>
</MateriaBox>
</MateriaWrapper>
</MateriasContainer>
</Container>
</Fragment>
);
}
}
export default Main;
|
186f23a417112a34004176ce56b25f1e64283bbe
|
[
"JavaScript"
] | 17 |
JavaScript
|
EduardoGFreitas/blog-fcam
|
d739599952595db01b4efb1b5934903989583d7e
|
76620872a2cb38d99ecec5a10c0f03bfeb3e5e08
|
refs/heads/master
|
<repo_name>AppleCEO/algorithm-baekjoon<file_sep>/10871.c
#include <stdio.h>
int main(){
int N, X, i, count=0;
scanf("%d %d", &N, &X);
int num[N];
int result[N];
for(i=0; i<N; i++){
scanf("%d ", &num[i]);
if(num[i]<X){
result[count] = num[i];
count++;
}
}
for(i=0; i<count; i++){
printf("%d ", result[i]);
}
return 0;
}
<file_sep>/README.md
# algorithm
algorithm ps
Online Judge :
https://www.acmicpc.net/
<file_sep>/11721.c
#include <stdio.h>
int main(){
int i, j, sum=0;
char ch;
char input[100]={0};
scanf("%s", input);
for(i=0; i<10; i++){
for(j=0; j<10; j++){
ch = input[j+i*10];
<<<<<<< HEAD
if(!(('a'<=ch && ch<='z') || ('A'<=ch && ch<='Z'))){
return 0;
}
printf("%c", ch);
}
=======
if(('a'<=ch && ch<='z') || ('A'<=ch && ch<='Z')){
printf("%c", ch);
} else {
return 0;
}
}
>>>>>>> c15c7eb0f122243f286858986422b9ed73131841
printf("\n");
}
return 0;
}
<<<<<<< HEAD
=======
>>>>>>> c15c7eb0f122243f286858986422b9ed73131841
<file_sep>/11720.c
#include <stdio.h>
<<<<<<< HEAD
int main(){
int i, N, sum=0;
scanf("%d", &N);
char input[N];
scanf("%s", input);
for(i=0; i<N; i++){
sum += (int)input[i]-48;
}
printf("%d", sum);
=======
int main(){
int i, N, sum=0;
scanf("%d", &N);
char input[N];
scanf("%s", input);
for(i=0; i<N; i++){
sum += input[i]-'0';
}
printf("%d", sum);
>>>>>>> c15c7eb0f122243f286858986422b9ed73131841
return 0;
}
<file_sep>/11718.cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> s;
string str;
while (getline(cin, str))
s.push_back(str);
vector<string>::iterator it;
for (it = s.begin(); it < s.end(); it++)
cout << *it << "\n";
return 0;
}
<file_sep>/1924.c
#include <stdio.h>
int main(){
int month, day, week;
scanf("%d %d", &month, &day);
switch(month){
case 2:
day += 31;
break;
case 3:
day += 59;
break;
case 4:
day += 90;
break;
case 5:
day += 120;
break;
case 6:
day += 151;
break;
case 7:
day += 181;
break;
case 8:
day += 212;
break;
case 9:
day += 243;
break;
case 10:
day += 273;
break;
case 11:
day += 304;
break;
case 12:
day += 334;
break;
}
week = day%7;
switch(week){
case 0:
printf("SUN");
break;
case 1:
printf("MON");
break;
case 2:
printf("TUE");
break;
case 3:
printf("WED");
break;
case 4:
printf("THU");
break;
case 5:
printf("FRI");
break;
case 6:
printf("SAT");
break;
}
return 0;
}
<file_sep>/algorithm/algorithm/main.swift
//
// main.swift
// algorithm
//
// Created by <NAME> on 5/24/19.
// Copyright © 2019 길준호. All rights reserved.
//
import Foundation
enum InputError: Error {
case isNotInt
}
func main() throws {
let input:String = readLine() ?? ""
let inputs = input.split(separator: " ")
guard let A = Int(inputs[0]), let B = Int(inputs[1]) else {
throw InputError.isNotInt
}
print(A-B)
}
try main()
<file_sep>/11718.c
#include <stdio.h>
int main(){
int i, j, sum=0;
char input[100][100] = {0};
char ch;
for(i=0; i<100; i++){
scanf("%s", input[i]);
ch = input[i][0];
if(!(('a'<=ch && ch<='z') || ('A'<=ch && ch<='Z'))){
break;
}
}
for(i=0; i<100; i++){
for(j=0; j<100; j++){
ch = input[i][j];
if(('a'<=ch && ch<='z') || ('A'<=ch && ch<='Z')){
printf("%c", ch);
} else {
break;
}
}
printf("\n");
}
return 0;
}
|
d8a25a20039bfc7da3cbdbeb1fc62027768df68f
|
[
"Markdown",
"C",
"C++",
"Swift"
] | 8 |
C
|
AppleCEO/algorithm-baekjoon
|
14dd3b49164a16a316c4e66476c1f9364c374fd5
|
9e9a1a2d03ad7d8fae38558a6ca681997cf2a49e
|
refs/heads/master
|
<repo_name>Ahmed-M-Rizk/AppEngine-JaxRS-Angular5-Demo<file_sep>/Rest/src/main/java/com/demos/models/Secret.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 com.demos.models;
/**
*
* @author GS
*/
public class Secret {
public String name = "";
public String secretName = "";
public Secret() {
}
public Secret(String name, String sec) {
this.name = name;
this.secretName = sec;
}
}
<file_sep>/Rest/src/main/java/com/demos/SecretsService.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 com.demos;
import com.demos.models.Secret;
import java.util.HashMap;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
*
* @author GS
*/
@Path("secrets")
public class SecretsService {
private static HashMap<String, Secret> secrets;
static {
secrets = new HashMap<>();
secrets.put("mouaz", new Secret("Mouaz", "notification.push()"));
secrets.put("rana", new Secret("Rana", "your bad dreams (they will make us do unit test in the pilot)"));
secrets.put("gamal", new Secret("Gamal", "You should chack your MI logs"));
secrets.put("amira", new Secret("Amira", "Yarab tezakry"));
}
@GET
@Path("/{name}")
@Produces(MediaType.APPLICATION_JSON)
public Secret getSeret(@PathParam("name")String name) {
if (secrets.containsKey(name.toLowerCase())) {
return secrets.get(name.toLowerCase());
}
return new Secret();
}
}
<file_sep>/README.md
# AppEngine-JaxRS-Angular5-Demo<file_sep>/Angular/src/app/services/app.service.ts.service.ts
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http'
@Injectable()
export class SecertService{
constructor(private _httpCLient:HttpClient) {}
public getSecret(secrectOwner:string){
return this._httpCLient.get('/rest/secrets/'+secrectOwner);
}
}
<file_sep>/Angular/src/app/app.component.ts
import {Component, Inject, OnInit} from '@angular/core';
import {SecertService} from './services/app.service.ts.service'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [SecertService]
})
export class AppComponent {
constructor(private _service: SecertService) {}
private userName: string;
private secret: {name: string, secretName: string};
getSecret() {
this._service.getSecret(this.userName).subscribe(
(data: {name: string, secretName: string}) => {
this.secret = data;
},
error => {
console.error(error);
});
}
}
|
88f957a0c75d3ed5003d1796f10b7334a6fe6474
|
[
"Markdown",
"Java",
"TypeScript"
] | 5 |
Java
|
Ahmed-M-Rizk/AppEngine-JaxRS-Angular5-Demo
|
11dcbc5eff83afdad0fa83934787465bf5840d7c
|
a2b7238d6201aed30200572b0e6e2d12ff49f614
|
refs/heads/master
|
<file_sep><?php
/**
* Unit tests for RandomProvider class
*/
use nicmart\Random\Provider\Provider;
use nicmart\Random\Provider\Collection;
class CollectionTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->mock1 = $this->getMock('\nicmart\Random\Provider\Provider');
$this->mock1->expects($this->any())
->method('get')
->will($this->returnValue('mock1'))
;
$this->mock2 = $this->getMock('\nicmart\Random\Provider\Provider');
$this->mock2->expects($this->any())
->method('get')
->will($this->returnValue('mock2'))
;
$this->collection = new Collection;
$this->collection
->register('a', $this->mock1)
->register('b', $this->mock2)
;
}
/**
* @expectedException InvalidArgumentException
*/
public function testRegisterAndGetProvider()
{
$this->assertEquals($this->mock1, $this->collection->provider('a'));
$this->assertEquals($this->mock2, $this->collection->provider('b'));
//This must throw an exception
$this->collection->provider('c');
}
public function testValue()
{
$collection = $this->collection;
$this->assertEquals('mock1', $collection->value('a'));
$this->assertEquals('mock2', $collection->value('b'));
}
public function testValueAndCachingProviderResults()
{
$collection = $this->collection;
$mock1 = $this->getMock('\nicmart\Random\Provider\Provider');
$mock1->expects($this->once())
->method('get')
->will($this->returnValue('aaa'))
;
$mock2 = $this->getMock('\nicmart\Random\Provider\Provider');
$mock2->expects($this->exactly(2))
->method('get')
->will($this->returnValue('bbb'))
;
$collection->register('cached', $mock1, true);
$collection->register('nocached', $mock2, false);
//Call both values twice
$collection->value('cached');
$collection->value('cached');
$collection->value('nocached');
$collection->value('nocached');
}
}
<file_sep><?php
/**
* Unit tests for PhpNumberGenerator class
*/
use nicmart\Random\Number\PhpNumberGenerator;
class PhpNumberGeneratorTest extends PHPUnit_Framework_TestCase
{
public function testRandBounds()
{
$generator = new PhpNumberGenerator;
$this->setExpectedException('OutOfRangeException');
$generator->rand(-1, 10);
$this->setExpectedException('OutOfRangeException');
$generator->rand(1, getrandmax()+1);
}
public function testRandRespectsGivenBoundsAndReturnsIntegers()
{
$generator = new PhpNumberGenerator;
$n = $generator->rand(1, 20);
$this->assertInternalType('int', $n);
$this->assertLessThanOrEqual(20, $n);
$this->assertGreaterThanOrEqual(1, $n);
}
public function testRandMax()
{
$generator = new PhpNumberGenerator;
$this->assertEquals(getrandmax(), $generator->randMax());
}
}
<file_sep><?php
namespace nicmart\Random\Provider;
/**
* Interface to retrieve a random Object
*/
interface Provider
{
/**
* @abstract
*
* @return mixed
*/
public function get();
}<file_sep><?php
/**
* Set up the class autoloader
*/
spl_autoload_register(function ($class) {
if (0 === strpos(ltrim($class, '/'), 'nicmart\Random')) {
if (file_exists($file = __DIR__.'/../source'.substr(str_replace('\\', '/', $class), strlen('nicmart\Random')).'.php')) {
require_once $file;
}
}
});<file_sep><?php
namespace nicmart\Random\Number;
/**
* Number Generator based on PHP's rand function
*/
class CyclicNumberGenerator implements NumberGenerator
{
/**
* @var array
*/
private $sequence;
/**
* @param array $sequence
*/
public function __construct(array $sequence = array())
{
$this->setSequence($sequence);
}
/**
* Returns the current integer in the sequence. If it is not between $min and $max
* an Exception is thrown
*
* @param int $min
* @param int $max
* @throws \OutOfRangeException
*
* @return int|mixed
*/
public function rand($min, $max)
{
$n = current($this->sequence);
if ($n < $min || $n > $max) {
throw new \OutOfRangeException(
"The generated number $n is not between $min and $max"
);
}
if (false === next($this->sequence))
reset($this->sequence);
return $n;
}
/**
* Returns the max integer supported by the generator
*
* @return int
*/
public function randMax()
{
return max($this->getSequence());
}
/**
* @param array $sequence
*
* @return CyclicNumberGenerator The current instance
*/
public function setSequence(array $sequence)
{
$this->sequence = $sequence;
}
/**
* @return array
*/
public function getSequence()
{
return $this->sequence;
}
}
<file_sep><?php
/**
* Unit tests for RandomProvider class
*/
use nicmart\Random\Provider\RandomProvider;
use nicmart\Random\Number\NumberGenerator;
use nicmart\Random\Number\PhpNumberGenerator;
use nicmart\Random\Number\CyclicNumberGenerator;
class RandomProviderTest extends PHPUnit_Framework_TestCase
{
public function testAddChoice()
{
$provider = new RandomProvider;
// A class of the standard library
$object = new SplStack();
$provider
->addChoice($object, 2)
->addChoice('b')
;
$strings = $provider->getChoices();
$this->assertEquals($object, $strings[0][0], 'Add string sets string correctly');
$this->assertEquals(2, $strings[0][1], 'Add string sets weight correctly');
$this->assertEquals('b', $strings[1][0], 'Add string sets string correctly');
$this->assertEquals(1, $strings[1][1], 'Add string sets default weight to 1');
}
public function testGetNumberGeneratorReturnsPhpNumberGeneratorAsDefault()
{
$provider = new RandomProvider;
$generator = $provider->getNumberGenerator();
$this->assertInstanceOf('\nicmart\Random\Number\PhpNumberGenerator', $generator);
}
public function testSetAndGetNumberGenerator()
{
$provider = new RandomProvider;
$provider->setNumberGenerator(new MockedNumberGenerator);
$generator = $provider->getNumberGenerator();
$this->assertInstanceOf('MockedNumberGenerator', $generator);
}
public function testGet()
{
$provider = new RandomProvider;
$provider->setNumberGenerator(new CyclicNumberGenerator(array(0, 1, 4)));
$weightedChoices = array(
array('miao', 1),
array('arrivederci', '1'),
array('buonasera', '2'),
);
$provider->addChoices($weightedChoices);
$this->assertEquals('miao', $provider->get());
$this->assertEquals('arrivederci', $provider->get());
$this->assertEquals('buonasera', $provider->get());
}
public function testGetChoices()
{
$provider = new RandomProvider;
$object = new SplStack();
$weightedChoices = array(
array($object, 1),
array('arrivederci', '1'),
array('buonasera', '2'),
);
$plainStrings = array_map(function($item){ return $item[0]; }, $weightedChoices);
$provider->addChoices($weightedChoices);
$this->assertEquals($weightedChoices, $provider->getChoices());
$this->assertEquals($plainStrings, $provider->getPlainChoices());
}
}
class MockedNumberGenerator implements NumberGenerator
{
/**
* Returns an integer between $min and $max
* @param int $min
* @param int $max
* @return mixed
*/
public function rand($min, $max)
{
return 1;
}
/**
* Returns the max integer supported by the generator
*
* @return int
*/
public function randMax()
{
return 4;
}
}
<file_sep><?php
namespace nicmart\Random\Number;
/**
* Number Generator based on PHP's rand function
*/
class PhpNumberGenerator implements NumberGenerator
{
/**
* Returns an integer between $min and $max
* @param int $min
* @param int $max
* @throws \OutOfRangeException
*
* @return int|mixed
*/
public function rand($min, $max)
{
if ($min < 0)
throw new \OutOfRangeException("Min argument must be greater or equal than 0. Was $min.");
$randmax = getrandmax();
if ($max > $randmax)
throw new \OutOfRangeException("Max argument must be smaller or equal than getrandmax ($randmax}. Was $max.");
return rand($min, $max);
}
/**
* Returns the max integer supported by the generator
*
* @return int
*/
public function randMax()
{
return getrandmax();
}
}
<file_sep><?php
namespace nicmart\Random\Provider;
use nicmart\Random\Provider\Provider;
use nicmart\Random\Number\NumberGenerator;
use nicmart\Random\Number\PhpNumberGenerator;
/**
* This class picks randomly an object from a fixed collection of objects
*/
class RandomProvider implements Provider
{
/**
* @var array
*/
private $choices;
/**
* @var NumberGenerator
*/
private $numberGenerator;
/**
* Get a random choice
*
* @return mixed
*/
public function get()
{
$totalWeight = $this->getWeightsSum();
$choices = $this->getChoices();
$randMax = $this->getNumberGenerator()->randMax();
$edge = 0;
$n = $this->getNumberGenerator()->rand(0, $randMax);
foreach ($choices as $choice) {
$edge = round( ($choice[1] * ($randMax + 1)) / $totalWeight) + $edge;
if($n < $edge)
return $choice[0];
}
return $choices[count($choices) - 1][0];
}
/**
* Add an array of strings. Each array item can be a plain string or an array with
* two elements, the string and the probabilistic weight for that string
*
* @param array $choicesAndWeights
*
* @return RandomProvider
*/
public function addChoices(array $choicesAndWeights)
{
foreach ($choicesAndWeights as $stringAndWeight) {
if (!is_array($stringAndWeight)) {
$stringAndWeight = array($stringAndWeight, 1);
}
list($choice, $weight) = $stringAndWeight;
$this->addChoice($choice, $weight);
}
return $this;
}
/**
* @param $choice The string to add
* @param int $weight The probabilistic weight of this string
*
* @return RandomProvider the current instance
*/
public function addChoice($choice, $weight = 1)
{
$this->choices[] = array($choice, $weight);
return $this;
}
/**
* Return the array of strings withought the probabilistic weights
*
* @return array The array of choices without weights
*/
public function getPlainChoices()
{
return array_map(function($item){
return $item[0];
}, $this->choices);
}
/**
* The array of the weighted choices
*
* @return array
*/
public function getChoices()
{
return $this->choices;
}
/**
* @param NumberGenerator $numberGenerator
*
* @return RandomProvider The current instance
*/
public function setNumberGenerator(NumberGenerator $numberGenerator)
{
$this->numberGenerator = $numberGenerator;
return $this;
}
/**
* @return NumberGenerator
*/
public function getNumberGenerator()
{
if (!isset($this->numberGenerator)) {
$this->numberGenerator = new PhpNumberGenerator;
}
return $this->numberGenerator;
}
/**
* Returns the sum of all choices weights
*
* @return int
*/
private function getWeightsSum()
{
$sum = 0;
foreach ($this->getChoices() as $choice) {
$sum += $choice[1];
}
return $sum;
}
}
<file_sep><?php
namespace nicmart\Random\Number;
/**
* NumberGenerator objects generate random integer numbers between a min and a max
*/
interface NumberGenerator
{
/**
* Returns an integer between $min and $max
* @abstract
* @param int $min
* @param int $max
* @return mixed
*/
public function rand($min, $max);
/**
* Returns the max integer supported by the generator
*
* @abstract
* @return int
*/
public function randMax();
}
<file_sep><?php
namespace nicmart\Random\Number;
use nicmart\Random\Number\NumberGenerator;
use nicmart\Random\Number\CyclicNumberGenerator;
/**
* A Decorator class built around another Generator that can record the
* returns value of that generator.
*/
class NumberGeneratorRecorder implements NumberGenerator
{
/**
* State constants
*/
const STATE_STOP = 0;
const STATE_RECORDING = 1;
const STATE_PLAYING = 2;
/**
* @var NumberGenerator
*/
private $recordedGenerator;
/**
* @var CyclicNumberGenerator
*/
private $playingGenerator;
/**
* This is a pointer to one of the previous generator, and the
* state determines which is pointed
* @var NumberGenerator
*/
private $currentGenerator;
/**
* @var array
*/
private $recording;
/**
* @var int the current recorder state
*/
private $state;
/**
* @param NumberGenerator $generator
*/
public function __construct(NumberGenerator $generator, CyclicNumberGenerator $cyclicGenerator = null)
{
if(!isset($cyclicGenerator))
{
$cyclicGenerator = new CyclicNumberGenerator();
}
$this->recordedGenerator = $this->currentGenerator = $generator;
$this->playingGenerator = $cyclicGenerator;
$this->state = static::STATE_RECORDING;
}
/**
* Returns an integer between $min and $max
*
* @param int $min
* @param int $max
* @return mixed
*/
public function rand($min, $max)
{
$n = $this->currentGenerator->rand($min, $max);
if($this->state === static::STATE_RECORDING)
{
$this->recording[] = $n;
}
return $n;
}
/**
* Returns the max integer supported by the generator
*
* @return int
*/
public function randMax()
{
return $this->recordedGenerator->randMax();
}
/**
* Put the recorder in playing state.
* The generator will cyclicly return the recorded numbers
*
* @return NumberGeneratorRecorder The current instance
*/
public function play()
{
$this->state = static::STATE_PLAYING;
$this->currentGenerator = $this->playingGenerator;
$this->playingGenerator->setSequence($this->getRecording());
return $this;
}
/**
* Put the recorder in recording state.
*
* @return NumberGeneratorRecorder The current instance
*/
public function record()
{
$this->state = static::STATE_RECORDING;
$this->currentGenerator = $this->recordedGenerator;
return $this;
}
/**
* Stop the recorder. The recorder will still return the numbers generated by the
* decorated generator, but it will not record that numbers.
*
* @return NumberGeneratorRecorder The current instance
*/
public function stop()
{
$this->state = static::STATE_STOP;
$this->currentGenerator = $this->recordedGenerator;
return $this;
}
/**
* Get the recorded sequence
*
* @return array
*/
public function getRecording()
{
return $this->recording;
}
/**
* @return NumberGenerator
*/
public function getRecordedGenerator()
{
return $this->recordedGenerator;
}
}
<file_sep><?php
/**
* Unit tests for NumberGeneratorRecorder class
*/
use nicmart\Random\Number\PhpNumberGenerator;
use nicmart\Random\Number\NumberGeneratorRecorder;
class NumberGeneratorRecorderTest extends PHPUnit_Framework_TestCase
{
public function testConstructorAndGetGenerator()
{
$generator = new PhpNumberGenerator;
$recorder = new NumberGeneratorRecorder($generator);
$this->assertEquals($generator, $recorder->getRecordedGenerator());
}
public function testRecordedNumbers()
{
$generator = new PhpNumberGenerator;
$recorder = new NumberGeneratorRecorder($generator);
for ($i = 1; $i <= 20; $i++) {
$numbers[] = $recorder->rand(1, 100);
}
$this->assertEquals($numbers, $recorder->getRecording());
}
public function testPlay()
{
$generator = new PhpNumberGenerator;
$recorder = new NumberGeneratorRecorder($generator);
for ($i = 1; $i <= 5; $i++) {
$numbers[] = $recorder->rand(1, 100);
}
$recorder->play();
for ($i = 1; $i <= 10; $i++) {
$this->assertEquals($numbers[(($i - 1) % 5)], $recorder->rand(1, 100));
}
}
public function testStop()
{
$generator = new PhpNumberGenerator;
$recorder = new NumberGeneratorRecorder($generator);
$n = $recorder->rand(1, 10);
$recorder->stop();
$recorder->rand(1, 10);
$this->assertEquals(array($n), $recorder->getRecording());
}
public function testRecord()
{
$generator = new PhpNumberGenerator;
$recorder = new NumberGeneratorRecorder($generator);
$n = $recorder->rand(1, 10);
$recorder->stop();
$recorder->record();
$m = $recorder->rand(1, 10);
$this->assertEquals(array($n, $m), $recorder->getRecording());
}
public function testRandMaxReturnsRecordedGeneratorMax()
{
$generator = new PhpNumberGenerator;
$recorder = new NumberGeneratorRecorder($generator);
$this->assertEquals($generator->randMax(), $recorder->randMax());
}
}
<file_sep>RandoXML
========
[](http://travis-ci.org/nicmart/RandoXML)
A PHP Library whose aim is to generate XML documents in a random way,
following probabilistic rules defined in a configuration file.
Note: this project is in early creation stage! There is nothing ready to use... But stay tuned!<file_sep><?php
namespace nicmart\Random\Provider;
/**
* A named collection of providers
*/
class Collection implements Provider
{
/**
* The array of providers
*
* @var array
*/
private $providers = array();
/**
* The array ov cached values returned by providers
*
* @var array
*/
private $cachedValues = array();
/**
*
* @return mixed
*/
public function get()
{
// TODO: Implement get() method.
}
/**
* @param string $name
* @param Provider $provider
* @param boolean $cached
*
* @return Collection The current instance
*/
public function register($name, Provider $provider, $cached = true)
{
$this->providers[$name] = array($provider, $cached);
return $this;
}
/**
* @param string $name
* @return Provider
* @throws \InvalidArgumentException
*/
public function provider($name)
{
if (!isset($this->providers[$name])) {
throw new \InvalidArgumentException("There is no provider registered with name '$name'");
}
return $this->providers[$name][0];
}
/**
* @param string $name
* @return mixed
* @throws \InvalidArgumentException
*/
public function value($name)
{
if (!isset($this->cachedValues[$name]) || !$this->isProviderCached($name)) {
$this->cachedValues[$name] = $this->provider($name)->get();
}
return $this->cachedValues[$name];
}
/**
* Is the provider cached?
*
* @param $name
* @return mixed
* @throws \InvalidArgumentException
*/
private function isProviderCached($name)
{
if (!isset($this->providers[$name])) {
throw new \InvalidArgumentException("There is no provider registered with name '$name'");
}
return $this->providers[$name][1];
}
}
<file_sep><?php
/**
* Unit tests for NumberGeneratorRecorder class
*/
use nicmart\Random\Number\CyclicNumberGenerator;
class CyclicNumberGeneratorTest extends PHPUnit_Framework_TestCase
{
public function testRand()
{
$generator = new CyclicNumberGenerator(array(4, 9, 13, 20, 18));
$this->assertEquals(4, $generator->rand(1,100));
$this->assertEquals(9, $generator->rand(1,100));
$this->assertEquals(13, $generator->rand(1,100));
$this->assertEquals(20, $generator->rand(1,100));
$this->assertEquals(18, $generator->rand(1,100));
$this->assertEquals(4, $generator->rand(1,100));
}
public function testRandBounds()
{
$generator = new CyclicNumberGenerator(array(4, 4));
$this->setExpectedException('OutOfRangeException');
$generator->rand(1, 3);
$this->setExpectedException('OutOfRangeException');
$generator->rand(5, 10);
}
public function testRandMaxReturnsSequenceMax()
{
$generator = new CyclicNumberGenerator(array(4, 76, 4));
$this->assertEquals(76, $generator->randMax());
}
}
|
5d490906ee7c1b43b27861ccc16ec11c6dfdfc45
|
[
"Markdown",
"PHP"
] | 14 |
PHP
|
nicmart/RandoXML
|
849107bd409f279095cc16c774e9bf7b594610ef
|
1b7be604e0cde4f0478b6bf5c417c6b2f17fe108
|
refs/heads/master
|
<file_sep>import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
import "./App.css";
import Card from "./Card";
import Info from "./Info";
import Scoreboard from "./Scoreboard";
import { positions } from "./constants";
import { comparePlayers, findSet, togglePresence } from "./helpers";
function App() {
const [socket, setSocket] = useState();
const [cards, setCards] = useState([]);
const [selectedCards, setSelectedCards] = useState([]);
const [players, setPlayers] = useState([]);
const [name, setName] = useState("");
const [startTime, setStartTime] = useState(Date.now());
const [highScores, setHighScores] = useState([]);
useEffect(() => {
const socket =
window.location.hostname === "localhost"
? socketIOClient("http://127.0.0.1:4000")
: socketIOClient();
setSocket(socket);
socket.on("refreshGame", (data) => {
setSelectedCards([]);
setCards(data.cards);
setPlayers(data.players.sort(comparePlayers));
if (data.startTime) {
setStartTime(Date.parse(data.startTime));
}
});
socket.on("refreshHighScores", (data) => {
console.log(data);
setHighScores(data.highScores);
});
socket.on("initialize", (data) => {
setName(data.name);
setHighScores(data.highScores);
});
return () => socket.disconnect();
}, []);
useEffect(() => {
window.addEventListener("keydown", handleKey);
return () => window.removeEventListener("keydown", handleKey);
}, [cards, selectedCards]);
function handleClick(card) {
let newSelectedCards = togglePresence(selectedCards, card);
if (newSelectedCards.length > 0) {
socket.emit("guess", newSelectedCards);
}
setSelectedCards(newSelectedCards);
}
function handleKey({ key }) {
if (cards[key - 1]) {
handleClick(cards[key - 1]);
}
}
async function solve() {
const solution = await findSet(cards);
setSelectedCards(solution);
setTimeout(() => socket.emit("guess", solution), 3000);
}
return (
<React.Fragment>
<Info solve={solve} startTime={startTime} highScores={highScores} />
<div id="table">
{cards.map((card, index) => {
if (card !== 0) {
return (
<Card
key={
card /* This makes React re-animate when card is replaced. */
}
value={card}
position={positions[index]}
selected={selectedCards.includes(card)}
handleClick={() => handleClick(card)}
/>
);
}
})}
</div>
<Scoreboard players={players} name={name} />
</React.Fragment>
);
}
export default App;
<file_sep>import React from "react";
function Scoreboard(props) {
return (
<div id="scoreboard">
<h1>Scoreboard</h1>
{props.players.map((player, index) => {
return (
<p
key={index}
style={{ fontWeight: player.name === props.name ? "bold" : "" }}
>
{player.name} <span style={{ float: "right" }}>{player.score}</span>
</p>
);
})}
</div>
);
}
export default Scoreboard;
<file_sep>// grid positions defined in css
const positions = ["one", "two", "three", "four", "five", "six", "seven"];
// color classes defined in css
const colors = ["red", "orange", "yellow", "green", "blue", "purple"];
export { positions, colors };
<file_sep>FROM node:14.4
COPY . /frontend
WORKDIR /frontend
RUN yarn install
<file_sep>const desserts = [
"Affogato",
"Apple Pie",
"Aztec Chocolate Ice Cream",
"Baked Alaska",
"Baklava",
"Banana Pudding",
"Bananas Foster",
"Bear Claw",
"Beignets",
"Black Sesame Ice Cream",
"Blondie",
"Blueberry Pie",
"Boston Cream Pie",
"Bread Pudding",
"Brown Sugar Cookie",
"Brownie",
"Bubble Tea",
"Bubur Cha Cha",
"Candied Apple",
"Cannoli",
"Carrot Cake",
"Cendol",
"Chocolate Babka",
"Chocolate Chip Cookie",
"Churro",
"Cider Donut",
"Cinnamon Roll",
"Cornbread",
"Cream Puff",
"Creme Brulee",
"Crepe",
"Cronut",
"Cruller",
"Dippin' Dots",
"Donut",
"Eclair",
"Egg Custard Tart",
"Flan",
"Fluffy Pancake",
"Frozn Yogurt",
"Funnel Cake",
"Gingerbread",
"Girl Scout Cookie",
"Gooey Butter Cake",
"Granita",
"Grass Jelly",
"Ice Cream Sandwich",
"Ice Kacang",
"Jell-O",
"Key Lime Pie",
"Lemon Bar",
"Macaron",
"Madeleines",
"Mango Sticky Rice",
"Marble Cake",
"Millefeuille",
"Mochi",
"Nanaimo Bar",
"New York Cheesecake",
"Pancake",
"Pandan Cake",
"Panna Cotta",
"Peach Cobbler",
"Pecan Pie",
"Pineapple Bun",
"Pineapple Upside Down Cake",
"Pumpkin Pie",
"Raspberry Crumble",
"Red Velvet Cake",
"Root Beer Float",
"S'more",
"Shortbread",
"Snickerdoodle",
"Sopapilla",
"Steamed Custard Buns",
"Sticky Bun",
"Strawberry Shortcake",
"Stroopwafel",
"Tang Yuen",
"Tapioca Pudding",
"Tiramisu",
"Tres Leches",
"Truffles",
"Waffle",
"Zucchini Bread",
];
module.exports = desserts;
<file_sep>import React from "react";
import { colors } from "./constants";
import { intToBinaryArray } from "./helpers";
function Card(props) {
const dotsPresent = intToBinaryArray(props.value, 6);
return (
<div
className={`card ${props.selected ? "selected" : ""}`}
style={{ gridArea: props.position }}
onClick={props.handleClick}
>
{" "}
{dotsPresent.map((dotPresent, index) => {
if (dotPresent) {
return <Dot key={index} color={colors[index]} />;
}
})}{" "}
</div>
);
}
function Dot(props) {
return <div className={`dot ${props.color}`}></div>;
}
export default Card;
<file_sep>FROM node:14.4
COPY . /backend
WORKDIR /backend
RUN yarn install
<file_sep>const mongoose = require("mongoose");
const desserts = require("./desserts");
const { Schema } = mongoose;
const userSchema = new Schema({
name: String,
score: Number,
});
const gameSchema = new Schema({
deck: [Number],
table: [Number],
players: [userSchema],
startTime: { type: Date, default: Date.now },
duration: Number,
});
const shuffle = (cards) => cards.sort(() => Math.random() - 0.5);
gameSchema.statics.createNewGame = function (players = []) {
const deck = shuffle([...Array(64).keys()].filter((c) => c !== 0));
const table = deck.splice(0, 7);
return this.create({ deck, table, players });
};
gameSchema.statics.findMostRecent = function () {
return this.findOne().sort("-startTime");
};
gameSchema.statics.getHighScores = async function () {
const games = await this.find({}).exec();
const highScores = games
.filter((g) => g.duration)
.map((g) => g.duration)
.sort((a, b) => a - b);
return highScores;
};
gameSchema.methods.updateGame = function (name, cardsToRemove) {
for (let i = 0; i < this.table.length; i++) {
if (cardsToRemove.includes(this.table[i])) {
const replacementCard = this.deck.length > 0 ? this.deck.shift() : 0;
this.table.splice(i, 1, replacementCard);
}
}
for (let i = 0; i < this.players.length; i++) {
if (this.players[i].name === name) {
this.players[i].score += cardsToRemove.length;
}
}
return this.save();
};
gameSchema.methods.isOver = function () {
return this.table.every((c) => c === 0);
};
gameSchema.methods.end = function (cb) {
this.duration = Date.now() - this.startTime;
this.save(cb);
};
gameSchema.methods.addPlayer = function () {
const name = desserts[Math.floor(Math.random() * desserts.length)];
this.players.push({ name: name, score: 0 });
this.save();
return name;
};
gameSchema.methods.removePlayer = function (name) {
for (let i = 0; i < this.players.length; i++) {
if (this.players[i].name === name) {
this.players[i].remove();
}
}
this.save();
};
const Game = mongoose.model("Game", gameSchema);
module.exports = { Game };
<file_sep>const comparePlayers = (a, b) => (a.name > b.name ? 1 : -1); // alphabetize players by name
const togglePresence = function (array, element) {
/* If array contains element, remove it, otherwise add it to the array. */
if (array.includes(element)) {
return array.filter((el) => el !== element);
} else {
return [...array, element];
}
};
const intToBinaryArray = (i, length) =>
i
.toString(2)
.padStart(length, "0")
.split("")
.map((s) => s === "1");
const isValidSet = (cards) =>
!cards.includes(0) && cards.reduce((acc, cur) => acc ^ cur) === 0;
const findSet = function (cards) {
for (let i = 1; i < 128; i++) {
const cardsPresent = intToBinaryArray(i, 7);
const guess = cards.filter((c, index) => cardsPresent[index]);
if (isValidSet(guess)) {
return guess;
}
}
};
export { comparePlayers, findSet, intToBinaryArray, togglePresence };
|
213d74b2ceef29e1f72f7d1a62fbd93622045ff8
|
[
"JavaScript",
"Dockerfile"
] | 9 |
JavaScript
|
evantey14/proset
|
28dd26265d38e90c80ee24328b85b25ed1c215c7
|
6c32c7e03e822637604cd6ac1e25093cdf2720d6
|
refs/heads/master
|
<repo_name>mingmxren/ehttpd<file_sep>/core/ehd_palloc.h
//
// Created by renmingxu on 12/21/17.
//
#ifndef UNTITLED_EHD_PALLOC_H
#define UNTITLED_EHD_PALLOC_H
#include <ehd_config.h>
#include <ehd_core.h>
/* 1024 * 1024 */
#define EHD_MAX_ALLOC_FROM_POOL 1048576
/* 16 * 1024 */
#define EHD_DEFAULT_POOL_SIZE 16384
typedef struct ehd_pool_large_s ehd_pool_large_t;
struct ehd_pool_large_s {
ehd_pool_large_t *next;
void *data;
};
struct ehd_pool_s {
char *last;
char *end;
ehd_pool_t *next;
ehd_pool_large_t *large;
};
ehd_pool_t *ehd_create_pool(size_t size);
ehd_pool_t *ehd_create_pool_default_size();
void ehd_destroy_pool(ehd_pool_t *pool);
void * ehd_palloc(ehd_pool_t * pool, size_t size);
void * ehd_pcalloc(ehd_pool_t * pool, size_t size);
#endif //UNTITLED_EHD_PALLOC_H
<file_sep>/core/ehttpd.h
//
// Created by renmingxu on 12/21/17.
//
#ifndef UNTITLED_EHTTPD_H
#define UNTITLED_EHTTPD_H
#define EHD_VERSION "ehttpd/0.0.1"
#endif //UNTITLED_EHTTPD_H
<file_sep>/core/ehd_string.c
//
// Created by renmingxu on 12/21/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
uint ehd_atoi(u_char *line, size_t n) {
uint value;
if (n == 0) {
return EHD_ERROR;
}
for (value = 0; n--;line++) {
if (*line < '0' || *line > '9') {
return EHD_ERROR;
}
value = value * 10 + (*line - '0');
}
if (value < 0) {
return EHD_ERROR;
}
return value;
}
u_char *ehd_cpystrn(u_char *dst, u_char *src, size_t n)
{
if (n == 0) {
return dst;
}
for (/* void */; --n; dst++, src++) {
*dst = *src;
if (*dst == '\0') {
return dst;
}
}
*dst = '\0';
return dst;
}
<file_sep>/core/ehd_connection.h
//
// Created by renmingxu on 12/21/17.
//
#ifndef EHTTPD_EHD_CONNECTION_H
#define EHTTPD_EHD_CONNECTION_H
#include <ehd_config.h>
#include <ehd_core.h>
struct ehd_connection_s {
/*
* ehd_http_request_t when process a http request
* or ehd_http_connection when keep alive
* */
void * data;
int fd;
ehd_event_t * event; /* we use only one ehd_event_t for epoll_impl */
/*
* event_impl.process will call c->read_handler(c)
* when EHD_READ_EVENT is avialable
* call c->write_handler(c)
* when EHD_WRITE_EVENT is avialable
* */
void (* read_handler)(ehd_connection_t *);
void (* write_handler)(ehd_connection_t *);
ehd_listening_t * listening;
ehd_pool_t * pool;
ehd_buf_t * buf;
ehd_sockaddr_t sockaddr;
socklen_t socklen;
};
struct ehd_listening_s {
int fd;
struct sockaddr * sockaddr;
socklen_t socklen;
size_t pool_size;
void (*handler) (ehd_connection_t *c);
int family;
int type;
int protocol;
int backlog;
};
int ehd_listening_init(ehd_cycle_t *cycle, ehd_conf_t * conf);
int ehd_open_listening_socket(ehd_cycle_t *cycle);
void ehd_close_connection(ehd_connection_t *c);
#endif //EHTTPD_EHD_CONNECTION_H
<file_sep>/core/ehd_palloc.c
//
// Created by renmingxu on 12/21/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
ehd_pool_t *ehd_create_pool(size_t size) {
ehd_pool_t *p;
/* malloc a block of memory to store pool struct and data */
if (!(p = malloc(size))) {
return NULL;
}
p->last = (char *)p + sizeof(ehd_pool_t);
p->end = (char *)p + size;
p->next = NULL;
p->large = NULL;
return p;
}
void ehd_destroy_pool(ehd_pool_t *pool) {
ehd_pool_t *p, *n;
ehd_pool_large_t *l;
for (l = pool->large; l; l = l->next) {
if (l->data) {
free(l->data);
}
}
for (p = pool, n = pool->next; /* void */; p = n, n = n->next) {
free(p);
if (n == NULL) {
break;
}
}
}
void *ehd_palloc(ehd_pool_t *pool, size_t size) {
char *m;
ehd_pool_t *p, *n;
ehd_pool_large_t *large, *last;
/* check if the size can be put in a pool */
if (size <= (size_t)EHD_MAX_ALLOC_FROM_POOL &&
size <= (size_t)(pool->end - (char *)pool) - sizeof(ehd_pool_t)) {
/* find a pool which has enough space and return it p->last */
for (p = pool, n = pool->next; /* void */; p = n, n = n->next) {
m = p->last;
if (size <= (size_t)(p->end - m)) {
p->last = m + size;
return m;
}
if (n == NULL) {
break;
}
}
/* allocate a new pool block */
if (!(n = ehd_create_pool((size_t)(p->end - (char *)p)))) {
return NULL;
}
p->next = n;
m = n->last;
n->last += size;
return m;
}
/* allocate a large block */
large = NULL;
last = NULL;
if (pool->large) {
for (last = pool->large; /* void */ ; last = last->next) {
if (last->data == NULL) {
large = last;
last = NULL;
break;
}
if (last->next == NULL) {
break;
}
}
}
if (large == NULL) {
if (!(large = ehd_palloc(pool, sizeof(ehd_pool_large_t)))) {
return NULL;
}
large->next = NULL;
}
if (!(m = malloc(size))) {
return NULL;
}
if (pool->large == NULL) {
pool->large = large;
} else if (last) {
last->next = large;
}
large->data = m;
return m;
}
void *ehd_pcalloc(ehd_pool_t * pool, size_t size) {
void *m;
if (!(m = ehd_palloc(pool,size))) {
return NULL;
}
memset(m,0,size);
return m;
}
ehd_pool_t * ehd_create_pool_default_size() {
return ehd_create_pool(EHD_DEFAULT_POOL_SIZE);
}
<file_sep>/core/ehd_string.h
//
// Created by renmingxu on 12/21/17.
//
#ifndef UNTITLED_EHD_STRING_H
#define UNTITLED_EHD_STRING_H
#include <ehd_config.h>
#include <ehd_core.h>
typedef struct ehd_str_s ehd_str_t;
struct ehd_str_s {
size_t len;
u_char* data;
};
#define ehd_string(str) { sizeof(str) - 1, (u_char*) str}
#define ehd_null_string {0, NULL}
uint ehd_atoi(u_char *line, size_t n);
u_char *ehd_cpystrn(u_char *dst, u_char *src, size_t n);
#endif //UNTITLED_EHD_STRING_H
<file_sep>/http/ehd_http.h
//
// Created by renmingxu on 1/2/18.
//
#ifndef EHTTPD_EHD_HTTP_H
#define EHTTPD_EHD_HTTP_H
#include <ehd_config.h>
#include <ehd_core.h>
#include <ehd_http_request.h>
#include <ehd_http_core.h>
typedef struct ehd_http_request_s ehd_http_request_t;
int ehd_http_init(ehd_cycle_t * cycle);
void ehd_http_init_connection(ehd_connection_t *c);
int ehd_http_parse_request_line(ehd_http_request_t * r, ehd_buf_t * buf);
int ehd_http_parse_complex_uri(ehd_http_request_t *r);
int ehd_http_parse_header_line(ehd_http_request_t *r, ehd_buf_t *b);
void ehd_http_keep_alive(ehd_http_request_t *r);
void ehd_http_close_request(ehd_http_request_t *r);
void ehd_http_close_connection(ehd_connection_t *c);
void ehd_http_handler(ehd_http_request_t * r);
void ehd_http_empty_handler(ehd_connection_t *c);
#endif //EHTTPD_EHD_HTTP_H
<file_sep>/event/ehd_epoll.c
//
// Created by renmingxu on 12/31/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
#include <ehd_epoll.h>
static int ehd_event_epoll_init(ehd_cycle_t * cycle){
size_t n;
int i;
if (ep == -1) {
ep = epoll_create(cycle->connection_num / 2);
if (ep == -1) {
return EHD_ERROR;
}
}
if (nevents < cycle->connection_num) {
if (event_list) {
free(event_list);
}
event_list = malloc(sizeof(struct epoll_event) * cycle->connection_num);
if (event_list == NULL) {
return EHD_ERROR;
}
}
nevents = cycle->connection_num;
ehd_event_funps = ehd_event_impl_epoll.funp;
return EHD_OK;
}
static int ehd_event_epoll_close(ehd_cycle_t * cyle) {
if (close(ep) == -1) {
return EHD_ERROR;
}
ep = -1;
free(event_list);
}
static int ehd_event_epoll_mod(ehd_event_t * ev, int event, uint flags) {
int op;
ehd_connection_t * c;
struct epoll_event ee;
c = ev->data;
op = EPOLL_CTL_MOD;
/*
if (ev->active) {
op = EPOLL_CTL_MOD;
} else {
op = EPOLL_CTL_ADD;
ev->active = 1;
}
*/
ee.events = event | flags;
ee.data.ptr = c;
ev->events = ee.events;
if (epoll_ctl(ep, op, c->fd, &ee) == -1) {
return EHD_ERROR;
}
return EHD_OK;
}
static int ehd_event_epoll_add(ehd_event_t * ev, int event, uint flags){
int op;
ehd_connection_t * c;
struct epoll_event ee;
c = ev->data;
if (ev->active) {
op = EPOLL_CTL_MOD;
} else {
op = EPOLL_CTL_ADD;
ev->active = 1;
}
ee.events = event | flags;
ee.data.ptr = c;
ev->events = ee.events;
if (epoll_ctl(ep, op, c->fd, &ee) == -1) {
perror("epoll_ctl(ehd_event_epoll_add)");
return EHD_ERROR;
}
return EHD_OK;
}
static int ehd_event_epoll_del(ehd_event_t * ev, int event, uint flags){
int op;
uint32_t events;
uint active;
ehd_connection_t * c;
struct epoll_event ee;
c = ev->data;
if (flags == EHD_CLOSE_EVENT) {
return EHD_OK;
}
op = EPOLL_CTL_DEL;
/*
if (ev->active) {
events = ev->events;
events &= event;
if (events == (EPOLLIN | EPOLLOUT)) {
op = EPOLL_CTL_MOD;
if (event == EPOLLIN)
events = EPOLLOUT;
else
events = EPOLLIN;
ee.events = events | flags;
ee.data.ptr = c;
ee.events = ee.events;
active = 1;
} else {
op = EPOLL_CTL_DEL;
ee.events = 0;
ee.data.ptr = NULL;
ev->events = 0;
active = 0;
}
} else {
op = EPOLL_CTL_DEL;
ee.events = 0;
ee.data.ptr = NULL;
ev->events = 0;
active = 0;
}
*/
if (epoll_ctl(ep, op, c->fd, NULL) == -1) {
return EHD_ERROR;
}
ev->active = active;
return EHD_OK;
}
int ehd_event_epoll_process(ehd_cycle_t *cycle) {
int events;
size_t n;
int i;
int err;
ehd_connection_t *c;
ehd_event_t *ev;
struct epoll_event *ee;
ehd_event_enable_accept(cycle);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-noreturn"
for( ; ; ) {
/*
* now epoll_wait timeout is -1 means block indefinitely
* because the timer has not been implemented yet
* */
events = epoll_wait(ep, event_list, nevents, -1);
if (events == 0) {
continue;
} else if (events == -1){
err = errno;
}
for(i = 0;i < events;i++) {
ee = &event_list[i];
c = ee->data.ptr;
ev = c->event;
if (c->fd == -1) {
continue;
}
if (ee->events & EPOLLOUT) {
ev->wready = 1;
if (ehd_threaded) {
} else {
c->write_handler(c);
}
}
if (ee->events & EPOLLIN) {
ev->rready = 1;
if (ehd_threaded) {
} else {
c->read_handler(c);
}
}
}
}
#pragma clang diagnostic pop
}
<file_sep>/http/ehd_http_request.c
//
// Created by renmiehdu on 12/21/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
#include <ehd_http.h>
static void ehd_http_init_request(ehd_connection_t * c);
static void ehd_http_process_request_line(ehd_connection_t *c) ;
static ssize_t ehd_http_read_request_header(ehd_http_request_t *r);
static void ehd_http_process_request_headers(ehd_connection_t *c);
static int ehd_http_process_request_header(ehd_http_request_t *r);
static void ehd_http_block_read(ehd_connection_t * c) ;
ehd_http_header_t ehd_http_headers_in[] = {
{ ehd_string("Host"), offsetof(ehd_http_headers_in_t, host) },
{ ehd_string("Connection"), offsetof(ehd_http_headers_in_t, connection) },
{ ehd_string("If-Modified-Since"),
offsetof(ehd_http_headers_in_t, if_modified_since) },
{ ehd_string("User-Agent"), offsetof(ehd_http_headers_in_t, user_agent) },
{ ehd_string("Referer"), offsetof(ehd_http_headers_in_t, referer) },
{ ehd_string("Content-Length"),
offsetof(ehd_http_headers_in_t, content_length) },
{ ehd_string("Range"), offsetof(ehd_http_headers_in_t, range) },
{ ehd_string("Authorization"),
offsetof(ehd_http_headers_in_t, authorization) },
{ ehd_string("Keep-Alive"), offsetof(ehd_http_headers_in_t, keep_alive) },
{ ehd_null_string, 0 }
};
void ehd_http_init_connection(ehd_connection_t *c) {
ehd_event_t *ev;
ev = c->event;
c->read_handler = ehd_http_init_request;
c->write_handler = ehd_http_empty_handler;
if (!ev->closed) {
ehd_http_init_request(c);
}
}
static void ehd_http_init_request(ehd_connection_t * c) {
ehd_event_t * ev;
ehd_http_connection_t * hc;
ehd_http_request_t * r;
ehd_pool_t * cpool, * rpool;
hc = c->data;
cpool = c->pool;
if (!hc) {
if (!(hc = ehd_pcalloc(cpool, sizeof(ehd_http_connection_t)))) {
ehd_http_close_connection(c);
return;
}
}
r = hc->request;
if (r) {
bzero(r,sizeof(ehd_http_request_t));
} else {
if (!(r = ehd_pcalloc(c->pool, sizeof(ehd_http_request_t)))) {
ehd_http_close_connection(c);
return;
}
hc->request = r;
}
r->http_state = EHD_HTTP_INITING_REQUEST_STATE;
c->data = r;
r->http_connection = hc;
r->conf = ehd_cycle->conf;
if (c->buf == NULL) {
c->buf = ehd_create_temp_buf(cpool, EHD_DEFAULT_BUF_SIZE);
if (c->buf == NULL) {
ehd_http_close_connection(c);
return;
}
}
if (r->header_in_buf == NULL) {
r->header_in_buf = c->buf;
}
if (!(r->pool = ehd_create_pool_default_size())) {
ehd_http_close_connection(c);
return;
}
rpool = r->pool;
if (ehd_list_init(&r->headers_out.headers, rpool, 20, sizeof(ehd_table_data_t)) == EHD_ERROR) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
r->connection = c;
r->headers_in.content_length_n = -1;
r->headers_out.content_length_n = -1;
r->headers_out.last_moddified_time = -1;
r->http_state = EHD_HTTP_READING_REQUEST_STATE;
c->read_handler = ehd_http_process_request_line;
c->read_handler(c);
}
void ehd_http_close_request(ehd_http_request_t *r) {
if (r->pool == NULL) {
return;
}
ehd_destroy_pool(r->pool);
}
static void ehd_http_process_request_line(ehd_connection_t *c) {
printf("process request line\n");
ehd_http_request_t * r;
ehd_event_t * ev;
r = c->data;
ev = c->event;
ssize_t n;
int i;
i = EHD_AGAIN;
for( ;; ) {
if (i == EHD_AGAIN) {
n = ehd_http_read_request_header(r);
printf("recv %ld\n", n);
if (n == EHD_AGAIN) {
return;
} else if (n == EHD_ERROR) {
/* handler error */
// ehd_http_close_request(r);
// ehd_http_close_connection(c);
return;
}
}
i = ehd_http_parse_request_line(r, r->header_in_buf);
if (i == EHD_OK) {
/*
* request line has been parsed successfully
* */
/* copy unparsed_uri */
r->unparsed_uri.len = r->uri_end - r->uri_start;
r->unparsed_uri.data = ehd_palloc(r->pool, r->unparsed_uri.len + 1);
if (r->unparsed_uri.data == NULL) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
ehd_cpystrn(r->unparsed_uri.data, r->uri_start,
r->unparsed_uri.len + 1);
/* copy URI */
if (r->args_start) {
r->uri.len = r->args_start - 1 - r->uri_start;
} else {
r->uri.len = r->uri_end - r->uri_start;
}
if (!(r->uri.data = ehd_palloc(r->pool, r->uri.len + 1))) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
if (r->complex_uri) {
i = ehd_http_parse_complex_uri(r);
if (i == EHD_HTTP_INTERNAL_SERVER_ERROR) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
if (i != EHD_OK) {
r->request_line.len = r->request_end - r->request_start;
r->request_line.data = r->request_start;
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
} else {
ehd_cpystrn(r->uri.data, r->uri_start, r->uri.len + 1);
}
r->request_line.len = r->request_end - r->request_start;
r->request_line.data = r->request_start;
r->request_line.data[r->request_line.len] = '\0';
if (r->method == 0) {
r->method_name.len = r->method_end - r->request_start + 1;
r->method_name.data = r->request_line.data;
}
if (r->uri_ext) {
/* copy URI extention */
if (r->args_start) {
r->exten.len = r->args_start - 1 - r->uri_ext;
} else {
r->exten.len = r->uri_end - r->uri_ext;
}
if (!(r->exten.data = ehd_palloc(r->pool, r->exten.len + 1))) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
ehd_cpystrn(r->exten.data, r->uri_ext, r->exten.len + 1);
}
r->request_line.len = r->request_end - r->request_start;
r->request_line.data = r->request_start;
r->request_line.data[r->request_line.len] = '\0';
if (r->method == 0) {
r->method_name.len = r->method_end - r->request_start + 1;
r->method_name.data = r->request_line.data;
}
if (r->uri_ext) {
/* copy URI extention */
if (r->args_start) {
r->exten.len = r->args_start - 1 - r->uri_ext;
} else {
r->exten.len = r->uri_end - r->uri_ext;
}
if (!(r->exten.data = ehd_palloc(r->pool, r->exten.len + 1))) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
ehd_cpystrn(r->exten.data, r->uri_ext, r->exten.len + 1);
}
if (ehd_list_init(&r->headers_in.headers, r->pool, 20,
sizeof(ehd_table_data_t)) == EHD_ERROR)
{
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
if (ehd_array_init(&r->headers_in.cookies, r->pool, 5,
sizeof(ehd_table_data_t *)) == EHD_ERROR)
{
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
c->read_handler = ehd_http_process_request_headers;
ehd_http_process_request_headers(c);
return;
} else if (i != EHD_AGAIN) {
/* error */
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
if (r->header_in_buf->pos == r->header_in_buf->end) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
}
}
static void ehd_http_process_request_headers(ehd_connection_t *c){
printf("process request headers\n");
int rc, i;
ssize_t n;
ehd_event_t *ev;
ehd_table_data_t *h,**cookie;
ehd_http_request_t * r;
ev = c->event;
r = c->data;
rc = EHD_AGAIN;
for(;;) {
if (rc == EHD_AGAIN) {
if (r->header_in_buf->pos == r->header_in_buf->end) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
n = ehd_http_read_request_header(r);
if (n == EHD_AGAIN) {
return;
} else if(n == EHD_ERROR) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
}
rc = ehd_http_parse_header_line(r, r->header_in_buf);
if (rc == EHD_OK) {
/* one header line of a request has been parsed successfully */
r->headers_n++;
if (!(h = ehd_list_push(&r->headers_in.headers))) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
h->key.len = r->header_name_end - r->header_name_start;
h->key.data = r->header_name_start;
h->key.data[h->key.len] = '\0';
h->value.len = r->header_end - r->header_start;
h->value.data = r->header_start;
h->value.data[h->value.len] = '\0';
if (h->key.len == sizeof("Cookie") - 1
&& strcasecmp((const char *) h->key.data, "Cookie") == 0)
{
if (!(cookie = ehd_array_push(&r->headers_in.cookies))) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
*cookie = h;
} else {
for (i = 0; ehd_http_headers_in[i].name.len != 0; i++) {
if (ehd_http_headers_in[i].name.len != h->key.len) {
continue;
}
if (strcasecmp((const char *) ehd_http_headers_in[i].name.data,
(const char *) h->key.data) == 0)
{
*((ehd_table_data_t **) ((char *) &r->headers_in
+ ehd_http_headers_in[i].offset)) = h;
break;
}
}
}
continue;
} else if (rc == EHD_HTTP_PARSE_HEADER_DONE) {
r->http_state = EHD_HTTP_PROCESS_REQUEST_STATE;
rc = ehd_http_process_request_header(r);
if (rc != EHD_OK) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
c->read_handler = ehd_http_block_read;
ehd_http_handler(r);
return;
} else if (rc != EHD_AGAIN) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
}
}
static int ehd_http_process_request_header(ehd_http_request_t *r) {
return EHD_OK;
}
static void ehd_http_block_read(ehd_connection_t * c) {
printf("ehd_http_block_read\n");
ehd_http_request_t * r;
if (ehd_del_event(c->event, EHD_READ_EVENT, 0) == EHD_ERROR) {
r = c->data;
ehd_http_close_request(r);
ehd_http_close_connection(c);
}
}
static ssize_t ehd_http_read_request_header(ehd_http_request_t *r) {
ssize_t n;
ehd_event_t *ev;
ev = r->connection->event;
n = r->header_in_buf->last - r->header_in_buf->pos;
if (n > 0) {
return n;
}
if (!ev->rready) {
return EHD_AGAIN;
}
n = ehd_recv(r->connection, r->header_in_buf->last, r->header_in_buf->end - r->header_in_buf->last);
if (n == EHD_AGAIN) {
return EHD_AGAIN;
}
if (n == 0 || n == EHD_ERROR) {
ehd_http_close_request(r);
ehd_http_close_connection(r->connection);
return EHD_ERROR;
}
r->header_in_buf->last += n;
return n;
}
void ehd_http_keep_alive(ehd_http_request_t *r) {
ehd_http_connection_t *hc;
ehd_connection_t * c;
ehd_buf_t * b;
hc = r->http_connection;
hc->request = NULL;
c = r->connection;
c->data = hc;
c->read_handler = ehd_http_init_request;
b = r->header_in_buf;
int i;
if (b->pos < b->last) {
for(i = 0;i < b->last - b->pos;i++) {
b->start[i] = b->pos[i];
}
b->pos = b->start;
b->last = b->start + i;
} else {
b->pos = b->start;
b->last = b->start;
}
ehd_http_close_request(r);
c->write_handler = ehd_http_empty_handler;
if (ehd_add_event(c->event,EHD_READ_EVENT,EPOLLET) == EHD_ERROR) {
ehd_http_close_connection(c);
}
}
<file_sep>/core/ehd_core.h
//
// Created by renmingxu on 12/21/17.
//
#ifndef UNTITLED_EHD_CORE_H
#define UNTITLED_EHD_CORE_H
#define EHD_OK 0
#define EHD_ERROR (-1)
#define EHD_AGAIN (-2)
#define LF (u_char) 10
#define CR (u_char) 13
#define CRLF "\x0d\x0a"
#define ehd_return_if_null(x,y,z) if (((x) = (y)) == NULL) return (z);
typedef struct ehd_pool_s ehd_pool_t;
typedef struct ehd_event_s ehd_event_t;
typedef struct ehd_cycle_s ehd_cycle_t;
typedef struct ehd_connection_s ehd_connection_t;
typedef struct ehd_listening_s ehd_listening_t;
typedef struct ehd_list_s ehd_list_t;
typedef struct ehd_conf_s ehd_conf_t;
typedef struct ehd_file_s ehd_file_t;
typedef void(*ehd_event_handler_fp)(ehd_event_t*ev);
#include <ehd_palloc.h>
#include <ehd_buf.h>
#include <ehd_string.h>
#include <ehd_file.h>
#include <ehd_list.h>
#include <ehd_array.h>
#include <ehd_conf.h>
#include <ehd_cycle.h>
#include <ehd_socket.h>
#include <ehd_event.h>
#include <ehd_connection.h>
#include <ehttpd.h>
#endif //UNTITLED_EHD_CORE_H
<file_sep>/core/ehd_file.c
//
// Created by renmingxu on 12/27/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
#include <sys/stat.h>
int ehd_file_open_r(ehd_file_t *file, ehd_str_t name) {
int fd;
if ((fd = open((char*)name.data, O_RDONLY)) == -1) {
return EHD_ERROR;
}
file->fd = fd;
file->name = name;
file->offset = 0;
file->sys_offset = 0;
file->size = 0;
}
int ehd_file_open_rs(ehd_file_t *file, ehd_str_t name) {
int fd;
struct stat s;
if ((fd = open((char*)name.data, O_RDONLY)) == -1) {
return EHD_ERROR;
}
if (stat((char*)name.data, &s) == -1) {
return EHD_ERROR;
}
file->size = s.st_size;
file->fd = fd;
file->name = name;
file->offset = 0;
file->sys_offset = 0;
}
<file_sep>/event/ehd_event_echo.c
//
// Created by renmingxu on 12/31/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
void ehd_event_echo_read(ehd_connection_t *c) {
ehd_pool_t * pool;
int fd;
ehd_buf_t *buf;
int err;
ssize_t n;
pool = c->pool;
fd = c->fd;
if (c->buf == NULL) {
buf = c->buf = ehd_create_temp_buf(pool, 4096);
} else {
buf = c->buf;
buf->pos = buf->start;
buf->last = buf->start;
bzero(buf->start, buf->end - buf->start);
}
for(;;) {
n = recv(fd, buf->last, buf->end - buf->last, 0);
if (n == -1) {
err = errno;
if (err == EAGAIN) {
break;
}
ehd_close_connection(c);
return;
} else if(n == 0) {
ehd_close_connection(c);
return;
} else {
buf->last += n;
if (buf->last == buf->end) {
break;
}
}
}
// printf("recv len %ld from %d\n", buf->last - buf->pos, fd);
ehd_mod_event(c->event, EHD_WRITE_EVENT, EPOLLET);
}
void ehd_event_echo_write(ehd_connection_t *c) {
ehd_buf_t * buf;
buf = c->buf;
ssize_t n;
int err;
for(;;) {
n = send(c->fd, buf->pos, buf->last - buf->pos, 0);
if (n == -1) {
err = errno;
if (err == EAGAIN) {
break;
}
ehd_close_connection(c);
return;
} else if(n == 0) {
ehd_close_connection(c);
return;
} else {
buf->pos += n;
if (buf->pos == buf->last) {
break;
}
}
}
ehd_mod_event(c->event, EHD_READ_EVENT, EPOLLET);
}
<file_sep>/event/ehd_event.c
//
// Created by renmingxu on 12/21/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
ehd_event_impl_t ehd_event_impl;
int ehd_event_init(ehd_cycle_t *cycle) {
uint i;
int fd;
ehd_conf_t * conf;
ehd_pool_t * pool;
ehd_connection_t * conns;
ehd_event_t * evs;
ehd_listening_t *l;
ehd_connection_t *c;
if (cycle->pool == NULL) {
cycle->pool = ehd_create_pool_default_size();
}
pool = cycle->pool;
conf = cycle->conf;
uint conn_n = conf->connection_num;
cycle->connection_num = conn_n;
ehd_return_if_null(cycle->connections, ehd_palloc(pool, sizeof(ehd_connection_t) * conn_n), EHD_ERROR);
conns = cycle->connections;
ehd_return_if_null(cycle->events, ehd_palloc(pool, sizeof(ehd_event_t) * conn_n), EHD_ERROR);
evs = cycle->events;
for (i = 0;i < conn_n;i++) {
conns[i].fd = -1;
conns[i].data = NULL;
}
for (i = 0;i < conn_n;i++) {
evs[i].data = NULL;
evs[i].closed = 1;
}
for (i = 0;i < conn_n;i++) {
evs[i].data = NULL;
evs[i].closed = 1;
}
for (i = 0;i < cycle->listening.ndata;i++) {
l = cycle->listening.data + i * cycle->listening.size;
fd = l->fd;
c = conns + fd;
evs = cycle->events + fd;
bzero(evs, sizeof(ehd_event_t));
bzero(c, sizeof(ehd_connection_t));
evs->accept = 1;
evs->data = c;
evs->closed = 0;
c->fd = fd;
c->event = evs;
c->listening = l;
c->read_handler = ehd_event_accept_handler;
}
ehd_event_impl = ehd_event_impl_epoll;
ehd_event_impl.funp.init(cycle);
return EHD_OK;
}
<file_sep>/core/ehd_list.h
//
// Created by renmingxu on 12/21/17.
//
#ifndef UNTITLED_EHD_LIST_H
#define UNTITLED_EHD_LIST_H
#include <ehd_config.h>
#include <ehd_core.h>
typedef struct ehd_list_node_s ehd_list_node_t;
struct ehd_list_node_s {
/* ptr to ndata * size block */
void *data;
/* numbers of elements used (no more than ndata)*/
uint ndata;
ehd_list_node_t *next;
};
struct ehd_list_s {
/* end of node list */
ehd_list_node_t *last;
/* head of node list */
ehd_list_node_t head;
/* sizeof value type in list */
size_t size;
/* numbers of element in each node */
unsigned int ndata;
/* ehd_pool_t used by this list */
ehd_pool_t *pool;
};
/* create a list */
ehd_list_t *ehd_list_create(ehd_pool_t *pool, u_int n, size_t size);
/*
* NOT need to call after ehd_list_create
* call after an ehd_list_t type is member of a struct
*/
int ehd_list_init(ehd_list_t *list, ehd_pool_t *pool, u_int n, size_t size);
/* add a ehd_list_node_t after last */
void *ehd_list_push(ehd_list_t *list);
#endif //UNTITLED_EHD_LIST_H
<file_sep>/event/ehd_event.h
//
// Created by renmingxu on 12/21/17.
//
#ifndef EHTTPD_EHD_EVENT_H
#define EHTTPD_EHD_EVENT_H
#include <ehd_config.h>
#include <ehd_core.h>
typedef struct ehd_event_s ehd_event_t;
typedef union ehd_sockaddr_u ehd_sockaddr_t;
typedef struct ehd_event_impl_s ehd_event_impl_t;
extern ehd_event_impl_t ehd_event_impl_epoll;
extern ehd_event_impl_t ehd_event_impl;
extern struct ehd_event_impl_funp_s ehd_event_funps;
#define ehd_add_event ehd_event_funps.add
#define ehd_del_event ehd_event_funps.del
#define ehd_mod_event ehd_event_funps.mod
#define ehd_process_event ehd_event_funps.process
#define EHD_READ_EVENT EPOLLIN
#define EHD_WRITE_EVENT EPOLLOUT
#define EHD_CLOSE_EVENT 1
struct ehd_event_s {
void *data; /* now it is always ehd_connection */
uint32_t events;
unsigned closed:1;
unsigned accept:1;
unsigned active:1;
unsigned rready:1;
unsigned wready:1;
unsigned eof:1;
unsigned disalbed:1;
unsigned error:1;
};
union ehd_sockaddr_u {
struct sockaddr sockaddr;
struct sockaddr_in sockaddr_in;
};
struct ehd_event_impl_funp_s {
int (*process) (ehd_cycle_t *cycle);
int (*add) (ehd_event_t *ev, int event, uint flags);
int (*del) (ehd_event_t *ev, int event, uint flags);
int (*mod) (ehd_event_t *ev, int event, uint flags);
int (*init) (ehd_cycle_t * cycle);
int (*close) (ehd_cycle_t * cycl);
};
struct ehd_event_impl_s {
ehd_str_t * name;
struct ehd_event_impl_funp_s funp;
};
int ehd_event_init(ehd_cycle_t *cycle);
void ehd_event_accept_handler(ehd_connection_t *c);
int ehd_event_enable_accept(ehd_cycle_t * cycle);
int ehd_event_disable_accept(ehd_cycle_t * cycle);
void ehd_event_echo_read(ehd_connection_t *c);
void ehd_event_echo_write(ehd_connection_t *c);
#endif //EHTTPD_EHD_EVENT_H
<file_sep>/core/ehd_conf.c
//
// Created by renmingxu on 12/27/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
uint ehd_threaded;
int ehd_conf_init(ehd_conf_t *conf, ehd_file_t *file) {
ehd_pool_t * pool;
ehd_list_t * addrs;
ehd_list_t * ports;
ehd_str_t * addr;
ehd_str_t addr1 = ehd_string("0.0.0.0");
ehd_str_t addr2 = ehd_string("127.0.1.1");
ehd_str_t index = ehd_string("index.html");
uint * port;
uint port1 = 8080;
uint port2 = 9999;
ehd_str_t root = ehd_string("/var/www/html/");
if (conf->pool == NULL) {
conf->pool = ehd_create_pool_default_size();
}
pool = conf->pool;
conf->connection_num = 1024;
addrs = &conf->addrs_str;
ehd_list_init(addrs, pool, 4, sizeof(ehd_str_t));
ehd_threaded = 0;
addr = ehd_list_push(addrs);
*addr = addr1;
addr = ehd_list_push(addrs);
*addr = addr2;
ports = &conf->ports_int;
ehd_list_init(ports, pool, 4, sizeof(int));
port = ehd_list_push(ports);
*port = port1;
port = ehd_list_push(ports);
*port = port2;
printf("asdf\n");
fflush(stdout);
conf->root = root;
conf->index = index;
}
<file_sep>/core/ehd_cycle.c
//
// Created by renmingxu on 12/25/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
#include <ehd_http.h>
volatile ehd_cycle_t * ehd_cycle;
int ehd_cycle_init(ehd_cycle_t * cycle, ehd_conf_t * conf) {
uint i;
ehd_pool_t * pool;
if (cycle->pool == NULL) {
cycle->pool = ehd_create_pool_default_size();
}
pool = cycle->pool;
cycle->conf = conf;
ehd_array_init(&cycle->listening, pool, EHD_CYCLE_LISTENING_SIZE, sizeof(ehd_listening_t));
if (ehd_listening_init(cycle, conf) == EHD_ERROR) {
perror("ehd_listening_init");
return EHD_ERROR;
}
if (ehd_open_listening_socket(cycle) == EHD_ERROR) {
perror("ehd_open_listening_socket");
return EHD_ERROR;
}
if (ehd_event_init(cycle) == EHD_ERROR) {
perror("ehd_event_init");
return EHD_ERROR;
}
if (ehd_http_init(cycle) == EHD_ERROR) {
return EHD_ERROR;
}
return EHD_OK;
}
<file_sep>/core/ehd_cycle.h
//
// Created by renmingxu on 12/25/17.
//
#ifndef EHTTPD_EHD_CYCLE_H
#define EHTTPD_EHD_CYCLE_H
#include <ehd_config.h>
#include <ehd_core.h>
#define EHD_CYCLE_LISTENING_SIZE 4
extern volatile ehd_cycle_t *ehd_cycle;
extern uint ehd_threaded; // init in ehd_conf_init()
struct ehd_cycle_s {
ehd_pool_t *pool;
ehd_array_t listening;
uint connection_num;
ehd_connection_t * connections;
ehd_event_t * events;
ehd_str_t root;
ehd_conf_t * conf;
};
int ehd_cycle_init(ehd_cycle_t * cycle, ehd_conf_t * conf);
#endif //EHTTPD_EHD_CYCLE_H
<file_sep>/core/ehd_conf.h
//
// Created by renmingxu on 12/27/17.
//
#ifndef EHTTPD_EHD_CONF_H
#define EHTTPD_EHD_CONF_H
#include <ehd_config.h>
#include <ehd_core.h>
struct ehd_conf_s {
uint connection_num;
ehd_list_t addrs_str;
ehd_list_t ports_int;
ehd_str_t root;
ehd_str_t index;
ehd_pool_t * pool;
};
int ehd_conf_init(ehd_conf_t * conf, ehd_file_t *file);
#endif //EHTTPD_EHD_CONF_H
<file_sep>/http/ehd_http_request.h
//
// Created by renmingxu on 12/21/17.
//
#ifndef EHTTPD_EHD_HTTP_REQUEST_H
#define EHTTPD_EHD_HTTP_REQUEST_H
#include <ehd_config.h>
#include <ehd_palloc.h>
#include <ehd_connection.h>
#define EHD_HTTP_PARSE_INVALID_METHOD 10
#define EHD_HTTP_PARSE_INVALID_REQUEST 11
#define EHD_HTTP_PARSE_TOO_LONG_URI 12
#define EHD_HTTP_PARSE_INVALID_09_METHOD 13
#define EHD_HTTP_PARSE_INVALID_HEADER 15
#define EHD_HTTP_PARSE_HEADER_DONE 16
#define EHD_HTTP_GET 1
#define EHD_HTTP_HEAD 2
#define EHD_HTTP_POST 3
#define EHD_HTTP_OK 200
#define EHD_HTTP_PARTIAL_CONTENT 206
#define EHD_HTTP_SPECIAL_RESPONSE 300
#define EHD_HTTP_MOVED_PERMANENTLY 301
#define EHD_HTTP_MOVED_TEMPORARILY 302
#define EHD_HTTP_NOT_MODIFIED 304
#define EHD_HTTP_BAD_REQUEST 400
#define EHD_HTTP_FORBIDDEN 403
#define EHD_HTTP_NOT_FOUND 404
#define EHD_HTTP_NOT_ALLOWED 405
#define EHD_HTTP_REQUEST_TIME_OUT 408
#define EHD_HTTP_REQUEST_ENTITY_TOO_LARGE 413
#define EHD_HTTP_REQUEST_URI_TOO_LARGE 414
#define EHD_HTTP_RANGE_NOT_SATISFIABLE 416
#define EHD_HTTP_EHD_CODES EHD_HTTP_TO_HTTPS
#define EHD_HTTP_TO_HTTPS 497
#define EHD_HTTP_INVALID_HOST 498
#define EHD_HTTP_CLIENT_CLOSED_REQUEST 499
#define EHD_HTTP_INTERNAL_SERVER_ERROR 500
#define EHD_HTTP_NOT_IMPLEMENTED 501
#define EHD_HTTP_BAD_GATEWAY 502
#define EHD_HTTP_SERVICE_UNAVAILABLE 503
#define EHD_HTTP_GATEWAY_TIME_OUT 504
typedef enum {
EHD_HTTP_INITING_REQUEST_STATE = 0,
EHD_HTTP_READING_REQUEST_STATE,
EHD_HTTP_PROCESS_REQUEST_STATE,
EHD_KEEP_ALIVE_STATE,
}ehd_http_state_e;
typedef struct ehd_http_request_s ehd_http_request_t;
typedef struct {
ehd_str_t name;
size_t offset;
} ehd_http_header_t;
typedef struct {
ehd_http_request_t * request;
}ehd_http_connection_t;
typedef struct {
ehd_list_t headers;
ehd_table_data_t * host;
ehd_table_data_t * connection;
ehd_table_data_t * if_modified_since;
ehd_table_data_t * content_length;
ehd_table_data_t * user_agent;
ehd_table_data_t * referer;
ehd_table_data_t * range;
ehd_table_data_t * accept_encoding;
ehd_table_data_t * keep_alive;
ehd_table_data_t * authorization;
ehd_array_t cookies;
ssize_t content_length_n;
}ehd_http_headers_in_t;
typedef struct {
ehd_list_t headers;
uint status;
ehd_str_t status_line;
ehd_table_data_t *server;
ehd_table_data_t *date;
ehd_table_data_t *content_type;
ehd_table_data_t *content_length;
ehd_table_data_t *content_ranges;
ehd_table_data_t *etag;
ehd_table_data_t *charset;
time_t date_time;
time_t last_moddified_time;
off_t content_length_n;
}ehd_http_headers_out_t;
typedef struct ehd_http_response_s ehd_http_response_t;
struct ehd_http_response_s {
ehd_chain_t *data;
ehd_chain_t *last;
unsigned begin:1;
};
struct ehd_http_request_s {
ehd_pool_t * pool;
ehd_http_connection_t * http_connection;
ehd_http_state_e http_state;
ehd_conf_t *conf;
ehd_connection_t * connection;
ehd_buf_t * header_in_buf;
ehd_http_headers_in_t headers_in;
int headers_n;
ehd_http_headers_out_t headers_out;
uint method;
uint http_version;
uint http_major;
uint http_minor;
ehd_str_t request_line;
ehd_str_t uri;
ehd_str_t unparsed_uri;
ehd_str_t args;
ehd_str_t exten;
ehd_str_t method_name;
ehd_http_response_t response;
uint port;
ehd_str_t * port_text;
ehd_str_t * server_name;
off_t sent;
/* used to parse http headers */
uint state;
u_char *request_start;
u_char *method_end;
u_char *uri_start;
u_char *schema_start;
u_char *schema_end;
u_char *host_start;
u_char *host_end;
u_char *port_end;
u_char *uri_end;
u_char *args_start;
u_char *uri_ext;
u_char *request_end;
u_char *header_end;
u_char *header_name_start;
u_char *header_name_end;
unsigned proxy:1;
unsigned complex_uri:1;
u_char *header_start;
};
#endif //EHTTPD_EHD_HTTP_REQUEST_H
<file_sep>/core/ehd_array.c
//
// Created by renmingxu on 12/25/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
ehd_array_t * ehd_array_create(ehd_pool_t * pool, uint n, size_t size) {
ehd_array_t *array = ehd_palloc(pool, sizeof(ehd_array_t));
array->data = ehd_palloc(pool, size * n);
array->size = size;
array->nblock = n;
array->ndata = 0;
array->pool = pool;
return array;
}
void ehd_array_destroy(ehd_array_t * array) {
ehd_pool_t *p;
p = array->pool;
if ((char*)array->data + array->size * array->ndata == p->last) {
p->last = array->data;
}
if ((char*) array + sizeof(ehd_array_t) == p->last) {
p->last = (void*)array;
}
}
void * ehd_array_push(ehd_array_t * array) {
void * new, *data;
ehd_pool_t *p;
if (array->ndata == array->nblock) {
p = array->pool;
if ((char*)array->data + array->size * array->ndata == p->last
&& (unsigned)(p->end - p->last ) >= array->size) {
p->last += array->size;
array->nblock++;
} else {
ehd_return_if_null(new, ehd_palloc(p, 2 * array->size * array->nblock), NULL);
memcpy(new, array->data, array->size * array->nblock);
array->data = new;
array->nblock *= 2;
}
}
data = array->data + array->size * array->ndata;
array->ndata ++;
return data;
}
<file_sep>/event/ehd_event_accept.c
//
// Created by renmingxu on 1/1/18.
//
#include <ehd_config.h>
#include <ehd_core.h>
#include <ehd_http.h>
void ehd_event_accept_handler(ehd_connection_t * c) {
socklen_t len;
ehd_sockaddr_t addr;
ehd_pool_t *pool;
int s, err;
ehd_event_t * aev, *ev;
ehd_connection_t *conn, *lconn;
lconn = c;
ev = c->event;
pool = NULL;
while(1) {
len = sizeof(ehd_sockaddr_t);
#ifdef _GNU_SOURCE
s = accept4(lconn->fd, &addr.sockaddr, &len, SOCK_NONBLOCK);
#else
s = accept(lconn->fd, &addr.sockaddr, &len);
#endif
if (s == -1) {
err = errno;
if (err == EAGAIN) {
return;
}
ev->disalbed = 1;
ev->error = 1;
return;
}
if (s >= ehd_cycle->connection_num) {
close(s);
return;
}
pool = ehd_create_pool(lconn->listening->pool_size);
if (pool == NULL) {
return;
}
if (ehd_setnonblocking(s) < 0){
return;
}
conn = ehd_cycle->connections + s;
aev = ehd_cycle->events + s;
bzero(conn, sizeof(ehd_connection_t));
bzero(aev, sizeof(ehd_event_t));
conn->pool = pool;
conn->listening = lconn->listening;
conn->fd = s;
conn->sockaddr = addr;
conn->socklen = len;
conn->event = aev;
aev->data = conn;
aev->accept = 0;
aev->active = 0;
aev->events = 0;
aev->closed = 0;
conn->read_handler = lconn->listening->handler;
conn->write_handler = NULL;
ehd_add_event(aev, EHD_READ_EVENT, EPOLLET);
}
}
int ehd_event_enable_accept(ehd_cycle_t *cycle) {
uint i;
ehd_listening_t *l;
l = cycle->listening.data;
for(i = 0;i < cycle->listening.ndata;i++) {
if (ehd_add_event(&cycle->events[l[i].fd], EHD_READ_EVENT, EPOLLET) == EHD_ERROR) {
return EHD_ERROR;
}
}
return EHD_OK;
}
int ehd_event_disable_accept(ehd_cycle_t *cycle) {
uint i;
ehd_listening_t *l;
for(i = 0;i < cycle->listening.ndata;i++) {
if (!cycle->events[l[i].fd].active) {
continue;
}
if (ehd_del_event(&cycle->events[l[i].fd], EHD_READ_EVENT,0) == EHD_ERROR) {
return EHD_ERROR;
}
}
return EHD_OK;
}
<file_sep>/core/ehd_list.c
//
// Created by renmingxu on 12/21/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
ehd_list_t* ehd_list_create(ehd_pool_t* pool, u_int n, size_t size) {
ehd_list_t* list;
if (!(list = ehd_palloc(pool, sizeof(ehd_list_t)))) {
return NULL;
}
if (ehd_list_init(list, pool, n, size) != EHD_OK) {
return NULL;
}
return list;
}
int ehd_list_init(ehd_list_t* list, ehd_pool_t* pool, u_int n, size_t size) {
list->head.data = ehd_palloc(pool, n * size);
if (list->head.data == NULL) {
return EHD_ERROR;
}
list->head.ndata = 0;
list->head.next = NULL;
list->pool = pool;
list->last = &list->head;
list->ndata = n;
list->size = size;
return EHD_OK;
}
void* ehd_list_push(ehd_list_t* list) {
void * data;
ehd_list_node_t *last;
last = list->last;
if (last->ndata == list->ndata) {
/*
* the data block of the last node is full
* allocate a new node
*/
if (!(last = ehd_palloc(list->pool, sizeof(ehd_list_node_t)))) {
return NULL;
}
if (!(last->data = ehd_palloc(list->pool, list->ndata * list->size))) {
return NULL;
}
last->ndata = 0;
last->next = NULL;
list->last->next = last;
list->last = last;
}
data = (char*) last->data + list->size * last->ndata;
last->ndata++;
return data;
}<file_sep>/http/ehd_http_core.h
//
// Created by renmingxu on 1/3/18.
//
#ifndef EHTTPD_EHD_HTTP_CORE_H
#define EHTTPD_EHD_HTTP_CORE_H
#include <ehd_config.h>
#include <ehd_core.h>
#include <ehd_http.h>
#include <ehd_http_request.h>
#endif //EHTTPD_EHD_HTTP_CORE_H
<file_sep>/core/ehd_socket.c
//
// Created by renmingxu on 12/26/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
int ehd_setnonblocking(int fd) {
/*
int opts = 0;
if ((opts = fcntl(fd, F_GETFL, 0)) < 0) {
return EHD_ERROR;
}
if (fcntl(fd, F_SETFL, opts | O_NONBLOCK) < 0) {
return EHD_ERROR;
}
return EHD_OK;
*/
int nb;
nb = 1;
return ioctl(fd, FIONBIO, &nb);
}
int ehd_setblocking(int fd) {
/*
int opts = 0;
if ((opts = fcntl(fd, F_GETFL, 0)) < 0) {
return EHD_ERROR;
}
if (fcntl(fd, F_SETFL, opts | O_NONBLOCK) < 0) {
return EHD_ERROR;
}
return EHD_OK;
*/
int nb;
nb = 0;
return ioctl(fd, FIONBIO, &nb);
}
ssize_t ehd_recv(ehd_connection_t *c, u_char *buf, size_t size) {
ssize_t n;
ehd_event_t *ev;
int err;
ev = c->event;
do {
n = recv(c->fd, buf, size, 0);
if (n == 0) {
ev->rready = 0;
ev->eof = 1;
return n;
} else if (n > 0) {
if ((size_t) n < size) {
ev->rready = 0;
}
return n;
}
err = errno;
if (err == EAGAIN) {
ev->rready = 0;
n = EHD_AGAIN;
return n;
} if (err == EINTR){
n = EHD_AGAIN;
} else {
n = EHD_ERROR;
break;
}
} while(err == EINTR);
ev->rready = 0;
ev->error = 1;
return n;
}
ssize_t ehd_send(ehd_connection_t *c, u_char *buf, size_t size) {
ssize_t n;
ehd_event_t *ev;
int err;
ev = c->event;
do {
n = send(c->fd, buf, size, 0);
if (n > 0) {
if ((size_t) n < size) {
ev->wready = 0;
}
return n;
}
if (n == 0) {
ev->wready = 0;
return n;
}
err = errno;
if (err == EAGAIN) {
ev->wready = 0;
n = EHD_AGAIN;
return n;
} if (err == EINTR){
n = EHD_AGAIN;
} else {
n = EHD_ERROR;
break;
}
} while(err == EINTR);
ev->rready = 0;
ev->error = 1;
return n;
}
<file_sep>/test/test_all.h
//
// Created by renmingxu on 12/25/17.
//
#ifndef EHTTPD_TEST_ALL_H
#define EHTTPD_TEST_ALL_H
int test_all();
int test_pool();
#endif //EHTTPD_TEST_ALL_H
<file_sep>/core/ehd_buf.c
//
// Created by renmingxu on 12/21/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
ehd_buf_t* ehd_create_temp_buf(ehd_pool_t *pool, size_t size) {
ehd_buf_t* b;
if (!(b = ehd_pcalloc(pool, sizeof(ehd_buf_t)))) {
return NULL;
}
if (!(b->start = ehd_palloc(pool, size))) {
return NULL;
}
b->pos = b->start;
b->last = b->start;
b->end = b->start + size;
b->temporary = 1;
return b;
}
<file_sep>/core/ehd_socket.h
//
// Created by renmingxu on 12/26/17.
//
#ifndef EHTTPD_EHD_SOCKET_H
#define EHTTPD_EHD_SOCKET_H
#include <ehd_config.h>
#include <ehd_core.h>
int ehd_setnonblocking(int fd);
int ehd_setblocking(int fd);
ssize_t ehd_recv(ehd_connection_t * c, u_char * buf, size_t size);
ssize_t ehd_send(ehd_connection_t * c, u_char * buf, size_t size);
#endif //EHTTPD_EHD_SOCKET_H
<file_sep>/http/ehd_http_core.c
//
// Created by renmingxu on 1/3/18.
//
#include <ehd_config.h>
#include <ehd_core.h>
#include <ehd_http.h>
#include "ehd_http_core.h"
static ehd_str_t mime[][2] = {
{ehd_string("html"), ehd_string("text/html")},
{ehd_string("png"),ehd_string("image/png")},
{ehd_string("jpg"),ehd_string("image/jpeg")},
{ehd_string("js"),ehd_string("application/javascript")},
{ehd_string("ttf"),ehd_string("font/ttf")},
{ehd_string("otf"),ehd_string("font/otf")},
{ehd_string("svg"),ehd_string("image/svg+xml")},
{ehd_string("woff"),ehd_string("font/woff")},
{ehd_string("woff2"),ehd_string("font/woff2")},
{ehd_string("css"),ehd_string("text/css")},
};
static u_char error_tail[] =
"<hr><center>" EHD_VERSION "</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;
static ehd_str_t error_tail_t = ehd_string(error_tail);
static char error_301_page[] =
"<html>" CRLF
"<head><title>301 Moved Permanently</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>301 Moved Permanently</h1></center>" CRLF
;
static char error_302_page[] =
"<html>" CRLF
"<head><title>302 Found</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>302 Found</h1></center>" CRLF
;
static char error_400_page[] =
"<html>" CRLF
"<head><title>400 Bad Request</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>400 Bad Request</h1></center>" CRLF
;
static char error_403_page[] =
"<html>" CRLF
"<head><title>403 Forbidden</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>403 Forbidden</h1></center>" CRLF
;
static char error_404_page[] =
"<html>" CRLF
"<head><title>404 Not Found</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>404 Not Found</h1></center>" CRLF
;
static char error_405_page[] =
"<html>" CRLF
"<head><title>405 Not Allowed</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>405 Not Allowed</h1></center>" CRLF
;
static char error_408_page[] =
"<html>" CRLF
"<head><title>408 Request Time-out</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>408 Request Time-out</h1></center>" CRLF
;
static char error_413_page[] =
"<html>" CRLF
"<head><title>413 Request Entity Too Large</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>413 Request Entity Too Large</h1></center>" CRLF
;
static char error_414_page[] =
"<html>" CRLF
"<head><title>414 Request-URI Too Large</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>414 Request-URI Too Large</h1></center>" CRLF
;
static char error_416_page[] =
"<html>" CRLF
"<head><title>416 Requested Range Not Satisfiable</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>416 Requested Range Not Satisfiable</h1></center>" CRLF
;
static char error_497_page[] =
"<html>" CRLF
"<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>"
CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>400 Bad Request</h1></center>" CRLF
"<center>The plain HTTP request was sent to HTTPS port</center>" CRLF
;
static char error_500_page[] =
"<html>" CRLF
"<head><title>500 Internal Server Error</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>500 Internal Server Error</h1></center>" CRLF
;
static char error_501_page[] =
"<html>" CRLF
"<head><title>501 Method Not Implemented</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>500 Method Not Implemented</h1></center>" CRLF
;
static char error_502_page[] =
"<html>" CRLF
"<head><title>502 Bad Gateway</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>502 Bad Gateway</h1></center>" CRLF
;
static char error_503_page[] =
"<html>" CRLF
"<head><title>503 Service Temporarily Unavailable</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>503 Service Temporarily Unavailable</h1></center>" CRLF
;
static char error_504_page[] =
"<html>" CRLF
"<head><title>504 Gateway Time-out</title></head>" CRLF
"<body bgcolor=\"white\">" CRLF
"<center><h1>504 Gateway Time-out</h1></center>" CRLF
;
static ehd_str_t error_pages[] = {
/* ehd_null_string, */ /* 300 */
ehd_string(error_301_page),
ehd_string(error_302_page),
ehd_null_string, /* 303 */
ehd_string(error_400_page),
ehd_null_string, /* 401 */
ehd_null_string, /* 402 */
ehd_string(error_403_page),
ehd_string(error_404_page),
ehd_string(error_405_page),
ehd_null_string, /* 406 */
ehd_null_string, /* 407 */
ehd_string(error_408_page),
ehd_null_string, /* 409 */
ehd_null_string, /* 410 */
ehd_null_string, /* 411 */
ehd_null_string, /* 412 */
ehd_string(error_413_page),
ehd_string(error_414_page),
ehd_null_string, /* 415 */
ehd_string(error_416_page),
ehd_string(error_497_page), /* 497, http to https */
ehd_string(error_404_page), /* 498, invalid host name */
ehd_null_string, /* 499, client closed connection */
ehd_string(error_500_page),
ehd_string(error_501_page),
ehd_string(error_502_page),
ehd_string(error_503_page),
ehd_string(error_504_page)
};
static void ehd_http_writer(ehd_connection_t *c);
void ehd_http_file_writer_handler(ehd_http_request_t *r);
void ehd_http_special_response_handler(ehd_http_request_t *r, int error) ;
int ehd_http_response_gen_header(ehd_http_request_t *r) ;
void ehd_http_handler(ehd_http_request_t * r) {
r->state = 0;
if (r->method == EHD_HTTP_GET) {
ehd_http_file_writer_handler(r);
} else {
ehd_http_special_response_handler(r, EHD_HTTP_NOT_IMPLEMENTED);
}
}
void ehd_http_file_writer_handler(ehd_http_request_t *r) {
printf("writer init for uri: %s\n", r->uri.data);
ehd_conf_t *conf;
ehd_event_t * ev;
ehd_connection_t *c;
struct stat stbuf;
int n,i,j,k,tmp_flag;
ehd_file_t file;
ehd_str_t filename, *content_type, *uri;
ehd_pool_t *pool;
u_char * f;
ehd_table_data_t *t;
ehd_http_headers_out_t *h;
ehd_file_t * open_file;
void (*write_handler)(ehd_connection_t*);
c = r->connection;
ev = c->event;
pool = r->pool;
conf = r->conf;
uri = &r->uri;
h = &r->headers_out;
filename.data = ehd_pcalloc(pool, conf->root.len + uri->len + conf->index.len + 2);
filename.len = 0;
memcpy(filename.data, conf->root.data, conf->root.len);
memcpy(filename.data + conf->root.len, uri->data, uri->len);
filename.len = conf->root.len + uri->len;
f = filename.data;
if ((n = stat((const char *) f, &stbuf)) == -1){
ehd_http_special_response_handler(r,EHD_HTTP_NOT_FOUND);
return;
}
if (S_ISDIR(stbuf.st_mode)) {
if (uri->data[uri->len - 1] != '/') {
t = ehd_list_push(&r->headers_out.headers);
t->key.data = (u_char *) "Location";
t->key.len = sizeof("Location") - 1;
memcpy(filename.data, uri->data, uri->len);
filename.data[uri->len] = '/';
filename.len = uri->len + 1;
t->value = filename;
ehd_http_special_response_handler(r,EHD_HTTP_MOVED_TEMPORARILY);
return;
} else {
memcpy(filename.data + filename.len, conf->index.data, conf->index.len);
filename.len += conf->index.len;
f = filename.data;
if ((n = stat((const char *) f, &stbuf)) == -1){
ehd_http_special_response_handler(r,EHD_HTTP_FORBIDDEN);
return;
}
}
} else if (!S_ISREG(stbuf.st_mode)) {
ehd_http_special_response_handler(r, EHD_HTTP_NOT_FOUND);
return;
}
n = sizeof(mime) / sizeof(ehd_str_t) / 2;
content_type = NULL;
for (i = 0;i < n;i++) {
tmp_flag = 1;
for(j = (int) mime[i][0].len; j; j--) {
if (mime[i][0].data[j - 1] != uri->data[uri->len - mime[i][0].len + j - 1]) {
tmp_flag = 0;
break;
}
}
if (tmp_flag) {
content_type = &mime[i][1];
break;
}
}
if (content_type != NULL) {
printf("%s\n", content_type->data);
h->content_type = t = ehd_list_push(&h->headers);
t->key.data = (u_char *) "Content-Type";
t->key.len = sizeof("Content-Type") - 1;
t->value = *content_type;
}
h->status = 200;
open_file = ehd_pcalloc(pool,sizeof(ehd_file_t));
ehd_file_open_rs(open_file, filename);
h->content_length_n = open_file->size;
ehd_http_response_gen_header(r);
r->response.last->next = ehd_pcalloc(pool,sizeof(ehd_chain_t));
r->response.last = r->response.last->next;
r->response.last->buf = ehd_pcalloc(pool,sizeof(ehd_buf_t));
r->response.last->next = NULL;
r->response.last->buf->type = 1;
r->response.last->buf->file = open_file;
c->write_handler = ehd_http_writer;
if (ehd_add_event(ev, EHD_WRITE_EVENT, EPOLLET) == EHD_ERROR) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
}
ehd_http_writer(c);
}
void ehd_http_special_response_handler(ehd_http_request_t *r, int error) {
int err;
ehd_pool_t *pool;
ehd_buf_t *b;
ehd_connection_t *c;
ehd_event_t *ev;
c = r->connection;
ev = c->event;
pool = r->pool;
if (error < EHD_HTTP_BAD_REQUEST) {
/* 3XX */
err = error - EHD_HTTP_MOVED_PERMANENTLY;
} else if (error < EHD_HTTP_EHD_CODES) {
/* 4XX */
err = error - EHD_HTTP_BAD_REQUEST + 3;
} else {
/* 49X, 5XX */
err = error - EHD_HTTP_EHD_CODES + 3 + 17;
switch (error) {
case EHD_HTTP_TO_HTTPS:
r->headers_out.status = EHD_HTTP_BAD_REQUEST;
error = EHD_HTTP_BAD_REQUEST;
break;
case EHD_HTTP_INVALID_HOST:
r->headers_out.status = EHD_HTTP_NOT_FOUND;
error = EHD_HTTP_NOT_FOUND;
break;
}
}
r->headers_out.content_type = ehd_list_push(&r->headers_out.headers);
r->headers_out.content_type->key.len = sizeof("Content-Type") - 1;
r->headers_out.content_type->key.data = (u_char *) "Content-Type";
r->headers_out.content_type->value.len = sizeof("text/html") - 1;
r->headers_out.content_type->value.data = (u_char *) "text/html";
b = ehd_create_temp_buf(pool, error_pages[err].len + error_tail_t.len);
memcpy(b->last, error_pages[err].data, error_pages[err].len);
b->last += error_pages[err].len;
memcpy(b->last , error_tail_t.data, error_tail_t.len);
b->last += error_tail_t.len;
r->headers_out.content_length_n = b->last - b->pos;
r->headers_out.status = error;
ehd_http_response_gen_header(r);
r->response.last->next = ehd_pcalloc(pool,sizeof(ehd_chain_t));
r->response.last = r->response.last->next;
r->response.last->buf = b;
c->write_handler = ehd_http_writer;
if (ehd_add_event(ev, EHD_WRITE_EVENT, EPOLLET) == EHD_ERROR) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
}
ehd_http_writer(c);
}
int ehd_http_response_gen_header(ehd_http_request_t *r) {
ehd_http_response_t * resp;
ehd_pool_t * pool;
ehd_http_headers_out_t *h;
ehd_buf_t * buf;
int n,i;
ehd_list_node_t *node;
ehd_table_data_t *list, *t;
u_char keyn,valuen;
pool = r->pool;
resp = &r->response;
h = &r->headers_out;
resp->data = ehd_pcalloc(pool,sizeof(ehd_chain_t));
resp->last = r->response.data;
buf = resp->data->buf = ehd_create_temp_buf(pool, 8192);
resp->data->next = NULL;
if (h->status_line.data != NULL) {
n = snprintf((char *) buf->last, buf->end - buf->last, "HTTP/1.1 %d %s\r\n", h->status, h->status_line.data);
} else {
n = snprintf((char *) buf->last, buf->end - buf->last, "HTTP/1.1 %d\r\n", h->status);
}
buf->last += n;
if (h->server == NULL) {
h->content_type = t = ehd_list_push(&h->headers);
t->key.data = (u_char *) "Server";
t->key.len = sizeof("Server") - 1;
t->value.data = (u_char *) EHD_VERSION;
t->value.len = sizeof(EHD_VERSION) - 1;
}
if (h->content_length == NULL && h->content_length_n > 0) {
h->content_type = t = ehd_list_push(&h->headers);
t->key.data = (u_char *) "Content-Length";
t->key.len = sizeof("Content-Length") - 1;
t->value.data = ehd_pcalloc(pool, 20);
t->value.len = (size_t) snprintf((char *) t->value.data, 20, "%ld", h->content_length_n);
}
for (node = &h->headers.head;node != NULL;node = node->next) {
list = node->data;
for (i = 0;i < node->ndata;i++) {
t = &list[i];
if (buf->end - buf->last > t->key.len + 2) {
memcpy(buf->last, t->key.data, t->key.len);
buf->last += t->key.len;
*buf->last = (u_char) ':';
buf->last++;
*buf->last = (u_char) ' ';
buf->last++;
if (buf->end - buf->last > t->value.len + 2) {
memcpy(buf->last, t->value.data, t->value.len);
buf->last += t->value.len;
*buf->last = (u_char)CR;
buf->last++;
*buf->last = (u_char) LF;
buf->last++;
continue;
}
}
/* palloc a bigger mem */
}
}
if (buf->end - buf->last >= 2) {
*buf->last = (u_char) CR;
buf->last++;
*buf->last = (u_char) LF;
buf->last++;
return EHD_OK;
}
}
static void ehd_http_writer(ehd_connection_t *c) {
ehd_http_request_t * r;
r = c->data;
ehd_chain_t *chain, *last;
ehd_http_connection_t *hc;
ssize_t n;
int err;
if (!r->response.begin) {
r->response.last = r->response.data;
r->response.begin = 1;
}
last = r->response.last;
for(;;) {
if (last->buf->type == 0) {
n = ehd_send(c, last->buf->pos, last->buf->last - last->buf->pos);
if (n > 0) {
last->buf->pos += n;
if (last->buf->pos == last->buf->last) {
if (last->next == NULL) {
ehd_http_keep_alive(r);
return;
} else {
last = last->next;
}
} else {
continue;
}
} else if (n == 0) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
} else {
err = errno;
if (err == EAGAIN) {
return;
}
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
} else {
n = sendfile(c->fd,
last->buf->file->fd,
&last->buf->file->sys_offset,
(size_t) (last->buf->file->size - last->buf->file->sys_offset));
// last->buf->file->sys_offset = lseek(last->buf->file->fd, 0, SEEK_CUR );
printf("%ld\n", last->buf->file->sys_offset);
if (n > 0) {
if (last->buf->file->sys_offset == last->buf->file->size) {
if (last->next == NULL) {
ehd_http_keep_alive(r);
return;
} else {
last = last->next;
}
} else {
// last->buf->pos += n;
continue;
}
} else if (n == 0) {
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
} else {
err = errno;
if (err == EAGAIN) {
return;
}
ehd_http_close_request(r);
ehd_http_close_connection(c);
return;
}
}
}
}
<file_sep>/core/ehd_file.h
//
// Created by renmingxu on 12/27/17.
//
#ifndef EHTTPD_EHD_FILE_H
#define EHTTPD_EHD_FILE_H
#include <ehd_config.h>
#include <ehd_core.h>
struct ehd_file_s {
int fd;
ehd_str_t name;
off_t offset;
off_t sys_offset;
off_t size;
};
int ehd_file_open_r(ehd_file_t * file, ehd_str_t name);
int ehd_file_open_rs(ehd_file_t * file, ehd_str_t name);
#endif //EHTTPD_EHD_FILE_H
<file_sep>/test/test_all.c
//
// Created by renmingxu on 12/25/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
#include <test_all.h>
int test_pool() {
ehd_pool_t *pool = ehd_create_pool_default_size();
ehd_pool_t pool1;
int *n;
n = ehd_palloc(pool, sizeof(int) * 100000);
for(int i = 0;i < 100000;i++) {
n[i] = i;
}
for(int i = 0;i < 100000;i++) {
if (n[i] != i)
return -1;
}
n = ehd_palloc(pool, sizeof(int) * 100000);
for(int i = 0;i < 100000;i++) {
n[i] = i;
}
for(int i = 0;i < 100000;i++) {
if (n[i] != i)
return -1;
}
ehd_destroy_pool(pool);
return 0;
}
int test_array() {
ehd_pool_t * pool = ehd_create_pool_default_size();
ehd_array_t * array = ehd_array_create(pool, 100, sizeof(int));
for(int i = 0;i < 522241;i ++) {
*(int*)ehd_array_push(array) = i;
}
printf("array size %d\n", array->nblock);
}
int test_list() {
ehd_pool_t * pool = ehd_create_pool_default_size();
ehd_list_t * list = ehd_list_create(pool, 256, sizeof(int));
for(int i = 0;i < 5000;i++) {
*(int*)ehd_list_push(list) = i;
}
ehd_list_node_t * node;
int n = 0;
int m = 0;
int * p;
for (node = &list->head;node != NULL;node = node->next) {
for(int n = 0;n < node->ndata;n++,m++) {
p = (int*)(node->data + n * list->size);
if (*p != m) {
return EHD_ERROR;
}
}
}
}
int test_all() {
int n = 0;
if (test_pool() < 0){
return -1;
}
n++;
if (test_array() < 0){
return -1;
}
n++;
if (test_list() < 0){
return -1;
}
n++;
return n;
}
<file_sep>/core/ehd_buf.h
//
// Created by renmingxu on 12/21/17.
//
#ifndef UNTITLED_EHD_BUF_H
#define UNTITLED_EHD_BUF_H
#include <ehd_config.h>
#include <ehd_core.h>
#define EHD_DEFAULT_BUF_SIZE 4096
typedef struct ehd_buf_s ehd_buf_t;
typedef struct ehd_chain_s ehd_chain_t;
struct ehd_chain_s {
ehd_buf_t * buf;
ehd_chain_t * next;
};
struct ehd_buf_s {
/* read position */
u_char* pos;
u_char* last;
/* buffer size */
u_char* start;
u_char* end;
int type;
off_t file_pos;
off_t file_last;
ehd_file_t * file;
/* content of the buf could be changed */
unsigned temporary : 1;
};
ehd_buf_t* ehd_create_temp_buf(ehd_pool_t* pool, size_t size);
#endif //UNTITLED_EHD_BUF_H
<file_sep>/core/ehttpd.c
//
// Created by renmingxu on 12/21/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
#include <test_all.h>
int main(int argc, char ** argv) {
/*
int t;
if (( t = test_all())<0) {
printf("test fail %d\n", t);
} else {
printf("test success %d\n", t);
}
*/
ehd_pool_t * pool = ehd_create_pool_default_size();
ehd_conf_t * conf = ehd_palloc(pool, sizeof(ehd_conf_t));
ehd_cycle_t * cycle = ehd_palloc(pool, sizeof(ehd_cycle_t));
conf->pool = pool;
cycle->pool = pool;
ehd_file_t conf_file;
ehd_str_t conf_file_name = ehd_string("ehttpd.conf");
//ehd_file_open_r(&conf_file, conf_file_name);
ehd_conf_init(conf, &conf_file);
ehd_cycle_init(cycle, conf);
ehd_cycle = cycle;
ehd_process_event(cycle);
}
<file_sep>/core/ehd_array.h
//
// Created by renmingxu on 12/25/17.
//
#ifndef EHTTPD_EHD_ARRAY_H
#define EHTTPD_EHD_ARRAY_H
#include <ehd_config.h>
#include <ehd_core.h>
typedef struct ehd_array_s ehd_array_t;
struct ehd_array_s {
void * data;
size_t size;
uint nblock;
uint ndata;
ehd_pool_t * pool;
};
ehd_array_t *ehd_array_create(ehd_pool_t * pool, uint n, size_t size);
inline static int ehd_array_init(ehd_array_t *array, ehd_pool_t *pool, uint n, size_t size) {
if (!(array->data = ehd_palloc(pool, n * size))) {
return EHD_ERROR;
}
array->ndata = 0;
array->size = size;
array->nblock = n;
array->pool = pool;
}
typedef struct {
ehd_str_t key;
ehd_str_t value;
} ehd_table_data_t;
void ehd_array_destroy(ehd_array_t *array);
void * ehd_array_push(ehd_array_t *array);
#endif //EHTTPD_EHD_ARRAY_H
<file_sep>/core/ehd_config.h
//
// Created by renmingxu on 12/21/17.
//
#ifndef UNTITLED_EHD_CONFIG_H
#define UNTITLED_EHD_CONFIG_H
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stddef.h>
#include <errno.h>
#include <asm/ioctls.h>
#include <stropts.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/fcntl.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <sys/sendfile.h>
#endif //UNTITLED_EHD_CONFIG_H
<file_sep>/http/ehd_http.c
//
// Created by renmingxu on 1/2/18.
//
#include <ehd_config.h>
#include <ehd_core.h>
#include <ehd_http.h>
int ehd_http_init(ehd_cycle_t * cycle){
uint i;
ehd_listening_t * ls;
for(i = 0;i < cycle->listening.ndata;i++) {
ls = cycle->listening.data;
ls[i].handler = ehd_http_init_connection;
}
return EHD_OK;
}
void ehd_http_empty_handler(ehd_connection_t *c) {
return;
}
void ehd_http_close_connection(ehd_connection_t *c) {
ehd_close_connection(c);
}
<file_sep>/event/ehd_epoll.h
//
// Created by renmingxu on 12/31/17.
//
#ifndef EHTTPD_EHD_EPOLL_H
#define EHTTPD_EHD_EPOLL_H
#include <ehd_config.h>
#include <ehd_core.h>
static ehd_str_t epoll_name = ehd_string("epoll");
static int ep = -1;
static struct epoll_event *event_list;
static u_int nevents = 0;
struct ehd_event_impl_funp_s ehd_event_funps;
static int ehd_event_epoll_init(ehd_cycle_t * cycle);
static int ehd_event_epoll_close(ehd_cycle_t * cycle);
static int ehd_event_epoll_add(ehd_event_t * ev, int event, uint flags);
static int ehd_event_epoll_mod(ehd_event_t * ev, int event, uint flags);
static int ehd_event_epoll_del(ehd_event_t * ev, int event, uint flags);
static int ehd_event_epoll_process(ehd_cycle_t *cycle);
struct ehd_event_impl_s ehd_event_impl_epoll = {
&epoll_name,
{
ehd_event_epoll_process,
ehd_event_epoll_add,
ehd_event_epoll_del,
ehd_event_epoll_mod,
ehd_event_epoll_init,
ehd_event_epoll_close,
},
};
#endif //EHTTPD_EHD_EPOLL_H
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(ehttpd)
set(CMAKE_C_STANDARD 11)
INCLUDE_DIRECTORIES(core/ event/ http/ test/)
set(SOURCE_FILES
core/ehd_config.h
core/ehd_core.h
core/ehd_buf.h
core/ehd_list.h
core/ehd_palloc.h
core/ehd_string.h
core/ehttpd.h
core/ehd_buf.c
core/ehd_list.c
core/ehd_palloc.c
core/ehd_string.c
core/ehttpd.c
event/ehd_event.c
event/ehd_event.h
http/ehd_http_request.h
http/ehd_http_request.c
core/ehd_connection.h
core/ehd_cycle.c
core/ehd_cycle.h
core/ehd_array.c
core/ehd_array.h
test/test_all.c
test/test_all.h core/ehd_connection.c core/ehd_socket.h core/ehd_socket.c core/ehd_conf.c core/ehd_conf.h core/ehd_file.h core/ehd_file.c event/ehd_event_echo.c event/ehd_epoll.h event/ehd_epoll.c event/ehd_event_accept.c http/ehd_http.c http/ehd_http.h http/ehd_http_parse.c http/ehd_http_core.c http/ehd_http_core.h)
add_executable(ehttpd ${SOURCE_FILES})
<file_sep>/core/ehd_connection.c
//
// Created by renmingxu on 12/25/17.
//
#include <ehd_config.h>
#include <ehd_core.h>
int ehd_open_listen_socket(ehd_cycle_t cycle) {
return 0;
}
int ehd_listening_init(ehd_cycle_t *cycle, ehd_conf_t *conf) {
ehd_pool_t * pool;
ehd_list_t * addr_list;
ehd_list_t * port_list;
ehd_list_node_t *addr_node;
ehd_list_node_t *port_node;
ehd_str_t *addr;
uint16_t port;
ehd_listening_t *listening;
struct sockaddr_in *sockaddr;
pool = cycle->pool;
int n;
addr_list = &conf->addrs_str;
port_list = &conf->ports_int;
for(addr_node = &addr_list->head, port_node= &port_list->head;
addr_node != NULL && port_node != NULL;
addr_node = addr_node->next, port_node = port_node->next)
{
for(n = 0;n < addr_node->ndata && n < port_node->ndata;n++) {
addr = addr_node->data + n * addr_list->size;
port = *(uint16_t *)(port_node->data + n * port_list->size);
listening = ehd_array_push(&cycle->listening);
sockaddr = ehd_palloc(pool, sizeof(struct sockaddr_in));
listening->sockaddr = (struct sockaddr*)sockaddr;
listening->socklen = sizeof(struct sockaddr_in);
listening->family = AF_INET;
listening->type = SOCK_STREAM;
listening->protocol = 0;
listening->fd = -1;
listening->backlog = 0;
listening->pool_size = 16 * 1024;
bzero(sockaddr, sizeof(struct sockaddr_in));
sockaddr->sin_family = AF_INET;
sockaddr->sin_port = ntohs(port);
inet_pton(sockaddr->sin_family, (char *) addr->data, &sockaddr->sin_addr);
printf("addr: %s ", addr->data);
printf("port: %d \n", port);
}
}
}
int ehd_open_listening_socket(ehd_cycle_t *cycle) {
ehd_listening_t *listenings = cycle->listening.data;
ehd_listening_t * lis;
int sockfd, reuse_int, err, tries, failed;
reuse_int = 1;
failed = 0;
int i;
for(tries = 5;tries;tries--) {
failed = 0;
for (i = 0;i < cycle->listening.ndata;i++) {
lis = listenings + i;
if (lis->fd != -1) {
continue;
}
sockfd = socket(lis->family, lis->type, lis->protocol);
if (sockfd == -1) {
return EHD_ERROR;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse_int, sizeof(int)) == -1) {
return EHD_ERROR;
}
if (ehd_setnonblocking(sockfd) == -1) {
return EHD_ERROR;
}
if (bind(sockfd, lis->sockaddr, lis->socklen) == -1) {
err = errno;
if (err == EADDRINUSE)
return EHD_ERROR;
failed = 1;
continue;
}
if (listen(sockfd, lis->backlog) == -1) {
return EHD_ERROR;
}
lis->fd = sockfd;
}
if(!failed) {
break;
}
usleep(500);
}
if (failed) {
return EHD_ERROR;
}
return EHD_OK;
}
void ehd_close_connection(ehd_connection_t *c) {
int fd;
if (c->pool == NULL) {
/* this error does not need to be handled */
return;
}
if (ehd_del_event) {
ehd_del_event(c->event, 0, EHD_CLOSE_EVENT);
}
c->event->closed = 1;
fd = c->fd;
c->fd = -1;
c->data = NULL;
ehd_destroy_pool(c->pool);
if (close(fd) == -1) {
/* this error does not need to be handled */
return;
}
}
|
c18d2e8e7c451d2b00c6041b69a17f53b976240f
|
[
"C",
"CMake"
] | 39 |
C
|
mingmxren/ehttpd
|
8a424080b1c227906325eff1c08495bb2f73d1f9
|
e03c1a5e6edf5e3b062eba6e6791ea832dd9fd21
|
refs/heads/master
|
<repo_name>gabrielx3500/Capella-One<file_sep>/template-parts/biography.php
<div id="author-info">
<div id="author-image">
<a href="<?php the_author_meta('user_url'); ?>"><?php echo get_avatar( get_the_author_meta('user_email'), '80', '' ); ?></a>
</div>
<div id="author-bio">
<h4>Written by <?php the_author_link(); ?></h4>
<p><?php the_author_meta('description'); ?></p>
</div>
</div><!--Author Info-->
<file_sep>/comments.php
<div class="comments-grids">
<div class="comments-grid">
<?php
foreach($comments as $comment){
?>
<div class="comments-grid-left">
<?php echo get_avatar( $comment, 32 ); ?>
</div>
<div class="comments-grid-right">
<h4><a href="<?php comment_author_url();?>"><?php comment_author();?></a></h4>
<ul>
<li><?php comment_date();?><i>|</i></li>
<li><a href="#">Reply</a></li>
</ul>
<p><?php comment_text();?></p>
</div>
<div class="clearfix"> </div>
<?php
}
?>
</div>
</div>
<?php
if(comments_open()){
?>
<div class="leave-coment-form">
<h3>Leave a Comment</h3>
<form action="<?php echo site_url('wp-comments-post.php');?>" method="post" id="commentform">
<input type="hidden" name="comment_post_ID" value='<?php echo $post->ID;?>' id='comment_post_ID'/>
<input type="text" name="Name" placeholder="Name" required="">
<input type="text" name="Email" placeholder="Email" required="">
<textarea rows="7" cols="60" name="comment" placeholder="Your comment here..."></textarea>
<div class="w3_single_submit">
<button type="submit" class="btn btn-primary">Add Comment</button>
</div>
</form>
</div>
<?php
}else{
_e('Comments are closed','theme');
}<file_sep>/content.php
<div class="post-content">
<div class="container">
<div class="col-md-12 col-sm-12 col-xs-12 post-left">
<article>
<div class="post-header">
<span class='cat'><?php the_category();?></span>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<span class='date'><i class="fa fa-calendar calendario"> <?php the_date();?></i></span><span class='comment'><i class="fa fa-comments-o" aria-hidden="true"><a href="<?php comments_link(); ?>"></a></i></span><span class='author'>
<?php
printf( _nx( 'One Comment', '%1$s Comments', get_comments_number(), 'comments title', 'textdomain' ), number_format_i18n( get_comments_number() ) ); ?>
</a></i></span>
<span class="user"><i class="fa fa-user"> <a href=''><?php the_author_posts_link();;?></a></i></span>
</div>
<?php if ( has_post_thumbnail() ) {?>
<div class="tch-img">
<?php the_post_thumbnail(); ?>
</div>
<?php } else { ?>
<?php } ?>
<section class="tc-ch">
<?php the_excerpt(); ?>
</section>
</article>
</div>
</div>
</div>
<file_sep>/search.php
<?php get_header();?>
<!-- banner -->
<div class="agile-banner">
</div>
<!-- //banner -->
<!-- breadcrumbs -->
<div class="breadcrumbs">
<div class="container">
<ol class="breadcrumb breadcrumb1">
<li><a href="index.html">Home</a></li>
<li class="active">Single Page</li>
</ol>
</div>
</div>
<!-- //breadcrumbs -->
<div class="container">
<div class="banner-btm-agile">
<!-- //btm-wthree-left -->
<div class="col-md-9 btm-wthree-left">
<div class="single-left">
<div class="single-left1">
</div>
<div class="messaje404">
<p><?php _e("Search Result for","Capella") ;?></p>
<span class="text-info"><?php the_search_query();?></span>
</div>
</div>
</div>
</div>
</div>
<?php get_footer();?><file_sep>/footer.php
<!-- Footer-->
<footer>
<div class="agileits-w3layouts-footer">
<div class="container">
<div class="col-md-4 w3-agile-grid">
<div class="w3-address">
<div class="w3-address-grid">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('about-me') ) : ?>
<?php endif; ?>
<div class="clearfix"> </div>
</div>
<div class="w3-address-grid">
<div class="w3-address-right">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('my-archives') ) : ?>
<?php endif; ?>
</div>
<div class="clearfix"> </div>
</div>
<div class="w3-address-grid">
<div class="w3-address-left">
<i class="fa fa-map-marker" aria-hidden="true"></i>
</div>
<div class="w3-address-right">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('my-categories') ) : ?>
<?php endif; ?>
</div>
<div class="clearfix"> </div>
</div>
</div>
</div>
<div class="col-md-4 w3-agile-grid">
<div class="w3ls-post-grids">
<div class="w3ls-post-grid">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('last-post') ) : ?>
<?php endif; ?>
<div class="clearfix"> </div>
</div>
</div>
</div>
<div class="col-md-4 w3-agile-grid">
<div class="w3-address">
<div class="w3-address-grid">
<!-- search -->
<div class="subscribe">
<div class="w3-capella-search-form">
<form action="#" method="post">
<input type="text" placeholder="Search" name="Search" required="">
<button class="btn2"><i class="fa fa-search" aria-hidden="true"></i></button>
</form>
</div>
</div>
<!-- search -->
<div class="clearfix"> </div>
</div>
<div class="w3-address-grid">
<div class="w3-address-right">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('my-tags') ) : ?>
<?php endif; ?>
</div>
<div class="clearfix"> </div>
</div>
<div class="w3-address-grid">
<div class="w3-address-right one tweet">
<h6>Tweets</h6>
<ul>
<li>
<a href="#"><i class="fa fa-twitter"></i>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accus.
<i>http//example.com</i></a>
<span>About 15 minutes ago<span>
</span></span></li>
<li>
<a href="#"> <i class="fa fa-twitter"></i>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit.
<i>http//example.com</i></a>
<span>About a day ago<span>
</span></span></li>
<li>
<a href="#"><i class="fa fa-twitter"></i>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accus.
<i>http//example.com</i></a>
<span>About 15 minutes ago<span>
</span></span></li>
<li>
<a href="#"> <i class="fa fa-twitter"></i>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit.
<i>http//example.com</i></a>
<span>About a day ago<span>
</span></span></li>
</ul>
</div>
<div class="clearfix"> </div>
</div>
</div>
</div>
<div class="clearfix"> </div>
</div>
</div>
<div class="copyright">
<div class="container">
<p>© <?php echo date("Y") ?> Minimalist Blog Capella. All rights reserved</p>
</div>
</div>
</footer>
<?php wp_footer(); ?>
</body>
</html>
<file_sep>/content-page.php
<!-- breadcrumbs -->
<div class="breadcrumbs">
<div class="container">
<ol class="breadcrumb breadcrumb1">
<li><a href="index.html">Home</a></li>
<li class="active">Single Page</li>
</ol>
</div>
</div>
<!-- //breadcrumbs -->
<div class="container">
<div class="banner-btm-agile">
<!-- //btm-wthree-left -->
<div class="col-md-9 btm-wthree-left">
<div class="single-left text-justify">
<?php if ( has_post_thumbnail() ) {?>
<div class="single-left1">
<?php the_post_thumbnail(); ?>
<?php } else { ?>
<?php } ?>
<h3>Sed ut perspiciatis unde omnis iste natus error sit facilisis erat posuere erat</h3>
<p> <?php the_content(); ?></p>
</div>
</div>
</div>
<!-- //btm-wthree-left -->
<div class="clearfix"></div>
</div>
</div>
<file_sep>/content-single.php
<!-- breadcrumbs -->
<div class="breadcrumbs">
<div class="container">
<ol class="breadcrumb breadcrumb1">
<li><a href="index.html">Home</a></li>
<li class="active">Single Page</li>
</ol>
</div>
</div>
<!-- //breadcrumbs -->
<div class="container">
<div class="banner-btm-agile">
<!-- //btm-wthree-left -->
<div class="col-md-9 btm-wthree-left">
<div class="single-left text-justify">
<?php if ( has_post_thumbnail() ) {?>
<div class="single-left1">
<?php the_post_thumbnail(); ?>
<?php } else { ?>
<?php } ?>
<h3>Sed ut perspiciatis unde omnis iste natus error sit facilisis erat posuere erat</h3>
<ul>
<li><span class="glyphicon glyphicon-user" aria-hidden="true"></span><a href="#"><?php the_author_posts_link();;?></a></li>
<li><span class="glyphicon glyphicon-tag" aria-hidden="true"></span><a href="#"><?php the_category();?></a></li>
<li><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span><a href="<?php comments_link(); ?>">5 Comments</a></li>
</ul>
<p> <?php the_content(); ?></p>
</div>
<div class="comments">
<?php comments_template();?>
</div>
</div>
</div>
<!-- //btm-wthree-left -->
<div class="clearfix"></div>
</div>
</div>
<file_sep>/functions.php
<?php
// Add scripts and stylesheets
function startwordpress_scripts() {
wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6' );
wp_enqueue_style( 'style', get_template_directory_uri() . '/css/capella.css' );
wp_enqueue_style( 'awesome', get_template_directory_uri() . '/css/font-awesome.min.css' );
wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '3.3.6', true );
}
add_action( 'wp_enqueue_scripts', 'startwordpress_scripts' );
/*
==========================================
Activate menus
==========================================
*/
function capella_my_menu() {
register_nav_menu('header-menu',__( 'Header Menu' ));
}
add_action( 'init', 'capella_my_menu' );
// WordPress Titles
function startwordpress_wp_title( $title, $sep ) {
global $paged, $page;
if ( is_feed() ) {
return $title;
}
// Add the site name.
$title .= get_bloginfo( 'name' );
// Add the site description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) ) {
$title = "$title $sep $site_description";
}
return $title;
}
add_filter( 'wp_title', 'startwordpress_wp_title', 10, 2 );
// Custom settings
function custom_settings_add_menu() {
add_menu_page( 'Custom Settings', 'Custom Settings', 'manage_options', 'custom-settings', 'custom_settings_page', null, 99);
}
add_action( 'admin_menu', 'custom_settings_add_menu' );
// Create Custom Global Settings
function custom_settings_page() { ?>
<div class="wrap">
<h1>Custom Settings</h1>
<form method="post" action="options.php">
<?php
settings_fields('section');
do_settings_sections('theme-options');
submit_button();
?>
</form>
</div>
<?php }
// facebook
function setting_facebook() { ?>
<input type="text" name="facebook" id="facebook" value="<?php echo get_option('facebook'); ?>" />
<?php }
// twitter
function setting_twitter() { ?>
<input type="text" name="twitter" id="twitter" value="<?php echo get_option('twitter'); ?>" />
<?php }
// google
function setting_googleplus() { ?>
<input type="text" name="googleplus" id="googleplus" value="<?php echo get_option('googleplus'); ?>" />
<?php }
// linkedin
function setting_linkedin() { ?>
<input type="text" name="linkedin" id="linkedin" value="<?php echo get_option('linkedin'); ?>" />
<?php }
// instagram
function setting_instagram() { ?>
<input type="text" name="instagram" id="instagram" value="<?php echo get_option('instagram'); ?>" />
<?php }
function custom_settings_page_setup() {
add_settings_section('section', 'All Settings', null, 'theme-options');
add_settings_field('facebook', 'Facebook URL', 'setting_facebook', 'theme-options', 'section');
add_settings_field('twitter', 'Twitter URL', 'setting_twitter', 'theme-options', 'section');
add_settings_field('google', 'Google URL', 'setting_github', 'theme-options', 'section');
add_settings_field('linkedin', 'Linkedin URL', 'setting_facebook', 'theme-options', 'section');
add_settings_field('pinterest', 'Pinterest URL', 'setting_facebook', 'theme-options', 'section');
register_setting('section', 'facebook');
register_setting('section', 'twitter');
register_setting('section', 'google');
register_setting('section', 'linkedin');
register_setting('section', 'pinterest');
}
add_action( 'admin_init', 'custom_settings_page_setup' );
// Support Featured Images
add_theme_support( 'post-thumbnails' );
// Custom Post Type
function create_my_custom_post() {
register_post_type('my-custom-post',
array(
'labels' => array(
'name' => __('My Custom Post'),
'singular_name' => __('My Custom Post'),
),
'public' => true,
'has_archive' => true,
'supports' => array(
'title',
'editor',
'thumbnail',
'custom-fields'
)
));
}
add_action('init', 'create_my_custom_post');
/* Pagination*/
function pagination($prev = '«', $next = '»') {
global $wp_query, $wp_rewrite;
$wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;
$pagination = array(
'base' => @add_query_arg('paged','%#%'),
'format' => '',
'total' => $wp_query->max_num_pages,
'current' => $current,
'prev_text' => __($prev),
'next_text' => __($next),
'type' => 'plain'
);
if( $wp_rewrite->using_permalinks() )
$pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' );
if( !empty($wp_query->query_vars['s']) )
$pagination['add_args'] = array( 's' => get_query_var( 's' ) );
echo paginate_links( $pagination );
};
/* Widget Footer*/
/* Widget Footer About me */
register_sidebar(array(
'name'=> 'about-me',
'id' => 'about-me',
'description' => 'Widget about',
'before_widget' => '<div class="widget w3-agile-grid">',
'after_widget' => '</div>',
'before_title' => '<h5>',
'after_title' => '</h5>',
));
/*%1$s */
/* Widget Footer Last Post */
register_sidebar(array(
'name'=> 'Last post',
'id' => 'last-post',
'description' => 'Widget Last post',
'before_widget' => '<div class="widget w3ls-post-info">',
'after_widget' => '</div>',
'before_title' => '<h5>',
'after_title' => '</h5>',
));
/* Widget Footer Archives */
register_sidebar(array(
'name'=> 'Archives',
'id' => 'my-archives',
'description' => 'Widget My Archives',
'before_widget' => '<div class="widget w3ls-archives-my">',
'after_widget' => '</div>',
'before_title' => '<h5>',
'after_title' => '</h5>',
));
/* Widget Footer Tags */
register_sidebar(array(
'name'=> 'Tags',
'id' => 'my-tags',
'description' => 'Widget My Tags',
'before_widget' => '<div class="widget w3ls-tags-my">',
'after_widget' => '</div>',
'before_title' => '<h5>',
'after_title' => '</h5>',
));
/* Widget Footer Archives */
register_sidebar(array(
'name'=> 'Categories',
'id' => 'my-categories',
'description' => 'Widget My Categories',
'before_widget' => '<div class="widget w3ls-categories-my">',
'after_widget' => '</div>',
'before_title' => '<h5>',
'after_title' => '</h5>',
));
/*Function to Add Author Box*/
function add_author_box($content){
if( is_single() ) {
/*Editable*/
$img_ext = 'jpg'; //Replace this with png if you are using PNG images.
$img_size = 82; //Edit this value to change the author image size.
/*Getting author info*/
$auth_id = get_the_author_meta('ID'); //Get author ID.
$auth_name = get_the_author_meta('display_name'); // Get author name.
$auth_des = get_the_author_meta('description'); // Get author description.
$auth_page_url = get_author_posts_url($auth_id); //Get author Page URL.
$upload_dir = wp_upload_dir();
$uploads_folder_url = $upload_dir['url']; //uploads folder URL.
$uploads_folder_path = $upload_dir['path']; //uploads folder path.
$auth_avt = $uploads_folder_url.'/author'.$auth_id.'.'.$img_ext; //author image URL.
$auth_avt_path = $uploads_folder_path.'/author'.$auth_id.'.'.$img_ext; //author image path.
/*Check if user uploaded avatar exists*/
if(file_exists($auth_avt_path)){
$auth_img = '<img src="'. $auth_avt .'" width="'. $img_size .'" height="'. $img_size .'" >'; //If user uploaded avatar exists, use it in the display.
}else{$auth_img = get_avatar( $auth_id, $img_size ); //If user uploaded avatar does not exist use gavatar.
}
/*Output*/
$content .= "<div id='authorbox'><h3>Article by <a href='$auth_page_url'>$auth_name</a></h3> $auth_img $auth_des </div>";
}
return $content;
}
add_filter ( 'the_content', 'add_author_box', 0 );
/* Related Posts*/
/* Function to add related posts with thumb on single post pages */
function related_posts_with_thumb($content){
global $post;
if( is_single() ){
$rel_posts = '';
# 1. get category IDs of the current article and save to variable as an array.
$categories = get_the_category();
foreach($categories as $category){
$rel_cat[] = $category->cat_ID;
}
# 2. arguments for wp_query.
$rep_args = array(
'post__not_in' => array($post->ID), # don't display current post.
'category__in' => $rel_cat, # get posts within current categories.
'posts_per_page' => 4, # number of posts to display.
'orderby' => 'rand' # display random posts.
);
# 3. run the query.
$rep_query = new wp_query($rep_args);
# 4. if the query has posts start the loop.
if($rep_query->have_posts()){
while($rep_query->have_posts()) : $rep_query->the_post();
$rel_img = get_the_post_thumbnail($post->ID, 'thumbnail'); ## get featured image with default thumbnail size.
$rel_title = get_the_title(); # get post title.
$rel_link = get_permalink(); # get post link.
$rel_posts .= "<div id='content_rel_posts'> <a href='$rel_link'>$rel_img</a> <p><a href='$rel_link'> $rel_title </a></p></div>";
endwhile;
wp_reset_postdata();
}
# 5. Output.
$content .= "<h2 class='heading_rel_posts'>Related Articles</h2> $rel_posts";
}
return $content;
}
add_filter('the_content', 'related_posts_with_thumb', 2);<file_sep>/index.php
<?php get_header(); ?>
<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile; ?>
<!--Pagination-->
<!--<ul class="pagination myPagination">-->
<div class="row text-center">
<div class="col-lg-12">
<ul class="pagination">
<li><?php pagination('«', '»'); ?></li>
</ul>
</div>
<!-- subscribe -->
<div class="subscribe">
<div class="container">
<div class="w3-agileits-subscribe-form">
<form action="#" method="post">
<input type="text" placeholder="Subscribe" name="Subscribe" required="">
<button class="btn1">Subscribe</button>
</form>
</div>
</div>
</div>
<!-- //subscribe -->
</div>
<!--End Pagination-->
<?php endif; ?>
<?php get_footer(); ?>
|
386c834ec7cea052b372c8df1c2e391465b46962
|
[
"PHP"
] | 9 |
PHP
|
gabrielx3500/Capella-One
|
5952061433454a6d6e104b38b32a21b8c04ade85
|
da7afeaf201bcb2c5ea929949219c9e5f5e56dc8
|
refs/heads/master
|
<file_sep>package org.example.entities;
import lombok.Data;
@Data
public abstract class Employee {
private Integer id;
private String name;
private ContractType contractTypeName;
private Integer roleId;
private String roleName;
private String roleDescription;
private Long hourlySalary;
private Long monthlySalary;
private Long totalSalary;
public abstract void calculateTotalSalary();
}
<file_sep>package org.example.config;
import org.example.gateway.ClientGateway;
import org.example.usecase.ClientUseCase;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class UseCaseConfig {
@Bean
public ClientUseCase clientUseCase(ClientGateway clientGateway) {
return new ClientUseCase(clientGateway);
}
}
<file_sep>dependencies {
implementation project(':domain-model')
compile project(":driven-adapters-rest-repository")
implementation 'org.springframework:spring-context:5.2.0.RELEASE'
}<file_sep>package org.example.entities;
public class EmployeeMonthly extends Employee{
private static final Integer AMOUNT_MONTHS = 12;
@Override
public void calculateTotalSalary() {
this.setTotalSalary(this.getMonthlySalary() * AMOUNT_MONTHS);
}
}
<file_sep>package org.example.rest;
import org.example.rest.dto.EmployeeDto;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.web.client.RestTemplate;
@RunWith(MockitoJUnitRunner.class)
public class ClientMasGlobalTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private ClientMasGlobal clientMasGlobal;
@Test
public void getAllEmployeesRestTemplateTest() {
//arrange
//act
Mockito.when(restTemplate.getForObject(Mockito.anyString(), Mockito.eq(EmployeeDto[].class)))
.thenReturn(new EmployeeDto[]{});
//assert
Assert.assertEquals(0, clientMasGlobal.getEmployeeService().size());
Mockito.verify(restTemplate, Mockito.times(1)).getForObject(Mockito.anyString(), Mockito.eq(EmployeeDto[].class));
}
}
<file_sep>package org.example.usecase.testdatabuilder;
import org.example.entities.ContractType;
import org.example.entities.Employee;
import org.example.entities.EmployeeHourly;
public class HourlyEmployeeTestDataBuilder {
private Integer id;
private String name;
private ContractType contractTypeName;
private Integer roleId;
private String roleName;
private String roleDescription;
private Long hourlySalary;
private Long monthlySalary;
private Long totalSalary;
public HourlyEmployeeTestDataBuilder() {
this.id = 1;
this.name = "Berta";
this.contractTypeName = ContractType.HourlySalaryEmployee;
this.roleId = 1;
this.roleName = "Contractor";
this.roleDescription = "roleDescription";
this.hourlySalary = 10000L;
this.monthlySalary = 50000L;
this.totalSalary = 0L;
}
public HourlyEmployeeTestDataBuilder conId(Integer id) {
this.id = id;
return this;
}
public HourlyEmployeeTestDataBuilder conName(String name) {
this.name = name;
return this;
}
public HourlyEmployeeTestDataBuilder conContractTypeName(ContractType contractTypeName) {
this.contractTypeName = contractTypeName;
return this;
}
public HourlyEmployeeTestDataBuilder conRoleId(Integer roleId) {
this.roleId = roleId;
return this;
}
public HourlyEmployeeTestDataBuilder conRoleName(String roleName) {
this.roleName = roleName;
return this;
}
public HourlyEmployeeTestDataBuilder conRoleDescription(String roleDescription) {
this.roleDescription = roleDescription;
return this;
}
public HourlyEmployeeTestDataBuilder conHourlySalary(Long hourlySalary) {
this.hourlySalary = hourlySalary;
return this;
}
public HourlyEmployeeTestDataBuilder conMonthlySalary(Long monthlySalary) {
this.monthlySalary = monthlySalary;
return this;
}
public HourlyEmployeeTestDataBuilder conTotalSalary(Long totalSalary) {
this.totalSalary = totalSalary;
return this;
}
public Employee build() {
Employee employee = new EmployeeHourly();
employee.setId(this.id);
employee.setName(this.name);
employee.setContractTypeName(this.contractTypeName);
employee.setRoleId(this.roleId);
employee.setRoleName(this.roleName);
employee.setRoleDescription(this.roleDescription);
employee.setHourlySalary(this.hourlySalary);
employee.setMonthlySalary(this.monthlySalary);
employee.setTotalSalary(this.totalSalary);
return employee;
}
}
<file_sep>dependencies {
implementation project(':domain-model')
implementation 'org.springframework:spring-context:5.2.0.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-web'
}<file_sep>//plugins {
// id 'java'
//}
//
//group 'org.example'
//version '1.0-SNAPSHOT'
//
//repositories {
// mavenCentral()
//}
//
//dependencies {
// testCompile group: 'junit', name: 'junit', version: '4.12'
//}
buildscript {
ext {
springBootVersion = '2.2.5.RELEASE'
springCloudVersion = 'Greenwich.M1'
//2020.0.
springDependencyManagementVersion = '1.0.9.RELEASE'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/milestone" }
maven { url "https://repo.spring.io/snapshot" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
plugins {
id "org.sonarqube" version "2.6"
}
apply from: './main.gradle'
<file_sep>apply plugin: 'org.springframework.boot'
dependencies{
compile 'org.springframework.boot:spring-boot-starter'
implementation project(":domain-model")
implementation project(":domain-usecase")
implementation project(":entry-points-web")
implementation project(":driven-adapters-adapters-repository")
implementation project(":driven-adapters-rest-repository")
runtime('org.springframework.boot:spring-boot-devtools')
}<file_sep>FROM openjdk:8-jdk-alpine
WORKDIR /app
EXPOSE 8080
ARG JAR_FILE=build/libs/applications-hands.db-init.jar
COPY ${JAR_FILE} /app/handsOnTest.jar
ENTRYPOINT ["java","-jar","/app/handsOnTest.jar"]
<file_sep>package org.example.gateway;
import org.example.entities.Employee;
import java.util.List;
public interface ClientGateway {
List<Employee> getAllEmployees();
Employee getEmployee(Integer idEmployee);
}
<file_sep>package org.example.entities;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
public enum ContractType {
HourlySalaryEmployee("HourlySalaryEmployee"),
MonthlySalaryEmployee("MonthlySalaryEmployee");
private String contractType;
@Override
public String toString() {
return contractType;
}
}
|
8f12d881253cf81454b5c434a4cc8ddc43ffec9b
|
[
"Java",
"Dockerfile",
"Gradle"
] | 12 |
Java
|
gio96/HandsOnTestBack
|
aebc3dcb692876a838f590369d110e76de02126d
|
7fe6790e8eca41bfb9885f03ba1a707e547f7e98
|
refs/heads/master
|
<repo_name>kuldeep325/Group-6<file_sep>/main.js
"use strict";
//variables
const body = document.querySelector('body');
const cartBtn = document.querySelector(".cart-btn");
const closeCartBtn = document.querySelector(".close-cart");
const clearCartBtn = document.querySelector(".clear-cart");
const cartDOM = document.querySelector(".cart");
const cartOverlay = document.querySelector(".cart-overlay");
const cartItems = document.querySelector(".cart-items");
const cartTotal = document.querySelector(".cart-total");
const cartContent = document.querySelector(".cart-content");
const productsDOM = document.querySelector(".products-center");
const loginBtn = document.querySelector(".login-button")
const loginModal = document.querySelector('.login-modal')
const loginClose = document.querySelector('.login-close')
const forgotPass = document.querySelector('.pass');
const forgotPassClose = document.querySelector('.forgot-close')
const signupModal = document.querySelector(".signup_link");
const account = document.querySelector(".account_name");
const userName = document.querySelector(".userName");
const signoutbtn = document.querySelector('.signoutbtn');
const renderModalContent = document.querySelector('.modal-content')
// cart
let cart = [];
let buttonsDOM = [];
let loginStatus = false;
//end of test
// getting the products
class Products {
async getProducts() {
try {
let result = await fetch('./games.json', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
let data = await result.json();
let products = data.items;
products = products.map(item => {
const { id } = item.sys;
const { Title, Price, Release_date, Game_file_size, Genre, Description } = item.fields;
const image = item.fields.image.fields.file.url;
return { Title, Price, id, image, Release_date, Game_file_size, Genre, Description }
})
return products
} catch (error) {
document.write(`<h1 style="margin-top: 40vh; text-align: center">Sorry! <br>File not found${error}</h1>`)
console.log("File not found", error);
}
}
}
// display products
class UI {
displayProducts(products) {
let result = '';
products.forEach(product => {
result += `
<article id="p-scroll" class="product">
<div class="img-container">
<img src=${product.image} alt="product" class="product-img">
<div class="imageBtns">
<button class="info-btn" onclick="productModal(${product.id})" data-id=${product.id}>
<i class="fas fa-bars"></i>
</button>
</button>
<button class="bag-btn" data-id=${product.id}>
<i class="fas fa-shopping-cart"></i>
add to cart
</button>
</div>
</div>
<div class="product-tile">
<p>24/07/21</p>
<h3>${product.Title}</h3>
<h4>$${product.Price}</h4>
<p>${product.Genre}</p>
</div>
</article>
`
});
productsDOM.innerHTML = result;
}
addToCartBtns() {
const buttons = [...document.querySelectorAll('.bag-btn')];
buttonsDOM = buttons;
buttons.forEach(button => {
let id = button.dataset.id;
let inCart = cart.find(item => item.id === id);
if (inCart) {
button.innerText = "In- Cart";
button.disabled = true;
}
button.addEventListener('click', (e) => {
e.target.innerText = "In cart";
e.target.disabled = true;
// get product from products
let cartItem = { ...Storage.getProducts(id), amount: 1 };
// add the product to cart
cart = [...cart, cartItem]
// save cart in the local storage
Storage.saveCart(cart);
// set cart values
this.setCartValues(cart);
// display cart item
this.addCartItem(cartItem)
//show the cart
this.showCart();
})
});
}
setCartValues(cart) {
let tempTotal = 0;
let itemsTotal = 0;
cart.map(item => {
tempTotal += item.Price * item.amount;
itemsTotal += item.amount
})
cartTotal.innerText = parseFloat(tempTotal.toFixed(2));
cartItems.innerText = itemsTotal;
}
addCartItem(item) {
const div = document.createElement('div');
div.classList.add('cart-item');
div.innerHTML = `
<img src=${item.image}>
<div>
<h4>${item.Title}</h4>
<h5>$${item.Price}</h5>
<span class="remove-item" data-id=${item.id}>remove</span>
</div>
<div>
<i class="fas fa-chevron-up" data-id=${item.id}> </i>
<p class="item-amount">${item.amount}</p>
<i class="fas fa-chevron-down" data-id=${item.id}></i>
</div>
`
cartContent.appendChild(div);
}
showDescModal() {
}
showCart() {
if (loginStatus) {
cartOverlay.classList.add('transparentBcg');
cartDOM.classList.add('showCart');
body.style.overflow = "hidden"
} else {
login();
}
}
setupAPP() {
cart = Storage.getCart();
this.setCartValues(cart);
this.populateCart(cart);
cartBtn.addEventListener('click', this.showCart);
closeCartBtn.addEventListener('click', this.hideCart)
}
populateCart(cart) {
cart.forEach(item => this.addCartItem(item));
}
hideCart() {
cartOverlay.classList.remove("transparentBcg");
cartDOM.classList.remove("showCart");
body.style.overflow = "auto"
}
cartLogic() {
clearCartBtn.addEventListener('click', () => {
this.clearCart();
});
cartContent.addEventListener('click', event => {
if (event.target.classList.contains('remove-item')) {
let removeItem = event.target;
let id = removeItem.dataset.id;
cartContent.removeChild
(removeItem.parentElement.parentElement);
this.removeItem(id);
}
else if (event.target.classList.contains('fa-chevron-up')) {
let addAmount = event.target;
let id = addAmount.dataset.id;
let tempItem = cart.find(item => item.id === id);
tempItem.amount = tempItem.amount + 1;
Storage.saveCart(cart);
this.setCartValues(cart);
addAmount.nextElementSibling.innerHTML = tempItem.amount;
}
else if (event.target.classList.contains('fa-chevron-down')) {
let lowerAmount = event.target;
let id = lowerAmount.dataset.id;
let tempItem = cart.find(item => item.id === id);
tempItem.amount = tempItem.amount - 1;
if (tempItem.amount > 0) {
Storage.saveCart(cart);
this.setCartValues(cart);
lowerAmount.previousElementSibling.innerText = tempItem.amount;
} else {
cartContent.removeChild(lowerAmount.parentElement.parentElement);
this.removeItem(id)
}
}
})
}
clearCart() {
let cartItems = cart.map(item => item.id);
cartItems.forEach(id => this.removeItem(id));
cartContent.innerHTML = ""
this.hideCart()
}
removeItem(id) {
cart = cart.filter(item => item.id !== id);
this.setCartValues(cart);
Storage.saveCart(cart);
let button = this.getSingleButton(id);
button.disabled = false;
button.innerHTML = `<i class="fas fa-shopping-cart"></i>add to cart`
}
getSingleButton(id) {
return buttonsDOM.find(button => button.dataset.id === id);
}
}
// local storage
class Storage {
static saveProducts(products) {
localStorage.setItem("products", JSON.stringify(products))
}
static getProducts(id) {
let products = JSON.parse(localStorage.getItem('products'));
return products.find(product => product.id === id)
}
static saveCart(cart) {
localStorage.setItem('cart', JSON.stringify(cart))
}
static getCart() {
return localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : []
}
}
document.addEventListener("DOMContentLoaded", () => {
const ui = new UI()
const products = new Products();
ui.setupAPP();
products.getProducts().then(products => {
ui.displayProducts(products)
Storage.saveProducts(products)
}).then(() => {
ui.addToCartBtns();
ui.cartLogic()
})
})
// log in
$(document).ready(function () {
$("#signup-form").submit(function () {
var nm1 = $("#name1").val().trim();
var ps1 = $("#pass1").val().trim();
var email = $("#email").val().trim();
var ps1confirm = $("#confirmPass").val().trim();
var patternEmail = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
var patternUsername = /^[A-Za-z0-9]{3,30}$/;
var patternPassword = /^[<PASSWORD>!@#$%^&*]{6,20}$/;
var isValid = true;
if (email == "") {
document.querySelector('.signup-error').style.display = "block";
document.querySelector('.signup-error').innerHTML = "Email is Required";
setTimeout(function () {
document.querySelector('.signup-error').style.display = "none"
}, 3000)
isValid = false;
}
else if (!patternEmail.test(email)) {
document.querySelector('.signup-error').style.display = "block";
document.querySelector('.signup-error').innerHTML = "Invalid Email";
setTimeout(function () {
document.querySelector('.signup-error').style.display = "none"
}, 3000)
isValid = false;
}
if (isValid) {
if (nm1 == "") {
document.querySelector('.signup-error').style.display = "block";
document.querySelector('.signup-error').innerHTML = "Name Required";
setTimeout(function () {
document.querySelector('.signup-error').style.display = "none"
}, 3000)
isValid = false;
}
else if (!patternUsername.test(nm1)) {
document.querySelector('.signup-error').style.display = "block";
document.querySelector('.signup-error').innerHTML = "Invalid Name";
setTimeout(function () {
document.querySelector('.signup-error').style.display = "none"
}, 3000)
isValid = false;
}
}
if (isValid) {
if (ps1 == "") {
document.querySelector('.signup-error').style.display = "block";
document.querySelector('.signup-error').innerHTML = "Password Required";
setTimeout(function () {
document.querySelector('.signup-error').style.display = "none"
}, 3000)
isValid = false;
}
else if (!patternPassword.test(ps1)) {
document.querySelector('.signup-error').style.display = "block";
document.querySelector('.signup-error').innerHTML = "Invalid Password. Length Should be atleast 6 Characters";
setTimeout(function () {
document.querySelector('.signup-error').style.display = "none"
}, 3000)
isValid = false;
}
else if (ps1 !== ps1confirm) {
document.querySelector('.signup-error').style.display = "block";
document.querySelector('.signup-error').innerHTML = "Passwords do not match";
setTimeout(function () {
document.querySelector('.signup-error').style.display = "none"
}, 3000)
isValid = false;
}
}
if (isValid) {
document.getElementById('signup-form').innerHTML = "";
document.getElementById('signupHead').innerHTML = `<p>Signup successful</p><br><p>Please login!</p> `
setTimeout(function () {
login()
}, 1500)
localStorage.setItem("username", nm1);
localStorage.setItem("password", ps1);
localStorage.setItem("email", email);
}
});
$("#login-form").submit(function () {
var enteredName = $("#name2").val();
var enteredPass = $("#pass2").val();
var storedName = localStorage.getItem("username");
var storedPass = localStorage.getItem("password");
if (enteredName == storedName && enteredPass == storedPass) {
loginBtn.style.display = "none";
account.style.display = "flex";
userName.innerHTML = enteredName;
loginStatus = true;
closeLogin();
}
else {
document.querySelector('.error').style.display = "block"
setTimeout(function () {
document.querySelector('.error').style.display = "none"
}, 3000)
}
});
$("#forgotPassword").submit(function () {
var RegisteredEmail = localStorage.getItem("email")
var ForgotPassEmail = $("#forgotPasswordEmail").val();
if (ForgotPassEmail == RegisteredEmail) {
document.querySelector('.displayMsg').innerHTML = "password has been sent to your email!"
setTimeout(function () {
closeForgotPass();
}, 1200)
} else {
document.querySelector('.displayMsg').innerHTML = ForgotPassEmail, "Please check your Email and try again!"
}
})
});
// event click
loginBtn.addEventListener("click", login);
signupModal.addEventListener("click", signUp);
forgotPass.addEventListener('click', forgotPassModal);
signoutbtn.addEventListener('click', signout)
// event close
loginClose.addEventListener("click", closeLogin);
document.querySelector('.signup-close').addEventListener("click", closesignUp);
forgotPassClose.addEventListener("click", closeForgotPass);
// close modal
function closeLogin() {
loginModal.style.display = "none";
document.querySelector('.pass-modal').style.display = "none";
body.style.overflow = "auto";
document.querySelector('.products').style.display = 'block';
}
function closeForgotPass() {
document.querySelector('.pass-modal').style.display = "none";
body.style.overflow = "auto";
document.querySelector('.products').style.display = 'block';
}
function closesignUp() {
document.querySelector('.signup-modal').style.display = "none";
body.style.overflow = "auto";
document.querySelector('.products').style.display = 'block';
}
// login modal
function login() {
loginModal.style.display = "flex";
document.querySelector('.signup-modal').style.display = "none";
body.style.overflow = "hidden";
document.querySelector('.products').style.display = 'none';
}
//
function signUp() {
body.style.overflow = "none";
loginModal.style.display = "none";
document.querySelector('.pass-modal').style.display = "none";
document.querySelector('.products').style.display = 'none';
document.querySelector('.signup-modal').style.display = "flex";
}
// forgot pass modal
function forgotPassModal() {
loginModal.style.display = "none";
document.querySelector('.pass-modal').style.display = "flex";
}
function signout() {
loginBtn.style.display = "flex";
account.style.display = "none";
loginStatus = false;
}
// Description modal
var btn = document.querySelector(".info-btn");
var modal = document.getElementById("modal-description");
var closeIcon = document.querySelector(".close");
// btn.onclick = descriptionModalShow;
closeIcon.onclick = descriptionModalClose;
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
function descriptionModalShow() {
modal.style.display = "flex";
}
function descriptionModalClose() {
modal.style.display = "none";
}
function productModal(elementId) {
const products = new Products();
const singleProduct = [];
products.getProducts().then((allProducts) => {
for (let i = 0; i < allProducts.length; i++) {
if (allProducts[i].id == elementId) {
// singleProduct.push(allProducts[i]);
console.log('allProducts[i]', allProducts[i]);
const productID = allProducts[i].id;
const productTitle = allProducts[i].Title;
const productDesc = allProducts[i].Description;
const productImage = allProducts[i].image;
const productPrice = allProducts[i].price;
const productSize = allProducts[i].Game_file_size;
let result = "";
result += `
<span class="close" onclick="descriptionModalClose()">×</span>
<h2 class="titleDescrition">${productTitle}</h2>
<div class="details">
<img src=${productImage} alt="">
<div class="content">
<h4>Description:</h4>
<br>
<p>${productDesc}</p>
<br>
<h4>Size: <span class="size">${productSize}</span></h4>
</div>
</div>
`
renderModalContent.innerHTML = result;
}
}
})
// console.log('singleProduct', singleProduct);
// let abc = singleProduct && singleProduct.map((a) => a.id);
// console.log('abc', abc);
descriptionModalShow();
}
<file_sep>/README.md
# Group-6
Collaborative work of three people for developing a gaming e-commerce website.
# Start
install http development server, to run web page from a web server, due to browser security restrictions:
Steps:
1. install node js.
2. npm install -g http-server
3. http-server.
|
20f8fac7ece92a5c1b5ae2cd408ab91eb3f32cb7
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
kuldeep325/Group-6
|
b79851e371231d3d19718883b3bec0d8dd748141
|
69c1c56ab91d2b75d3e6ca2721f58bb8bc764924
|
refs/heads/main
|
<repo_name>tsksila/Ru-Planner-Frontend<file_sep>/src/pages/Register/register.js
import React, { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { api_url } from "../../configs/api";
import axios from "axios";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import {
TextField,
Input,
Typography,
InputAdornment,
IconButton,
} from "@material-ui/core";
import Autocomplete from "@material-ui/lab/Autocomplete";
import Swal from "sweetalert2";
import Visibility from "@material-ui/icons/Visibility";
import VisibilityOff from "@material-ui/icons/VisibilityOff";
import { useHistory } from "react-router-dom";
import { CircularProgress } from "@material-ui/core";
const regexText = /^[ก-๏sa-zA-Z]+$/u;
const SignupSchema = yup.object().shape({
firstName: yup
.string()
.required("กรุณากรอกข้อมูล")
.matches(regexText, "กรุณากรอกแต่ตัวอักษรเท่านั้น"),
lastName: yup
.string()
.required("กรุณากรอกข้อมูล")
.matches(regexText, "กรุณากรอกแต่ตัวอักษรเท่านั้น"),
password: yup
.string()
.required("กรุณากรอกข้อมูล")
.matches(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#:$%:^&:*])(?=.{6,})/,
"รหัสผ่านต้องประกอบด้วย ตัวพิมพ์เล็ก พิมพ์ใหญ่ ตัวเลข อักขระพิเศษ และมากกว่า 6 ตัวอักษร"
),
passwordConfirmation: yup
.string()
.oneOf([yup.ref("password"), null], "กรุณากรอกรหัสผ่านให้ตรงกัน"),
universityData: yup
.string()
.required("กรุณากรอกข้อมูล")
.matches(regexText, "กรุณากรอกแต่ตัวอักษรเท่านั้น"),
facultyData: yup
.string()
.required("กรุณากรอกข้อมูล")
.matches(regexText, "กรุณากรอกแต่ตัวอักษรเท่านั้น"),
majorData: yup
.string()
.required("กรุณากรอกข้อมูล")
.matches(regexText, "กรุณากรอกแต่ตัวอักษรเท่านั้น"),
});
var university_id = null;
var faculty_id = null;
var major_id = null;
function Register() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: yupResolver(SignupSchema),
});
const [university, setUniversity] = useState([]);
const [faculty, setFaculty] = useState([]);
const [majors, setMajors] = useState([]);
const [disable, setDisable] = useState(true);
const [disableMajor, setDisableMajor] = useState(true);
const [loading, setLoading] = useState(false);
//------ Show / Hide Password ------
const [values, setValues] = useState({
showPassword: false,
});
const [valuesRe, setValuesRe] = useState({
showPassword: false,
});
const handleMouseDownPassword = (event) => {
event.preventDefault();
};
const history = useHistory();
function getUniversityAPI() {
axios
.get("https://ruplanner.herokuapp.com/universities")
.then((res) => {
// console.log(res.data);
setUniversity(res.data);
})
.catch((error) => {
console.log(error);
});
}
function getfacultiesAPI_1(params) {
axios
.get( api_url +"/faculties?university=" + params)
.then((res) => {
//console.log(res.data);
setFaculty(res.data);
})
.catch((error) => {
console.log(error);
});
}
function getMajorsAPI_1(params) {
axios
.get(api_url +"/majors?faculty=" + params)
.then((res) => {
// console.log("-------------------------------");
// console.log(res.data);
setMajors(res.data);
// console.log("ลองเข้าสุดท้าย");
// console.log(university_id);
// console.log(faculty_id);
})
.catch((error) => {
console.log(error);
});
}
useEffect(() => {
getUniversityAPI();
}, []);
const onSubmit = async (data) => {
alert(JSON.stringify(data));
setLoading(true);
console.log("onSubmit");
if (university_id !== null) {
// console.log("มีมหาลัยนีเแล้วจ้าาา");
// console.log("2. university ID = ", university_id);
} else {
// console.log("ไม่มหาลัยนี้ !!!!!!");
// console.log("2. university ID = ", data.universityData);
await axios
.post(api_url +"/universities", {
uni_name: data.universityData,
})
.then((res) => {
// console.log("****** ลงทะเบียนมหาวิทยาลัยสำเร็จ ********");
// console.log("Data = ", JSON.stringify(res.data));
// console.log("Data ID = ", JSON.stringify(res.data._id));
university_id = res.data._id;
})
.catch((error) => {
if (error.response) {
console.log("error.response" + error.response);
} else if (error.request) {
console.log("error.request" + error.request);
} else if (error.message) {
console.log("error.message" + error.message);
}
});
}
if (faculty_id !== null) {
// console.log("มีคณะนีเแล้วจ้า");
// console.log("2. faculty ID = ", faculty_id);
} else {
//ถ้าไม่พบ ID คณะ จะทำการเพิ่ม คณะและ มหาลัยเข้าไป
// console.log("ไม่มีคณะนี้ !!!!!!");
// console.log("ชื่อคณะ : ", data.facultyData);
// console.log("รหัสมหาวิทยาลัย : ", university_id);
await axios
.post(api_url +"/faculties", {
fac_name: data.facultyData,
university: university_id,
})
.then((res) => {
// console.log("****** ลงทะเบียนคณะสำเร็จ ********");
// //console.log("Data = ", JSON.stringify(res.data));
// //console.log("Data ID = ", JSON.stringify(res.data._id));
// console.log("Data = ", res.data);
// console.log("Data ID = ", res.data._id);
faculty_id = res.data._id;
})
.catch((error) => {
if (error.response) {
console.log("error.response" + error.response);
} else if (error.request) {
console.log("error.request" + error.request);
} else if (error.message) {
console.log("error.message" + error.message);
}
});
}
console.log("*** major -----------");
if (major_id !== null) {
// ถ้าพบ ID major
// console.log("มีสาขานี้แล้วจ้าา");
} else {
//ถ้าไม่พบ ID คณะ จะทำการเพิ่ม คณะและ มหาลัยเข้าไป
// console.log("ไม่มีคณะนี้นะจ๊ะ !!!!!!");
// console.log("1.marjor : ", data.majorData);
// console.log("2.faculty : ", faculty_id);
await axios
.post(api_url +"/majors", {
maj_name: data.majorData,
faculty: faculty_id,
})
.then((res) => {
// console.log("****** ลงทะเบียนสาขาสำเร็จ ********");
// console.log("Data = ", res.data);
// console.log("Data ID = ", res.data._id);
// console.log("Data = ", JSON.stringify(res.data));
// console.log("Data ID = ", JSON.stringify(res.data._id));
major_id = res.data._id;
})
.catch((error) => {
if (error.response) {
console.log("error.response" + error.response);
} else if (error.request) {
console.log("error.request" + error.request);
} else if (error.message) {
console.log("error.message" + error.message);
}
});
}
await axios
.post(api_url +"/auth/local/register", {
username: data.firstName + " " + data.lastName,
email: data.email,
password: <PASSWORD>,
major: major_id,
})
.then((response) => {
setLoading(false);
// console.log("Well done!");
// console.log("User profile", response.data.user);
// console.log("Token", response.data.jwt);
Swal.fire({
position: "top-end",
icon: "success",
title: "ลงทะเบียนสำเร็จ",
showConfirmButton: false,
timer: 1500,
});
history.push("/login");
})
.catch((error) => {
if (error.response) {
console.log("error.response" + error.response);
let statusErr = error.response.status;
if (statusErr === 400) {
Swal.fire({
icon: "error",
title: "Oops...",
text: "อีเมลล์นี้ได้สมัครสมาชิกแล้ว",
});
}
} else if (error.request) {
console.log("error.request" + error.request);
} else if (error.message) {
console.log("error.message" + error.message);
}
});
};
return (
<div className="min-h-screen bg-blue-100 flex flex-col justify-center font-base ">
<form
onSubmit={handleSubmit(onSubmit)}
className="w-9/12 bg-white p-10 mx-auto rounded-3xl shadow-lg"
>
<div className="flex flex-wrap -mx-3 mb-6">
<div className="w-full px-3">
<label className="block uppercase tracking-wide text-gray-700 text-l mb-2">
อีเมล
</label>
<TextField
className="appearance-none block w-full bg-white text-gray-200 border border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"
type="email"
placeholder="<EMAIL>"
{...register("email", {
required: true,
})}
inputProps={{
style: { fontFamily: "Mitr" },
}}
/>
<span className="text-red-500 text-l italic">
{errors.email?.type === "required" && "กรุณากรอกอีเมล"}
</span>
</div>
</div>
<div className="flex flex-wrap -mx-3 mb-6">
<div className="w-full md:w-1/2 px-3">
<label className="block uppercase tracking-wide text-gray-700 text-l mb-2">
รหัสผ่าน
</label>
<Input
fullWidth
className="appearance-none block w-full bg-white text-gray-200 border border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"
type={values.showPassword ? "text" : "password"}
placeholder="******************"
{...register("password")}
style={{ padding: 0, border: 0 }}
endAdornment={
<InputAdornment position="end">
<IconButton
onClick={(handleClickShowPassword) => {
setValues({
...values,
showPassword: !values.showPassword,
});
}}
onMouseDown={handleMouseDownPassword}
>
{values.showPassword ? (
<Visibility fontSize="small" />
) : (
<VisibilityOff fontSize="small" />
)}
</IconButton>
</InputAdornment>
}
inputProps={{
style: { fontFamily: "Mitr", magin: "auto" },
}}
/>
<span className="text-red-500 text-l italic">
<span className="text-red-500 text-l italic">
{errors.password && <p>{errors.password.message}</p>}
</span>
</span>
</div>
<div className="w-full md:w-1/2 px-3">
<label className="block uppercase tracking-wide text-gray-700 text-l mb-2">
ยืนยันรหัสผ่าน
</label>
<Input
fullWidth
className="appearance-none block w-full bg-white text-gray-200 border border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"
type={valuesRe.showPassword ? "text" : "password"}
placeholder="******************"
{...register("passwordConfirmation")}
style={{ padding: 0, border: 0 }}
endAdornment={
<InputAdornment position="end">
<IconButton
onClick={(handleClickShowPassword) => {
setValuesRe({
...values,
showPassword: !valuesRe.showPassword,
});
}}
onMouseDown={handleMouseDownPassword}
>
{valuesRe.showPassword ? (
<Visibility fontSize="small" />
) : (
<VisibilityOff fontSize="small" />
)}
</IconButton>
</InputAdornment>
}
inputProps={{
style: { fontFamily: "Mitr", magin: "auto" },
}}
/>
<span className="text-red-500 text-l italic">
<span className="text-red-500 text-l italic">
{errors.passwordConfirmation && (
<p>{errors.passwordConfirmation.message}</p>
)}
</span>
</span>
</div>
</div>
<div className="flex flex-wrap -mx-3 mb-6">
<div className="w-full md:w-1/2 px-3 mb-6 md:mb-0">
<label className="block uppercase tracking-wide text-gray-700 text-l mb-2">
ชื่อ
</label>
<TextField
className="appearance-none block w-full bg-white text-gray-200 border border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"
placeholder="ราม"
{...register("firstName")}
inputProps={{
style: { fontFamily: "Mitr" },
}}
/>
<span className="text-red-500 text-l italic">
<span className="text-red-500 text-l italic">
{errors.firstName && <p>{errors.firstName.message}</p>}
</span>
</span>
</div>
<div className="w-full md:w-1/2 px-3">
<label className="block uppercase tracking-wide text-gray-700 text-l mb-2">
นามสกุล
</label>
<TextField
className="appearance-none block w-full bg-white text-gray-200 border border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"
placeholder="รักเรียน"
{...register("lastName")}
inputProps={{
style: { fontFamily: "Mitr" },
}}
/>
<span className="text-red-500 text-l italic">
<span className="text-red-500 text-l italic">
{errors.lastName && <p>{errors.lastName.message}</p>}
</span>
</span>
</div>
</div>
<div className="flex flex-wrap -mx-3 mb-6">
<div className="w-full px-3">
<label className="block uppercase tracking-wide text-gray-700 text-l mb-2">
มหาวิทยาลัย
</label>
<Autocomplete
id="combo-demo"
freeSolo
options={university}
renderOption={(option) => (
<Typography style={{ fontFamily: "Mitr" }}>
{option.uni_name}
</Typography>
)}
getOptionLabel={(option) => option.uni_name}
onChange={(event, value) => {
university_id = value;
if (value !== null) {
university_id = value._id;
getfacultiesAPI_1(university_id);
}
}}
renderInput={(params) => (
<TextField
className="appearance-none block w-full bg-white text-gray-200 border border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"
placeholder="รามคำแหง"
{...register("universityData")}
{...params}
inputProps={{
...params.inputProps,
style: { fontFamily: "Mitr" },
}}
onClick={() => setDisable(false)}
/>
)}
/>
<span className="text-red-500 text-l italic">
<span className="text-red-500 text-l italic">
{errors.university && <p>{errors.university.message}</p>}
</span>
</span>
</div>
</div>
<div className="flex flex-wrap -mx-3 mb-6">
<div className="w-full md:w-1/2 px-3">
<label className="block uppercase tracking-wide text-gray-700 text-l mb-2">
คณะ
</label>
<Autocomplete
id="combo-faculty"
freeSolo
disabled={disable}
options={faculty}
renderOption={(option) => (
<Typography style={{ fontFamily: "Mitr" }}>
{option.fac_name}
</Typography>
)}
getOptionLabel={(option) => option.fac_name}
onChange={(event, value) => {
faculty_id = value;
if (value !== null) {
faculty_id = value._id;
getMajorsAPI_1(faculty_id);
}
}}
renderInput={(params) => (
<TextField
className="appearance-none block w-full bg-white text-gray-200 border border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"
placeholder="วิทยาศาสตร์"
{...register("facultyData")}
{...params}
inputProps={{
...params.inputProps,
style: { fontFamily: "Mitr" },
}}
onChange={() => setDisableMajor(false)}
/>
)}
/>
<span className="text-red-500 text-l italic">
<span className="text-red-500 text-l italic">
{errors.faculty && <p>{errors.faculty.message}</p>}
</span>
</span>
</div>
<div className="w-full md:w-1/2 px-3 mb-6 md:mb-0">
<label className="block uppercase tracking-wide text-gray-700 text-l mb-2">
สาขา
</label>
<Autocomplete
id="combo-major"
freeSolo
disabled={disableMajor}
options={majors}
renderOption={(option) => (
<Typography style={{ fontFamily: "Mitr" }}>
{option.maj_name}
</Typography>
)}
getOptionLabel={(option) => option.maj_name}
onChange={(event, value) => {
major_id = value;
if (value !== null) {
major_id = value._id;
}
}}
renderInput={(params) => (
<TextField
className="appearance-none block w-full bg-white text-gray-200 border border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"
placeholder="วิทยาการคอมพิวเตอร์"
{...register("majorData")}
{...params}
inputProps={{
...params.inputProps,
style: { fontFamily: "Mitr" },
}}
/>
)}
/>
<span className="text-red-500 text-l italic">
<span className="text-red-500 text-l italic">
{errors.major && <p>{errors.major.message}</p>}
</span>
</span>
</div>
</div>
<div className="md:flex mt-6 justify-end ">
<button
className="bg-blue-500 hover:bg-blue-700 text-white rounded-xl py-2 px-4"
type="submit"
>
{loading ? (
<CircularProgress style={{ color: "#30BDFF" }} size={20} />
) : (
"สมัครสมาชิก"
)}
</button>
</div>
</form>
</div>
);
}
export default Register;
<file_sep>/src/pages/Community/PlanCommunity.js
import React, { useMemo, useState } from "react";
import styles from './table.css';
function StarRatingDemo({ count, value,
inactiveColor = '#ddd',
size = 24,
activeColor = '#f00', onChange }) {
// short trick
const stars = Array.from({ length: count }, () => '🟊')
// Internal handle change function
const handleChange = (value) => {
onChange(value + 1);
}
return (
<div>
{stars.map((s, index) => {
let style = inactiveColor;
if (index < value) {
style = activeColor;
}
return (
<span className={"star"}
key={index}
style={{ color: style, width: size, height: size, fontSize: size }}
onClick={() => handleChange(index)}>{s}</span>
)
})}
{value}
</div>
)
}
function Plan() {
// Get the rating from a db if required.
// The value 3 is just for testing.
const [rating, setRating] = useState(3);
const handleChange = (value) => {
setRating(value);
}
return (
<div>
<h2>Star Rating Demo</h2>
<StarRatingDemo
count={5}
size={40}
value={rating}
activeColor={'red'}
inactiveColor={'#ddd'}
onChange={handleChange} />
</div>
)
}
export default Plan;<file_sep>/src/pages/Profile/CreatePlan.js
import React, { useState, useEffect } from "react"
import {useHistory} from 'react-router-dom'
import {If,Else,Then} from 'react-if'
import {api_url} from '../../configs/api'
import Autocomplete, {
createFilterOptions,
} from "@material-ui/lab/Autocomplete"
import Cancel from "@material-ui/icons/CancelRounded"
import {CircularProgress} from '@material-ui/core';
import axios from "axios"
/* dialog */
import Swal from "sweetalert2"
const OPTIONS_LIMIT = 5
const defaultFilterOptions = createFilterOptions()
const SwalWithStyle = Swal.mixin({
customClass: {
title: "font-base",
confirmButton:"p-3 bg-blue-300 font-base rounded-xl focus:outline-none text-blue-800 ",
cancelButton: "p-3 ml-2 bg-red-300 font-base rounded-xl focus:outline-none text-red-800 ",
},
buttonsStyling: false,
});
function CreatePlan() {
const history = useHistory()
/** ข้อมูลรายวิชา ในเทอม*/
const [termSubj, setTermSubj] = useState([])
const [totalCredit, setTotalCredit] = useState(0)
/** ข้อมูล ปีและเทอม */
const [year, setYear] = useState('1')
const [term, setTerm] = useState('1')
/** ข้อมูล รายวิชาทั่งหมด */
const [subjectList, setSubjectList] = useState([])
/** ข้อมูลวิชา */
const [subjID ,setSubjID] = useState()
const [subjCode, setSubjCode] = useState()
const [subjName, setSubjName] = useState()
const [subjCredit, setSubjCredit] = useState()
const [termList, setTermList] = useState([])
const [planCredit, setPlanCredit] = useState(0)
const [planname , setPlanname] = useState()
const [loading , setLoading] = useState(false)
const [usePlan , setUsePlan] = useState(false)
const [newPlan , setnewPlan] = useState()
/** get all subject api */
useEffect(() => {
let mounted = true
axios.get(`${api_url}/subjects`).then((res) => {
if (mounted) {
setSubjectList(res.data);
}
})
return () => {
mounted = false
}
});
/** Total credit term */
useEffect(() => {
const reducer = termSubj.reduce(
(total, item) => total + item.subjCredit,
0
);
setTotalCredit(reducer);
}, [termSubj]);
/** Total credit plan */
useEffect(() => {
const reducer = termList.reduce((total, item) => {
return (
total + item.subject.reduce((total, subj) => total + subj.subjCredit, 0)
);
}, 0);
setPlanCredit(reducer);
termList.sort((a,b) => parseInt(a.year+a.term) - parseInt(b.year+b.term))
}, [termList]);
function add_new_subject(input) {
SwalWithStyle.fire({
title: 'เพิ่มวิชาใหม่',
text: 'กรุณากรอกรายละเอียดวิชา',
html:
'<table>'+
`<tr><td><lable>รหัสวิชา</lable></td><td><input id="swal-input1" value= ${input.toUpperCase()} class="swal2-input"></td></tr>`+
'<tr><td><lable>ชื่อวิชา </lable></td><td><input id="swal-input2" class="swal2-input"></td></tr>'+
'<tr><td><lable>หน่วยกิต</lable></td><td><input id="swal-input3" class="swal2-input"></td></tr>'+
'</table>' ,
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: 'เพิ่มวิชาใหม่',
showLoaderOnConfirm: true,
preConfirm: () => {
const subjCode = document.getElementById('swal-input1').value.toUpperCase()
const subjName = document.getElementById('swal-input2').value
const subjCredit = document.getElementById('swal-input3').value
if(!isNaN(subjCredit) && subjName !== '' && subjCode !== '') {
const body = {
subj_code : subjCode,
subj_fullname :subjName ,
subj_credit : subjCredit
}
axios.post(`${api_url}/subjects`,body, {
headers: { Authorization: 'Bearer ' + localStorage.getItem('accessToken') }
},)
.then((res) => {
console.log(res.data)
setSubjectList((prev) => [res.data , ...prev])
}).catch((err) => {
Swal.showValidationMessage(
`ผิดพลาด : ${err}`
)
})
}else {
Swal.showValidationMessage(
`กรุณากรอกข้อมูลให้ถูกต้องครบถ้วน`
)
}
},
allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
if (result.isConfirmed) {
Swal.fire({
position: 'center',
icon: 'success',
title: 'เพิ่มวิชาสำเร็จ!',
text : 'ขอบคุณที่ท่านเป็นส่วนหนึ่งในการช่วยพัฒนาชุมชนของเรา!' ,
showConfirmButton: false,
timer: 500
})
}
})
}
function set_subject(value) {
setSubjID(value ? value.id :'')
setSubjCode(value ? value.subj_code : "");
setSubjName(value ? value.subj_fullname : "");
setSubjCredit(value ? value.subj_credit : "");
}
function add_term_subject() {
if (subjCode || subjName || subjCredit !== "") {
const checkdupicate = termSubj.filter(
(subj) => subj.subjCode === subjCode
);
if (checkdupicate.length === 0) {
setTermSubj((prev) => [...prev, { subjID,subjCode, subjName, subjCredit }]);
} else {
const SwalWithStyle = Swal.mixin({
customClass: {
title: "font-base",
confirmButton:
"p-3 bg-blue-300 font-base rounded-xl focus:outline-none text-blue-800 ",
},
buttonsStyling: false,
});
SwalWithStyle.fire({
icon: "error",
title: "คุณมีวิชานี้อยู่ในรายการอยู่แล้ว!",
});
}
} else {
const SwalWithStyle = Swal.mixin({
customClass: {
title: "font-base",
confirmButton:
"p-3 bg-blue-300 font-base rounded-xl focus:outline-none text-blue-800 ",
},
buttonsStyling: false,
});
SwalWithStyle.fire({
icon: "error",
title: "กรุณากำหนดรายละเอียดวิชา!",
});
}
}
function remove_term_subject(code) {
setTermSubj((prev) => prev.filter((subj) => subj.subjCode !== code))
}
function add_plan_term() {
if (termSubj.length === 0) {
SwalWithStyle.fire({
icon: "warning",
title: "กรุณาเพิ่มวิชาในภาคเรียน!",
});
return;
}
setTermList((prev) => {
const checkdupicate = prev.filter(
(data) => data.year === year && data.term === term
);
if (checkdupicate.length === 0) {
return [...prev, { year, term, subject: termSubj }];
} else {
SwalWithStyle.fire({
icon: "error",
title: "มีภาคเรียนนี้อยู่แล้ว!",
});
return [...prev];
}
});
setTermSubj([]);
}
function remove_plan_term(select){
setTermList((prev) => prev.filter((term) => term !== select))
}
function add_new_plan() {
setLoading(true)
if(!planname) {
SwalWithStyle.fire({
icon: "error",
title: "กรุณากรอกชื่อแผนการเรียน!",
});
setLoading(false)
}else if (termList.length <= 0 ) {
SwalWithStyle.fire({
icon: "warning",
title: "กรุณาเพิ่มภาคการศึกษา!",
});
setLoading(false)
return
}
else{
let plan_id =""
const body = {
plan_name : planname,
user : localStorage.getItem('user_id')
}
/** create plan */
axios.post(`${api_url}/plans` , body , {
headers: { Authorization: 'Bearer ' + localStorage.getItem('accessToken') }
}).then( async (res) => {
plan_id = res.data.id
/** add term */
await Promise.all(termList.map( async(term) => {
const data ={
term_year : term.year ,
term_num : term.term ,
plan : plan_id ,
subjects : [...term.subject.map(item => item.subjID)]
}
await axios.post(`${api_url}/plan-terms` , data , {
headers: { Authorization: 'Bearer ' + localStorage.getItem('accessToken') }
}).then(({data})=> {
setnewPlan(data)
})
}))
setLoading(false)
setUsePlan(true)
})
}
}
function use_this_plan() {
const uid = localStorage.getItem('user_id')
setLoading(true)
if(newPlan) {
const body = {
select_plans : [newPlan.plan.id]
}
axios.put(`${api_url}/users/${uid}`,body,{
headers: { Authorization: 'Bearer ' + localStorage.getItem('accessToken') }
}).then((res)=> {
setLoading(false)
history.push('/profile/my-list')
}).catch((err) => {
setLoading(false)
SwalWithStyle.fire(({
icon: "error" ,
title : "มีบางอย่างผิดพลาด!"
}))
})
}
}
return (
<div className=" grid grid-cols-1 md:grid-cols-2 ">
{/** Add term */}
<div className="mx-auto w-full p-5 ">
<div className="w-full bg-white rounded-xl float-right shadow-lg text-sm">
{/** Head */}
<div className="h-10 bg-blue-300 rounded-t-xl flex items-center justify-end ">
<label className=" ml-2 mr-2">ปี</label>
<select
defaultValue={year}
onChange={(e) => setYear(e.target.value)}
className=" rounded-md focus:outline-none mr-2"
>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<label className=" ml-2 mr-2">เทอม</label>
<select
defaultValue={term}
onChange={(e) => setTerm(e.target.value)}
className=" rounded-md focus:outline-none mr-2"
>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">S</option>
</select>
</div>
{/** add subject field */}
<div className="flex flex-row bg-blue-100 p-3 ">
<div className="flex flex-col w-3/12 mr-1">
<label>รหัสวิชา</label>
<Autocomplete
id="sub-code"
getOptionSelected={(option, value) => option.subj_code === value.subj_code}
filterOptions={(options, params) => {
const filtered = defaultFilterOptions(options, params).slice(0, OPTIONS_LIMIT);
if (params.inputValue !== '') {
filtered.push({
inputValue: params.inputValue,
subj_code: `เพิ่ม "${params.inputValue}"`,
});
}
return filtered;
}
}
options={subjectList}
getOptionLabel={(option) => {
if ( typeof option === 'string') {
return option;
}
if (option.inputValue) {
return option.inputValue;
}
return option.subj_code;
}}
onChange={(event, value) => {
if (typeof value === 'string') {
console.log(typeof value)
} else if (value && value.inputValue) {
add_new_subject(value.inputValue)
} else {
set_subject(value)
}
}}
renderOption={(option) => option.subj_code}
renderInput={(params) => (
<div ref={params.InputProps.ref}>
<input
style={{
width: "100%",
borderRadius: "0.375rem",
paddingLeft: "0.5rem",
}}
type="text"
{...params.inputProps}
/>
</div>
)}
/>
</div>
<div className="flex flex-col w-8/12 mr-1">
<label>ชื่อวิชา</label>
<input
className="rounded-md focus:outline-none w-full pl-2"
defaultValue={subjName || ""}
/>
</div>
<div className="flex flex-col w-2/12">
<label>หน่วยกิต</label>
<input
type="number"
min={0}
className="rounded-md focus:outline-none w-full pl-2 "
defaultValue={subjCredit || ""}
/>
</div>
</div>
<div className="flex bg-blue-100 justify-end pb-2 pr-3">
<button
className="px-4 bg-white rounded-xl shadow-lg focus:shadow-none focus:outline-none"
onClick={add_term_subject}
>
เพิ่มวิชา
</button>
</div>
{/** Subject list */}
{termSubj.map((item, i) => {
return (
<div
className="m-2 h-8 bg-blue-100 rounded-md p-1 flex justify-between items-center "
key={i}
>
<div className="w-3/12 mr-1"> {item.subjCode} </div>
<div className="w-7/12 mr-1 truncate">{item.subjName}</div>
<div className=" w-1/12 mr-1"> {item.subjCredit} </div>
<div
className=" w-1/12 flex justify-end text-red-400 cursor-pointer mr-2 hover:text-red-600 "
onClick={() => remove_term_subject(item.subjCode)}
>
<Cancel />
</div>
</div>
);
})}
{/** Add term */}
<div className="bg-blue-300 h-10 rounded-b-xl flex items-center justify-between p-2">
<div className="p-1 rounded-md bg-white flex items-center">หน่วยกิต : {`${totalCredit}`} </div>
<button
className=" px-4 bg-white rounded-xl shadow-lg focus:shadow-none focus:outline-none "
onClick={add_plan_term}
>
เพิ่มภาคเรียน
</button>
</div>
</div>
</div>
{/** Add Plan */}
<div className=" mx-auto w-full p-5 " style={{ height: "90vh" }} >
<div className="w-full bg-white rounded-xl float-right shadow-lg h-full flex flex-col justify-between ">
{/** Head */}
<div className="h-10 bg-blue-300 rounded-t-xl flex items-center justify-start ">
<label className=" ml-2 mr-2 w-2/12 ">ชื่อแผน</label>
<input className=" rounded-md focus:outline-none mr-5 pl-2 w-10/12" defaultValue={planname} onChange={(e) => setPlanname(e.target.value)} />
</div>
{/** Term list */}
<div className="h-full overflow-y-auto">
{termList.length === 0 ? (
<div className="text-xl flex justify-center text-gray-300 pt-5">
ไม่มีรายการ ..
</div>
) : (``)}
{termList.map((term, i) => (
<div className="bg-white rounded-lg border-2 border-blue-100 m-2" key={i} >
{/** term headder */}
<div className="bg-blue-200 h-8 rounded-t-lg pl-2 flex justify-between items-center">
<div>
<span>ปี {term.year}</span> <span>เทอม { term.term === '3' ? 'ฤดูร้อน' : term.term}</span>
</div>
<div className=" text-red-400 cursor-pointer mr-2 hover:text-red-600 " onClick={()=> remove_plan_term(term)}>
<Cancel />
</div>
</div>
{/** Subject list */}
{term.subject.map((subj, i) => (
<div className="m-2 h-8 bg-blue-100 rounded-md p-1 flex items-center " key={i}>
<div className="w-3/12 mr-1"> {subj.subjCode} </div>
<div className="w-7/12 mr-1 truncate">{subj.subjName}</div>
<div className=" w-1/12 mr-1"> {subj.subjCredit} </div>
</div>
))}
</div>
))}
</div>
{/** Add Plan */}
<div className="bg-blue-300 h-10 rounded-b-xl flex justify-between p-2 ">
<div className="p-2 rounded-md bg-white flex items-center">หน่วยกิตรวม : {`${planCredit}`}</div>
<If condition={usePlan} >
<Then>
<button
className=" w-40 px-4 bg-green-400 rounded-xl shadow-lg text-white border border-white focus:shadow-none focus:outline-none "
onClick={()=> use_this_plan()}
>
{loading ? ( <CircularProgress style={{'color': '#ffff'}} size={20} /> ) : "ใช้แผนนี้"}
</button>
</Then>
<Else>
<button className=" w-40 px-4 bg-white rounded-xl shadow-lg focus:shadow-none focus:outline-none " onClick={add_new_plan}>
{loading ? ( <CircularProgress style={{'color': '#30BDFF'}} size={20} /> ) : "สร้างแผนการเรียน"}
</button>
</Else>
</If>
</div>
</div>
</div>
</div>
)
}
export default CreatePlan;
<file_sep>/src/redux/store.js
import { configureStore } from "@reduxjs/toolkit";
import userReducer from './features/userSlice'
export const store = configureStore({
reducer: {
user: userReducer,
},
devTools: process.env.NODE_ENV !== 'production',
});
<file_sep>/src/pages/Shedule/Shedule.js
import React ,{useEffect ,useState} from 'react'
import { useForm } from "react-hook-form"
import {If ,Then ,Else} from 'react-if'
import {api_url} from '../../configs/api'
import ArrowBack from '@material-ui/icons/ArrowBackRounded'
import ArrowForward from '@material-ui/icons/ArrowForwardRounded'
import Add from '@material-ui/icons/AddCircleRounded'
import Fab from '@material-ui/core/Fab'
import {CircularProgress} from '@material-ui/core';
import Swal from "sweetalert2"
import axios from 'axios'
const SwalWithStyle = Swal.mixin({
customClass: {
title: "font-base",
confirmButton:"p-3 bg-blue-300 font-base rounded-xl focus:outline-none text-blue-800 ",
cancelButton: "p-3 ml-2 bg-red-300 font-base rounded-xl focus:outline-none text-red-800 ",
},
buttonsStyling: false,
})
function Shedule() {
const today = new Date()
const [modal, setModal] = useState(false);
const [load , setLoad] = useState(false)
const {
register,
handleSubmit,
formState: { errors },
} = useForm();
const onSubmitAddSheduel = async (e) => {
if(e.etime <= e.stime ) {
SwalWithStyle.fire({
icon:"warning",
title:"รูปแบบเวลาไม่ถูกต้อง" ,
text:"กรุณาระบุเวลาเริ่ม-สิ้นสุดอีกครั้ง"
})
setLoad(false)
}else{
setLoad(true)
const body = {
topic:e.topic ,
room :e.room ,
day : e.day ,
s_time :`${e.stime}:00` ,
e_time :`${e.etime}:00` ,
note : e.note ,
user : localStorage.getItem('user_id')
}
axios.post(`${api_url}/my-schedules`,body , {
headers: { Authorization: 'Bearer ' + localStorage.getItem('accessToken') }
}).then(res => {
console.log(res.data)
setLoad(false)
SwalWithStyle.fire({
position: 'center',
icon: 'success',
title: 'บันทึกรายการใหม่สำเร็จ',
showConfirmButton: false,
timer: 1000
})
}).catch(()=>{
setLoad(false)
})
}
}
function date () {
let Day = initDay.filter((day)=> day.id === today.getDay() )
let Month = initMonth.filter((month) => month.id === today.getMonth())
let Year = today.getFullYear()+543 // พศ
return (`${Day[0].lable} ${today.getDate()} ${Month[0].lable} ${Year}`)
}
useEffect(() => {
// document.getElementById(`T${today.getHours()}`).scrollIntoView({behavior: 'smooth'});
},[])
return (
<div className=" h-full relative bg-blue-100 flex flex-col ">
<div className=" md:h-full w-4/5 mx-auto my-5 rounded-2xl shadow-lg relative" style={{backgroundColor :'#F0F8FF' ,height: "88vh"}}>
{/** Head */}
<div className="bg-indigo-400 w-full h-12 rounded-t-2xl text-white flex justify-between ">
<select defaultValue='mon' className="text-sm my-2 ml-4 rounded-xl bg-white bg-opacity-25 w-21 pl-2 focus:outline-none focus:ring-2 focus:ring-white ">
{initDay.map((day ,i) => (<option key={i} className="bg-indigo-300 " value={day.value}>{day.lable}</option>))}
</select>
<div className="bg-white bg-opacity-25 rounded-xl m-2 text-sm flex items-center px-5"> {date()} </div>
<div className="flex items-center bg-white rounded-lg bg-opacity-25 my-2 mr-4">
<button className="rounded-l-lg mr-2 focus:outline-none focus:ring-2 focus:ring-white" ><ArrowBack/></button>
<button className="rounded-r-lg focus:outline-none focus:ring-2 focus:ring-white" ><ArrowForward/></button>
</div>
</div>
{/** Body */}
<div className="bg-white shadow-md m-3 rounded-lg" >
<div className="overflow-y-auto rounded-lg w-full h-full " style={{height: "80vh"}} >
<table className="w-full rounded-lg " >
<tbody >
{initTime.map ((time) =>
(
<tr className = " border-b-2 " id={`T${time.id}`} key={time.id}>
<th className="w-1/5 border-r-2 h-20 text-gray-500 font-light">{time.lable} น.</th>
<th className="w-4/5 h-20 pl-2 relative "> {time.note ? (<div className="w-11/12 h-28 absolute top-0 font-normal text-white bg-red-300 rounded-xl ">{time.note}</div>):""}</th>
</tr>
)
)}
</tbody>
</table>
</div>
</div>
{/** footer */}
<div className="absolute bottom-3 right-3" onClick={()=> setModal(true)}> <Fab color="primary" className="focus:outline-none" > <Add style={{ fontSize: 50 }} className="text-white"/> </Fab></div>
</div>
{/** modal */}
<div className={`bg-gray-800 bg-opacity-50 font-normal flex items-center justify-center absolute top-0 left-0 right-0 bottom-0 ${modal ? ``:`hidden`}`} id="schedulemodal" onClick={(e)=> e.target.id === 'schedulemodal' ? setModal(false) : setModal(true) }>
<form className="bg-white w-4/5 md:w-3/5 block rounded-xl p-10 absolute z-20 " onSubmit={handleSubmit(onSubmitAddSheduel)}>
<div className="text-xl mb-3 text-gray-500"> เพิ่มรายการ </div>
<div className="flex flex-col">
<label> หัวข้อ </label>
<input type='text' className="bg-blue-100 rounded-md focus:outline-none focus:ring focus:border-blue-300 pl-3" {...register("topic", { required: true })} />
<span className="text-xs font-light text-red-400">{errors.topic?.type === "required" && "กรุณากรอกหัวข้อ"}</span>
</div>
<div className=" flex flex-col mt-3 ">
<label> สถานที่ </label>
<input type='text' className="bg-blue-100 rounded-md focus:outline-none focus:ring focus:border-blue-300 pl-3" {...register("room", { required: true })} />
<span className="text-xs font-light text-red-400">{errors.room?.type === "required" && "กรุณากรอกห้องเรียน"}</span>
</div>
<div className=" w-full flex flex-col md:flex-row justify-between mt-3 relative">
<div className="w-full md:w-2/5 flex flex-col">
<label> ทุกวัน </label>
<select className="bg-blue-100 rounded-md h-6 pl-2 focus:outline-none " {...register("day", { required: true })}>
{initDay.map((day) => (<option value={day.id} key={day.id}>{day.lable}</option>))}
</select>
<span className="text-xs font-light text-red-400">{errors.day?.type === "required" && "กรุณาเลือกวัน"}</span>
</div>
<div className="w-full md:w-1/5 flex flex-col">
<label> เวลาเริ่ม </label>
<input type="time" defaultValue="06:00" min="06:00" max="24:00" className="bg-blue-100 rounded-md focus:outline-none focus:ring focus:border-blue-300 pl-3 " id="stime" {...register("stime", { required: true })}/>
<span className="text-xs font-light text-red-400">{errors.stime?.type === "required" && "กรุณาเลือกเวลาเริ่ม"}</span>
</div>
<div className="w-full md:w-1/5 flex flex-col">
<label> เวลาสิ้นสุด </label>
<input type="time" defaultValue="06:00" min="06:00" max="24:00" className="bg-blue-100 rounded-md focus:outline-none focus:ring focus:border-blue-300 pl-3 " id="etime" {...register("etime", { required: true })}/>
<span className="text-xs font-light text-red-400"> {errors.etime?.type === "required" && "กรุณาเลือกเวลาสิ้นสุด"} </span>
</div>
</div>
<div className="flex flex-col mt-2">
<label> จดบันทึก </label>
<textarea maxLength="100" type='text' className="bg-blue-100 rounded-md focus:outline-none focus:ring focus:border-blue-300 pl-3 " style={{ resize: 'none'}} {...register("note")} />
</div>
<div className="mt-3 flex justify-end">
<If condition={load}>
<Then>
<button className="bg-green-600 text-white px-5 py-1 shadow-lg focus:shadow-none rounded-lg focus:outline-none focus:ring focus:ring-green-200"><CircularProgress style={{'color': '#FFF'}} size={10}/></button>
</Then>
<Else>
<button type="submit" className="bg-green-600 text-white px-5 py-1 shadow-lg focus:shadow-none rounded-lg focus:outline-none focus:ring focus:ring-green-200">เพิ่ม</button>
</Else>
</If>
</div>
</form>
</div>
</div>
)
}
const initDay = [
{id:0 ,lable:"อาทิตย์" , value :"sun"},
{id:1 ,lable:"จันทร์" , value :"mon"},
{id:2 ,lable:"อังคาร" , value :"tue"},
{id:3 ,lable:"พุธ" , value :"wed"},
{id:4 ,lable:"พฤหัสบดี" ,value :"thu"},
{id:5 ,lable:"ศุกร์" , value :"fri"},
{id:6 ,lable:"เสาร์" , value :"sat"},
]
const initMonth = [
{id:1 ,lable:"มกราคม"},
{id:2 ,lable:"กุมภาพันธ์"},
{id:3 ,lable:"มีนาคม"},
{id:4 ,lable:"เมษายน"},
{id:5 ,lable:"พฤษภาคม"},
{id:6 ,lable:"มิถุนายน"},
{id:7 ,lable:"กรกฏาคม"},
{id:8 ,lable:"สิงหาคม"},
{id:9 ,lable:"กันยายน"},
{id:10 ,lable:"ตุลาคม"},
{id:11 ,lable:"พฤศจิกายน"},
{id:12 ,lable:"ธันวาคม"},
]
const initTime = [
{id:6 , lable :"6:00"},
{id:7 , lable :"7:00"},
{id:8 , lable :"8:00" ,note:"Note"},
{id:9 , lable :"9:00"},
{id:10 , lable :"10:00"},
{id:11 , lable :"11:00"},
{id:12 , lable :"12:00"},
{id:13 , lable :"13:00"},
{id:14 , lable :"14:00"},
{id:15 , lable :"15:00"},
{id:16 , lable :"16:00",note:"Note 2"},
{id:17 , lable :"17:00"},
{id:18 , lable :"18:00"},
{id:19 , lable :"19:00"},
{id:20 , lable :"20:00"},
{id:21 , lable :"21:00"},
{id:22 , lable :"22:00"},
{id:23 , lable :"23:00"},
{id:24 , lable :"24:00"},
]
export default Shedule
<file_sep>/src/pages/Community/Community.js
import React from "react";
import { Switch, Route, Link, Redirect, useLocation } from "react-router-dom";
import MunuButton from "../../components/MunuButton";
import Course from "../Community/CourseCommunity";
import Plan from "../Community/PlanCommunity";
function Community() {
const { pathname } = useLocation();
return (
<div className="min-h-screen bg-blue-100 flex flex-col ">
<div className="min-w-full p-2 mb-5">
<Link to={`/community/course-community`}>
<MunuButton
active={pathname === "/community/course-community" ? true : false}
name={"รายวิชา"}
/>
</Link>
<Link to={`/community/Plan`}>
<MunuButton
active={pathname === "/community/Plan" ? true : false}
name={"แผนการเรียน"}
/>
</Link>
</div>
<Switch>
<Route path="/community/course-community">
<Course />
</Route>
<Route path="/community/Plan">
<Plan />
</Route>
{/* <Route path="/profile">
<Redirect to="/community/course-community" />
</Route> */}
</Switch>
</div>
);
}
export default Community;
<file_sep>/src/pages/Profile/Profile.js
import React from "react";
import {
Switch,
Route,
Link,
Redirect , useLocation } from 'react-router-dom'
import MunuButton from "../../components/MunuButton";
import CreatePlan from './CreatePlan'
import MyList from './MyList'
function Profile() {
const {pathname} = useLocation()
return (
<div className="min-h-screen bg-blue-100 flex flex-col ">
<div className="min-w-full p-2 mb-5">
<Link to={`/profile/my-list`} >
<MunuButton
active={pathname === "/profile/my-list" ? true : false}
name={"รายการของฉัน"}
/>
</Link>
<Link to={`/profile/create-plan`} >
<MunuButton
active={pathname === "/profile/create-plan" ? true : false}
name={"สร้างแผนการเรียน"}
/>
</Link>
</div>
<Switch>
<Route path="/profile/my-list" > <MyList/> </Route>
<Route path="/profile/create-plan" > <CreatePlan/></Route>
<Route path="/profile">
<Redirect to="/profile/my-list" />
</Route>
</Switch>
</div>
);
}
export default Profile;
<file_sep>/src/pages/Login/login.js
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import {Link ,useHistory} from 'react-router-dom'
import {useDispatch} from 'react-redux'
import {login} from '../../redux/features/userSlice'
import {CircularProgress} from '@material-ui/core';
import axios from 'axios'
function Login() {
const [loading , setLoading] = useState(false)
const [checkUser , setCheckUser] = useState(true)
const history = useHistory()
const dispatch = useDispatch()
const {
register,
handleSubmit,
formState: { errors },
} = useForm();
const onSubmitLogin = async (e) => {
setLoading(true)
const {data} = await axios.post('https://ruplanner.herokuapp.com/auth/local',{
identifier: e.email,
password: <PASSWORD>
})
.catch(()=> {
setLoading(false)
setCheckUser(false)
})
dispatch(login({
accessToken : data.jwt ,
user_id : data.user.id ,
username : data.user.username,
loggedIn :true
}))
setLoading(false)
history.push('/')
}
function handelRemember (e) {
const email = document.getElementById('email').value
if(e.target.checked) {
localStorage.setItem('remember_email' , email)
localStorage.setItem('remember_me' , true)
}else {
localStorage.removeItem('remember_email')
localStorage.removeItem('remember_me' )
}
}
return (
<div className="min-h-screen bg-blue-100 flex flex-col justify-center ">
<div className="max-w-md w-full mx-auto">
{/** Delete on production */}
<div className="text-center font-base font-medium text-sm">
email : <EMAIL> <br></br>
pass : <PASSWORD>
</div>
</div>
<div className="max-w-md w-full mx-auto mt-4 bg-white p-8 rounded-3xl shadow-lg">
<form className="space-y-6" onSubmit={handleSubmit(onSubmitLogin)}>
<div>
<label className="text-l font-base text-gray-600 block"> อีเมล </label>
<input
type="text"
id="email"
defaultValue={localStorage.getItem('remember_email')}
{...register("email", { required: true })}
className="appearance-none block w-full bg-gray-100 text-gray-700 border border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white "
style={{borderColor : errors.email ? "red" : ""}}
/>
<div className="text-sm text-red-300 font-base">
{errors.email?.type === "required" && "กรุณากรอกชื่อผู้ใช้"}
{!checkUser ? 'ชื่อหรือรหัสผ่านไม่ถูกต้อง' :''}
</div>
</div>
<div>
<label className="text-l font-base text-gray-600 block"> พาสเวิร์ด </label>
<input
type="password"
defaultValue="<PASSWORD>"
{...register("password", { required: true })}
className="appearance-none block w-full bg-gray-100 text-gray-700 border border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"
style={{ borderColor : errors.password ? "red" : ""}}
/>
<div className="text-sm text-red-300 font-base">
{errors.password?.type === "required" && "<PASSWORD>"}
</div>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center">
<input
type="checkbox"
id="remember"
className="h-4 w-4 checked:bg-blue-600 checked:border-transparent"
onChange={(e)=> handelRemember(e)}
defaultChecked={localStorage.getItem('remember_me')? 'checked':''}
/>
<label htmlFor="" className="ml-2 text-sm text-gray-600 font-base" > จำชื่อผู้ใช้ </label>
</div>
<div>
<Link to="/"> <div href="" className="font-base font-medium text-sm text-gray-500" > ลืมรหัสผ่าน? </div> </Link>
</div>
</div>
<div>
<button
type="submit"
className="w-full items-center py-2 px-4 font-base text-white bg-green-500 hover:bg-green-800 focus:outline-none focus:ring-2 focus:ring-gray-600 focus:ring-opacity-50 rounded-lg "
>
{loading ? ( <CircularProgress style={{'color': '#fafafa'}} size={20} /> ) : "เข้าสู่ระบบ"}
</button>
</div>
</form>
<div className="flex items-end mt-5">
<Link to="/register"> <div className="font-base font-medium text-sm text-gray-800"> สมัครสมาชิก... </div> </Link>
</div>
</div>
</div>
);
}
export default Login;
<file_sep>/src/pages/Community/CourseCommunity.js
import React, { useState, useEffect } from "react";
import { api_url } from "../../configs/api";
import { CircularProgress } from "@material-ui/core";
import axios from "axios";
import Swal from "sweetalert2";
import styles from './table.css';
function Course() {
const [subjectList, setSubjectList] = useState([]);
const [subjectReviews, setSubjectReviews] = useState([]);
const [search, setSearch] = useState("");
const [loading, setLoading] = useState(true)
/** get all subject api */
//------------------------------- Rating ------------------------------------------
function StarRating({ count, value,
inactiveColor,
size,
activeColor, onChange }) {
// short trick
const stars = Array.from({ length: count }, () => '🟊')
// Internal handle change function
const handleChange = (value) => {
onChange(value + 1);
}
return (
<div>
{stars.map((s, index) => {
let style = inactiveColor;
if (index < value) {
style = activeColor;
}
return (
<span className={"star"}
key={index}
style={{ color: style, width: size, height: size, fontSize: size }}
onClick={() => handleChange(index)}>{s}</span>
)
})}
<div style={{ fontSize: "12px" }} >{value}</div>
</div>
)
}
const [rating, setRating] = useState();
const handleChange = (value) => {
setRating(value);
}
//------------------------------- END Rating ------------------------------------------
function getSubjectReviewsAPI() {
var sum = 0;
console.log("เรียก API Subject Reviews");
axios
//.get(`${api_url}/subject-reviews?subject=${parm}`)
.get(`${api_url}/subject-reviews`)
.then((res) => {
setSubjectReviews(res.data);
console.log(subjectReviews);
// subjectReviews.map((subjectReviews) => {
// console.log(subjectReviews);
// console.log("Rating : ", subjectReviews.rating);
// // sum = subjectReviews.rating+ subjectReviews.rating;
// // console.log("Sum : ",sum);
// // console.log("เข้าtReviews");
// // console.log(subjectReviews._id);
// // console.log(subjectReviews.rating);
// });
})
.catch((error) => {
console.log(error);
});
}
function getSubjectListAPI() {
axios
.get(`${api_url}/subjects`)
.then((res) => {
setSubjectList(res.data);
console.log(res.data);
setLoading(false);
// console.log(res.data[0].subject_reviews[0].rating);
// subjectList.map((subjectList) => {
// if (subjectList.subject_reviews.length > 0) {
// console.log("ต้น ---------------------------------");
// console.log(subjectList._id);
// console.log(getSubjectReviewsAPI(subjectList._id));
// console.log("--------------------------------- จบ");
// } else {
// console.log("ต้น else ---------------------------------");
// var t = subjectList.subject_reviews.rating;
// t = 0;
// console.log(t);
// console.log("---------------------------------else จบ");
// }
// });
})
.catch((error) => {
console.log(error);
});
}
useEffect(() => {
getSubjectListAPI();
getSubjectReviewsAPI();
}, []);
// for (let index = 0; index < array.length; index++) {
// const element = array[index];
// }
// if()
// console.log("TEST = ", subjectList[0].subject_reviews[0].rating);
//console.log("TEST = ", subjectList.subject_reviews[0].rating);
//const pro = [...subjectList, ...subjectReviews];
//const combined1 = subjectList.push(...subjectReviews);
return (
<div className="min-h-screen bg-blue-100 flex flex-col ">
<div className="min-w-full p-2 mb-5">
<div
className="mx-auto w-full p-5 font-base flex flex-col justify-between "
style={{ height: "100%" }}
>
<div className="w-full h-3/5 bg-white rounded-xl float-right shadow-lg text-sm flex flex-col justify-between ">
{/** Head */}
<div className="w-full h-10 rounded-t-xl bg-blue-300 flex items-center pl-3">
ชุมชนรายวิชา
</div>
<div className="flex flex-wrap flex-row bg-blue-100 p-5 ">
<div className="display-flex flex-row w-full pr-1 center">
<label>ค้นหารหัสวิชา</label>
<input
style={{
width: "88%",
height: "2.5rem",
borderRadius: "0.375rem",
paddingLeft: "1rem",
marginLeft:"1.2rem"
}}
type="text"
placeholder="Search here"
onChange={(e) => {
setSearch(e.target.value);
}}
/>
</div>
</div>
<div className=" md:w-auto justify-center" style={{ margin: "50px" }}>
<table className="w-full table-fixed content-start border-0 border-opacity-0 py-1" className={styles.table}>
<thead className="border-0 border-opacity-2 w-full mx-1">
<tr>
<th className="border-0 border-opacity-0 w-1/6 py-5">
รหัสวิชา
</th>
<th className="border-0 border-opacity-0 w-2/6 py-5">
ชื่อวิชา
</th>
<th className="border-0 border-opacity-0 w-1/6 py-5">
หน่วยกิต
</th>
<th className="border-0 border-opacity-0 w-1/6 py-5">
คะแนนรีวิว
</th>
<th className="border-0 border-opacity-0 w-1/6 py-5">
จำนวนรีวิว
</th>
</tr>
</thead>
<tbody className="px-8">
{/* ติด Error loading */}
{loading ? (<tr><td></td> <td></td> <td><div className=" Loader text-center md:w-auto justify-center "></div></td></tr>) : ""}
{subjectList
.filter((item) => {
if (search == "") {
return item;
} else if (
item.subj_code.toLowerCase().includes(search.toLowerCase())
) {
return item;
}
})
.map((item, index) => {
if (item.subject_reviews.length > 0) {
let max = item.subject_reviews.length;
console.log("Max : ", max);
for (let i = 0; i < max; i++) {
// const element = array[i]; subjectList[0].subject_reviews[0].rating
var sum = subjectList[index].subject_reviews[i].rating;
console.log("รอบ : ", i, " ", sum);
// const result = subjectList.reduce((total, subject_reviews) => total = total + subject_reviews.rating, 0);
// console.log("result : ", result);
}
//const result = data.reduce((total, currentValue) => total = total + currentValue.prix, 0);
// setRating(sum);
} else {
sum = 0;
// setRating(0);
}
return (
<tr
className="border-2 border-gray-900 hover:bg-blue-500 shadow-lg"
key={index}
>
<td className="py-4 text-center mt-24">
{item.subj_code}
</td>
<td className="py-4 mt-24">
{item.subj_fullname}
</td>
<td className="py-4 text-center mt-24" >
{item.subj_credit}
</td>
<td className="py-4 mt-24 text-center">
<StarRating
count={5}
size={16}
value={sum}
// value={rating}
activeColor={'#ffc107'}
inactiveColor={'#ddd'} //สีที่ไม่ถูกเลือก
//onChange={handleChange} //เปล่ยนค่าดาว
/>
</td>
<td className="py-4 mt-24 text-center"> {item.subject_reviews.length} </td>
</tr>
)
})
}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
);
}
export default Course;
<file_sep>/src/App.js
import React from "react";
import {Route, Switch ,Redirect } from "react-router-dom"
import Layout from "./components/Layout"
import PrivateRoute from './components/PrivateRoute'
import Login from "./pages/Login"
import Register from "./pages/Register"
import Logout from './pages/Logout'
import Profile from './pages/Profile'
import Shedule from './pages/Shedule'
import Community from './pages/Community'
function App() {
const withLayout = (Component) => (props) =>
(
<Layout>
<Component {...props} />
</Layout>
);
return (
<Switch>
<Route path="/login" component={Login} exact />
<Route path="/register" component={Register} />
<Route path="/logout" component={Logout} />
<PrivateRoute path="/profile" component={withLayout(Profile)} />
<PrivateRoute path="/community" component={withLayout(Community)} />
<PrivateRoute path="/shedule" component={withLayout(Shedule)} />
<PrivateRoute path="/">
<Redirect to="/profile" />
</PrivateRoute>
</Switch>
);
}
export default App;
<file_sep>/src/components/PrivateRoute.js
import React , {useEffect} from 'react'
import {Redirect, Route } from 'react-router-dom'
import {useDispatch} from 'react-redux'
import {logout} from '../redux/features/userSlice'
import * as JWT from 'jsonwebtoken'
/* dialog */
import Swal from 'sweetalert2'
const getExpFromToken = (token ) => {
const { exp } = Object(JWT.decode(token))
return exp
}
const sessionExprired = ()=>{
const SwalWithStyle = Swal.mixin({
customClass: {
title : 'font-base',
content :'font-base',
confirmButton: 'p-3 bg-blue-300 font-base text-blue-800',
},
buttonsStyling: false
})
SwalWithStyle.fire({
icon: 'error',
title: 'เซสชั่นหมดอายุ!',
})
}
function PrivateRoute({component : Component , ...rest}) {
const dispatch = useDispatch()
const loggedIn = localStorage.getItem('loggedIn')
const accessToken = localStorage.getItem('accessToken')
const currentTimeStamp = new Date().getTime().toString().substr(0 ,10)
const accessTokenExp = getExpFromToken(accessToken)
useEffect(() => {
if (currentTimeStamp >= accessTokenExp) {
sessionExprired()
dispatch(logout())
return
}
else if(!loggedIn) {
sessionExprired()
dispatch(logout())
return
}
})
return (
<Route {...rest} render={
(props) => (
loggedIn ? <Component {...props} /> :<Redirect to="/login" />
)
} />
)
}
export default PrivateRoute
<file_sep>/src/components/MunuButton.js
import React from 'react'
function MunuButton({active , name}) {
return (
<button className={`bg-white border font-base text-l mt-2 float-right p-2 w-56 mr-4 rounded-full focus:outline-none ${active ? `text-blue-500 border-purple-300`:`border-purple-600 text-blue-700 shadow-lg `} `}>
{name}
</button>
)
}
export default MunuButton
<file_sep>/src/components/Layout.js
import React , {useState ,useEffect} from 'react';
import Sidebar from "./Sidebar";
import MenuIcon from '@material-ui/icons/Menu';
function Layout({children}) {
const [show ,setShow] = useState(false);
function close (e) { setShow(false) }
useEffect(() => {
const resizeListener = () => {
// change width from the state object
setShow(false)
};
// set resize listener
window.addEventListener('resize', resizeListener);
// clean up function
return () => {
// remove resize listener
window.removeEventListener('resize', resizeListener);
}
}, [])
return (
<div className="flex min-h-screen ">
<div className='relative h-screen md:flex '>
<Sidebar show={show} close={close} />
</div>
<div className=" flex-1 h-screen justify-center ">
<div className='md:flex'>
<div className="bg-blue-300 text-gray-100 flex justify-between md:relative md:hidden">
<button className="mobile-menu-button p-4 focus:outline-none focus:bg-gray-700" onClick={()=> setShow(!show)} >
<MenuIcon />
</button>
<span className=' m-3 text-2xl flex justify-center'> <img alt="Planner" src={process.env.PUBLIC_URL + '/logo512.png' } className="h-10 rounded-full" /> </span>
</div>
</div>
{children}
</div>
</div>
);
}
export default Layout;<file_sep>/src/components/sidebar.js
import React from 'react'
import {Link ,useHistory ,useRouteMatch} from 'react-router-dom'
/** icon */
import EventIcon from '@material-ui/icons/Event';
import StorageIcon from '@material-ui/icons/Storage';
import ForumIcon from '@material-ui/icons/Forum';
import CloseIcon from '@material-ui/icons/CloseRounded';
/* dialog */
import Swal from 'sweetalert2'
function Sidebar({show ,close}) {
const history = useHistory()
const {path } = useRouteMatch()
/** customstyle sweet alert2 */
const SwalWithStyle = Swal.mixin({
customClass: {
title : 'font-base',
confirmButton: 'p-3 bg-blue-300 font-base mr-4 text-blue-800 ',
cancelButton: 'p-3 bg-red-300 font-base text-red-800 ',
},
buttonsStyling: false
})
const logout = () => {
SwalWithStyle.fire({
title: 'คุณต้องการออกจากระบบ ?',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'ยืนยัน!',
cancelButtonText:'ยกเลิก'
}).then((result) => {
if (result.isConfirmed) {
history.push('/logout')
}
})
}
const user = localStorage.getItem('username')
return (
<div className= {`side-bar w-64 font-base justify-center h-screen bg-white z-50 fixed top-0 inset-y-0 left-0 transform ${ show ? ``:`-translate-x-full`} md:relative md:translate-x-0 transition duration-200 ease-in-out `}>
<button className="text-blue-500 md:hidden float-right mb-5 focus:outline-none " onClick={close}><CloseIcon/></button>
{/* Logo */}
<img alt="Planner" src={process.env.PUBLIC_URL + '/logo512.png'} className="h-44 mt-5 mx-auto" />
<span className='mt-5 text-l flex justify-center w-full bg-blue-200 p-3'>Welcome : {user ? user: "ไม่มีผู้ใช้"}</span>
<nav className="mt-10 mx-4 px-1 pt-7 pb-40 " >
<Link to="/"> <div className={`flex items-center py-2 px-4 ${path === '/profile' ? 'bg-blue-200 bg-opacity-25 text-blue-900':'text-gray-500'} rounded-md`} ><StorageIcon className="mr-2"/> รายการของฉัน </div> </Link>
<Link to="/shedule"> <div className={`flex items-center py-2 px-4 ${path === '/shedule' ? 'bg-blue-200 bg-opacity-25 text-blue-900':'text-gray-500'} rounded-md`}><EventIcon className="mr-2"/> ตารางเรียน</div> </Link>
<Link to="/community"> <div className={`flex items-center py-2 px-4 ${path === '/community' ? 'bg-blue-200 bg-opacity-25 text-blue-900':'text-gray-500'} rounded-md`}><ForumIcon className="mr-2"/> ชุมชน </div> </Link>
</nav>
<div className="grid justify-items-center">
<button className=" border-light-blue-500 border-opacity-25 w-52 bg-blue-300 text-black p-2 rounded-xl focus:outline-none focus:bg-blue-500 focus:text-white" onClick={logout} >ลงชื่อออก</button>
</div>
</div>
)
}
export default Sidebar
<file_sep>/src/redux/features/userSlice.js
import {createSlice} from '@reduxjs/toolkit'
export const userSlice = createSlice({
name:'user' ,
initialState:{
user:null
},
reducers:{
login:(state ,action) => {
state.user = action.payload;
localStorage.setItem('user_id', action.payload.user_id)
localStorage.setItem('username', action.payload.username)
localStorage.setItem('accessToken', action.payload.accessToken)
localStorage.setItem('loggedIn', true)
},
logout:(state) => {
state.user = null;
localStorage.removeItem('user_id')
localStorage.removeItem('username')
localStorage.removeItem('accessToken')
localStorage.removeItem('loggedIn')
}
}
})
export const { login ,logout} = userSlice.actions
export const selectUser = (state) => state.user.user
export default userSlice.reducer<file_sep>/src/pages/Logout/Logout.js
import React ,{useEffect} from 'react'
import {useHistory} from 'react-router-dom'
import {logout} from '../../redux/features/userSlice'
import {useDispatch} from 'react-redux'
function Logout() {
const history = useHistory()
const dispatch = useDispatch()
useEffect (()=> {
dispatch(logout())
return history.push('/login')
})
return (<> Logout </>)
}
export default Logout
|
77070fc21790bda22701fc932df49f7069170126
|
[
"JavaScript"
] | 16 |
JavaScript
|
tsksila/Ru-Planner-Frontend
|
184877eeccc74cb0d81bb62c8e6622a6b3ea0866
|
0acbbbb4090a6790a98f5efbed0be0a17450a12b
|
refs/heads/master
|
<file_sep>class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
};
const has_path = function(root, sum) {
const stack = [{node: root, sum: 0}];
while (stack.length) {
const node = stack.pop();
const newSum = node.node.value + node.sum;
if (newSum === sum && !node.node.left && !node.node.right) {
return true;
}
if (node.node.left) {
stack.push({node: node.node.left, sum: newSum});
}
if (node.node.right) {
stack.push({node: node.node.right, sum: newSum});
}
}
return false;
};
var root = new TreeNode(12)
root.left = new TreeNode(7)
root.right = new TreeNode(1)
root.left.left = new TreeNode(9)
root.right.left = new TreeNode(10)
root.right.right = new TreeNode(5)
console.log(`Tree has path: ${has_path(root, 23)}`)
console.log(`Tree has path: ${has_path(root, 16)}`)
// ==================================================================
const find_paths = function(root, sum) {
const allPaths = [];
const stack = [{node: root, sum: 0, path: []}];
while (stack.length) {
const item = stack.pop();
const newSum = item.node.value + item.sum;
const newPath = [...item.path, item.node.value];
if (newSum === sum && !item.node.left && !item.node.right) {
allPaths.push(newPath);
}
if (item.node.left) {
stack.push({node: item.node.left, sum: newSum, path: newPath});
}
if (item.node.right) {
stack.push({node: item.node.right, sum: newSum, path: newPath});
}
}
return allPaths;
};
var root = new TreeNode(12)
root.left = new TreeNode(7)
root.right = new TreeNode(1)
root.left.left = new TreeNode(4)
root.right.left = new TreeNode(10)
root.right.right = new TreeNode(5)
find_paths(root, 23);
// ======
const find_sum_of_path_numbers = function(root) {
let sum = 0;
const stack = [{node: root, currNum: ""}];
while (stack.length) {
const {node, currNum} = stack.pop();
const newNum = currNum + node.value.toString();
if (!node.left && !node.right) {
sum += Number(newNum);
}
if (node.left) {
stack.push({node: node.left, currNum: newNum});
}
if (node.right) {
stack.push({node: node.right, currNum: newNum});
}
}
return sum;
};
var root = new TreeNode(1)
root.left = new TreeNode(0)
root.right = new TreeNode(1)
root.left.left = new TreeNode(1)
root.right.left = new TreeNode(6)
root.right.right = new TreeNode(5)
console.log(`Total Sum of Path Numbers: ${find_sum_of_path_numbers(root)}`)
// ==================
const find_path = function(root, sequence) {
const stack = [{node: root, remaining: sequence}];
while (stack.length) {
const {node, remaining} = stack.pop();
const num = remaining[0];
if (num !== node.value) {
continue;
}
const newRemaining = remaining.slice(1);
if (!newRemaining.length) {
if (!node.left && !node.right) {
return true;
}
continue;
}
if (node.left) {
stack.push({node: node.left, remaining: newRemaining});
}
if (node.right) {
stack.push({node: node.right, remaining: newRemaining});
}
}
return false;
};
var root = new TreeNode(1)
root.left = new TreeNode(0)
root.right = new TreeNode(1)
root.left.left = new TreeNode(1)
root.right.left = new TreeNode(6)
root.right.right = new TreeNode(5)
console.log(`Tree has path sequence: ${find_path(root, [1, 0, 7])}`)
console.log(`Tree has path sequence: ${find_path(root, [1, 1, 6])}`)
const count_paths = function(root, S) {
let numPaths = 0;
const stack = [{node: root, path: []}];
while (stack.length) {
const {node, path} = stack.pop();
path.push(node.value);
path.reduceRight((a, b) => {
if (a + b === S) {
numPaths++;
}
return a + b;
}, 0);
if (node.left) {
stack.push({node: node.left, path: [...path, node.value]});
}
if (node.right) {
stack.push({node: node.right, path: [...path, node.value]});
}
}
return numPaths;
};
var root = new TreeNode(12)
root.left = new TreeNode(7)
root.right = new TreeNode(1)
root.left.left = new TreeNode(4)
root.right.left = new TreeNode(10)
root.right.right = new TreeNode(5)
console.log(`Tree has paths: ${count_paths(root, 11)}`)
/*
12
7 1
4 10 5
8 9
*/
class TreeDiameter {
static find_diameter(node) {
let treeDiameter = 0;
function findHeight(node) {
if (!node) {
return 0;
}
const leftHeight = findHeight(node.left);
const rightHeight = findHeight(node.right);
let currDiameter = 1 + leftHeight + rightHeight;
treeDiameter = Math.max(treeDiameter, currDiameter);
return Math.max(leftHeight, rightHeight) + 1;
}
findHeight(node);
return treeDiameter;
}
};
// var root = new TreeNode(1)
// root.left = new TreeNode(2)
// root.right = new TreeNode(3)
// root.left.left = new TreeNode(4)
// root.right.left = new TreeNode(5)
// root.right.right = new TreeNode(6)
// TreeDiameter.find_diameter(root); //?
// root.left.left = null
// root.right.left.left = new TreeNode(7)
// root.right.left.right = new TreeNode(8)
// root.right.right.left = new TreeNode(9)
// root.right.left.right.left = new TreeNode(10)
// root.right.right.left.left = new TreeNode(11)
// TreeDiameter.find_diameter(root); //?
const find_maximum_path_sum = function(root) {
let globalMax = -Infinity;
function traverse(node) {
if (!node) {
return 0;
}
let maxLeft = traverse(node.left);
let maxRight = traverse(node.right);
globalMax = Math.max(globalMax, node.value + maxLeft + maxRight);
return node.value + Math.max(maxLeft, maxRight);
}
traverse(root);
return globalMax;
};
var root = new TreeNode(1)
root.left = new TreeNode(2)
root.right = new TreeNode(3)
console.log(`Maximum Path Sum: ${find_maximum_path_sum(root)}`)
root.left.left = new TreeNode(1)
root.left.right = new TreeNode(3)
root.right.left = new TreeNode(5)
root.right.right = new TreeNode(6)
root.right.left.left = new TreeNode(7)
root.right.left.right = new TreeNode(8)
root.right.right.left = new TreeNode(9)
console.log(`Maximum Path Sum: ${find_maximum_path_sum(root)}`)
root = new TreeNode(-1)
root.left = new TreeNode(-3)
console.log(`Maximum Path Sum: ${find_maximum_path_sum(root)}`)
<file_sep>// Get the total possible profit given a list of profits, a corresponding list of weights, and a total capacity of the knapsack
class KnapsackSolver {
constructor(profits, weights, capacity) {
this.capacity = capacity;
this.items = profits.map((profit, idx) => ({profit, weight: weights[idx]}));
}
getMaxProfit() {
let prevRow = new Array(this.capacity + 1).fill(0);
let currRow = [];
for (let item of this.items) {
for (let currWeight = 0; currWeight <= this.capacity; currWeight++) {
const includedProfit = item.weight > currWeight ? prevRow[currWeight] : item.profit + prevRow[currWeight - item.weight];
const excludedProfit = prevRow[currWeight];
currRow[currWeight] = Math.max(includedProfit, excludedProfit);
}
prevRow = currRow.slice();
}
return currRow[this.capacity];
}
}
const kp = new KnapsackSolver([ 4, 5, 3, 7 ], [ 2, 3, 1, 4 ], 5);
kp.getMaxProfit(); // 10
const kp2 = new KnapsackSolver([16, 1, 6, 10], [5, 1, 2, 3], 7);
kp2.getMaxProfit(); // 22
// ======================
function isEvenlyPartitionable(arr) {
const midway = arr.reduce((a, b) => a + b, 0) / 2;
if (Math.floor(midway) !== midway) {
return false;
}
let prev = new Array(midway).fill(false);
prev.unshift(true);
let curr = [];
for (let num of arr) {
for (let sum = 0; sum <= midway; sum++) {
const included = num <= sum && prev[sum - num];
const excluded = prev[sum];
curr[sum] = included || excluded;
}
prev = curr.slice();
}
return curr.pop();
}
isEvenlyPartitionable([1, 2, 3, 4]); // true
isEvenlyPartitionable([1, 1, 3, 4, 7]); // true
isEvenlyPartitionable([2, 3, 4, 6]); // false
// Given a set of positive numbers, determine if a subset exists whose sum is equal to a given number ‘S’.
function hasSubsetSum(nums, total) {
let prev = new Array(total).fill(false);
prev.unshift(true);
let curr = [];
for (let num of nums) {
for (let sum = 0; sum <= total; sum++) {
const included = num <= sum && prev[sum - num];
const excluded = prev[sum];
curr[sum] = included || excluded;
}
if (curr[curr.length - 1]) {
return true;
}
prev = curr.slice();
}
return curr.pop();
}
hasSubsetSum([1, 2, 3, 7], 6); // true
hasSubsetSum([1, 2, 7, 1, 5], 10); // true
hasSubsetSum([1, 3, 4, 8], 6); // false
// runtime: O(nums) * O(total)
// Given a set of positive numbers, partition the set into two subsets with minimum difference between their subset sums. Return the difference.
function minimumDifferenceSubsets(nums) {
const total = nums.reduce((a, b) => a + b);
const midway = Math.floor(total / 2);
let closestSum = 0;
let prev = new Array(midway).fill(false);
prev.unshift(true);
let curr = [];
for (let num of nums) {
for (let sum = 0; sum <= midway; sum++) {
const include = num <= sum && prev[sum - num];
const exclude = prev[sum];
if (include || exclude) {
curr[sum] = true;
closestSum = Math.max(closestSum, sum);
}
}
prev = curr.slice();
}
return total - 2 * closestSum;
}
minimumDifferenceSubsets([1, 2, 3, 9]); // 3
minimumDifferenceSubsets([1, 2, 7, 1, 5]); // 0
minimumDifferenceSubsets([1, 3, 100, 4]); // 92
function countSubsets(nums, total) {
const curr = [1];
for (let numIdx = 0; numIdx < nums.length; numIdx++) {
for (let sum = total; sum >= 0; sum--) {
const included = curr[sum - nums[numIdx]] || 0;
const excluded = curr[sum] || 0;
curr[sum] = excluded + included;
}
}
return curr.pop();
}
countSubsets([1, 1, 2, 3], 4);
// 3 sets
countSubsets([1, 2, 7, 1, 5], 9);
// 3 sets
function generateSubsets(nums, total) {
const matrix = [];
const zeroithRow = new Array(total).fill({possible: false});
zeroithRow.unshift({possible: true, included: true});
matrix.push(zeroithRow);
nums.unshift(0);
let allSubsets = [];
function computeSubsets(row) {
const stack = [{rowIdx: row, remaining: total, subset: []}];
while (stack.length) {
const {rowIdx, remaining, subset} = stack.pop();
if (!remaining) {
allSubsets.push(subset);
} else {
const node = matrix[rowIdx][remaining];
if (node.included) {
const includedNum = nums[rowIdx];
stack.push({rowIdx: rowIdx - 1, remaining: remaining - includedNum, subset: [...subset, includedNum]});
}
if (node.excluded) {
stack.push({rowIdx: rowIdx - 1, remaining, subset});
}
}
}
}
for (let row = 1; row < nums.length; row++) {
const num = nums[row];
const currRow = [];
for (let sum = 0; sum <= total; sum++) {
const included = num <= sum && matrix[row - 1][sum - num].possible;
const excluded = matrix[row - 1][sum].possible;
currRow.push({
possible: included || excluded,
included,
excluded
});
}
matrix.push(currRow);
}
computeSubsets(matrix.length - 1);
return allSubsets;
}
generateSubsets([1, 1, 2, 3], 4);
// 3 sets {1, 1, 2}, {1, 3}, {1, 3}
generateSubsets([1, 2, 7, 1, 5], 9);
// 3 sets {2, 7}, {1, 7, 1}, {1, 2, 1, 5}
function findTargetSubsets(nums, S) {
const total = nums.reduce((a, b) => a + b);
const target = (S + total) / 2;
const ways = [1];
for (let num of nums) {
for (let sum = target; sum >= 0; sum--) {
const included = ways[sum - num] || 0;
const excluded = ways[sum] || 0;
ways[sum] = included + excluded;
}
}
return ways.pop();
};
findTargetSubsets([1, 1, 2, 3], 1); //3
// Explanation: The given set has '3' ways to make a sum of '1': {+1-1-2+3} & {-1+1-2+3} & {+1+1+2-3}
findTargetSubsets([1, 2, 7, 1], 9); //2
// Explanation: The given set has '2' ways to make a sum of '9': {+1+2+7-1} & {-1+2+7+1}
<file_sep>import Heap from "collections/heap";
const cyclic_sort = function(nums) {
let i = 0;
while (i < nums.length) {
if (nums[i] !== i + 1) {
let num = nums[i];
let idx = nums[i] - 1;
let swapNum = nums[idx];
nums[idx] = num;
nums[i] = swapNum;
} else {
i++;
}
}
return nums;
}
// console.log(`${cyclic_sort([3, 1, 5, 4, 2])}`);
// console.log(`${cyclic_sort([2, 6, 4, 3, 1, 5])}`)
// console.log(`${cyclic_sort([1, 5, 6, 4, 3, 2])}`)
const find_missing_number = function(nums) {
let missingIdx = nums.length;
let idx = 0;
while (idx < nums.length) {
if (nums[idx] !== idx) {
if (typeof(nums[idx]) !== "number") {
missingIdx = idx;
idx++;
} else {
[nums[nums[idx]], nums[idx]] = [nums[idx], nums[nums[idx]]];
}
} else {
idx++;
}
}
return missingIdx;
};
// find_missing_number([8, 3, 5, 2, 4, 6, 0, 1]); //?
const find_missing_numbers = function(nums) {
missingNumbers = new Set();
let idx = 0;
while (idx < nums.length) {
if (nums[idx] !== idx + 1) {
missingNumbers.delete(nums[idx]);
let oldNum = nums[idx];
let newNum = nums[nums[idx] - 1];
if (oldNum === newNum) {
missingNumbers.add(idx + 1);
idx++;
} else {
[nums[nums[idx] - 1], nums[idx]] = [nums[idx], nums[nums[idx] - 1]];
}
} else {
idx++;
}
}
return Array.from(missingNumbers);
};
// find_missing_numbers([2, 3, 1, 8, 2, 3, 5, 1]); //?
// Output: 4, 6, 7
const find_duplicate = function(nums) {
let idx = 0;
while (idx < nums.length) {
if (nums[idx] !== idx + 1) {
if (nums[idx] === nums[nums[idx] - 1]) {
return nums[idx];
}
[nums[nums[idx] - 1], nums[idx]] = [nums[idx], nums[nums[idx] - 1]];
} else {
idx++;
}
}
};
// find_duplicate([1, 4, 4, 3, 2]); //?
// find_duplicate([2, 1, 3, 3, 5, 4]); //?
const find_duplicate_non_mutate = function(nums) {
}
find_duplicate_non_mutate([1, 4, 4, 3, 2]); //?
const find_all_duplicates = function(nums) {
const duplicateNumbers = new Set();
let idx = 0;
while (idx < nums.length) {
if (nums[idx] === idx + 1) {
idx++;
} else {
if (nums[idx] === nums[nums[idx] - 1]) {
duplicateNumbers.add(nums[idx]);
idx++;
}
[nums[nums[idx] - 1], nums[idx]] = [nums[idx], nums[nums[idx] - 1]];
}
}
return Array.from(duplicateNumbers);
};
// find_all_duplicates([3, 4, 4, 5, 5]); //?
// Output: [4, 5]
// find_all_duplicates([5, 4, 7, 2, 3, 5, 3]);
// Output: [3, 5]
const find_corrupt_numbers = function(nums) {
let missingIdx;
let idx = 0;
while (idx < nums.length) {
if (nums[idx] === idx + 1) {
idx++;
} else {
if (nums[idx] === nums[nums[idx] - 1]) {
missingIdx = idx;
idx++;
} else {
[nums[nums[idx] - 1], nums[idx]] = [nums[idx], nums[nums[idx] - 1]];
}
}
}
return [nums[missingIdx], missingIdx + 1];
};
// find_corrupt_numbers([3, 1, 2, 5, 2]); //?
// Output: [2, 4]
// find_corrupt_numbers([3, 1, 2, 3, 6, 4]); //?
// Output: [3, 5]
const find_first_missing_positive = function(nums) {
const missing = new Set();
let idx = 0;
while (idx < nums.length) {
if (nums[idx] <= 0 || nums[idx] > nums.length) {
missing.add(idx + 1);
idx++;
} else if (nums[idx] !== idx + 1) {
if (nums[idx] === nums[nums[idx] - 1]) {
missing.add(idx);
idx++;
} else {
missing.delete(nums[idx]);
[nums[nums[idx] - 1], nums[idx]] = [nums[idx], nums[nums[idx] - 1]];
}
} else {
missing.delete(idx + 1);
idx++;
}
}
return Math.min(...Array.from(missing));
};
find_first_missing_positive([3,2,5,1]) //?
// find_first_missing_positive([-3, 1, 5, 4, 2]); //?
// Output: 3
// find_first_missing_positive([3, -2, 0, 1, 2]);
// Output: 4
// find_first_missing_positive([3, 2, 5, 1]);
// Output: 4<file_sep>class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
this.next = null;
}
// level order traversal using 'next' pointer
print_level_order() {
console.log("Level order traversal using 'next' pointer: ");
let nextLevelRoot = this;
while (nextLevelRoot !== null) {
let current = nextLevelRoot;
nextLevelRoot = null;
while (current != null) {
process.stdout.write(`${current.value} `);
if (nextLevelRoot === null) {
if (current.left !== null) {
nextLevelRoot = current.left;
} else if (current.right !== null) {
nextLevelRoot = current.right;
}
}
current = current.next;
}
console.log();
}
}
};
const traverse = function(root) {
const result = [];
const queue = [{node: root, level: 0}];
while (queue.length) {
const {node, level} = queue.shift();
result[level] = result[level] || [];
result[level] = [...result[level], node.value];
if (node.left) {
queue.push({node: node.left, level: level + 1});
}
if (node.right) {
queue.push({node: node.right, level: level + 1});
}
}
return result;
};
var root = new TreeNode(12);
root.left = new TreeNode(7);
root.right = new TreeNode(1);
root.left.left = new TreeNode(9);
root.right.left = new TreeNode(10);
root.right.right = new TreeNode(5);
// console.log(`Level order traversal: ${traverse(root)}`);
const traverse_reverse = function(root) {
const result = [];
let currLevel = 0;
let nodes = [];
const queue = [{node: root, level: 0}];
while (queue.length) {
const {node, level} = queue.shift();
if (level !== currLevel) {
result.unshift(nodes);
nodes = [];
currLevel = level;
}
nodes.push(node.value);
if (node.left) {
queue.push({node: node.left, level: level + 1});
}
if (node.right) {
queue.push({node: node.right, level: level + 1});
}
}
result.unshift(nodes);
return result;
}
var root = new TreeNode(12)
root.left = new TreeNode(7)
root.right = new TreeNode(1)
root.left.left = new TreeNode(9)
root.right.left = new TreeNode(10)
root.right.right = new TreeNode(5)
// console.log(traverse_reverse(root));
const traverse_zigzag = function(root) {
const result = [];
let isLTR = true;
let currLevel = 0;
let nodes = [];
const queue = [{node: root, level: 0}];
while (queue.length) {
const {node, level} = queue.shift();
if (level !== currLevel) {
result.push(nodes);
isLTR = !isLTR;
currLevel = level;
nodes = [];
}
if (isLTR) {
nodes.push(node.value);
} else {
nodes.unshift(node.value);
}
if (node.left) {
queue.push({node: node.left, level: level + 1});
}
if (node.right) {
queue.push({node: node.right, level: level + 1});
}
}
result.push(nodes);
return result;
};
var root = new TreeNode(12)
root.left = new TreeNode(7)
root.right = new TreeNode(1)
root.left.left = new TreeNode(9)
root.right.left = new TreeNode(10)
root.right.right = new TreeNode(5)
root.right.left.left = new TreeNode(20)
root.right.left.right = new TreeNode(17)
// console.log(`Zigzag traversal: ${traverse(root)}`)
function calculateAverage(nums) {
let sum = 0;
for (let num of nums) {
sum += num;
}
return sum / nums.length;
}
const find_level_averages = function(root) {
const averages = [];
let nums = [];
const queue = [{node: root, level: 0}];
while (queue.length) {
const {node, level} = queue.shift();
if (level !== averages.length) {
averages.push(calculateAverage(nums));
nums = [];
}
nums.push(node.value);
if (node.left) {
queue.push({node: node.left, level: level + 1});
}
if (node.right) {
queue.push({node: node.right, level: level + 1});
}
}
averages.push(calculateAverage(nums));
return averages;
};
var root = new TreeNode(12)
root.left = new TreeNode(7)
root.right = new TreeNode(1)
root.left.left = new TreeNode(9)
root.left.right = new TreeNode(2)
root.right.left = new TreeNode(10)
root.right.right = new TreeNode(5)
// console.log(`Level averages are: ${find_level_averages(root)}`)
const find_minimum_depth = function(root) {
const queue = [{node: root, depth: 1}];
while (queue.length) {
const {node, depth} = queue.shift();
if (!node.left && !node.right) {
return depth;
}
if (node.left) {
queue.push({node: node.left, depth: depth + 1});
}
if (node.right) {
queue.push({node: node.right, depth: depth + 1});
}
};
};
var root = new TreeNode(12)
root.left = new TreeNode(7)
root.right = new TreeNode(1)
root.right.left = new TreeNode(10)
root.right.right = new TreeNode(5)
// console.log(`Tree Minimum Depth: ${find_minimum_depth(root)}`)
root.left.left = new TreeNode(9)
root.right.left.left = new TreeNode(11)
// console.log(`Tree Minimum Depth: ${find_minimum_depth(root)}`)
const find_successor = function(root, key) {
let keyLocated = false;
const queue = [root];
while (queue.length) {
const node = queue.shift();
if (keyLocated) {
return node;
}
if (node.value === key) {
keyLocated = true;
}
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
}
return null;
};
var root = new TreeNode(12)
root.left = new TreeNode(7)
root.right = new TreeNode(1)
root.left.left = new TreeNode(9)
root.right.left = new TreeNode(10)
root.right.right = new TreeNode(5)
result = find_successor(root, 12)
result.value //?
result = find_successor(root, 9)
if (result != null)
console.log(result.value)
const connect_level_order_siblings = function(root) {
let prev;
let currLevel = 1;
const queue = [{node: root, level: 1}];
while (queue.length) {
let {node, level} = queue.shift();
// conditions:
// 1) no previous or previous level is different -> set prev to current
// 2. same level -> set prev's next to current, then set prev to current
if (prev && currLevel === level) {
prev.next = node;
}
prev = node;
currLevel = level;
if (node.left) {
queue.push({node: node.left, level: level + 1});
}
if (node.right) {
queue.push({node: node.right, level: level + 1});
}
}
return root;
};
var root = new TreeNode(12);
root.left = new TreeNode(7);
root.right = new TreeNode(1);
root.left.left = new TreeNode(9);
root.right.left = new TreeNode(10);
root.right.right = new TreeNode(5);
connect_level_order_siblings(root);
root.print_level_order()
class TreeNode2 {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
// tree traversal using 'next' pointer
print_tree() {
let result = "Traversal using 'next' pointer: ";
let current = this;
while (current != null) {
result += current.value + " ";
current = current.next;
}
console.log(result);
}
};
const connect_all_siblings = function(root) {
const queue = [root];
let prev;
while (queue.length) {
const node = queue.shift();
if (prev) {
prev.next = node;
}
prev = node;
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
}
};
var root = new TreeNode2(12)
root.left = new TreeNode2(7)
root.right = new TreeNode2(1)
root.left.left = new TreeNode2(9)
root.right.left = new TreeNode2(10)
root.right.right = new TreeNode2(5)
connect_all_siblings(root)
root.print_tree()
const tree_right_view = function(root) {
const result = [];
const queue = [{node: root, level: 1}];
let prev;
while (queue.length) {
const node = queue.shift();
if (prev && prev.level !== node.level) {
result.push(prev.node.value);
}
prev = node;
if (node.node.left) {
queue.push({node: node.node.left, level: node.level + 1});
}
if (node.node.right) {
queue.push({node: node.node.right, level: node.level + 1});
}
}
result.push(prev.node.value);
return result;
};
var root = new TreeNode(12);
root.left = new TreeNode(7);
root.right = new TreeNode(1);
root.left.left = new TreeNode(9);
root.right.left = new TreeNode(10);
root.right.right = new TreeNode(5);
root.left.left.left = new TreeNode(3);
console.log("Tree right view: " + tree_right_view(root))
const find_tree_boundary = function(root) {
let prev;
let currDepth = 0;
let isMarked = false;
const queue = [{node: root, depth: 1}];
while (queue.length) {
isMarked = false;
let {node, depth} = queue.shift();
// push prev if it's the last node of depth
if (prev && depth !== prev.depth && !prev.isMarked) {
// result.push(prev.node.value);
prev.node.isEdge = true;
}
if (depth !== currDepth) { // push if first node of depth
// result.push(node.value);
node.isEdge = true;
isMarked = true;
}
currDepth = depth;
// push curr if it's a leaf node, but only if not already pushed
if (!node.left && !node.right && !isMarked) {
// result.push(node.value);
node.isEdge = true;
isMarked = true;
}
prev = {node, depth, isMarked};
if (node.left) {
queue.push({node: node.left, depth: depth + 1});
}
if (node.right) {
queue.push({node: node.right, depth: depth + 1});
}
}
function traversePreorder(node) {
let values = [];
if (node.isEdge) {
values.push(node.value);
}
if (node.left) {
values = values.concat(traversePreorder(node.left));
}
if (node.right) {
values = values.concat(traversePreorder(node.right));
}
return values;
}
function traversePostorder(node) {
let values = [];
if (node.left) {
values = values.concat(traversePostorder(node.left));
}
if (node.right) {
values = values.concat(traversePostorder(node.right));
}
if (node.isEdge) {
values.push(node.value);
}
return values;
}
let result = [root.value];
let isPreorder = true;
if (root.left) {
isPreorder = false;
result = result.concat(traversePreorder(root.left));
}
if (root.right) {
if (isPreorder) {
result = result.concat(traversePreorder(root.right));
} else {
result = result.concat(traversePostorder(root.right));
}
}
return result;
};
var root = new TreeNode(12);
root.left = new TreeNode(7);
root.right = new TreeNode(1);
root.left.left = new TreeNode(4);
root.left.left.left = new TreeNode(9);
root.left.right = new TreeNode(3);
root.left.right.left = new TreeNode(15);
root.right.left = new TreeNode(10);
root.right.right = new TreeNode(5);
root.right.right.left = new TreeNode(6);
find_tree_boundary(root); //?
// process.stdout.write('Tree boundary: ');
// for (i = 0; i < result.length; i++) {
// process.stdout.write(`${result[i].value} `);
// }
<file_sep>const find_subsets = function(nums) {
const subsets = [[]];
for (let num of nums) {
const oldSubsets = subsets.slice();
for (let subset of oldSubsets) {
subsets.push([...subset, num]);
}
}
return subsets;
};
// find_subsets([1, 3]); //?
// Output: [], [1], [3], [1,3]
// find_subsets([1, 5, 3]); //?
// Output: [], [1], [5], [3], [1,5], [1,3], [5,3], [1,5,3]
const find_subsets_unique = function(nums) {
nums = nums.sort((a, b) => a - b);
let subsets = [[]];
let prev;
for (let i = 0; i < nums.length; i++) {
const oldSubsets = nums[i] === nums[i - 1] ? prev : subsets.slice();
let newAdditions = [];
for (let subset of oldSubsets) {
newAdditions.push([...subset, nums[i]]);
}
prev = newAdditions;
subsets = subsets.concat(newAdditions);
}
return subsets;
};
// find_subsets_unique([1, 3, 3]) //?
// [], [1], [3], [1,3], [3,3], [1,3,3]
// find_subsets_unique([1, 5, 3, 3]); //?
// [], [1], [5], [3], [1,5], [1,3], [5,3], [1,5,3], [3,3], [1,3,3], [3,3,5], [1,5,3,3]
// const find_permutations = function(nums) {
// const permutations = [];
// function generate(curr, nums) {
// if (!nums) {
// }
// for (let i = 0; i < nums.length; i++) {
// }
// }
// return permutations;
// };
// find_permutations([1, 3, 5]);
// Notes:
// Each letter can be upper or lower, but numbers are not transformed
/*
test: ad52 -> a/A + d/D + 5 + 2
[aD52], [AD52]
[aD], [AD], [ad], [aD]
each permutation must be full length
*/
const find_letter_case_string_permutations = function(str) {
let permutations = [""];
for (let char of str) {
if (isNaN(+char)) {
let newLayer1 = permutations.slice();
let newLayer2 = permutations.slice();
// push in both lower + upper variations
const lower = char.toLowerCase();
const upper = char.toUpperCase();
permutations = newLayer1.map(permutation => permutation + lower)
.concat(newLayer2.map(permutation => permutation + upper));
} else {
permutations = permutations.map(permutation => permutation + char);
}
}
return permutations;
};
// find_letter_case_string_permutations("ad52"); //?
// find_letter_case_string_permutations("ab7c"); //?
const generate_valid_parentheses = function(num) {
const result = [];
const queue = [{str: "", opening: 0, closing: 0}];
while (queue.length) {
const {str, opening, closing} = queue.shift();
if (str.length === num * 2) {
result.push(str);
} else {
if (opening >= num) {
queue.push({str: str + ")", opening, closing: closing + 1});
} else if (opening === closing) {
queue.push({str: str + "(", opening: opening + 1, closing});
} else {
queue.push({str: str + "(", opening: opening + 1, closing});
queue.push({str: str + ")", opening, closing: closing + 1});
}
}
}
return result;
};
/*
1: ()
2: ()(), (())
3: ()()(), (()()), ()(()), (())(), ((()))
Parens are only valid when:
The # of closing parens at any point in the string does not exceed the # of opening parens
*/
generate_valid_parentheses(2); //?
generate_valid_parentheses(3); //?
<file_sep>// Given an array of unsorted numbers and a target number, find all unique quadruplets in it, whose sum is equal to the target number.
// Example 1:
// Input:
// Output:
// Explanation: Both the quadruplets add up to the target.
// Example 2:
// Input: [
// Output:
// Explanation: Both the quadruplets add up to the target.
const search_quadruplets = (arr, target) => {
const quadruplets = [];
arr = arr.sort((a, b) => a - b); //?
let p1 = 0;
let p4 = arr.length - 1;
while (p1 + 1 < p4 - 1) {
// while (arr[p1] === arr[p1 + 1]) {
// p1++;
// }
// while (arr[p4] === arr[p4 - 1]) {
// p4--;
// }
let p2 = p1 + 1;
let p3 = p4 - 1;
while (p2 < p3) {
const sum = arr[p1] + arr[p2] + arr[p3] + arr[p4];
if (sum === target) {
quadruplets.push([arr[p1], arr[p2], arr[p3], arr[p4]]);
p2++;
p3--;
} else if (sum > target) {
p3--;
} else {
p2++;
}
}
// p1++;
// p4--;
if (arr[p1] + arr[p1 + 1] + arr[p4] + arr[p4 - 1] > target) {
while (arr[p4] === arr[p4 - 1]) {
p4--;
}
} else {
while (arr[p1] === arr[p1 + 1]) {
p1++;
}
}
}
return quadruplets;
};
// search_quadruplets([4, 1, 2, -1, 1, -3], 1); //?
// [-3, -1, 1, 4], [-3, 1, 1, 2]
search_quadruplets([2, 0, -1, 1, -2, 2], 2); //?
//[-2, 0, 2, 2], [-1, 0, 1, 2]
// search_quadruplets([0, 2, 2, 2, 7, 9, 9], 18) //?
|
e095ac31988c106b23f9e6416b328f42613c952d
|
[
"JavaScript"
] | 6 |
JavaScript
|
R-SE/grokking-algos
|
2a0e61d86e476642b5e36e653b004ae6303ef500
|
449f24438d5c837bd52a6224c98fcc4a5b3d0965
|
refs/heads/master
|
<file_sep>require('dotenv').config();
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
const shortid = require('shortid');
const dns = require('dns');
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const urlSchema = mongoose.Schema({
originalUrl: {
type: String,
required: true,
},
shortUrl: {
type: String,
required: true,
unique: true,
},
});
const Url = mongoose.model('Url', urlSchema);
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use('/public', express.static(`${process.cwd()}/public`));
app.get('/', function (req, res) {
res.sendFile(process.cwd() + '/views/index.html');
});
// Your first API endpoint
app.get('/api/hello', function (req, res) {
res.json({ greeting: 'hello API' });
});
app.post('/api/shorturl', (req, res) => {
const { url } = req.body;
if (!url || !/^((http|https):\/\/)/.test(url))
return res.json({ error: 'invalid url' });
const original_url = url;
const { hostname } = new URL(url);
dns.lookup(hostname, async (err) => {
console.log(err);
if (err) return res.json({ error: 'invalid url' });
let short_url = shortid.generate();
while ((await Url.findOne({ shortUrl: short_url })) !== null) {
short_url = shortid.generate();
}
const newUrl = new Url({
originalUrl: original_url,
shortUrl: short_url,
});
await newUrl.save();
res.json({ original_url, short_url });
});
});
app.get('/api/shorturl/:short_url', async (req, res) => {
const { short_url } = req.params;
const url = await Url.findOne({ shortUrl: short_url });
if (!url) return res.json({ error: 'No short URL found for the given input' });
let redirect_url = url.originalUrl;
if (!/^((http|https):\/\/)/.test(redirect_url))
redirect_url = `http://${url.originalUrl}`;
res.redirect(redirect_url);
});
app.listen(port, function () {
console.log(`Listening on port ${port}`);
});
<file_sep>const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
require('dotenv').config();
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const User = mongoose.model(
'User',
mongoose.Schema({
username: {
type: String,
required: true,
unique: [true, 'Username already taken'],
},
log: [
{
description: {
type: String,
required: true,
},
duration: {
type: Number,
required: true,
},
date: {
type: Date,
default: Date.now,
},
},
],
})
);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html');
});
app.post('/api/users', async (req, res) => {
const exist = await User.findOne({ username: req.body.username });
if (exist) return res.send('Username already taken');
try {
const user = await User.create(req.body);
const { username, _id } = user;
res.json({ username, _id });
} catch (error) {
return res.send(error.errors[Object.keys(error.errors)[0]].message);
}
});
app.get('/api/users', async (req, res) => {
const users = await User.find({}, 'username _id');
res.json(users);
});
app.post('/api/users/:id/exercises', async (req, res) => {
const { id } = req.params;
const user = await User.findById(id);
if (!user) return res.json('User not found');
let { description, duration, date } = req.body;
if (!date) date = new Date();
user.log.push({ description, duration, date: new Date(date) });
try {
await user.save();
} catch (error) {
return res.send(error.errors[Object.keys(error.errors)[0]].message);
}
const { username, _id } = user;
const data = {
_id,
username,
date: new Date(date).toDateString(),
duration: parseInt(duration),
description,
};
res.json(data);
});
app.get('/api/users/:id/logs', async (req, res) => {
const { id } = req.params;
const { from, to, limit } = req.query;
const options = {};
if (limit) options['log'] = { $slice: parseInt(limit) };
const user = await User.findById(id, options);
if (!user) return res.json('User not found');
if (from)
user.log = user.log.filter((x) => x.date.getTime() > new Date(from).getTime());
if (to)
user.log = user.log.filter(
(x) => x.date.getTime() < new Date(req.query.to).getTime()
);
const { _id, username, log } = user;
const data = { _id, username, count: log.length, log };
res.json(data);
});
const listener = app.listen(process.env.PORT || 3000, () => {
console.log('Your app is listening on port ' + listener.address().port);
});
|
e11c95a119759dbaaeb53c9f9bcc4f8a1284ea96
|
[
"JavaScript"
] | 2 |
JavaScript
|
xynoipse/apis-microservices
|
d872124c7cf707dca8602c04dbc9c40392d26787
|
3b8b6bfbce498eb544aa1a1d9365444483264f95
|
refs/heads/master
|
<file_sep>import React from "react";
import PropTypes from "prop-types";
import {
View,
Text,
TouchableOpacity,
Dimensions,
ViewPropTypes
} from "react-native";
import { Feather } from "@expo/vector-icons";
import * as Consts from "../../../constants/styleConstants";
import { isEmpty } from "../../";
const { height: SCREEN_HEIGHT } = Dimensions.get("window");
const RequestTimeout = props => {
return (
<TouchableOpacity
activeOpacity={0.6}
onPress={props.onPress}
style={[
{
alignItems: "center",
justifyContent: "center",
padding: 20,
width: "100%"
},
props.style
]}
>
{props.text && (
<View style={{ marginBottom: 10 }}>
<Text style={{ color: Consts.colorDark3, fontSize: 16 }}>
{props.text}
</Text>
</View>
)}
<View
style={{
flexDirection: "row",
alignItems: "center",
paddingVertical: 8,
paddingHorizontal: 15,
borderRadius: 3,
borderWidth: 1,
borderColor: Consts.colorDark4
}}
>
<Feather name="rotate-cw" size={16} color={Consts.colorDark3} />
<View style={{ width: 5 }} />
<Text style={{ color: Consts.colorDark3, fontSize: 13 }}>
{props.buttonText}
</Text>
</View>
</TouchableOpacity>
);
};
RequestTimeout.propTypes = {
text: PropTypes.string,
onPress: PropTypes.func,
style: ViewPropTypes.style
};
RequestTimeout.defaultProps = {
onPress: () => {}
};
const RequestTimeoutWrapped = props => {
const { ...viewProps } = props;
return (
<View {...viewProps}>
{props.isTimeout ? (
<RequestTimeout
text={props.text}
buttonText={props.buttonText}
onPress={props.onPress}
style={{ minHeight: props.fullScreen ? SCREEN_HEIGHT - 100 : 0 }}
/>
) : (
props.children
)}
</View>
);
};
RequestTimeoutWrapped.propTypes = {
isTimeout: PropTypes.bool,
fullScreen: PropTypes.bool,
onPress: PropTypes.func
};
RequestTimeoutWrapped.defaultProps = {
onPress: () => {}
};
export default RequestTimeoutWrapped;
<file_sep>import * as types from "../constants/actionTypes";
import axios from "axios";
import { filterMax } from "../wiloke-elements";
/**
* GET LISTING DETAIL
* @param {*} id listing
*/
export const getListingDetail = id => dispatch => {
return axios
.get(`listing-detail/${id}`)
.then(res => {
const {
oReview,
oFavorite,
oNavigation,
oHomeSections
} = res.data.oResults;
dispatch({
type: types.GET_LISTING_DETAIL,
payload: {
oReview,
oFavorite,
oNavigation,
oHomeSections
}
});
dispatch({
type: types.ADD_LISTING_DETAIL_FAVORITES,
id: oFavorite.isMyFavorite ? id : null
});
})
.catch(err => console.log(err));
};
/**
* GET LISTING DETAIL DESCRIPTIONS
* @param {*} id listing
* @param {*} key = content
*/
export const getListingDescription = (id, key, max) => dispatch => {
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: true
});
dispatch({
type: types.LISTING_DETAIL_DES_REQUEST_TIMEOUT,
isTimeout: false
});
return axios
.get(`listing-meta/${id}/${key}`)
.then(res => {
const payload = res.data.status === "success" ? [res.data.oResults] : [];
if (max !== null) {
dispatch({
type: types.GET_LISTING_DESTINATION,
payload
});
} else {
dispatch({
type: types.GET_LISTING_DESTINATION_ALL,
payload
});
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: false
});
}
// dispatch({
// type: types.LISTING_DETAIL_DES_REQUEST_TIMEOUT,
// isTimeout: false
// });
})
.catch(err => {
// dispatch({
// type: types.LISTING_DETAIL_DES_REQUEST_TIMEOUT,
// isTimeout: true
// });
console.log(err.message);
});
};
/**
* GET LISTING DETAIL LIST FEATURE
* @param {*} id listing
* @param {*} key = tags
* @param {*} max (maximumItemsOnHome)
*/
export const getListingListFeature = (id, key, max) => dispatch => {
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: true
});
dispatch({
type: types.LISTING_DETAIL_LIST_REQUEST_TIMEOUT,
isTimeout: false
});
return axios
.get(`listing-meta/${id}/${key}`, {
params: {
maximumItemsOnHome: max !== "" ? max : null
}
})
.then(res => {
const payload = res.data.status === "success" ? res.data.oResults : [];
if (max !== null) {
dispatch({
type: types.GET_LISTING_LIST_FEATURE,
payload
});
} else {
dispatch({
type: types.GET_LISTING_LIST_FEATURE_ALL,
payload
});
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: false
});
}
// dispatch({
// type: types.LISTING_DETAIL_LIST_REQUEST_TIMEOUT,
// isTimeout: false
// });
})
.catch(err => {
// dispatch({
// type: types.LISTING_DETAIL_LIST_REQUEST_TIMEOUT,
// isTimeout: true
// });
console.log(err.message);
});
};
/**
* GET LISTING DETAIL PHOTOS
* @param {*} id listing
* @param {*} key = photos
* @param {*} max (maximumItemsOnHome)
*/
export const getListingPhotos = (id, key, max) => dispatch => {
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: true
});
dispatch({
type: types.LISTING_DETAIL_PHOTOS_REQUEST_TIMEOUT,
isTimeout: false
});
return axios
.get(`listing-meta/${id}/${key}`, {
params: {
maximumItemsOnHome: max !== "" ? max : null
}
})
.then(res => {
const { large, medium } = res.data.oResults;
const galleryLarge = filterMax(large);
const galleryMedium = filterMax(medium);
const gallery = maxItem =>
res.data.status === "success"
? {
large: !maxItem ? large : galleryLarge(maxItem),
medium: !maxItem ? medium : galleryMedium(maxItem)
}
: {};
if (max !== null) {
dispatch({
type: types.GET_LISTING_PHOTOS,
payload: gallery(false)
});
} else {
dispatch({
type: types.GET_LISTING_PHOTOS_ALL,
payload: gallery(false)
});
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: false
});
}
// dispatch({
// type: types.LISTING_DETAIL_PHOTOS_REQUEST_TIMEOUT,
// isTimeout: false
// });
})
.catch(err => {
// dispatch({
// type: types.LISTING_DETAIL_PHOTOS_REQUEST_TIMEOUT,
// isTimeout: true
// });
console.log(err.message);
});
};
export const resetListingDetail = () => dispatch => {
dispatch({
type: types.RESET_LISTING_DETAIL
});
};
/**
* GET LISTING DETAIL VIDEOS
* @param {*} id listing
* @param {*} key = videos
* @param {*} max (maximumItemsOnHome)
*/
export const getListingVideos = (id, key, max) => dispatch => {
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: true
});
dispatch({
type: types.LISTING_DETAIL_VID_REQUEST_TIMEOUT,
isTimeout: false
});
return axios
.get(`listing-meta/${id}/${key}`, {
params: {
maximumItemsOnHome: max !== "" ? max : null
}
})
.then(res => {
const videos = res.data.status === "success" ? res.data.oResults : [];
if (max !== null) {
dispatch({
type: types.GET_LISTING_VIDEOS,
payload: filterMax(videos)(1)
});
} else {
dispatch({
type: types.GET_LISTING_VIDEOS_ALL,
payload: filterMax(videos)(12)
});
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: false
});
}
// dispatch({
// type: types.LISTING_DETAIL_VID_REQUEST_TIMEOUT,
// isTimeout: false
// });
})
.catch(err => {
// dispatch({
// type: types.LISTING_DETAIL_VID_REQUEST_TIMEOUT,
// isTimeout: true
// });
console.log(err.message);
});
};
/**
* GET LISTING DETAIL REVIEWS
* @param {*} id listing
* @param {*} key = reviews
* @param {*} max (maximumItemsOnHome)
*/
export const getListingReviews = (id, key, max) => dispatch => {
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: true
});
dispatch({
type: types.LOADING_REVIEW,
loading: true
});
dispatch({
type: types.LISTING_DETAIL_REVIEWS_REQUEST_TIMEOUT,
isTimeout: false
});
return axios
.get(`listing-meta/${id}/${key}`, {
params: {
maximumItemsOnHome: max !== "" ? max : null
}
})
.then(res => {
const payload = res.data.status === "success" ? res.data.oResults : [];
if (max !== null) {
dispatch({
type: types.GET_LISTING_REVIEWS,
payload
});
dispatch({
type: types.LOADING_REVIEW,
loading: false
});
} else {
dispatch({
type: types.GET_LISTING_REVIEWS_ALL,
payload
});
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: false
});
dispatch({
type: types.LOADING_REVIEW,
loading: false
});
}
// dispatch({
// type: types.LISTING_DETAIL_REVIEWS_REQUEST_TIMEOUT,
// isTimeout: false
// });
})
.catch(err => {
// dispatch({
// type: types.LISTING_DETAIL_REVIEWS_REQUEST_TIMEOUT,
// isTimeout: true
// });
console.log(err.message);
});
};
/**
* GET COMMENT LISTING REVIEWS
* @param {*} commentId by listing reviews
*/
export const getCommentInReviews = commentId => dispatch => {
return axios
.get(`review-discussion/${commentId}`)
.then(res => {
dispatch({
type: types.GET_COMMENT_IN_REVIEWS,
payload:
res.data.data.status === "success"
? res.data.data.oResults.aDiscussion
: []
});
})
.catch(err => console.log(err.message));
};
/**
* GET LISTING DETAIL EVENTS
* @param {*} id listing
* @param {*} key = events
* @param {*} max (maximumItemsOnHome)
*/
export const getListingEvents = (id, key, max) => dispatch => {
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: true
});
// dispatch({
// type: types.LISTING_DETAIL_EVENT_REQUEST_TIMEOUT,
// isTimeout: false
// });
return axios
.get(`listing-meta/${id}/${key}`, {
params: {
maximumItemsOnHome: max !== "" ? max : null
}
})
.then(res => {
const payload = res.data.status === "success" ? res.data.oResults : [];
if (max !== null) {
dispatch({
type: types.GET_LISTING_EVENTS,
payload: filterMax(payload)(2)
});
} else {
dispatch({
type: types.GET_LISTING_EVENTS_ALL,
payload
});
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: false
});
}
// dispatch({
// type: types.LISTING_DETAIL_EVENT_REQUEST_TIMEOUT,
// isTimeout: false
// });
})
.catch(err => {
// dispatch({
// type: types.LISTING_DETAIL_EVENT_REQUEST_TIMEOUT,
// isTimeout: true
// });
console.log(err.message);
});
};
/**
* GET_LISTING_BOX_CUSTOM
* @param {*} id listing
* @param {*} key = events
* @param {*} max (maximumItemsOnHome)
*/
export const getListingBoxCustom = (id, key, max) => dispatch => {
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: true
});
return axios
.get(`listing-meta/${id}/${key}`, {
params: {
maximumItemsOnHome: max !== "" ? max : null
}
})
.then(res => {
const data = res.data.status === "success" ? res.data.oResults : [];
if (max !== null) {
dispatch({
type: types.GET_LISTING_BOX_CUSTOM,
payload: {
data,
key
}
});
} else {
dispatch({
type: types.GET_LISTING_BOX_CUSTOM_ALL,
payload: {
data,
key
}
});
dispatch({
type: types.LOADING_LISTING_DETAIL,
loading: false
});
}
})
.catch(err => {
console.log(err.message);
});
};
/**
* GET LISTING DETAIL NAVIGATION
* @param {*} data = oNavigation
*/
export const getListingDetailNavigation = data => dispatch => {
dispatch({
type: types.GET_LISTING_DETAIL_NAV,
detailNav: data
});
};
/**
* CHANGE LISTING DETAIL NAVIGATION
* @param {*} key
*/
export const changeListingDetailNavigation = key => dispatch => {
dispatch({
type: types.CHANGE_LISTING_DETAIL_NAV,
key
});
};
export const getListingSidebar = listingId => dispatch => {
dispatch({
type: types.LISTING_DETAIL_SIDEBAR_REQUEST_TIMEOUT,
isTimeout: false
});
return axios
.get(`listing/sidebar/${listingId}`)
.then(res => {
dispatch({
type: types.GET_LISTING_SIDEBAR,
payload: res.data.status === "success" ? res.data.oResults : []
});
// dispatch({
// type: types.LISTING_DETAIL_SIDEBAR_REQUEST_TIMEOUT,
// isTimeout: false
// });
})
.catch(err => {
// dispatch({
// type: types.LISTING_DETAIL_SIDEBAR_REQUEST_TIMEOUT,
// isTimeout: true
// });
console.log(err.message);
});
};
<file_sep>import * as types from "../constants/actionTypes";
import axios from "axios";
const POSTS_PER_PAGE = 12;
export const getArticles = _ => dispatch => {
dispatch({
type: types.LOADING,
loading: true
});
dispatch({
type: types.ARTICLE_REQUEST_TIMEOUT,
isTimeout: false
});
return axios
.get(`posts`, {
params: {
page: 1,
postsPerPage: POSTS_PER_PAGE
}
})
.then(res => {
dispatch({
type: types.GET_ARTICLES,
payload: res.data
});
dispatch({
type: types.LOADING,
loading:
(res.data.oResults && res.data.oResults.length > 0) ||
res.data.status === "error"
? false
: true
});
dispatch({
type: types.ARTICLE_REQUEST_TIMEOUT,
isTimeout: false
});
})
.catch(err => {
dispatch({
type: types.ARTICLE_REQUEST_TIMEOUT,
isTimeout: true
});
console.log(err.message);
});
};
export const getArticlesLoadmore = next => dispatch => {
return axios
.get(`posts`, {
params: {
page: next,
postsPerPage: POSTS_PER_PAGE
}
})
.then(res => {
dispatch({
type: types.GET_ARTICLES_LOADMORE,
payload: res.data
});
})
.catch(err => console.log(err.message));
};
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { TouchableOpacity } from "react-native";
const TIME_TAB_DOUBLE = 300;
export default class DoublePress extends PureComponent {
static propTypes = {
onDoublePress: PropTypes.func.isRequired,
onPressOut: PropTypes.func,
onLayout: PropTypes.func,
children: PropTypes.element
};
static defaultProps = {
onDoublePress: () => {},
onPressOut: () => {},
onLayout: () => {}
};
constructor(props) {
super(props);
this.state = {
width: 0,
height: 0,
prevTimestamp: 0
};
}
_getSize = event => {
const { width, height } = event.nativeEvent.layout;
this.setState({ width, height });
this.props.onLayout(event);
};
_boundingCheck = (lx, ly, w, h) => {
return lx > 0 && lx < w && ly > 0 && ly < h;
};
_handlePressOut = event => {
const { width, height, prevTimestamp } = this.state;
const { locationX, locationY, timestamp } = event.nativeEvent;
if (this._boundingCheck(locationX, locationY, width, height)) {
this.setState({ prevTimestamp: timestamp });
if (timestamp - prevTimestamp <= TIME_TAB_DOUBLE) {
this.props.onDoublePress(event);
this.props.onPressOut(event);
}
}
};
render() {
return (
<TouchableOpacity
{...this.props}
activeOpacity={1}
onPressOut={this._handlePressOut}
onLayout={this._getSize}
>
{this.props.children}
</TouchableOpacity>
);
}
}
<file_sep>import React, { Component, Fragment } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
Image,
ActivityIndicator,
TouchableHighlight,
Dimensions,
FlatList,
ScrollView,
StyleSheet
} from "react-native";
import _ from "lodash";
import he from "he";
import ListingItem from "../dumbs/ListingItem";
import { Loader } from "../../wiloke-elements";
import * as Consts from "../../constants/styleConstants";
const { width: SCREEN_WIDTH } = Dimensions.get("window");
class ListingLayoutHorizontal extends Component {
static propTypes = {
data: PropTypes.array,
colorPrimary: PropTypes.string
};
static defaultProps = {
colorPrimary: Consts.colorPrimary
};
renderItem = ({ item }) => {
const { navigation } = this.props;
return (
<ListingItem
image={item.oFeaturedImg.medium}
title={he.decode(item.postTitle)}
tagline={item.tagLine ? he.decode(item.tagLine) : null}
logo={item.logo !== "" ? item.logo : item.oFeaturedImg.thumbnail}
location={he.decode(item.oAddress.address)}
reviewMode={item.oReview.mode}
reviewAverage={item.oReview.average}
businessStatus={item.businessStatus}
colorPrimary={this.props.colorPrimary}
onPress={() =>
navigation.navigate("ListingDetailScreen", {
id: item.ID,
name: he.decode(item.postTitle),
tagline: !!item.tagLine ? he.decode(item.tagLine) : null,
link: item.postLink,
author: item.oAuthor,
image:
SCREEN_WIDTH > 420
? item.oFeaturedImg.large
: item.oFeaturedImg.medium,
logo: item.logo !== "" ? item.logo : item.oFeaturedImg.thumbnail
})
}
layout={this.props.layout}
/>
);
};
renderItemLoader = () => (
<ListingItem contentLoader={true} layout={this.props.layout} />
);
render() {
const { data } = this.props;
return (
<View style={styles.container}>
{data.length > 0 ? (
<FlatList
data={data}
renderItem={this.renderItem}
keyExtractor={item => item.ID.toString()}
numColumns={this.props.layout === "horizontal" ? 1 : 2}
horizontal={this.props.layout === "horizontal" ? true : false}
showsHorizontalScrollIndicator={false}
/>
) : (
<FlatList
data={[
{ key: "1" },
{ key: "2" },
{ key: "3" },
{ key: "4" },
{ key: "5" },
{ key: "6" }
]}
renderItem={this.renderItemLoader}
numColumns={1}
horizontal={true}
showsHorizontalScrollIndicator={false}
/>
)}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "row",
padding: 5
}
});
export default ListingLayoutHorizontal;
<file_sep>import { createStackNavigator } from "react-navigation";
import stackOpts from "./stackOpts";
import * as Consts from "../constants/styleConstants";
import AccountScreen from "../components/screens/AccountScreen";
import FavoritesScreen from "../components/screens/FavoritesScreen";
import ProfileScreen from "../components/screens/ProfileScreen";
import EditProfile from "../components/screens/EditProfile";
import MyListingsScreen from "../components/screens/MyListingsScreen";
import MyEventsScreen from "../components/screens/MyEventsScreen";
import NotificationsScreen from "../components/screens/NotificationsScreen";
import MessageScreen from "../components/screens/MessageScreen";
import SettingScreen from "../components/screens/SettingScreen";
import NotificationSettingScreen from "../components/screens/NotificationSettingScreen";
const accountStack = createStackNavigator(
{
AccountScreen: {
screen: AccountScreen
// navigationOptions: {
// title: "Wilcity",
// headerStyle: {
// backgroundColor: Consts.colorDark
// },
// headerTintColor: Consts.colorPrimary,
// headerTitleStyle: {
// fontWeight: "400",
// fontSize: 14
// }
// }
// navigationOptions: ({ navigation }) => ({
// header: false
// })
},
FavoritesScreen: {
screen: FavoritesScreen
},
ProfileScreen: {
screen: ProfileScreen
},
EditProfile: {
screen: EditProfile
},
MyListingsScreen: {
screen: MyListingsScreen
},
MyEventsScreen: {
screen: MyEventsScreen
},
NotificationsScreenInAccount: {
screen: NotificationsScreen
},
MessageScreenInAccount: {
screen: MessageScreen
},
SettingScreen: {
screen: SettingScreen
},
NotificationSettingScreen: {
screen: NotificationSettingScreen
}
},
stackOpts
);
export default accountStack;
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { View, Text, StyleSheet, Dimensions } from "react-native";
import { FontIcon } from "../../";
import * as Consts from "../../../constants/styleConstants";
import he from "he";
const { width: SCREEN_WIDTH } = Dimensions.get("window");
export default class IconTextMedium extends PureComponent {
static propTypes = {
iconSize: PropTypes.number,
texNumberOfLines: PropTypes.number,
iconName: PropTypes.string,
iconColor: PropTypes.string,
textStyle: Text.propTypes.style,
text: PropTypes.string,
iconBackgroundColor: PropTypes.string,
renderBoxFirstText: PropTypes.func,
renderBoxLastText: PropTypes.func
};
static defaultProps = {
iconSize: 36,
iconName: "map",
iconColor: Consts.colorDark2,
iconBackgroundColor: Consts.colorGray2
};
render() {
const {
iconSize,
texNumberOfLines,
iconName,
iconColor,
textStyle,
text,
iconBackgroundColor,
renderBoxFirstText,
renderBoxLastText
} = this.props;
return (
<View
style={[
styles.container,
{ paddingLeft: iconSize, minHeight: iconSize }
]}
>
<View
style={[
styles.iconWrapper,
{
width: iconSize,
height: iconSize,
borderRadius: iconSize / 2,
backgroundColor: iconBackgroundColor
}
]}
>
<FontIcon
name={iconName}
size={iconSize * (18 / 36)}
color={iconColor}
/>
</View>
<View style={styles.textWrapper}>
{renderBoxFirstText && (
<View style={styles.firstText}>{renderBoxFirstText()}</View>
)}
<Text
style={[
{
fontSize: 12,
color: Consts.colorDark2,
marginLeft: 8
},
textStyle
]}
numberOfLines={texNumberOfLines}
>
{he.decode(text)}
</Text>
</View>
{renderBoxLastText && (
<View style={styles.lastText}>{renderBoxLastText()}</View>
)}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
position: "relative",
justifyContent: "center",
width: "100%"
},
iconWrapper: {
justifyContent: "center",
alignItems: "center",
position: "absolute",
top: 0,
left: 0
},
textWrapper: {
flexDirection: "row"
},
firstText: {
width: 50,
height: 50,
borderRadius: Consts.round,
backgroundColor: Consts.colorGray1,
marginLeft: 10,
overflow: "hidden"
},
lastText: {
width: SCREEN_WIDTH / 1.5,
height: ((SCREEN_WIDTH / 1.5) * 9) / 16,
borderRadius: Consts.round,
backgroundColor: Consts.colorGray1,
marginTop: 10,
marginLeft: 10,
overflow: "hidden"
}
});
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { View, Text, Image, TouchableOpacity, StyleSheet } from "react-native";
import { Feather } from "@expo/vector-icons";
import * as Consts from "../../../constants/styleConstants";
import stylesBase from "../../../stylesBase";
export default class MoreBtn extends PureComponent {
static propTypes = {
onPress: PropTypes.func,
colorPrimary: PropTypes.string
};
static defaultProps = {
onPress: () => {},
colorPrimary: Consts.colorPrimary
};
render() {
return (
<View style={styles.container}>
<TouchableOpacity activeOpacity={0.8} onPress={this.props.onPress}>
<View style={styles.inner}>
<Text style={[stylesBase.h6, stylesBase.colorPrimary, styles.text]}>
{this.props.text}
</Text>
<Feather
style={styles.icon}
name="arrow-right"
size={16}
color={this.props.colorPrimary}
/>
</View>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginBottom: 5
},
inner: {
flexDirection: "row",
alignItems: "center"
},
icon: {
marginLeft: 5
}
});
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, Text } from "react-native";
import { Rated, RatedSmall } from "../dumbs";
import { connect } from "react-redux";
import {
isEmpty,
Loader,
ContentBox,
ViewWithLoading
} from "../../wiloke-elements";
import * as Consts from "../../constants/styleConstants";
class AverageDetailReviewContainer extends Component {
renderItem = (mode, len) => (item, index) => {
return (
<RatedSmall
key={index.toString()}
max={mode}
rate={item.average}
text={item.text}
horizontal={true}
style={{
borderTopWidth: 1,
borderTopColor: Consts.colorGray1,
paddingTop: 10,
paddingBottom: index === len - 1 ? 0 : 10,
paddingHorizontal: 10,
marginHorizontal: -10
}}
/>
);
};
renderAverageReviews = () => {
const { listingReviews } = this.props;
const { oAverageDetailsReview, mode } = listingReviews;
return oAverageDetailsReview.map(
this.renderItem(mode, oAverageDetailsReview.length)
);
};
renderAverageTotal = () => {
const { listingReviews } = this.props;
const { mode, average, quality } = listingReviews;
return (
<View style={{ marginBottom: 10 }}>
<Rated max={mode} rate={average} text={quality} />
</View>
);
};
render() {
const {
translations,
listingReviews,
loadingReview,
settings
} = this.props;
return (
<ViewWithLoading isLoading={loadingReview} contentLoader="contentHeader">
{!isEmpty(listingReviews) && (
<ContentBox
headerIcon="star"
headerTitle={translations.averageRating}
style={{ marginBottom: 10 }}
colorPrimary={settings.colorPrimary}
>
<View>
{this.renderAverageTotal()}
{this.renderAverageReviews()}
</View>
</ContentBox>
)}
</ViewWithLoading>
);
}
}
const mapStateToProps = state => ({
listingReviews: state.listingReviews,
loadingReview: state.loadingReview,
translations: state.translations,
settings: state.settings
});
export default connect(mapStateToProps)(AverageDetailReviewContainer);
<file_sep>import { combineReducers } from "redux";
import * as requestTimeout from "./requestTimeout";
import { listings } from "./listings";
import { listingSearchResults } from "./listingSearchResults";
import { listingByCat } from "./listingByCat";
import { loading, loadingListingDetail, loadingReview } from "./loading";
import * as listingDetailAll from "./listingDetail";
import { listingFilters } from "./listingFilters";
import { homeScreen } from "./homeScreen";
import { locationList } from "./locationList";
import { categoryList } from "./categoryList";
import { locations } from "./locations";
import { translations } from "./translations";
import { scrollTo } from "./scrollTo";
import { events } from "./events";
import { eventDetail } from "./eventDetail";
import {
eventDiscussion,
eventDiscussionLatest,
commentInDiscussionEvent
} from "./eventDiscussion";
import { eventSearchResults } from "./eventSearchResults";
import { articles } from "./articles";
import { articleDetail } from "./articleDetail";
import { tabNavigator, stackNavigator } from "./navigators";
import { nearByFocus } from "./nearByFocus";
import { page } from "./page";
import { settings } from "./settings";
import {
auth,
isTokenExpired,
loginError,
isLoginLoading,
signupError,
isSignupLoading
} from "./reducerAuth";
import {
myFavorites,
listIdPostFavorites,
listIdPostFavoritesRemoved
} from "./reducerMyFavorites";
import { reportForm, reportMessage } from "./reducerReportForm";
import { accountNav } from "./reducerAccountNav";
import { myProfile, myProfileError, shortProfile } from "./reducerMyProfile";
import { editProfileForm } from "./reducerEditProfileForm";
import { myListings, myListingError } from "./reducerMyListings";
import { listingStatus, eventStatus } from "./reducerListingStatus";
import { postTypes } from "./reducerPostTypes";
import { myEvents, myEventError } from "./reducerMyEvents";
import {
myNotifications,
myNotificationError,
deleteMyNotificationError
} from "./reducerMyNotifications";
import { signUpForm } from "./reducerSignupForm";
import { countNotify, countNotifyRealTimeFaker } from "./reducerCounts";
import {
messageChat,
isWritingMessageChat,
messageNewCount,
isCurrentSendMessageScreen
} from "./reducerMessage";
import {
users,
usersError,
user,
usersFromFirebase,
usersFromFirebaseLoading,
usersFromFirebaseError,
keyFirebase,
keyFirebase2,
userConnections
} from "./reducerUsers";
import { deviceToken } from "./reducerDeviceToken";
import {
notificationSettings,
notificationAdminSettings
} from "./reducerNotificationSettings";
import { db } from "./reducerFirebase";
import { reviewFields } from "./reducerReviewFields";
const reducers = combineReducers({
reviewFields,
db,
notificationSettings,
notificationAdminSettings,
deviceToken,
users,
usersError,
user,
usersFromFirebase,
usersFromFirebaseLoading,
usersFromFirebaseError,
keyFirebase,
keyFirebase2,
userConnections,
messageChat,
isWritingMessageChat,
messageNewCount,
isCurrentSendMessageScreen,
countNotify,
countNotifyRealTimeFaker,
signUpForm,
myNotifications,
myNotificationError,
deleteMyNotificationError,
myEvents,
myEventError,
postTypes,
listingStatus,
eventStatus,
myListings,
myListingError,
listings,
listingSearchResults,
listingByCat,
...listingDetailAll,
listingFilters,
homeScreen,
loading,
loadingListingDetail,
loadingReview,
locationList,
categoryList,
locations,
translations,
scrollTo,
events,
eventDetail,
eventDiscussion,
eventDiscussionLatest,
commentInDiscussionEvent,
eventSearchResults,
articles,
articleDetail,
tabNavigator,
stackNavigator,
nearByFocus,
page,
settings,
auth,
isTokenExpired,
loginError,
isLoginLoading,
signupError,
isSignupLoading,
myFavorites,
listIdPostFavorites,
listIdPostFavoritesRemoved,
reportForm,
reportMessage,
accountNav,
myProfile,
myProfileError,
shortProfile,
editProfileForm,
...requestTimeout
});
export default reducers;
<file_sep>import { Linking, Platform } from "react-native";
import axios from "axios";
import { WebBrowser } from "expo";
const searcher = str => s => str.search(s) !== -1;
const replacer = str => str.replace(/(\/|\?.*)$/g, "").replace(/^.*\//g, "");
const checkYoutubeTypeAccount = url =>
searcher(url)("/user/") ? "user" : "chanel";
const getUrl = url => {
if (searcher(url)("instagram.com")) {
return {
ios: `instagram://user?username=${replacer(url)}`,
android: `intent://instagram.com/_u/${replacer(
url
)}/#Intent;package=com.instagram.android;scheme=https;end`,
browser: url
};
} else if (searcher(url)("plus.google.com")) {
return {
ios: `gplus://plus.google.com/u/0/${replacer(url)}`,
android: `gplus://plus.google.com/u/0/${replacer(url)}`,
browser: url
};
} else if (searcher(url)(/fb:\/\/|facebook.com/g)) {
return {
ios: url,
android: `intent://#Intent;package=com.facebook.katana;scheme=${url};end`,
browser: !searcher(url)("fb://")
? url
: `https://www.facebook.com/${url.replace(
/fb:\/\/(profile|page|group)\/(\?id=|)/g,
""
)}`
};
} else if (searcher(url)("twitter.com")) {
return {
ios: `twitter://user?screen_name=${replacer(url)}`,
android: `intent://twitter.com/${replacer(
url
)}#Intent;package=com.twitter.android;scheme=https;end`,
browser: url
};
} else if (searcher(url)("youtube.com")) {
return {
ios: `vnd.youtube://www.youtube.com/${checkYoutubeTypeAccount(
url
)}/${replacer(url)}`,
android: `intent://www.youtube.com/${checkYoutubeTypeAccount(
url
)}/${replacer(
url
)}#Intent;package=com.google.android.youtube;scheme=https;end`,
browser: url
};
} else if (searcher(url)("pinterest.com")) {
return {
ios: `pinterest://user/${replacer(url)}`,
android: `pinterest://www.pinterest.com/${replacer(url)}`,
browser: url
};
} else {
return {
ios: url,
android: url,
browser: url
};
}
};
const socialLinking = url => {
return Linking.openURL(
Platform.OS === "ios" ? getUrl(url).ios : getUrl(url).android
).catch(_ => {
WebBrowser.openBrowserAsync(getUrl(url).browser);
});
};
export const DeepLinkingSocial = async url => {
if (searcher(url)("facebook.com")) {
try {
const { data } = await axios.get(url);
const metaPropertyIos = data
.replace(/\/>/g, "/>\n")
.match(/<meta property="al:ios:url".*\/>/g)[0];
const metaPropertyAndroid = data
.replace(/\/>/g, "/>\n")
.match(/<meta property="al:android:url".*\/>/g)[0];
const metaPropertyContent = (Platform.OS === "ios"
? metaPropertyIos
: metaPropertyAndroid
)
.match(/content.*(?=")/g)[0]
.replace(/content="/g, "");
socialLinking(metaPropertyContent);
} catch (err) {
socialLinking(url);
}
} else {
socialLinking(url);
}
};
<file_sep>import React, { PureComponent } from "react";
import { Text, View, TouchableOpacity, StyleSheet } from "react-native";
import { connect } from "react-redux";
import { Layout } from "../dumbs";
import { Feather } from "@expo/vector-icons";
import { ListItemTouchable, Switch, P, Loader } from "../../wiloke-elements";
import {
colorDark4,
colorGray2,
colorDark3,
colorDark1
} from "../../constants/styleConstants";
import {
setNotificationSettings,
getNotificationSettings
} from "../../actions";
class NotificationSettingScreen extends PureComponent {
state = {
data: [],
dataObj: {},
isLoading: true
};
async componentDidMount() {
const { shortProfile, notificationAdminSettings } = this.props;
const myID = shortProfile.userID;
await this.props.getNotificationSettings(myID);
this.setState({
isLoading: false
});
const { notificationSettings } = this.props;
const data = Object.keys(notificationSettings).map(key => ({
key,
id: notificationAdminSettings[key].id,
label: notificationAdminSettings[key].title,
description: notificationAdminSettings[key].desc,
checked: notificationSettings[key],
visible: key === "toggleAll" ? true : notificationSettings.toggleAll
}));
this.setState({ data, dataObj: notificationSettings });
}
_handleNotificationToggle = key => async (name, isChecked) => {
const { shortProfile } = this.props;
const myID = shortProfile.userID;
await this.setState(prevState => ({
dataObj: {
...prevState.dataObj,
[key]: isChecked
},
data: prevState.data.map(item => {
return {
...item,
checked: item.key === key ? isChecked : item.checked,
visible:
item.key === key ? true : key === "toggleAll" ? isChecked : true
};
})
}));
const { dataObj } = this.state;
this.props.setNotificationSettings(myID, dataObj);
};
_renderItem = item => {
const { settings } = this.props;
return (
item.visible && (
<View key={item.key}>
<View style={styles.switchWrap}>
<Switch
checked={item.checked}
name={item.label}
size={24}
swipeActiveColor={settings.colorPrimary}
circleAnimatedColor={[colorDark4, settings.colorPrimary]}
colorActive={settings.colorPrimary}
label={item.label}
onPress={this._handleNotificationToggle(item.key)}
/>
</View>
<View style={styles.destWrap}>
<P style={styles.desc}>{item.description}</P>
</View>
</View>
)
);
};
_renderContent = () => {
const { data, isLoading } = this.state;
if (isLoading) return <Loader size="small" />;
return (
<View style={styles.content}>
{data.sort((a, b) => a.id - b.id).map(this._renderItem)}
</View>
);
};
render() {
const { navigation, settings, translations } = this.props;
return (
<Layout
navigation={navigation}
headerType="headerHasBack"
title={`${translations.notifications} ${translations.settings}`}
goBack={() => navigation.goBack()}
renderRight={() => (
<TouchableOpacity
activeOpacity={0.5}
onPress={() => navigation.navigate("SearchScreen")}
>
<Feather name="search" size={20} color="#fff" />
</TouchableOpacity>
)}
renderContent={this._renderContent}
colorPrimary={settings.colorPrimary}
textSearch={translations.search}
scrollViewStyle={styles.scrollView}
/>
);
}
}
const styles = StyleSheet.create({
scrollView: {
backgroundColor: colorGray2
},
content: {
paddingBottom: 20
},
switchWrap: {
backgroundColor: "#fff",
paddingVertical: 10,
paddingHorizontal: 10,
marginVertical: 15
},
destWrap: {
paddingHorizontal: 10,
marginTop: -10
},
desc: {
fontSize: 12,
color: colorDark3
},
switchLabel: {
color: colorDark1
}
});
const mapStateToProps = state => ({
settings: state.settings,
translations: state.translations,
notificationSettings: state.notificationSettings,
notificationAdminSettings: state.notificationAdminSettings,
shortProfile: state.shortProfile
});
const mapDispatchToProps = {
setNotificationSettings,
getNotificationSettings
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(NotificationSettingScreen);
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, Text, FlatList } from "react-native";
export default class FlatListRedux extends Component {
static propsTypes = {
...FlatList.propTypes,
asyncActions: PropTypes.func
};
static defaultProps = {
asyncActions: () => {}
};
constructor(props) {
super(props);
this.state = {
isLoading: false
};
}
componentDidMount() {
this.props.componentDidMount();
}
_getData = async () => {
try {
const { asyncActions } = this.props;
this.setState({ isLoading: true });
await asyncActions();
this.setState({ isLoading: false });
} catch (err) {
console.log(err);
}
};
render() {
const { ...flatListProps } = this.props;
return <FlatList {...flatListProps} />;
}
}
<file_sep>import { GET_LISTING_FILTERS } from "../constants/actionTypes";
import axios from "axios";
export const getListingFilters = (objPostType, postType) => dispatch => {
return axios
.get("search-fields/listing", {
params: {
postType
}
})
.then(res => {
if (res.status === 200) {
const { oResults } = res.data;
dispatch({
type: GET_LISTING_FILTERS,
payload: [
oResults.filter(item => item.key === "postType").length > 0
? {}
: objPostType,
...oResults
]
});
}
})
.catch(err => console.log(err.message));
};
<file_sep>import React, { Component } from "react";
import { View, TouchableOpacity, Text } from "react-native";
import { connect } from "react-redux";
import {
changeListingDetailNavigation,
getListingPhotos,
getScrollTo
} from "../../actions";
import {
NewGallery,
ViewWithLoading,
isEmpty,
ContentBox,
RequestTimeoutWrapped
} from "../../wiloke-elements";
import { ButtonFooterContentBox } from "../dumbs";
class ListingPhotosContainer extends Component {
state = {
imageIndex: 0,
isImageViewVisible: false,
isLoading: true
};
_getListingPhotos = async () => {
const { params, getListingPhotos, type } = this.props;
const { id, item, max } = params;
type === null && (await getListingPhotos(id, item.key, max));
this.setState({ isLoading: false });
};
async componentDidMount() {
this._getListingPhotos();
}
renderContent = (id, item, isLoading, photos, type) => {
const {
isListingDetailPhotosRequestTimeout,
translations,
settings
} = this.props;
return (
<ViewWithLoading
isLoading={isLoading}
contentLoader="contentSquareHeader"
contentSquareWidth="33.33%"
>
{!isEmpty(photos) && (
<ContentBox
headerTitle={item.name}
headerIcon={item.icon}
style={{ marginBottom: type !== "all" ? 10 : 50 }}
renderFooter={
item.status &&
item.status === "yes" &&
this.renderFooterContentBox(id, item.key)
}
colorPrimary={settings.colorPrimary}
>
<RequestTimeoutWrapped
isTimeout={isListingDetailPhotosRequestTimeout}
onPress={this._getListingPhotos}
text={translations.networkError}
buttonText={translations.retry}
>
<NewGallery
thumbnails={photos.medium}
modalSlider={photos.large}
thumbnailMax={type !== "all" && 3}
colorPrimary={settings.colorPrimary}
/>
</RequestTimeoutWrapped>
</ContentBox>
)}
</ViewWithLoading>
);
};
renderFooterContentBox = (listingId, key) => {
const {
translations,
changeListingDetailNavigation,
getListingPhotos,
getScrollTo
} = this.props;
return (
<ButtonFooterContentBox
text={translations.viewAll.toUpperCase()}
onPress={() => {
changeListingDetailNavigation(key);
getListingPhotos(listingId, key, null);
getScrollTo(0);
}}
/>
);
};
render() {
const {
listingPhotos,
listingPhotosAll,
loadingListingDetail,
params,
type
} = this.props;
const { id, item } = params;
const { isLoading } = this.state;
return type === "all"
? this.renderContent(
id,
item,
loadingListingDetail,
listingPhotosAll,
"all"
)
: this.renderContent(id, item, isLoading, listingPhotos);
}
// renderFooter = () => {
// const {
// params,
// translations,
// changeListingDetailNavigation,
// getListingPhotos
// } = this.props;
// const { status, key } = params.item;
// const listingId = params.id;
// return (
// status === "yes" && (
// <ButtonFooterContentBox
// text={translations.viewAll.toUpperCase()}
// onPress={() => {
// changeListingDetailNavigation(key);
// getListingPhotos(listingId, key, null);
// }}
// />
// )
// );
// };
// render() {
// const { params, listingPhotos } = this.props;
// return (
// !isEmpty(listingPhotos) && (
// <ContentBox
// headerTitle={params.item.name}
// headerIcon="image"
// style={stylesBase.mb10}
// // renderFooter={this.renderFooter()}
// >
// {this.renderGallery()}
// </ContentBox>
// )
// );
// }
}
const mapStateToProps = state => ({
listingPhotos: state.listingPhotos,
listingPhotosAll: state.listingPhotosAll,
translations: state.translations,
loadingListingDetail: state.loadingListingDetail,
isListingDetailPhotosRequestTimeout:
state.isListingDetailPhotosRequestTimeout,
settings: state.settings
});
export default connect(
mapStateToProps,
{
changeListingDetailNavigation,
getListingPhotos,
getScrollTo
}
)(ListingPhotosContainer);
<file_sep>import * as types from "../constants/actionTypes";
// const initialState = [
// { id: "wilokeListingLocation", name: "...", selected: true }
// ];
export const locationList = (state = {}, action) => {
switch (action.type) {
case types.GET_LOCATION_LIST:
return {
...state,
...action.payload
};
case types.CHANGE_LOCATION_LIST:
return {
...state,
...action.payload
};
case types.RESET_SELECTED_LOCATION_LIST:
const postType = Object.keys(action.payload)[0];
return state.map((item, index) => {
return { ...item, selected: index === 0 ? true : false };
});
default:
return state;
}
};
<file_sep>import { GET_TRANSLATIONS } from "../constants/actionTypes";
import axios from "axios";
import { isEmpty } from "../wiloke-elements";
export const getTranslations = _ => dispatch => {
return axios
.get("translations")
.then(res => {
dispatch({
type: GET_TRANSLATIONS,
payload: isEmpty(res.data.oResults) ? {} : res.data.oResults
});
})
.catch(err => console.log(err.message));
};
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import {
Text,
View,
StatusBar,
Keyboard,
TouchableWithoutFeedback
} from "react-native";
import he from "he";
import { NewGallery } from "../../wiloke-elements";
import { CommentReview } from "../dumbs";
import stylesBase from "../../stylesBase";
import { connect } from "react-redux";
import { getCommentInDiscussionEvent } from "../../actions";
const TIME_FAKE = 4000;
class EventCommentDiscussionScreen extends Component {
state = {
loading: true
};
async componentDidMount() {
const { navigation, getCommentInDiscussionEvent } = this.props;
const { params } = navigation.state;
const { item } = params;
const discussionId = item.ID;
await getCommentInDiscussionEvent(discussionId);
this.setState({ isLoading: false });
// RealTime Faker
this._realTimeFaker = setInterval(() => {
getCommentInDiscussionEvent(discussionId);
}, TIME_FAKE);
}
componentWillUnmount() {
clearInterval(this._realTimeFaker);
}
_handleGoBack = () => {
const { navigation } = this.props;
Keyboard.dismiss();
navigation.goBack();
};
renderReviewGallery = item => {
const { settings } = this.props;
return (
item.oGallery !== false && (
<View style={{ paddingTop: 8 }}>
<NewGallery
thumbnails={item.oGallery.medium}
modalSlider={item.oGallery.large}
colorPrimary={settings.colorPrimary}
/>
</View>
)
);
};
render() {
const { navigation, translations, commentInDiscussionEvent } = this.props;
const { params } = navigation.state;
const { item, autoFocus } = params;
const { isLoading } = this.state;
const dataComments =
commentInDiscussionEvent.oResults &&
commentInDiscussionEvent.oResults.length > 0
? commentInDiscussionEvent.oResults.map((item, index) => ({
id: index.toString(),
image: item.oAuthor.avatar,
title: item.oAuthor.displayName,
message: item.postContent,
text: item.postDate
}))
: [];
return (
<View>
{/* <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}> */}
<View>
<StatusBar barStyle="dark-content" />
<CommentReview
fullScreen={true}
colorPrimary={this.props.settings.colorPrimary}
inputAutoFocus={autoFocus ? true : false}
headerAuthor={{
image: item.oAuthor.avatar,
title: he.decode(item.oAuthor.displayName),
text: item.postDate
}}
renderContent={() => (
<View>
<Text style={stylesBase.text}>
{he.decode(item.postContent)}
</Text>
</View>
)}
shares={{
count: item.countShared,
text:
item.countShared > 1 ? translations.shares : translations.share
}}
comments={{
data: dataComments,
count: item.countDiscussions,
isLoading,
text:
item.countDiscussions > 1
? translations.comments
: translations.comment
}}
likes={{
count: item.countLiked,
text: item.countLiked > 1 ? translations.likes : translations.like
}}
commentsActionSheet={{
options: ["Cancel", "Remove", "Edit", "Report"],
title: "Comment by <NAME>",
destructiveButtonIndex: 1,
cancelButtonIndex: 0,
onPressButtonItem: () => {
console.log("press");
},
onAction: buttonIndex => {
console.log(buttonIndex);
if (buttonIndex === 1) {
// code
}
}
}}
goBack={this._handleGoBack}
style={{ borderWidth: 0 }}
/>
</View>
{/* </TouchableWithoutFeedback> */}
</View>
);
}
}
const mapStateToProps = state => ({
translations: state.translations,
commentInDiscussionEvent: state.commentInDiscussionEvent,
settings: state.settings
});
export default connect(
mapStateToProps,
{ getCommentInDiscussionEvent }
)(EventCommentDiscussionScreen);
<file_sep>const translations = {
"0": "You do not have permission to access this page",
"1": "You do not have permission to access this page",
sentYourLocation: "Sent Your Location",
shareOnFacebook: "Share on Facebook",
shareOnTwitter: "Share on Twitter",
shareToEmail: "Email Coupon",
pleaseUseThisCouponCode: "Please us this coupon code:",
reviewTitle: "Review Title",
setting: "Setting",
settings: "Settings",
youLeftAReviewBefore: "You already left a review before.",
couldNotInsertReview: "Oops! We could not insert the review",
reviewIDIsRequired: "The review id is required.",
yourReview: "Your Review",
thisFeatureIsNotAvailable: "This feature is not available yet",
currentAccount: "Current Account",
aMonths: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sept",
"Oct",
"Nov",
"Dec"
],
oneMinuteAgo: "1 minute ago",
aFewMinutesAgo: "A few minutes ago",
minutesAgo: "minutes ago",
hoursAgo: "hours ago",
hourAgo: "hour ago",
browserDoesNotSupportLocalStore:
"Sorry, your browser does not support Web Storage...",
deleteMyAccount: "Delete My Account",
permanentlyDeleteAccount: "Permanently Delete Account",
copy: "Copy",
copied: "Copied",
online: "Online",
offline: "Offline",
deleteMessage: "Do you want to delete this message?",
startConversation: "Starting a conversation with an author now.",
searchAuthor: "Search Author",
postType: "Post Type",
status: "Status",
connectWithSocialNetworks: "Or Connect With",
fbLoginWarning:
"Facebook Init is not loaded. Check that you are not running any blocking software or that you have tracking protection turned off if you use Firefox",
createdAccountSuccessfully:
"Congrats! Your account has been created successfully.",
couldNotCreateAccount:
"ERROR: We could not create your account. Please try later.",
usernameExists:
"ERROR: Sorry, The username is not available. Please with another username.",
emailExists:
"ERROR: An account with this email already exists on the website.",
invalidEmail: "ERROR: Invalid Email",
needCompleteAllRequiredFields: "ERROR: Please complete all required fields.",
needAgreeToTerm:
"ERROR: Sorry, To create an account on our site, you have to agree to our terms conditionals.",
needAgreeToPolicy:
"ERROR: Sorry, To create an account on our site, you have to agree to our privacy policy.",
disabledLogin: "Sorry, We are disabled this service temporary.",
youAreLoggedInAlready: "You are logged in already.",
deletedNotification:
"Congrats! The notification has been deleted successfully.",
couldNotDeleteNotification:
"Oops! We could not delete this notification. Please recheck your Notification ID.",
confirmDeleteNotification: "Do you want to delete this notification?",
idIsRequired: "The ID is required",
noDataFound: "No Data Found",
couldNotSendMessage:
"OOps! We could not send this message, please try clicking on Send again.",
messageContentIsRequired: "Message Content is required",
chatFriendIDIsRequired: "Chat friend id is required",
authorMessageHasBeenDelete:
"Congrats! The author messages has been deleted successfully.",
messageHasBeenDelete: "Congrats! The message has been deleted successfully.",
weCouldNotDeleteMessage:
"Oops! Something went wrong, We could not delete this message.",
weCouldNotDeleteAuthorMessage:
"Oops! Something went wrong, We could not delete the author messages.",
authorIDIsRequired: "Author ID is required",
msgIDIsRequired: "Message ID is required",
fetchedAllMessages: "Fetched all messages",
aFewSecondAgo: "A few seconds ago",
xMinutesAgo: "%s minutes ago",
xHoursAgo: "%s hours ago",
noMessage: "There are no messages",
allNotificationsIsLoaded: "All Notification is loaded",
passwordHasBeenUpdated:
"Congrats! Your password has been updated successfully.",
all: "All",
confirmDeleteFavorites: "Do you want delete it from your favorites",
backTo: "Back To",
logoutDesc: "Do you want to logout?",
requiredLogin: "You need to login to your account first",
continue: "Continue",
logout: "Logout",
favorite: "Favorite",
report: "Report",
editProfile: "Edit Profile",
foundNoUser: "User profile does not exist.",
userIDIsRequired: "Take a Photo",
takeAPhoto: "Take a Photo",
uploadPhoto: "Upload photo",
uploadPhotoFromLibrary: "Upload photo from Library",
firstName: "<NAME>",
lastName: "<NAME>",
displayName: "<NAME>",
avatar: "Avatar",
coverImg: "Cover Image",
email: "Email",
position: "Position",
introYourSelf: "Intro yourself",
address: "Address",
phone: "Phone",
website: "Website",
socialNetworks: "Social Networks",
changePassword: "<PASSWORD>",
currentPassword: "<PASSWORD>",
newPassword: "<PASSWORD>",
confirmNewPassword: "<PASSWORD>",
youNeedToCompleteAllRequired: "Please complete all required fields",
validationData: {
email: {
presence: {
message: "Email is required"
},
special: {
message: "Invalid email address"
}
},
phone: {
presence: {
message: "Phone number is required"
},
special: {
message: "Invalid phone number"
}
},
url: {
presence: {
message: "URL is required"
},
special: {
message: "Invalid URL"
}
},
username: {
presence: {
message: "Username is required"
},
length: {
minimum: 3,
message: "Your username must be at least 3 characters"
}
},
password: {
presence: {
message: "Please enter a password"
},
length: {
minimum: 5,
message: "Your password must be at least 5 characters"
}
},
confirmPassword: {
presence: {
message: "Password does not match the confirm password"
}
},
firstName: {
presence: {
message: "Please enter a password"
},
length: {
message: "Your first name must be at least %s characters"
}
},
lastName: {
presence: {
message: "Please enter your last name"
},
length: {
minimum: 3,
message: "Your last name must be at least 3 characters"
}
},
displayName: {
presence: {
message: "Please enter your display name"
},
length: {
minimum: 3,
message: "Your display name must be at least 3 characters"
}
},
agreeToTerms: {
presence: {
message: "You must agree to our terms conditionals."
}
},
agreeToPolicy: {
presence: {
message: "You must agree to our policy privacy."
}
}
},
invalidGooglereCaptcha: "Pleas verify reCaptcha first.",
profileHasBeenUpdated: "Congrats! Your profile have been updated",
errorUpdateProfile:
"ERROR: Something went wrong, We could not update your profile.",
errorUpdatePassword:
"ERROR: The password confirmation must be matched the new password.",
sendAnEmailIfIReceiveAMessageFromAdmin: "Receive message through email",
reportMsg: "Thank for your reporting!",
weNeedYourReportMsg: "Please give us your reason",
aPostStatus: [
{
status: "Published",
icon: "la la-share-alt",
bgColor: "bg-gradient-1",
post_status: "publish",
total: 0
},
{
status: "In Review",
icon: "la la-refresh",
bgColor: "bg-gradient-2",
post_status: "pending",
total: 0
},
{
status: "Unpaid",
icon: "la la-money",
bgColor: "bg-gradient-3",
post_status: "unpaid",
total: 0
},
{
status: "Expired",
icon: "la la-exclamation-triangle",
bgColor: "bg-gradient-4",
post_status: "expired",
total: 0
}
],
aEventStatus: [
{
status: "Upcoming",
icon: "la la-calendar-o",
bgColor: "bg-gradient-1",
post_status: "publish",
total: 0
},
{
status: "OnGoing",
icon: "la la-calendar-o",
bgColor: "bg-gradient-2",
post_status: "ongoing",
total: 0
},
{
status: "Expired",
icon: "la la-calendar-o",
bgColor: "bg-gradient-3",
post_status: "expired",
total: 0
},
{
status: "In Review",
icon: "la la-calendar-o",
bgColor: "bg-gradient-4",
post_status: "pending",
total: 0
},
{
status: "Temporary Close",
icon: "la la-calendar-o",
bgColor: "bg-gradient-4",
post_status: "temporary_close",
total: 0
}
],
gotAllFavorites: "All favorites have been displayed",
noFavorites: "There are no favorites",
tokenExpired:
"The token has been expired, please log into the app to generate a new token",
profile: "Profile",
messages: "Messages",
favorites: "Favorites",
doNotHaveAnyArticleYet: "You do not have any article yet.",
invalidUserNameOrPassword: "<PASSWORD> Or <PASSWORD>",
download: "Download",
geoCodeIsNotSupportedByBrowser:
"Geolocation is not supported by this browser.",
askForAllowAccessingLocationTitle:
"Allow accessing your location while you are using the app?",
askForAllowAccessingLocationDesc:
"Your current location will be used for nearby search results.",
seeMoreDiscussions: "See more discussions",
allRegions: "All Regions",
nearby: "Nearby",
networkError: "Network Error",
retry: "Tap To Retry",
weAreWorking: "We are working on this feature",
searchResults: "Search Results",
noPostFound: "No Posts Found",
discussion: "Discussion",
discussions: "Discussions",
hostedBy: "Hosted By",
editReview: "Edit review",
always_open: "Open 24/7",
whatAreULookingFor: "What are you looking for?",
notFound: "Not Found",
viewProfile: "View Profile",
inReviews: "In Reviews",
addSocial: "Add Social",
searchNow: "Search Now",
temporaryClose: "Temporary Close",
back: "Back",
expiryOn: "Expiry On",
views: "Views",
shares: "Shares",
home: "Home",
searchAsIMoveTheMap: "Search as I move the map",
allListings: "All Listings",
allCategories: "All Categories",
allLocations: "All Locations",
allTags: "All Tags",
geolocationError: "Geolocation is not supported by this browser.",
promotions: "Promotions",
askChangePlan:
"Just a friendly popup to ensure that you want to change your subscription level?",
changePlan: "Change Plan",
active: "Active",
getNow: "Get Now",
listingType: "Listing Type",
currency: "Currency",
billingType: "Billing Type",
nextBillingDate: "Next Billing Date",
currentPlan: "Current Plan",
remainingItems: "Remaining Items",
billingHistory: "Billing History",
subTotal: "Sub Total",
discount: "Discount",
plan: "Plan",
planName: "Plan Name",
planType: "Plan Type",
gateway: "Gateway",
payfor: "Invoice Pay For",
date: "Date",
description: "Description",
viewDetails: "View Details",
viewAll: "View All",
amount: "Amount",
more: "More",
categories: "Categories",
saveChanges: "Save Changes",
basicInfo: "Basic Info",
followAndContact: "Follow & Contact",
resetPassword: "<PASSWORD>",
ihaveanaccount: "Already have an account?",
username: "Username",
usernameOrEmail: "Username or Email Address",
password: "<PASSWORD>",
lostPassword: "<PASSWORD>?",
donthaveanaccount: "Don't have an account?",
rememberMe: "Remember me?",
login: "Login",
register: "Register",
isShowOnHome: "Do you want to show the section content on the Home tab?",
viewMoreComments: "View more comments",
reportTitle: "Report abuse",
pinToTopOfReview: "Pin to Top of Review",
unPinToTopOfReview: "Unpin to Top of Review",
seeMoreReview: "See More Reviews",
eventName: "Event Name",
peopleInterested: "People interested",
upcoming: "Upcoming",
unpaid: "Unpaid",
ongoing: "Ongoing",
expired: "Expired",
promote: "Promote",
title: "Title",
type: "Type",
oChart: {
oHeading: {
views: "Total Views",
favorites: "Total Favorites",
shares: "Total Shares",
ratings: "Average Rating"
},
oLabels: {
views: "Views",
favorites: "Favorites",
shares: "Shares",
ratings: "Ratings"
},
up: "Up",
down: "Down"
},
noOlderNotifications: "No older notifications.",
notifications: "Notifications",
seeAll: "See All",
of: "of",
gallery: "Gallery",
favoriteTooltip: "Save to my favorites",
oneResult: "Result",
twoResults: "Results",
moreThanTwoResults: "Results",
filterByTags: "Filter By Tags",
to: "To",
send: "Send",
message: "Message",
newMessage: "New Message",
searchUsersInChat: "Search by username",
recipientInfo: "Recipient information",
inbox: "Inbox",
deleteMsg: "Delete Message",
search: "Search",
couldNotAddProduct: "We could not add product to cart",
directBankTransfer: "Direct Bank Transfer",
totalLabel: "Total",
boostSaleBtn: "Boost now",
selectAdsPosition: "Select Ads Positions",
selectAdsDesc: "Boost this post to a specify positions on the website",
boostPost: "Boost Post",
boostEvent: "Boost Event",
selectPlans: "Select Plans",
name: "Name",
addVideoBtn: "Add Video",
videoLinkPlaceholder: "Video Link",
image: "Image",
images: "Images",
uploadVideosTitle: "Upload Videos",
uploadVideosDesc: "Add more videos to this listing",
uploadSingleImageTitle: "Upload Image",
uploadMultipleImagesTitle: "Upload Images",
uploadMultipleImagesDesc: "Add more images to this listing",
maximumVideosWarning: "You can add a maximum of %s videos",
maximumImgsWarning: "You can upload a maximum of %s images",
weNeedYour: "We need your",
showMap: "Show map",
enterAQuery: "Enter a query",
day: "Day",
starts: "Starts",
endsOn: "End",
time: "Time",
photo: "Photo",
photos: "Photos",
noComments: "No Comment",
comment: "Comment",
comments: "Comments",
share: "Share",
like: "Like",
likes: "Likes",
liked: "Liked",
typeAMessage: "Type a message...",
confirmHide: "Are you sure that you want to hide this listing?",
confirmRePublish: "Do you want to re-publish this listing?",
wrongConfirmation: "ERROR: Wrong the confirmation code.",
confirmDelete: "Press x to confirm that you want to delete this listing",
remove: "Remove",
hide: "Hide",
edit: "Edit",
delete: "Delete",
ok: "Ok",
publish: "Publish",
submit: "Submit",
cancel: "Cancel",
confirmDeleteComment: "Are you want to delete this comment?",
reportReview: "Report review",
reviewFor: "Review For",
reviewsFor: "Reviews For",
addReview: "Add a review",
averageRating: "Average Rating",
basicInfoEvent: "Basic Info",
basicInfoEventDesc:
"This info will also appear in Listing and any ads created for this event",
eventVideo: "Event Video",
addPhotoVideoPopupTitle: "Add Photos And Videos",
location: "Location",
aEventFrequency: [
{
name: "Occurs once",
value: "occurs_once"
},
{
name: "Daily",
value: "daily"
},
{
name: "Weekly",
value: "weekly"
}
],
frequency: "Frequency",
details: "Details",
detailsDesc:
"Let people know what type of event you're hosting and what to expect",
oDaysOfWeek: [
{
value: "sunday",
label: "Sun"
},
{
value: "monday",
label: "Mon"
},
{
value: "tuesday",
label: "Tue"
},
{
value: "wednesday",
label: "Wed"
},
{
value: "thursday",
label: "Thurs"
},
{
value: "friday",
label: "Fri"
},
{
value: "saturday",
label: "Sat"
}
],
claimListing: "Claim This Listing",
noClaimFields:
"There are no fields. Please go to Wiloke Listing Tools -> Claim Listing to add some fields",
pressToCopy: "Press Ctrl+C to copy this link",
copyLink: "Copy Link",
wantToDeleteDiscussion: "Are you sure want to delete this comment?",
passwordNotMatched: "The confirm password must be matched the new password",
reset: "Reset"
};
export default translations;
<file_sep>import * as types from "../constants/actionTypes";
import axios from "axios";
import he from "he";
import { zeroPad } from "../wiloke-elements";
export const getLocationList = (postType, locationName) => dispatch => {
return axios
.get(`taxonomies/listing-locations`, {
params: {
postType
}
})
.then(res => {
const locationList = [
{
id: "wilokeListingLocation",
name: locationName,
selected: true
},
...res.data.aTerms.map((item, index) => ({
id: item.term_id,
// name: `${he.decode(item.name)} (${zeroPad(item.count)})`,
name: `${he.decode(item.name)}`,
selected: false
}))
];
dispatch({
type: types.GET_LOCATION_LIST,
payload: {
[postType]: res.data.aTerms ? locationList : res.data.msg
}
});
})
.catch(err => console.log(err.message));
};
export const changeLocationList = (locationList, postType) => dispatch => {
dispatch({
type: types.CHANGE_LOCATION_LIST,
payload: {
[postType]: locationList
}
});
};
export const resetSelectedLocationList = _ => dispatch => {
dispatch({
type: types.RESET_SELECTED_LOCATION_LIST
});
};
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import {
View,
TouchableOpacity,
TextInput,
Animated,
StyleSheet,
ViewPropTypes,
Text,
Platform
} from "react-native";
import * as Consts from "../../../constants/styleConstants";
import { Feather } from "@expo/vector-icons";
/**
* Constants
*/
const INPUT_FOCUS_TOP = 29;
const INPUT_BLUR_TOP = 3;
const INPUT_FOCUS_FONTSIZE = 12;
const INPUT_BLUR_FONTSIZE = 14;
/**
* Create Component
*/
export default class InputMaterial extends PureComponent {
/**
* Prop Types
*/
static propTypes = {
...TextInput.propTypes,
placeholder: PropTypes.string,
placeholderTextColor: PropTypes.string,
style: ViewPropTypes.style,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
value: PropTypes.string,
iconName: PropTypes.string,
colorPrimary: PropTypes.string,
clearTextEnabled: PropTypes.bool,
required: PropTypes.bool
};
/**
* Default Props
*/
static defaultProps = {
placeholder: "TextInput",
placeholderTextColor: Consts.colorDark3,
onFocus: () => {},
onBlur: () => {},
colorPrimary: Consts.colorPrimary,
clearTextEnabled: true
};
/**
* State
*/
state = {
isFocusAnim: new Animated.Value(INPUT_BLUR_TOP),
isFocusAnimBorder: new Animated.Value(0),
itemWidth: 0,
isFocus: false
};
/**
* Focus TextInput
*/
_handleFocus = event => {
Animated.timing(this.state.isFocusAnim, {
toValue: INPUT_FOCUS_TOP,
duration: 150
}).start();
Animated.timing(this.state.isFocusAnimBorder, {
toValue: this.state.itemWidth
}).start(() => {
this.setState({
isFocus: true
});
});
this.props.onFocus(event);
};
/**
* End Editting TextInput
*/
_handleBlur = event => {
Animated.timing(this.state.isFocusAnim, {
toValue: event.nativeEvent.text === "" ? INPUT_BLUR_TOP : INPUT_FOCUS_TOP,
duration: 150
}).start();
Animated.timing(this.state.isFocusAnimBorder, {
toValue: 0
}).start(() => {
this.setState({
isFocus: false
});
});
this.props.onBlur(event);
};
/**
* Clear text
*/
_handleClearText = () => {
Animated.timing(this.state.isFocusAnim, {
toValue: INPUT_BLUR_TOP,
duration: 150
}).start();
Animated.timing(this.state.isFocusAnimBorder, {
toValue: 0
}).start(() => {
this.setState({
isFocus: false
});
});
this.props.onClearText();
};
/**
* Handle Animation Top For Placeholder
*/
_handleAnimTop = () => {
return this.state.isFocusAnim.interpolate({
inputRange: [0, INPUT_FOCUS_TOP - INPUT_BLUR_TOP],
outputRange: [
this.props.value === "" || typeof this.props.value === "undefined"
? INPUT_FOCUS_TOP
: INPUT_BLUR_TOP,
INPUT_BLUR_TOP
],
extrapolate: "clamp"
});
};
/**
* Handle Animation Size For Placeholder
*/
_handleAnimSize = () => {
return this.state.isFocusAnim.interpolate({
inputRange: [0, INPUT_FOCUS_TOP - INPUT_BLUR_TOP],
outputRange: [
this.props.value === "" || typeof this.props.value === "undefined"
? INPUT_BLUR_FONTSIZE
: INPUT_FOCUS_FONTSIZE,
INPUT_FOCUS_FONTSIZE
],
extrapolate: "clamp"
});
};
/**
* Get Width Container
*/
_handleLayout = event => {
this.setState({
itemWidth: event.nativeEvent.layout.width
});
};
/**
* Render Placeholder
*/
renderPlaceholder() {
const { placeholderTextColor, placeholder, required } = this.props;
return (
<Animated.View
style={[
styles.placeholder,
{
top: this._handleAnimTop()
}
]}
>
<Animated.Text
style={{
color: placeholderTextColor,
fontSize: this._handleAnimSize()
}}
>
{placeholder}
{required && (
<Text style={{ color: Consts.colorQuaternary }}> *</Text>
)}
</Animated.Text>
</Animated.View>
);
}
/**
* Render Border Animation
*/
renderBorderAnimation() {
return (
<Animated.View
style={[
styles.borderAnimation,
{
width: this.state.isFocusAnimBorder,
borderBottomColor: this.props.colorPrimary
}
]}
/>
);
}
/**
* Render TextInput
*/
renderTextInput() {
return (
<TextInput
{...this.props}
style={styles.input}
underlineColorAndroid="transparent"
selectionColor={this.props.colorPrimary}
placeholder=""
autoCorrect={false}
onFocus={this._handleFocus}
onBlur={this._handleBlur}
/>
);
}
/**
* Render Icon Right
*/
renderRight() {
const { value, clearTextEnabled, iconName } = this.props;
return (
<View style={styles.right}>
{typeof value !== "undefined" &&
clearTextEnabled &&
value.length > 0 && (
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleClearText}
style={styles.clear}
>
<Feather name={"x"} size={18} color={Consts.colorQuaternary} />
</TouchableOpacity>
)}
{iconName && (
<View style={{ height: 30, justifyContent: "center" }}>
<Feather name={iconName} size={18} color={Consts.colorDark3} />
</View>
)}
</View>
);
}
/**
* Render
*/
render() {
return (
<View
style={[styles.container, this.props.style]}
onLayout={this._handleLayout}
>
{this.renderPlaceholder()}
{this.renderBorderAnimation()}
{this.renderTextInput()}
{this.renderRight()}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
position: "relative",
zIndex: 9,
borderBottomWidth: 2,
borderBottomColor: Consts.colorDark5,
marginBottom: 10,
paddingRight: 20
},
input: {
borderBottomWidth: 0,
color: Consts.colorDark2,
paddingTop: 25,
paddingBottom: Platform.OS === "ios" ? 6 : 0,
fontSize: INPUT_BLUR_FONTSIZE
},
placeholder: {
position: "absolute",
left: 0,
top: INPUT_BLUR_TOP
},
borderAnimation: {
position: "absolute",
left: 0,
bottom: -2,
zIndex: 9,
width: 0,
height: 2,
borderBottomWidth: 2
},
right: {
position: "absolute",
right: 0,
bottom: 2,
flexDirection: "row",
alignItems: "center"
},
clear: {
width: 30,
height: 30,
alignItems: "center",
justifyContent: "center"
}
});
<file_sep>import React, { Component } from "react";
import {
View,
Text,
Dimensions,
TouchableHighlight,
StyleSheet
} from "react-native";
import * as Consts from "../../constants/styleConstants";
import stylesBase from "../../stylesBase";
import { ImageCover } from "../../wiloke-elements";
import { LinearGradient } from "expo";
const { width } = Dimensions.get("window");
const ITEM_WIDTH = width / 2.5;
export default class ListingCat extends Component {
static defaultProps = {
contentLoader: false
};
randomNumber = (min, max) => {
return Math.floor(Math.random() * max + min);
};
shuffle = array => {
var currentIndex = array.length,
temporaryValue,
randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
};
randomRgb = () => {
switch (this.randomNumber(1, 4)) {
case 1:
return [
this.randomNumber(0, 50),
this.randomNumber(30, 140),
this.randomNumber(150, 200)
];
case 2:
return [
this.randomNumber(0, 100),
this.randomNumber(100, 140),
this.randomNumber(30, 140)
];
case 3:
return [
this.randomNumber(30, 140),
this.randomNumber(0, 50),
this.randomNumber(100, 180)
];
default:
return [
this.randomNumber(100, 180),
this.randomNumber(0, 50),
this.randomNumber(30, 140)
];
}
};
render() {
const color1 = this.randomRgb();
const color2 = color1.map(item => {
let _item = item + this.randomNumber(-80, 80);
if (_item < 0) {
_item = 0;
} else if (_item > 180) {
_item = 160;
}
return _item;
});
return (
<View style={[styles.container, { width: this.props.itemWidth }]}>
<TouchableHighlight
underlayColor="rgba(255,255,255,0.2)"
onPress={this.props.onPress}
>
<View>
{this.props.image ? (
<ImageCover
src={this.props.image}
width="100%"
modifier="16by9"
overlay={0.9}
linearGradient={[
`rgba(${color1}, 0.8)`,
`rgba(${color2}, 0.4)`
]}
styles={{
borderRadius: Consts.round
}}
/>
) : (
<LinearGradient
colors={[`rgba(${color1}, 0.8)`, `rgba(${color2}, 0.4)`]}
start={{ x: 0.0, y: 1.0 }}
end={{ x: 1.0, y: 1.0 }}
style={{
width: this.props.itemWidth,
height: (this.props.itemWidth * 9) / 16
}}
/>
)}
<View style={[stylesBase.absFull, styles.name]}>
<Text style={[stylesBase.h6, styles.text]}>
{this.props.name}
</Text>
</View>
</View>
</TouchableHighlight>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
position: "relative",
zIndex: 9,
borderRadius: Consts.round,
overflow: "hidden"
},
name: {
flex: 1,
alignItems: "center",
justifyContent: "center"
},
text: {
color: "#fff",
letterSpacing: 0.5
}
});
<file_sep>import React, { Fragment, Component } from "react";
import PropTypes from "prop-types";
import { View, Text, StyleSheet, Platform } from "react-native";
import { connect } from "react-redux";
import {
getListings,
getEvents,
getLocationList,
getCategoryList,
changeLocationList,
changeCategoryList
} from "../../actions";
import { ModalPicker } from "../../wiloke-elements";
const RADIUS = 10;
class LocationModalPickerContainer extends Component {
static propTypes = {
postType: PropTypes.string
};
state = {
categorySelectedId: "wilokeListingCategory",
locationSelectedId: "wilokeListingLocation"
};
_getData = () => {
const {
postType,
translations,
getLocationList,
getCategoryList
} = this.props;
getLocationList(postType, translations.allRegions);
getCategoryList(postType, translations.allCategories);
};
componentDidMount() {
this._getData();
}
_handleChangeOptions = modify => (options, selected) => {
const { postType } = this.props;
this.setState({
categorySelectedId:
modify === "category" && selected.length > 0
? selected[0].id
: this.state.categorySelectedId,
locationSelectedId:
modify === "location" && selected.length > 0
? selected[0].id
: this.state.locationSelectedId
});
modify === "location" && this.props.changeLocationList(options, postType);
modify === "category" && this.props.changeCategoryList(options, postType);
};
componentDidUpdate(prevProps, prevState) {
const { locations, postType, nearByFocus } = this.props;
const { coords } = locations.location;
const nearby = {
lat: coords.latitude,
lng: coords.longitude,
unit: "km",
radius: RADIUS
};
if (
prevState.categorySelectedId !== this.state.categorySelectedId ||
prevState.locationSelectedId !== this.state.locationSelectedId
) {
if (postType === "event") {
this.props.getEvents(
this.state.categorySelectedId !== "wilokeListingCategory"
? this.state.categorySelectedId
: null,
this.state.locationSelectedId !== "wilokeListingLocation"
? this.state.locationSelectedId
: null,
postType,
nearByFocus ? nearby : null
);
} else {
this.props.getListings(
this.state.categorySelectedId !== "wilokeListingCategory"
? this.state.categorySelectedId
: null,
this.state.locationSelectedId !== "wilokeListingLocation"
? this.state.locationSelectedId
: null,
postType,
nearByFocus ? nearby : null
);
}
}
}
renderItemPicker(options, onChangeOptions, modify) {
const { settings } = this.props;
return (
<View style={styles.headerCenterWrapper}>
{options.length > 0 ? (
<ModalPicker
options={options}
onChangeOptions={onChangeOptions}
underlayBorder={false}
textResultStyle={{
color: "#fff",
fontSize: 12,
marginRight: 4,
width: 84
}}
textResultNumberOfLines={1}
iconResultColor="#fff"
clearSelectEnabled={false}
colorPrimary={settings.colorPrimary}
/>
) : (
<View style={{ height: 46, width: 84, justifyContent: "center" }}>
<Text style={{ color: "#fff" }}>...</Text>
</View>
)}
{modify === "category" && <View style={styles.lineVertical} />}
<View
style={[
styles.headerCenterBorder,
{
borderTopRightRadius: modify === "location" ? 0 : 5,
borderBottomRightRadius: modify === "location" ? 0 : 5,
borderTopLeftRadius: modify === "category" ? 0 : 5,
borderBottomLeftRadius: modify === "category" ? 0 : 5,
borderRightWidth: modify === "location" ? 0 : 1,
borderLeftWidth: modify === "category" ? 0 : 1
}
]}
/>
</View>
);
}
renderNearByText() {
const { translations } = this.props;
return (
<View
style={{
height: Platform.OS === "ios" ? 22 : 23,
width: 124,
justifyContent: "center",
borderTopLeftRadius: 5,
borderBottomLeftRadius: 5,
borderWidth: 1,
borderColor: "#fff",
borderRightWidth: 0,
marginTop: 12,
paddingHorizontal: 4
}}
>
<Text
style={{
color: "#fff",
fontSize: 12
}}
numberOfLines={1}
>
{translations.nearby}
</Text>
</View>
);
}
render() {
const { locationList, categoryList, postType, nearByFocus } = this.props;
return (
<View style={styles.container}>
{nearByFocus
? this.renderNearByText()
: this.renderItemPicker(
typeof locationList[postType] !== "undefined" &&
locationList[postType].length > 0 &&
locationList[postType],
this._handleChangeOptions("location"),
"location"
)}
{this.renderItemPicker(
typeof categoryList[postType] !== "undefined" &&
categoryList[postType].length > 0 &&
categoryList[postType],
this._handleChangeOptions("category"),
"category"
)}
</View>
);
}
}
const styles = StyleSheet.create({
headerCenterWrapper: {
position: "relative",
paddingLeft: 8,
paddingRight: 5,
zIndex: 9
},
headerCenterBorder: {
position: "absolute",
left: 0,
right: 0,
top: 12,
bottom: 12,
borderWidth: 1,
borderColor: "#fff",
opacity: 0.8,
borderRadius: 5,
zIndex: -1
},
container: {
flexDirection: "row"
},
lineVertical: {
position: "absolute",
top: 12,
bottom: 12,
left: 0,
width: 1,
backgroundColor: "#fff"
}
});
const mapStateToProps = state => ({
locationList: state.locationList,
categoryList: state.categoryList,
translations: state.translations,
nearByFocus: state.nearByFocus,
locations: state.locations,
settings: state.settings
});
export default connect(
mapStateToProps,
{
getListings,
getEvents,
getLocationList,
getCategoryList,
changeLocationList,
changeCategoryList
}
)(LocationModalPickerContainer);
<file_sep>import React, { Component } from "react";
import {
View,
StyleSheet,
Modal,
Dimensions,
TouchableOpacity,
StatusBar,
Platform
} from "react-native";
import {
Button,
InputMaterial,
CheckBox,
ModalPicker,
RangeSlider,
bottomBarHeight,
DatePicker
} from "../../wiloke-elements";
import { connect } from "react-redux";
import * as Consts from "../../constants/styleConstants";
import { Layout } from "../dumbs";
import { getListingFilters, getListingSearchResults } from "../../actions";
import { Loader } from "../../wiloke-elements";
import { GooglePlacesAutocomplete } from "react-native-google-places-autocomplete";
import Feather from "../../../node_modules/@expo/vector-icons/Feather";
import { Constants } from "expo";
const { height: SCREEN_HEIGHT } = Dimensions.get("window");
const HEADER_HEIGHT = 52 + Constants.statusBarHeight;
const CONTENT_HEIGHT = SCREEN_HEIGHT - HEADER_HEIGHT - 50 - bottomBarHeight;
class SearchScreen extends Component {
constructor(props) {
super(props);
this.state = {
text: "",
isScrollEnabled: true,
results: {},
isModalVisible: false,
location: null,
dateFrom: "",
dateTo: ""
};
this.googlePlaceText = "";
}
_checkValueDefault = item => {
switch (item.type) {
case "select":
if (!item.options) {
return {};
}
const selected = item.options.filter(item => item.selected);
return {
[item.key]:
item.multiple === "no"
? selected[0].id
: selected.map(item => item.id).join(",")
};
case "input":
return { [item.key]: item.value };
case "google_auto_complete":
return {
unit: item.unit,
radius: item.defaultRadius
};
case "checkbox":
return { [item.key]: item.value === "" ? "no" : "yes" };
case "date_range":
return {
[item.key]: {
from: "",
to: ""
}
};
default:
return {};
}
};
_setDefaultResults = async () => {
const { listingFilters } = this.props;
await this.setState({
results: listingFilters.reduce((acc, cur) => {
return { ...acc, ...this._checkValueDefault(cur) };
}, {})
});
this.googlePlaceText = "";
};
_getListingFilters = async () => {
await this.props.getListingFilters({}, null);
this._setDefaultResults();
};
componentDidMount() {
this._getListingFilters();
}
_handleRangeSliderBeginChangeValue = () => {
this.setState({
isScrollEnabled: false
});
};
_handleRangeSliderEndChangeValue = (radius, unit) => {
this.setState({
isScrollEnabled: true,
results: {
...this.state.results,
radius,
unit
}
});
};
_handleSearch = async () => {
const { navigation } = this.props;
const { results, location } = this.state;
const _results =
location === null
? { ...results, radius: "", unit: "" }
: { ...results, lat: location.lat, lng: location.lng };
const screen =
results.postType === "event"
? "EventSearchResultScreen"
: "ListingSearchResultScreen";
navigation.navigate(screen, { _results });
};
_handleInput = key => text => {
this.setState({
results: {
...this.state.results,
[key]: text
},
isModalVisible: key === "google_place" && text.length > 1 ? true : false
});
};
_handleTouchableInput = () => {
this.setState({
isModalVisible: true
});
};
_handleClearText = key => () => {
this.setState({
results: {
...this.state.results,
[key]: ""
}
});
};
_handleCheckBox = key => (name, checked) => {
this.setState({
results: {
...this.state.results,
[key]: checked ? "yes" : "no"
}
});
};
_handleModalPicker = item => async (options, selected) => {
if (item.key === "postType") {
await this.props.getListingFilters(
item,
selected.length > 0 ? selected[0].id : null
);
await this._setDefaultResults();
this.setState({
dateFrom: "",
dateTo: ""
});
}
this.setState({
results: {
...this.state.results,
[item.key]:
item.multiple === "no" && selected.length > 0
? selected[0].id
: selected.map(_item => _item.id).join(",")
}
});
};
_handleCloseModal = () => {
this.setState({
isModalVisible: false
});
this.googlePlaceText = "";
this.forceUpdate();
StatusBar.setBarStyle("light-content", true);
};
renderModalGooglePlaces() {
const { isModalVisible } = this.state;
return (
<Modal
animationType="slide"
transparent={true}
visible={isModalVisible}
onShow={this._handleShowModal}
onRequestClose={this._handleCloseModal}
style={styles.modalGooglePlaces}
>
<View style={styles.modalGooglePlacesInner}>
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleCloseModal}
style={{
position: "absolute",
top: Platform.OS === "ios" ? Constants.statusBarHeight + 15 : 15,
left: 8,
zIndex: 9
}}
>
<Feather name="chevron-down" size={30} color="#fff" />
</TouchableOpacity>
{this.renderGooglePlageAutocomplete()}
</View>
</Modal>
);
}
renderGooglePlageAutocomplete() {
const { settings, listingFilters } = this.props;
return (
<GooglePlacesAutocomplete
placeholder={
listingFilters.length > 0
? listingFilters.filter(item => item.key === "google_place")[0].name
: ""
}
minLength={2} // minimum length of text to search
autoFocus={true}
fetchDetails={true}
onPress={(data, details = null) => {
if (details !== null) {
const { location } = details.geometry;
const { lat, lng } = location;
this.setState({
location: {
lat,
lng
},
isModalVisible: false
});
}
this.googlePlaceText = data.description;
this.forceUpdate();
StatusBar.setBarStyle("light-content", true);
}}
getDefaultValue={() => {
return ""; // text input default value
}}
query={settings.oGoogleMapAPI}
styles={{
container: {
padding: 0
},
textInputContainer: {
backgroundColor: settings.colorPrimary,
height: "auto",
padding: 10,
paddingLeft: 50,
paddingTop:
Platform.OS === "ios" ? Constants.statusBarHeight + 10 : 10,
borderTopWidth: 0,
borderBottomWidth: 0
},
poweredContainer: {
display: "none"
},
description: {
fontWeight: "400",
fontSize: 14
},
predefinedPlacesDescription: {
color: Consts.colorDark2
}
}}
currentLocation={false}
nearbyPlacesAPI="GooglePlacesSearch"
GoogleReverseGeocodingQuery={
{
// available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
}
}
GooglePlacesSearchQuery={{
// available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
rankby: "distance",
types: "food"
}}
filterReverseGeocodingByTypes={[
"locality",
"administrative_area_level_3"
]}
predefinedPlacesAlwaysVisible={true}
textInputProps={{
autoCorrect: false,
style: {
paddingHorizontal: 10,
backgroundColor: "#fff",
width: "100%",
height: 40,
borderRadius: 5,
fontSize: 14,
color: Consts.colorDark2
}
}}
/>
);
}
renderInput(item, index) {
const { settings } = this.props;
return (
<InputMaterial
key={item.key}
placeholder={item.name}
onChangeText={this._handleInput(item.key)}
value={this.state.results[item.key]}
onClearText={this._handleClearText(item.key)}
iconName="search"
colorPrimary={settings.colorPrimary}
/>
);
}
renderInputAutoComplete(item, index) {
const { settings } = this.props;
return (
<View key={item.key} style={{ position: "relative", zIndex: 999 }}>
<TouchableOpacity
activeOpacity={1}
onPress={this._handleTouchableInput}
>
<InputMaterial
key={item.key}
placeholder={item.name}
returnKeyType="next"
onClearText={() => {
this.setState({
location: null
});
this.googlePlaceText = "";
this.forceUpdate();
}}
iconName="search"
colorPrimary={settings.colorPrimary}
editable={false}
pointerEvents="none"
value={this.googlePlaceText}
/>
</TouchableOpacity>
{this.googlePlaceText.length > 1 && (
<RangeSlider
label="Radius"
defaultValue={item.defaultRadius}
minValue={0}
maxValue={item.maxRadius}
onBeginChangeValue={this._handleRangeSliderBeginChangeValue}
onEndChangeValue={(event, radius) =>
this.state.location !== null
? this._handleRangeSliderEndChangeValue(radius, item.unit)
: {}
}
thumbTintColor={settings.colorPrimary}
fillLowerTintColor={settings.colorPrimary}
/>
)}
</View>
);
}
renderCheckBox(item, index) {
const { settings } = this.props;
return (
<CheckBox
key={item.key}
label={item.name}
name={item.key}
style={styles.checkBox}
onPress={this._handleCheckBox(item.key)}
circleAnimatedColor={[Consts.colorDark4, settings.colorPrimary]}
iconBackgroundColor={settings.colorPrimary}
/>
);
}
_handleDateFromChange = key => date => {
const { results } = this.state;
const to = !!results[key].to ? results[key].to : date;
this.setState({
dateFrom: date,
results: {
...results,
[key]: {
from: date,
to
}
}
});
};
_handleDateToChange = key => date => {
this.setState({
dateTo: date,
results: {
...this.state.results,
[key]: {
from: this.state.results[key].from,
to: date
}
}
});
};
renderDatePicker(item, index) {
const { translations } = this.props;
const { dateFrom, dateTo } = this.state;
return (
<View key={item.key}>
<DatePicker
date={dateFrom}
{...!!dateTo && { maxDate: dateTo }}
mode="date"
placeholder={item.fromLabel}
format="MM/DD/YYYY"
confirmBtnText={translations.ok}
cancelBtnText={translations.cancel}
onDateChange={this._handleDateFromChange(item.key)}
/>
<DatePicker
date={dateTo}
{...!!dateFrom && { minDate: dateFrom }}
mode="date"
placeholder={item.toLabel}
format="MM/DD/YYYY"
confirmBtnText={translations.ok}
cancelBtnText={translations.cancel}
onDateChange={this._handleDateToChange(item.key)}
/>
</View>
);
}
renderModalPicker(item, index) {
const { settings, translations } = this.props;
return (
item.options && (
<ModalPicker
key={item.key}
label={item.name}
options={item.options}
cancelText={translations.cancel}
matterial={true}
multiple={item.isMultiple === "no" ? false : true}
onChangeOptions={this._handleModalPicker(item)}
colorPrimary={settings.colorPrimary}
/>
)
);
}
renderContent = () => {
const { listingFilters } = this.props;
return (
<View style={{ padding: 10 }}>
{listingFilters.length > 0 ? (
listingFilters.map((item, index) => {
if (item.isDefault) {
switch (item.type) {
case "input":
return this.renderInput(item, index);
case "google_auto_complete":
return this.renderInputAutoComplete(item, index);
case "checkbox":
return this.renderCheckBox(item, index);
case "select":
return this.renderModalPicker(item, index);
case "date_range":
return this.renderDatePicker(item, index);
default:
return false;
}
}
})
) : (
<Loader size={30} height={150} />
)}
{listingFilters.filter(item => item.type === "google_auto_complete")
.length > 0 && this.renderModalGooglePlaces()}
</View>
);
};
renderAfterContent = () => (
<Button
size="lg"
block={true}
backgroundColor="secondary"
style={{
paddingVertical: 0,
height: 50,
justifyContent: "center"
}}
onPress={this._handleSearch}
>
{this.props.translations.searchNow}
</Button>
);
render() {
const { navigation, settings, translations } = this.props;
return (
<Layout
navigation={navigation}
headerType="headerHasBack"
title={translations.search}
goBack={() => navigation.goBack()}
goBackIconName="chevron-left"
keyboardDismiss={true}
renderContent={this.renderContent}
renderAfterContent={this.renderAfterContent}
scrollEnabled={this.state.isScrollEnabled}
colorPrimary={settings.colorPrimary}
contentHeight={CONTENT_HEIGHT}
/>
);
}
}
const styles = StyleSheet.create({
checkBox: {
marginBottom: 10,
paddingTop: 12,
paddingBottom: 6,
borderBottomWidth: 2,
borderBottomColor: Consts.colorDark5
},
modalGooglePlacesInner: {
position: "relative",
backgroundColor: "#fff",
height: SCREEN_HEIGHT
}
});
const mapStateToProps = state => ({
listingFilters: state.listingFilters,
translations: state.translations,
settings: state.settings
});
const mapDispatchToProps = { getListingFilters, getListingSearchResults };
export default connect(
mapStateToProps,
mapDispatchToProps
)(SearchScreen);
<file_sep>import React, { Component, Fragment } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
ImageBackground,
TouchableOpacity,
Animated,
ScrollView,
StatusBar,
Image,
Dimensions,
Platform,
StyleSheet
} from "react-native";
import { Overlay, ImageCover } from "../../wiloke-elements";
import { Constants } from "expo";
import stylesBase from "../../stylesBase";
import * as Consts from "../../constants/styleConstants";
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get("window");
const IOS = Platform.OS === "ios";
const HEADER_MAX_HEIGHT = SCREEN_HEIGHT / 2.5;
const HEADER_MIN_HEIGHT = 52 + Constants.statusBarHeight;
const HEADER_DISTANCE = HEADER_MAX_HEIGHT - HEADER_MIN_HEIGHT;
const SCROLL_EVENT_THROTTLE = 16;
const LOGO_MG_TOP = -40;
const WAVE_SIZE = 168;
const WAVE_MG_TOP = -84;
const TAB_NAVIGATOR_HEIGHT = 48;
function transformOrigin(matrix, origin) {
const { x, y, z } = origin;
const translate = MatrixMath.createIdentityMatrix();
MatrixMath.reuseTranslate3dCommand(translate, x, y, z);
MatrixMath.multiplyInto(matrix, translate, matrix);
const untranslate = MatrixMath.createIdentityMatrix();
MatrixMath.reuseTranslate3dCommand(untranslate, -x, -y, -z);
MatrixMath.multiplyInto(matrix, matrix, untranslate);
}
export default class LayoutHeaderParallax extends Component {
state = {
scrollY: new Animated.Value(IOS ? -HEADER_MAX_HEIGHT : 0),
logoWrapperHeight: 0,
tabItemCurrent: 0
};
animatedHeaderTranslate = (scrollY, logoWrapperHeight) => {
return scrollY.interpolate({
inputRange: [
0,
HEADER_DISTANCE + logoWrapperHeight + (logoWrapperHeight > 0 ? 30 : 0)
],
outputRange: [0, -HEADER_DISTANCE],
extrapolate: "clamp"
});
};
animatedImageTranslate = (scrollY, logoWrapperHeight) => {
return scrollY.interpolate({
inputRange: [
0,
HEADER_DISTANCE + logoWrapperHeight + (logoWrapperHeight > 0 ? 30 : 0)
],
outputRange: [0, 100],
extrapolate: "clamp"
});
};
animatedImageScale = scrollY => {
return scrollY.interpolate({
inputRange: [-300, 0],
outputRange: [1.5, 1],
extrapolate: "clamp"
});
};
animatedTitle = (scrollY, logoWrapperHeight, outputRange) => {
return scrollY.interpolate({
inputRange: [
0,
HEADER_DISTANCE / 2 +
logoWrapperHeight +
(logoWrapperHeight > 0 ? 30 : 0),
HEADER_DISTANCE + logoWrapperHeight + (logoWrapperHeight > 0 ? 30 : 0)
],
outputRange,
extrapolate: "clamp"
});
};
animatedOverlayOpacity = (scrollY, logoWrapperHeight, outputRange) => {
return scrollY.interpolate({
inputRange: [
0,
HEADER_DISTANCE + logoWrapperHeight + (logoWrapperHeight > 0 ? 30 : 0)
],
outputRange,
extrapolate: "clamp"
});
};
animatedGeneral = (scrollY, outputRange) => {
return scrollY.interpolate({
inputRange: [0, HEADER_DISTANCE / 2, HEADER_DISTANCE],
outputRange,
extrapolate: "clamp"
});
};
renderHeader = (scrollY, logoWrapperHeight) => (
<Fragment>
<Animated.View
pointerEvents="none"
style={[
styles.header,
{
transform: [
{
translateY: this.animatedHeaderTranslate(
scrollY,
logoWrapperHeight
)
}
]
}
]}
>
<Animated.Image
source={{ uri: this.props.backgroundImage }}
style={[
styles.backgroundImage,
{
transform: [
{
translateY: this.animatedImageTranslate(
scrollY,
logoWrapperHeight
)
},
{
scaleX: this.animatedImageScale(scrollY)
},
{
scaleY: this.animatedImageScale(scrollY)
}
],
opacity: this.animatedOverlayOpacity(scrollY, logoWrapperHeight, [
1,
0
])
}
]}
/>
<Overlay
animated={true}
opacity={this.animatedOverlayOpacity(scrollY, logoWrapperHeight, [
0.4,
0
])}
zIndex={1}
/>
<Overlay
animated={true}
opacity={this.animatedOverlayOpacity(scrollY, logoWrapperHeight, [
0,
1
])}
zIndex={2}
backgroundColor={this.props.colorPrimary}
/>
</Animated.View>
<View style={styles.headerHead}>
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
height: HEADER_MIN_HEIGHT,
paddingHorizontal: 10,
paddingTop: Constants.statusBarHeight
}}
>
<TouchableOpacity activeOpacity={0.8} onPress={this.props.goBack}>
{this.props.renderBackButton()}
</TouchableOpacity>
<Animated.View
style={{
transform: [
{
translateY: this.animatedTitle(scrollY, logoWrapperHeight, [
50,
50,
0
])
}
],
opacity: this.animatedTitle(scrollY, logoWrapperHeight, [0, 0, 1])
}}
>
<Text
style={[
stylesBase.h5,
{
color: "#fff"
}
]}
numberLines={1}
>
{this.props.name}
</Text>
</Animated.View>
{this.props.renderRightButton()}
</View>
</View>
<Animated.View
style={{
position: "absolute",
top: SCREEN_HEIGHT - TAB_NAVIGATOR_HEIGHT,
left: 0,
right: 0
}}
>
{this.renderTabNavigator()}
</Animated.View>
</Fragment>
);
randerAfterHeader = (scrollY, logoWrapperHeight) => {
return (
<Animated.View
pointerEvents="none"
style={[
styles.logoWrapper,
{
top: HEADER_MAX_HEIGHT,
opacity: this.animatedGeneral(scrollY, [1, 1, 0]),
transform: [
{
translateY: this.animatedGeneral(scrollY, [
0,
(-HEADER_DISTANCE + 50) / 2,
-HEADER_DISTANCE + 50
])
},
{
scaleX: this.animatedGeneral(scrollY, [1, 0.6, 0.1])
},
{
scaleY: this.animatedGeneral(scrollY, [1, 0.6, 0.1])
}
]
}
]}
>
<View
onLayout={event => {
this.setState({
logoWrapperHeight: event.nativeEvent.layout.width + WAVE_MG_TOP
});
}}
style={styles.logoInner}
>
<ImageCover
src={this.props.logo}
width={80}
borderRadius={40}
styles={styles.logo}
/>
<Image
source={require("../../../assets/wave.png")}
style={styles.wave}
/>
<View
style={{
justifyContent: "center",
alignItems: "center"
}}
>
<Text style={[stylesBase.h4, styles.title]}>{this.props.name}</Text>
<Text style={[stylesBase.text, styles.tagline]}>
{this.props.tagline}
</Text>
</View>
</View>
</Animated.View>
);
};
_handlePressTabItem = index => {
this.setState({ tabItemCurrent: index });
};
renderTabNavigator() {
const { tabNavigator } = this.props;
const { tabItemCurrent, tabScrollX } = this.state;
return (
<ScrollView
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="always"
horizontal={true}
showsHorizontalScrollIndicator={false}
style={{
height: TAB_NAVIGATOR_HEIGHT,
borderTopWidth: 1,
borderTopColor: Consts.colorGray1,
backgroundColor: "#fff"
}}
>
{tabNavigator.map((item, index) => (
<TouchableOpacity
activeOpacity={1}
style={{
height: TAB_NAVIGATOR_HEIGHT,
justifyContent: "center",
paddingHorizontal: 22
}}
key={index.toString()}
onPress={() => this._handlePressTabItem(index)}
>
<View
style={{
flexDirection: "row",
alignItems: "center"
}}
>
<View style={{ marginRight: 4 }}>
{item.icon &&
item.icon(
tabItemCurrent === index
? this.props.colorPrimary
: Consts.colorDark3
)}
</View>
<Text
style={{
fontSize: 12,
color:
tabItemCurrent === index
? this.props.colorPrimary
: Consts.colorDark3
}}
>
{item.label}
</Text>
</View>
</TouchableOpacity>
))}
</ScrollView>
);
}
render() {
const { logoWrapperHeight } = this.state;
const scrollY = Animated.add(
this.state.scrollY,
IOS ? HEADER_MAX_HEIGHT : 0
);
return (
<View style={styles.container}>
<Animated.ScrollView
scrollEventThrottle={SCROLL_EVENT_THROTTLE}
showsVerticalScrollIndicator={false}
onScroll={Animated.event(
[
{
nativeEvent: {
contentOffset: { y: this.state.scrollY }
}
}
],
{ useNativeDriver: true }
)}
contentInset={{
top: HEADER_MAX_HEIGHT
}}
contentOffset={{
y: -HEADER_MAX_HEIGHT
}}
>
{IOS && (
<Animated.View
style={{
backgroundColor: "#fff",
height: logoWrapperHeight + (logoWrapperHeight > 0 ? 30 : 0),
position: "relative",
top: -15,
transform: [
{
translateY: this.animatedGeneral(scrollY, [
0,
logoWrapperHeight + (logoWrapperHeight > 0 ? 15 : 0),
logoWrapperHeight + (logoWrapperHeight > 0 ? 15 : 0)
])
}
]
}}
/>
)}
{IOS && (
<View style={{ backgroundColor: "#fff" }}>
<View>{this.props.renderTopContent()}</View>
</View>
)}
<View
style={{
paddingTop: !IOS ? HEADER_MAX_HEIGHT + 15 : 0,
backgroundColor: Consts.colorGray2
}}
>
{!IOS && (
<Animated.View
style={{
backgroundColor: "#fff",
height:
logoWrapperHeight + (logoWrapperHeight > 0 ? 30 : 0) + 80,
position: "relative",
top: 0,
transform: [
{
translateY: this.animatedHeaderTranslate(
scrollY,
logoWrapperHeight + 100
)
}
]
}}
/>
)}
{!IOS && (
<View
style={{
backgroundColor: "#fff",
marginTop: -80
}}
>
<View>{this.props.renderTopContent()}</View>
</View>
)}
<View style={{ marginBottom: 15 }} />
{this.props.renderContent()}
</View>
</Animated.ScrollView>
{this.renderHeader(scrollY, logoWrapperHeight)}
{this.props.enableAfterHeader &&
this.randerAfterHeader(scrollY, logoWrapperHeight)}
</View>
);
}
}
LayoutHeaderParallax.defaultProps = {
renderBackButton: () => <Text style={styles.back}>Back</Text>,
renderRightButton: () => <Text />,
renderTopContent: () => {},
isLoading: false,
enableAfterHeader: true,
colorPrimary: Consts.colorPrimary
};
LayoutHeaderParallax.propTypes = {
renderBackButton: PropTypes.func.isRequired,
goBack: PropTypes.func.isRequired,
renderContent: PropTypes.func.isRequired,
backgroundImage: PropTypes.string,
logo: PropTypes.string,
enableAfterHeader: PropTypes.bool,
tabNavigator: PropTypes.array,
colorPrimary: PropTypes.string
};
const styles = StyleSheet.create({
container: {
backgroundColor: "#fff",
paddingBottom: TAB_NAVIGATOR_HEIGHT
},
header: {
position: "absolute",
top: 0,
left: 0,
right: 0,
zIndex: 1,
height: HEADER_MAX_HEIGHT,
overflow: "hidden"
},
backgroundImage: {
position: "absolute",
top: 0,
left: 0,
right: 0,
width: null,
height: HEADER_MAX_HEIGHT,
resizeMode: "cover"
},
headerHead: {
position: "absolute",
top: 0,
left: 0,
right: 0,
zIndex: 9
},
back: {
color: "#fff"
},
logoWrapper: {
position: "absolute",
left: 0,
right: 0,
zIndex: 10,
alignItems: "center",
overflow: "hidden",
marginTop: LOGO_MG_TOP,
paddingBottom: 15
},
logoInner: {
position: "relative",
alignItems: "center"
},
logo: {
marginTop: 4
},
title: {
marginBottom: 3
},
wave: {
marginTop: WAVE_MG_TOP,
marginBottom: 20,
tintColor: "#fff",
width: WAVE_SIZE,
height: (WAVE_SIZE * 131) / 317
}
});
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { View, StyleSheet, ViewPropTypes } from "react-native";
import * as Consts from "../../../constants/styleConstants";
import stylesBase from "../../../stylesBase";
import IconTextSmall from "../atoms/IconTextSmall";
export default class ContentBox extends PureComponent {
static propTypes = {
headerTitle: PropTypes.string,
headerIcon: PropTypes.string,
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.element),
PropTypes.element,
PropTypes.bool
]),
renderRight: PropTypes.oneOfType([
PropTypes.func,
PropTypes.element,
PropTypes.bool
]),
renderFooter: PropTypes.oneOfType([
PropTypes.func,
PropTypes.element,
PropTypes.bool
]),
style: ViewPropTypes.style,
headerStyle: ViewPropTypes.style,
footerStyle: ViewPropTypes.style,
colorPrimary: PropTypes.string
};
static defaultProps = {
renderRight: () => {}
};
render() {
return (
<View style={[styles.container, this.props.style]}>
<View style={[styles.header, this.props.headerStyle]}>
<View style={{ flexDirection: "row" }}>
<IconTextSmall
text={this.props.headerTitle.toUpperCase()}
iconName={this.props.headerIcon}
iconSize={16}
iconColor={Consts.colorDark2}
textStyle={{
color: Consts.colorDark1,
fontSize: 9,
fontWeight: "bold",
letterSpacing: 1,
marginTop: 2,
marginLeft: 5
}}
iconColor={this.props.colorPrimary}
/>
</View>
<View style={styles.headerRight}>{this.props.renderRight()}</View>
</View>
<View style={styles.content}>{this.props.children}</View>
{typeof this.props.renderFooter === "function" && (
<View style={[styles.footer, this.props.footerStyle]}>
{this.props.renderFooter()}
</View>
)}
{typeof this.props.renderFooter === "object" && (
<View style={[styles.footer, this.props.footerStyle]}>
{this.props.renderFooter}
</View>
)}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: "#fff",
borderWidth: 1,
borderColor: Consts.colorGray1
},
header: {
borderBottomWidth: 1,
borderBottomColor: Consts.colorGray1,
paddingHorizontal: 10,
paddingVertical: 16,
flexDirection: "row",
justifyContent: "space-between"
},
content: {
padding: 10
},
footer: {
borderTopWidth: 1,
borderTopColor: Consts.colorGray1,
paddingHorizontal: 10,
paddingVertical: 16
}
});
<file_sep>import React, { PureComponent } from "react";
import {
View,
Text,
Image,
TouchableOpacity,
Dimensions,
StyleSheet
} from "react-native";
import PropTypes from "prop-types";
import * as Consts from "../../constants/styleConstants";
import stylesBase from "../../stylesBase";
import Heading from "./Heading";
import { ImageCover, IconTextSmall } from "../../wiloke-elements";
const { width } = Dimensions.get("window");
const ITEM_WIDTH = width / 1.3;
export default class ListingPopItem extends PureComponent {
static propTypes = {
onPress: PropTypes.func,
image: PropTypes.string,
logo: PropTypes.string,
name: PropTypes.string,
tagline: PropTypes.string,
location: PropTypes.string,
colorPrimary: PropTypes.string
};
static defaultProps = {
contentLoader: false,
onPress: () => {},
colorPrimary: Consts.colorPrimary
};
renderLoader = () => <View style={styles.contentLoader} />;
renderContent = () => (
<TouchableOpacity activeOpacity={0.6} onPress={this.props.onPress}>
<View style={styles.inner}>
<View>
<ImageCover
src={this.props.image}
width={ITEM_WIDTH}
modifier="16by9"
overlay={0.4}
// linearGradient={["rgba(0, 107, 247, 1)", "rgba(237, 99, 146, 1)"]}
styles={{
borderRadius: Consts.round
}}
/>
</View>
<View style={[stylesBase.pd10, styles.content]}>
<View style={styles.logoWrap}>
<ImageCover
src={this.props.logo}
width={30}
styles={styles.logo}
borderRadius={15}
/>
</View>
<Heading
title={this.props.name}
text={this.props.tagline}
titleSize={13}
textSize={11}
titleNumberOfLines={1}
textNumberOfLines={1}
/>
<View style={{ marginRight: 20, marginTop: 2 }}>
<IconTextSmall
text={this.props.location}
iconName="map-pin"
textStyle={styles.metaText}
numberOfLines={1}
iconColor={this.props.colorPrimary}
/>
{/* <View style={{ width: 10 }} />
<IconTextSmall
text={this.props.phone}
iconName="phone"
textStyle={styles.metaText}
/> */}
</View>
</View>
</View>
</TouchableOpacity>
);
render() {
return (
<View style={styles.container}>
{!this.props.contentLoader ? this.renderContent() : this.renderLoader()}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
borderRadius: Consts.round,
overflow: "hidden",
width: ITEM_WIDTH
},
inner: {
position: "relative",
zIndex: 9,
paddingBottom: 60
},
logoWrap: {
marginBottom: 8
},
content: {
position: "absolute",
left: 10,
right: 10,
bottom: 0,
zIndex: 1,
backgroundColor: "#fff",
borderRadius: Consts.round
},
// metaText: {
// color: Consts.colorGray1
// },
contentLoader: {
backgroundColor: Consts.colorGray1,
borderRadius: Consts.round,
width: ITEM_WIDTH,
height: ITEM_WIDTH * (56.25 / 100)
}
});
<file_sep>import React, { Component } from "react";
import { Dimensions, TouchableOpacity, Alert } from "react-native";
import { Layout, ListingSmallCard, Rated } from "../dumbs";
import {
ViewWithLoading,
LoadingFull,
MessageError
} from "../../wiloke-elements";
import { connect } from "react-redux";
import { getMyFavorites, addMyFavorites } from "../../actions";
import { Feather } from "@expo/vector-icons";
import _ from "lodash";
import he from "he";
import Swipeout from "react-native-swipeout";
const { width: SCREEN_WIDTH } = Dimensions.get("window");
class FavoritesScreen extends Component {
state = {
isLoading: true,
isScrollEnabled: true,
isDeleteLoading: false
};
async componentDidMount() {
const { getMyFavorites, navigation } = this.props;
await getMyFavorites();
this.setState({ isLoading: false });
}
shouldComponentUpdate(nextProps, nextState) {
if (!_.isEqual(nextProps.myFavorites, this.props.myFavorites)) {
return true;
}
if (!_.isEqual(nextState.isLoading, this.state.isLoading)) {
return true;
}
if (!_.isEqual(nextState.isScrollEnabled, this.state.isScrollEnabled)) {
return true;
}
if (!_.isEqual(nextState.isDeleteLoading, this.state.isDeleteLoading)) {
return true;
}
return false;
}
_handlePressItem = item => () => {
const { navigation } = this.props;
navigation.navigate("ListingDetailScreen", {
id: item.ID,
name: he.decode(item.postTitle),
tagline: !!item.tagLine ? he.decode(item.tagLine) : null,
link: item.postLink,
author: item.oAuthor,
image:
SCREEN_WIDTH > 420 ? item.oFeaturedImg.large : item.oFeaturedImg.medium,
logo: item.logo ? item.logo : item.oFeaturedImg.thumbnail
});
};
_deleteListItem = ID => async _ => {
const { addMyFavorites } = this.props;
await this.setState({ isDeleteLoading: true });
await addMyFavorites(ID);
this.setState({ isDeleteLoading: false });
};
renderItem = item => {
const { listIdPostFavoritesRemoved, translations } = this.props;
const condition =
listIdPostFavoritesRemoved.filter(_item => _item.id === item.ID).length >
0;
return (
!condition && (
<Swipeout
key={item.ID.toString()}
right={[
{
text: translations.delete,
type: "delete",
onPress: () => {
Alert.alert(
`${translations.delete} ${he.decode(item.postTitle)}`,
translations.confirmDeleteFavorites,
[
{
text: translations.cancel,
style: "cancel"
},
{
text: translations.ok,
onPress: this._deleteListItem(item.ID)
}
],
{ cancelable: false }
);
}
}
]}
autoClose={true}
scroll={event => this.setState({ isScrollEnabled: event })}
style={{
backgroundColor: "#fff"
}}
>
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handlePressItem(item)}
>
<ListingSmallCard
image={item.oFeaturedImg.thumbnail}
image={
SCREEN_WIDTH > 420
? item.oFeaturedImg.large
: item.oFeaturedImg.medium
}
title={item.postTitle}
text={item.tagLine}
renderRate={() => {
return (
item.oReview && (
<Rated
rate={item.oReview.average}
max={item.oReview.mode}
rateStyle={{ fontSize: 13, marginRight: 2 }}
maxStyle={{ fontSize: 9 }}
style={{ marginVertical: 5 }}
/>
)
);
}}
/>
</TouchableOpacity>
</Swipeout>
)
);
};
renderContent = () => {
const { myFavorites, translations } = this.props;
const { oResults, status, msg } = myFavorites;
const { isLoading, isDeleteLoading } = this.state;
return (
<ViewWithLoading
isLoading={isLoading}
contentLoader="headerAvatar"
avatarSquare={true}
avatarSize={60}
contentLoaderItemLength={8}
gap={0}
>
{!_.isEmpty(oResults) && oResults.map(this.renderItem)}
<LoadingFull visible={isDeleteLoading} />
{status === "error" && <MessageError message={translations[msg]} />}
</ViewWithLoading>
);
};
render() {
const { navigation, settings, translations, auth } = this.props;
const { isLoggedIn } = auth;
const { name } = navigation.state.params;
return (
<Layout
navigation={navigation}
headerType="headerHasBack"
title={name}
goBack={() => navigation.goBack()}
renderRight={() => (
<TouchableOpacity
activeOpacity={0.5}
onPress={() => navigation.navigate("SearchScreen")}
>
<Feather name="search" size={20} color="#fff" />
</TouchableOpacity>
)}
renderContent={this.renderContent}
colorPrimary={settings.colorPrimary}
textSearch={translations.search}
isLoggedIn={isLoggedIn}
scrollEnabled={this.state.isScrollEnabled}
/>
);
}
}
const mapStateToProps = state => ({
myFavorites: state.myFavorites,
listIdPostFavoritesRemoved: state.listIdPostFavoritesRemoved,
settings: state.settings,
translations: state.translations,
auth: state.auth
});
const mapDispatchToProps = {
getMyFavorites,
addMyFavorites
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(FavoritesScreen);
<file_sep>import React from "react";
import { View, Dimensions } from "react-native";
import * as Consts from "../../constants/styleConstants";
import { EventDiscussionContainer } from "../smarts";
import { Layout } from "../dumbs";
import { Constants } from "expo";
import { connect } from "react-redux";
const { height: SCREEN_HEIGHT } = Dimensions.get("window");
const HEADER_HEIGHT = 52 + Constants.statusBarHeight;
const CONTENT_HEIGHT = SCREEN_HEIGHT - HEADER_HEIGHT;
const EventDiscussionAllScreen = props => {
const { navigation, eventDiscussion, settings } = props;
const { params } = navigation.state;
return (
<Layout
navigation={navigation}
headerType="headerHasBack"
title={eventDiscussion.discussionsOn}
goBack={() => navigation.goBack()}
renderRight={() => {}}
renderContent={() => (
<View style={{ padding: 10 }}>
<EventDiscussionContainer
id={params.id}
type=""
navigation={navigation}
colorPrimary={settings.colorPrimary}
/>
</View>
)}
scrollViewEnabled={false}
contentHeight={CONTENT_HEIGHT}
scrollViewStyle={{
backgroundColor: Consts.colorGray2
}}
colorPrimary={settings.colorPrimary}
/>
);
};
const mapStateToProps = state => ({
eventDiscussion: state.eventDiscussion,
settings: state.settings
});
export default connect(mapStateToProps)(EventDiscussionAllScreen);
<file_sep>import React, { PureComponent } from "react";
import {
View,
Text,
TouchableOpacity,
Share,
Platform,
Alert
} from "react-native";
import { Feather } from "@expo/vector-icons";
import { connect } from "react-redux";
import * as Consts from "../../constants/styleConstants";
import {
ActionSheet,
Row,
Col,
Modal,
bottomBarHeight,
P,
InputMaterial,
ModalPicker,
Toast,
Button,
Loader
} from "../../wiloke-elements";
import { ParallaxListingScreen } from "../dumbs";
import {
ListingDescriptionContainer,
ListingListFeatureContainer,
ListingPhotosContainer,
ListingReviewsContainer,
ListingDetailNavContainer,
ListingEventsContainer,
ListingVideosContainer,
ListingSidebarContainer,
AverageDetailReviewContainer
} from "../smarts";
import {
getListingDetail,
addMyFavorites,
getReportForm,
postReport,
getKeyFirebase,
resetListingDetail,
messageChatActive
} from "../../actions";
import _ from "lodash";
class ListingDetailScreen extends PureComponent {
state = {
isReviews: true,
isVisibleReport: false,
report: {},
isLoadingReport: true
};
async componentDidMount() {
const { navigation, getListingDetail } = this.props;
const { params } = navigation.state;
await getListingDetail(params.id);
const { listingDetail } = this.props;
this.setState({
isReviews:
typeof listingDetail.oHomeSections !== "undefined" &&
Object.keys(listingDetail.oHomeSections).length > 0 &&
Object.keys(listingDetail.oHomeSections).filter(
item => listingDetail.oHomeSections[item].category === "reviews"
).length > 0
});
}
componentDidUpdate() {
const { scrollTo } = this.props;
setTimeout(
() =>
this._scrollView
.getNode()
.scrollTo({ x: 0, y: scrollTo, animated: false }),
1
);
}
componentWillUnmount() {
this.props.resetListingDetail();
}
_hide = key => {
if (key) {
return {};
}
return {
opacity: 0,
display: "none"
// position: "absolute",
// bottom: "100%",
// zIndex: -999
};
};
renderHeaderLeft = () => {
const { navigation } = this.props;
return (
<TouchableOpacity activeOpacity={0.5} onPress={() => navigation.goBack()}>
<View
style={{
width: 30,
height: 30,
justifyContent: "center",
alignItems: "center"
}}
>
<Feather name="chevron-left" size={26} color="#fff" />
</View>
</TouchableOpacity>
);
};
renderHeaderCenter = () => {
const { navigation } = this.props;
const { params } = navigation.state;
return (
<Text style={{ color: "#fff" }} numberOfLines={1}>
{params.name}
</Text>
);
};
_handleWriteReview = () => {
const { auth, navigation, listingDetail } = this.props;
const { isReviews } = this.state;
const { isLoggedIn } = auth;
const { params } = navigation.state;
if (isReviews) {
isLoggedIn
? navigation.navigate("ReviewFormScreen", {
mode: listingDetail.oReview.mode,
id: params.id
})
: this._handleAccountScreen();
}
};
_handleReportForm = async () => {
this.setState({ isVisibleReport: true });
await this.props.getReportForm();
this.setState({ isLoadingReport: false });
};
_handleReportFormBackdropPress = () => {
this.setState({ isVisibleReport: false });
};
_handlePostReport = id => async () => {
await this.props.postReport(id, this.state.report);
setTimeout(() => {
this._toast.show(this.props.reportMessage, 3000);
}, 500);
};
_actionSheetMoreOptions = () => {
const { translations, auth } = this.props;
const { isLoggedIn } = auth;
return {
// options: ["Cancel", "Remove", "Report", "Write a review"],
options: [
translations.cancel,
translations.inbox,
translations.share,
// "Write a review",
translations.report
],
destructiveButtonIndex: 3,
cancelButtonIndex: 0,
onAction: buttonIndex => {
switch (buttonIndex) {
case 1:
isLoggedIn ? this._handleInbox() : this._handleAccountScreen();
break;
case 2:
this._handleShare();
break;
case 3:
this._handleWriteReview();
break;
case 4:
this._handleReportForm();
break;
default:
break;
}
}
};
};
renderHeaderRight = () => {
return (
<ActionSheet
{...this._actionSheetMoreOptions()}
renderButtonItem={() => (
<View
style={{
width: 40,
height: 40,
justifyContent: "center",
alignItems: "center"
}}
>
<Feather name="more-horizontal" size={24} color="#fff" />
</View>
)}
/>
);
};
_handleShare = () => {
const { navigation } = this.props;
const { link } = navigation.state.params;
Share.share(
{
...Platform.select({
ios: {
message: "",
url: link
},
android: {
message: link
}
})
// title: "Wow, did you see that?"
}
// {
// ...Platform.select({
// ios: {
// // iOS only:
// excludedActivityTypes: ["com.apple.UIKit.activity.PostToTwitter"]
// },
// android: {
// // Android only:
// dialogTitle: "Share : " + "this.props.title"
// }
// })
// }
);
};
_handleInbox = async () => {
const {
navigation,
getKeyFirebase,
shortProfile,
messageChatActive
} = this.props;
const { params } = navigation.state;
const { author } = params;
const { ID: userID, displayName } = author;
const myID = shortProfile.userID;
if (myID.toString() !== userID.toString()) {
await getKeyFirebase(myID, userID);
const { keyFirebase } = this.props;
!!keyFirebase && messageChatActive(myID, keyFirebase, true);
navigation.navigate("SendMessageScreen", {
userID,
displayName,
key: keyFirebase
});
}
};
_handleAddFavorite = () => {
const { navigation, addMyFavorites } = this.props;
const { id } = navigation.state.params;
addMyFavorites(id);
};
_renderReportFormItem = item => {
const { settings, translations } = this.props;
switch (item.type) {
case "text":
return (
<InputMaterial
key={item.key}
placeholder={item.label}
colorPrimary={settings.colorPrimary}
onChangeText={text => {
this.setState({
report: {
...this.state.report,
[item.key]: text
}
});
}}
/>
);
case "select":
return (
<ModalPicker
key={item.key}
label={item.label}
options={item.options}
cancelText={translations.cancel}
matterial={true}
colorPrimary={settings.colorPrimary}
onChangeOptions={(name, isChecked) => {
this.setState({
report: {
...this.state.report,
[item.key]: isChecked.length > 0 ? isChecked[0].id : ""
}
});
}}
/>
);
case "textarea":
return (
<InputMaterial
key={item.key}
placeholder={item.label}
multiline={true}
numberOfLines={4}
colorPrimary={settings.colorPrimary}
onChangeText={text => {
this.setState({
report: {
...this.state.report,
[item.key]: text
}
});
}}
/>
);
default:
return false;
}
};
_handleAccountScreen = () => {
const { translations, navigation } = this.props;
Alert.alert(translations.login, translations.requiredLogin, [
{
text: translations.cancel,
style: "cancel"
},
{
text: translations.continue,
onPress: () => navigation.navigate("AccountScreen")
}
]);
};
renderActions = () => {
const {
navigation,
listIdPostFavorites,
listIdPostFavoritesRemoved,
settings,
translations,
reportForm,
listingDetail,
auth
} = this.props;
const { isLoggedIn } = auth;
const { id } = navigation.state.params;
const listIdPostFavoritesFilter = listIdPostFavorites.filter(
item => item.id === id
);
const isListingFavorite =
!_.isEmpty(listingDetail) && listingDetail.oFavorite.isMyFavorite;
const condition =
listIdPostFavoritesFilter.length > 0 ||
(listIdPostFavoritesFilter.length > 0 &&
!_.isEmpty(listingDetail) &&
isListingFavorite) ||
(listIdPostFavoritesRemoved.length === 0 && isListingFavorite);
return (
<View
style={{
borderTopWidth: 1,
borderBottomWidth: 1,
borderColor: Consts.colorGray1,
paddingVertical: 15,
paddingBottom: 15,
backgroundColor: "#fff",
marginBottom: 10,
marginTop: -10,
marginHorizontal: -10
}}
>
<Row>
<Col column={4}>
<TouchableOpacity
activeOpacity={0.6}
onPress={
isLoggedIn ? this._handleAddFavorite : this._handleAccountScreen
}
style={{
flexDirection: "column",
alignItems: "center"
}}
>
<Feather
name="heart"
size={22}
color={condition ? Consts.colorQuaternary : Consts.colorDark3}
/>
<View style={{ height: 4 }} />
<Text
style={{
color: condition ? Consts.colorQuaternary : Consts.colorDark2,
fontSize: 12
}}
>
{translations.favorite}
</Text>
</TouchableOpacity>
</Col>
<Col column={4}>
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleShare}
style={{
flexDirection: "column",
alignItems: "center"
}}
>
<Feather name="share" size={22} color={Consts.colorDark3} />
<View style={{ height: 4 }} />
<Text style={{ color: Consts.colorDark2, fontSize: 12 }}>
{translations.share}
</Text>
</TouchableOpacity>
</Col>
<Col column={4}>
<Modal
isVisible={this.state.isVisibleReport}
headerIcon="alert-triangle"
headerTitle={translations.report}
colorPrimary={settings.colorPrimary}
cancelText={translations.cancel}
submitText={translations.submit}
onBackdropPress={this._handleReportFormBackdropPress}
renderButtonTextToggle={() => (
<View
style={{
flexDirection: "column",
alignItems: "center"
}}
>
<Feather
name="alert-triangle"
size={22}
color={Consts.colorDark3}
/>
<View style={{ height: 4 }} />
<Text style={{ color: Consts.colorDark2, fontSize: 12 }}>
{translations.report}
</Text>
</View>
)}
onButtonTextToggle={this._handleReportForm}
onSubmitAsync={this._handlePostReport(id)}
>
{this.state.isLoadingReport ? (
<View style={{ height: 100 }}>
<Loader size="small" height={100} />
</View>
) : (
<View>
{!_.isEmpty(reportForm) && (
<View>
<P>{reportForm.description}</P>
{!_.isEmpty(reportForm.aFields) &&
reportForm.aFields.map(this._renderReportFormItem)}
</View>
)}
</View>
)}
</Modal>
</Col>
<Col column={4}>
<TouchableOpacity
activeOpacity={0.6}
onPress={
isLoggedIn ? this._handleInbox : this._handleAccountScreen
}
style={{
flexDirection: "column",
alignItems: "center"
}}
>
<Feather
name="message-square"
size={22}
color={Consts.colorDark3}
/>
<View style={{ height: 4 }} />
<Text style={{ color: Consts.colorDark2, fontSize: 12 }}>
{translations.inbox}
</Text>
</TouchableOpacity>
</Col>
</Row>
</View>
);
};
renderDescription = type => (id, item, max) => (
<ListingDescriptionContainer
key={item.key}
params={{ id, item, max }}
type={type}
/>
);
renderListFeatures = type => (id, item, max) => (
<ListingListFeatureContainer
key={item.key}
params={{ id, item, max }}
type={type}
/>
);
renderPhotos = type => (id, item, max) => (
<ListingPhotosContainer
key={item.key}
params={{ id, item, max }}
type={type}
/>
);
renderReviews = type => (id, item, max) => {
const { navigation, settings, listingDetail } = this.props;
const { isReviews } = this.state;
const isAverage =
!_.isEmpty(listingDetail.oReview) && listingDetail.oReview.average !== 0;
return (
<View key={item.key}>
{isReviews && isAverage && type !== null && this.renderAverageRating()}
{/* <View style={{ marginBottom: 10 }}>
<Button
size="lg"
block={true}
backgroundColor="primary"
radius="round"
style={{
paddingVertical: 0,
height: 50,
justifyContent: "center"
}}
onPress={this._handleWriteReview}
colorPrimary={settings.colorPrimary}
>
Write a review
</Button>
</View> */}
<ListingReviewsContainer
navigation={navigation}
params={{ id, item, max }}
type={type}
colorPrimary={settings.colorPrimary}
/>
</View>
);
};
renderEvents = type => (id, item, max) => {
const { navigation } = this.props;
return (
<ListingEventsContainer
key={item.key}
navigation={navigation}
params={{ id, item, max }}
type={type}
/>
);
};
renderVideos = type => (id, item, max) => (
<ListingVideosContainer
key={item.key}
params={{ id, item, max }}
type={type}
/>
);
_checkRenderDetailBox = (id, item, index) => {
const { category, maximumItemsOnHome: max } = item;
switch (category) {
case "content":
case "text":
return this.renderDescription(null)(id, item, max);
case "tags":
case "boxIcon":
return this.renderListFeatures(null)(id, item, max);
case "photos":
return this.renderPhotos(null)(id, item, max);
case "reviews":
return this.renderReviews(null)(id, item, max);
case "events":
return this.renderEvents(null)(id, item, max);
case "videos":
return this.renderVideos(null)(id, item, max);
default:
return false;
}
};
_checkRenderTabContent = (item, index) => {
const { navigation } = this.props;
const { params } = navigation.state;
const { id } = params;
switch (item.category) {
case "home":
return this.renderDetailHomeContent();
case "content":
case "text":
return this.renderDescription("all")(id, item, null);
case "tags":
case "boxIcon":
return this.renderListFeatures("all")(id, item, null);
case "photos":
return this.renderPhotos("all")(id, item, null);
case "reviews":
return this.renderReviews("all")(id, item, null);
case "videos":
return this.renderVideos("all")(id, item, null);
case "events":
return this.renderEvents("all")(id, item, null);
default:
return false;
}
};
renderAverageRating = () => {
return <AverageDetailReviewContainer />;
};
renderDetailHomeContent = () => {
const { navigation, listingDetail, settings } = this.props;
const { params } = navigation.state;
const { id } = params;
const { isReviews } = this.state;
const isAverage =
!_.isEmpty(listingDetail.oReview) && listingDetail.oReview.average !== 0;
return (
<View>
{isReviews && isAverage && this.renderAverageRating()}
{settings.oSingleListing.contentPosition === "above_sidebar" && (
<ListingSidebarContainer
listingId={params.id}
navigation={navigation}
/>
)}
{typeof listingDetail.oHomeSections !== "undefined" &&
Object.keys(listingDetail.oHomeSections).length > 0 &&
Object.keys(listingDetail.oHomeSections).map((item, index) => {
const _item = listingDetail.oHomeSections[item];
return this._checkRenderDetailBox(id, _item, index);
})}
{settings.oSingleListing.contentPosition !== "above_sidebar" && (
<ListingSidebarContainer
listingId={params.id}
navigation={navigation}
/>
)}
</View>
);
};
renderContent = () => {
const { listingDetailNav } = this.props;
return (
<View
style={{
padding: 10,
backgroundColor: Consts.colorGray2,
marginBottom: bottomBarHeight
}}
>
{this.renderActions()}
<Toast ref={c => (this._toast = c)} />
{listingDetailNav.length > 0 &&
listingDetailNav.map((item, index) => (
<View
key={index.toString()}
style={this._hide(item.current && true)}
>
{this._checkRenderTabContent(item, index)}
</View>
))}
</View>
);
};
renderNavigation = () => {
const { navigation, translations, listingDetail, settings } = this.props;
const { params } = navigation.state;
const itemFirst = [
{
name: translations.home,
category: "home",
key: "home",
icon: "home",
current: true,
loaded: true
}
];
const navArr =
typeof listingDetail.oNavigation !== "undefined"
? Object.values(listingDetail.oNavigation).map(item => ({
name: item.name,
category: item.category,
key: item.key,
icon: item.icon,
current: false,
loaded: false
}))
: [];
const newData = [...itemFirst, ...navArr];
return (
<ListingDetailNavContainer
data={newData}
listingId={params.id}
colorPrimary={settings.colorPrimary}
/>
);
};
render() {
const { navigation, settings } = this.props;
const { params } = navigation.state;
return (
<ParallaxListingScreen
scrollViewRef={ref => (this._scrollView = ref)}
headerImageSource={params.image}
logo={params.logo}
title={params.name}
tagline={!!params.tagline ? params.tagline : null}
renderNavigation={this.renderNavigation}
overlayRange={[0, 1]}
overlayColor={settings.colorPrimary}
renderHeaderLeft={this.renderHeaderLeft}
renderHeaderCenter={this.renderHeaderCenter}
renderHeaderRight={this.renderHeaderRight}
renderContent={this.renderContent}
navigation={navigation}
/>
);
}
}
const mapStateToProps = state => ({
listingDetailNav: state.listingDetailNav,
listingDetail: state.listingDetail,
translations: state.translations,
scrollTo: state.scrollTo,
settings: state.settings,
listIdPostFavorites: state.listIdPostFavorites,
listIdPostFavoritesRemoved: state.listIdPostFavoritesRemoved,
reportForm: state.reportForm,
auth: state.auth,
reportMessage: state.reportMessage,
shortProfile: state.shortProfile,
keyFirebase: state.keyFirebase
});
const mapDispatchToProps = {
getListingDetail,
addMyFavorites,
getReportForm,
postReport,
getKeyFirebase,
resetListingDetail,
messageChatActive
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ListingDetailScreen);
<file_sep>import EventItem from "./EventItem";
import Header from "./Header";
import HeaderHasFilter from "./HeaderHasFilter";
import Heading from "./Heading";
import Hero from "./Hero";
import Layout from "./Layout";
import LayoutHeaderParallax from "./LayoutHeaderParallax";
import ListingCat from "./ListingCat";
import ListingItem from "./ListingItem";
import ListingPopItem from "./ListingPopItem";
import Rated from "./Rated";
import TextBox from "./TextBox";
import TextBoxColor from "./TextBoxColor";
import CommentReview from "./CommentReview";
import ListingLayoutHorizontal from "./ListingLayoutHorizontal";
import ListingLayoutPopular from "./ListingLayoutPopular";
import ListingLayoutCat from "./ListingLayoutCat";
import ParallaxListingScreen from "./ParallaxListingScreen";
import ButtonFooterContentBox from "./ButtonFooterContentBox";
import ListingHours from "./ListingHours";
import ListingBusinessInfo from "./ListingBusinessInfo";
import PriceRange from "./PriceRange";
import ListingCatList from "./ListingCatList";
import ListingStatistic from "./ListingStatistic";
import ListingTagList from "./ListingTagList";
import RatedSmall from "./RatedSmall";
import { WebItem } from "./WebItem";
import { PhoneItem } from "./PhoneItem";
import { AddressItem } from "./AddressItem";
import PostCard from "./PostCard";
import Form from "./Form";
import FormLv2 from "./FormLv2";
import ListingSmallCard from "./ListingSmallCard";
import Icon from "./Icon";
import ReviewForm from "./ReviewForm";
export {
EventItem,
Header,
HeaderHasFilter,
Heading,
Hero,
Layout,
LayoutHeaderParallax,
ListingCat,
ListingItem,
ListingPopItem,
Rated,
TextBox,
TextBoxColor,
CommentReview,
ListingLayoutHorizontal,
ListingLayoutPopular,
ListingLayoutCat,
ParallaxListingScreen,
ButtonFooterContentBox,
ListingHours,
ListingBusinessInfo,
PriceRange,
ListingCatList,
ListingStatistic,
ListingTagList,
RatedSmall,
WebItem,
PhoneItem,
AddressItem,
PostCard,
Form,
FormLv2,
ListingSmallCard,
Icon,
ReviewForm
};
<file_sep>import React, { Component } from "react";
import {
Text,
View,
TouchableOpacity,
Animated,
Keyboard,
Dimensions
} from "react-native";
import PropTypes from "prop-types";
import { Button, P, ViewWithLoading } from "../../wiloke-elements";
import { connect } from "react-redux";
import {
login,
getAccountNav,
getMyProfile,
register,
getSignUpForm,
getShortProfile,
setUserConnection,
getMessageChatNewCount,
setDeviceTokenToFirebase,
getNotificationAdminSettings,
setNotificationSettings
} from "../../actions";
import * as Consts from "../../constants/styleConstants";
import { Form } from "../dumbs";
import _ from "lodash";
const { width: SCREEN_WIDTH } = Dimensions.get("window");
class LoginFormContainer extends Component {
static propTypes = {
// onPressRegister: PropTypes.func
};
static defaultProps = {
// onPressRegister: () => {}
};
state = {
formTypeFocus: "login",
animation: new Animated.Value(0),
isLoading: true
};
async componentDidMount() {
await this.props.getSignUpForm();
this.setState({ isLoading: false });
}
_handleNotificationSettings = async myID => {
await this.props.getNotificationAdminSettings();
const { notificationAdminSettings } = this.props;
await this.props.setNotificationSettings(
myID,
notificationAdminSettings,
"start"
);
};
_handleLogin = (results, status) => async _ => {
const {
login,
getAccountNav,
getMyProfile,
getShortProfile,
setUserConnection,
getMessageChatNewCount,
deviceToken,
setDeviceTokenToFirebase
} = this.props;
await login(results);
getAccountNav();
getMyProfile();
await getShortProfile();
const { shortProfile, auth } = this.props;
const myID = shortProfile.userID;
const { firebaseID } = shortProfile;
if (auth.isLoggedIn && myID) {
setUserConnection(myID, true);
getMessageChatNewCount(myID);
setDeviceTokenToFirebase(myID, firebaseID, deviceToken);
await this._handleNotificationSettings(myID);
}
Keyboard.dismiss();
};
_handleRegister = async (results, status) => {
const {
register,
getAccountNav,
getMyProfile,
setUserConnection,
getShortProfile,
getMessageChatNewCount,
deviceToken,
setDeviceTokenToFirebase
} = this.props;
status === "success" && (await register(results));
getAccountNav();
getMyProfile();
await getShortProfile();
const { shortProfile, auth } = this.props;
const myID = shortProfile.userID;
const { firebaseID } = shortProfile;
if (auth.isLoggedIn) {
setUserConnection(myID, true);
getMessageChatNewCount(myID);
setDeviceTokenToFirebase(myID, firebaseID, deviceToken);
await this._handleNotificationSettings(myID);
}
Keyboard.dismiss();
};
_handleTab = type => async () => {
Animated.timing(this.state.animation, {
toValue:
type === "login" ? 10 - (SCREEN_WIDTH > 600 ? 600 : SCREEN_WIDTH) : 0,
duration: 200,
useNativeDriver: true
}).start(() => {
this.setState({
formTypeFocus: type
});
});
};
_renderFormLogin() {
const { settings, loginError, translations } = this.props;
return (
<View style={{ width: (SCREEN_WIDTH > 600 ? 600 : SCREEN_WIDTH) - 20 }}>
<Form
headerTitle={translations.login}
headerIcon="lock"
colorPrimary={settings.colorPrimary}
validationData={translations.validationData}
renderTopComponent={() =>
loginError && (
<P style={{ color: Consts.colorQuaternary }}>
{translations[loginError]}
</P>
)
}
data={[
{
type: "text",
name: "username",
label: translations.username,
required: true,
validationType: "username"
},
{
type: "<PASSWORD>",
name: "<PASSWORD>",
label: translations.password
}
]}
renderButtonSubmit={(results, status) => {
const { isLoginLoading } = this.props;
return (
<View>
<Button
backgroundColor="primary"
colorPrimary={settings.colorPrimary}
size="lg"
radius="round"
block={true}
isLoading={isLoginLoading}
onPress={this._handleLogin(results, status)}
>
{translations.login}
</Button>
{settings.isAllowRegistering === "yes" && (
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleTab("login")}
style={{ alignItems: "center", marginTop: 15 }}
>
<P>{translations.register}</P>
</TouchableOpacity>
)}
</View>
);
}}
/>
</View>
);
}
_renderFormRegister() {
const { settings, translations, signUpForm, signupError } = this.props;
const _signUpForm =
!_.isEqual(signUpForm) &&
signUpForm.map(item => ({
type: item.type,
label: !!translations[item.label]
? translations[item.label]
: item.label,
name: item.key,
...(item.required ? { required: item.required } : {}),
...(!!item.validationType
? { validationType: item.validationType }
: {}),
...(item.link ? { link: item.link } : {})
}));
return (
<View
style={{
position: "relative",
left: 10,
width: (SCREEN_WIDTH > 600 ? 600 : SCREEN_WIDTH) - 20
}}
>
<ViewWithLoading
isLoading={this.state.isLoading}
contentLoader="contentHeader"
>
<Form
headerTitle={translations.register}
headerIcon="check-square"
colorPrimary={settings.colorPrimary}
validationData={translations.validationData}
renderTopComponent={() =>
signupError && (
<P style={{ color: Consts.colorQuaternary }}>
{translations[signupError]}
</P>
)
}
data={_signUpForm}
renderButtonSubmit={(results, status) => {
const { translations, isSignupLoading, settings } = this.props;
return (
<View>
<Button
backgroundColor="primary"
colorPrimary={settings.colorPrimary}
size="lg"
radius="round"
block={true}
isLoading={isSignupLoading}
onPress={async () => this._handleRegister(results, status)}
>
{translations.register}
</Button>
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleTab("register")}
style={{ alignItems: "center", marginTop: 15 }}
>
<P>{translations.login}</P>
</TouchableOpacity>
</View>
);
}}
/>
</ViewWithLoading>
</View>
);
}
render() {
const { settings } = this.props;
return (
<Animated.View
style={{
flexDirection: "row",
width: (SCREEN_WIDTH > 600 ? 600 : SCREEN_WIDTH) * 2,
transform: [
{
translateX: this.state.animation
}
]
}}
>
{this._renderFormLogin()}
{settings.isAllowRegistering === "yes" && this._renderFormRegister()}
</Animated.View>
);
}
}
const mapStateToProps = state => ({
settings: state.settings,
auth: state.auth,
loginError: state.loginError,
isLoginLoading: state.isLoginLoading,
translations: state.translations,
signUpForm: state.signUpForm,
signupError: state.signupError,
isSignupLoading: state.isSignupLoading,
shortProfile: state.shortProfile,
deviceToken: state.deviceToken,
notificationAdminSettings: state.notificationAdminSettings
});
const mapDispatchToProps = {
login,
getAccountNav,
getMyProfile,
register,
getSignUpForm,
getShortProfile,
setUserConnection,
getMessageChatNewCount,
setDeviceTokenToFirebase,
getNotificationAdminSettings,
setNotificationSettings
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(LoginFormContainer);
<file_sep>import * as types from "../constants/actionTypes";
const reducers = type => (state = false, action) => {
switch (action.type) {
case type:
return action.isTimeout;
default:
return state;
}
};
export const requestTimeout = reducers(types.REQUEST_TIMEOUT);
export const isHomeRequestTimeout = reducers(types.HOME_REQUEST_TIMEOUT);
export const isListingRequestTimeout = reducers(types.LISTING_REQUEST_TIMEOUT);
export const isListingSearchRequestTimeout = reducers(
types.LISTING_SEARCH_REQUEST_TIMEOUT
);
export const isEventRequestTimeout = reducers(types.EVENT_REQUEST_TIMEOUT);
export const isListingDetailDesRequestTimeout = reducers(
types.LISTING_DETAIL_DES_REQUEST_TIMEOUT
);
export const isListingDetailPhotosRequestTimeout = reducers(
types.LISTING_DETAIL_PHOTOS_REQUEST_TIMEOUT
);
export const isListingDetailVideosRequestTimeout = reducers(
types.LISTING_DETAIL_VID_REQUEST_TIMEOUT
);
export const isListingDetailListRequestTimeout = reducers(
types.LISTING_DETAIL_LIST_REQUEST_TIMEOUT
);
export const isListingDetailReviewsRequestTimeout = reducers(
types.LISTING_DETAIL_REVIEWS_REQUEST_TIMEOUT
);
export const isListingDetailEventRequestTimeout = reducers(
types.LISTING_DETAIL_EVENT_REQUEST_TIMEOUT
);
export const isEventSearchRequestTimeout = reducers(
types.EVENT_SEARCH_REQUEST_TIMEOUT
);
export const isListingDetailSidebarRequestTimeout = reducers(
types.LISTING_DETAIL_SIDEBAR_REQUEST_TIMEOUT
);
export const isArticleRequestTimeout = reducers(types.ARTICLE_REQUEST_TIMEOUT);
export const isMenuRequestTimeout = reducers(types.MENU_REQUEST_TIMEOUT);
<file_sep>import { GET_DEVICE_TOKEN } from "../constants/actionTypes";
import { ctlGet } from "./reducerController";
export const deviceToken = (state = "", action) => {
return ctlGet(state, action)(GET_DEVICE_TOKEN);
};
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { TouchableOpacity, ViewPropTypes } from "react-native";
import { IconTextMedium } from "../../wiloke-elements";
import * as Consts from "../../constants/styleConstants";
import { MapView } from "expo";
export class AddressItem extends PureComponent {
_renderMap = () => {
const { address, navigation } = this.props;
const { name } = navigation.state.params;
const lat = Number(address.lat);
const lng = Number(address.lng);
return (
<MapView
style={{
width: "100%",
height: "100%"
}}
initialRegion={{
latitude: lat,
longitude: lng,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}}
pointerEvents="none"
>
<MapView.Marker
coordinate={{
latitude: lat,
longitude: lng
}}
title={name}
description={address.address}
/>
</MapView>
);
};
render() {
const {
address,
navigation,
style,
iconColor,
iconBackgroundColor
} = this.props;
const { name } = navigation.state.params;
const lat = Number(address.lat);
const lng = Number(address.lng);
return (
<TouchableOpacity
activeOpacity={0.5}
onPress={_ => {
navigation.navigate("WebViewScreen", {
url: {
title: name,
description: address.address,
lat,
lng
}
});
}}
style={style}
>
<IconTextMedium
iconName="map-pin"
iconSize={30}
iconColor={iconColor}
iconBackgroundColor={iconBackgroundColor}
text={address.address}
renderBoxLastText={this._renderMap}
/>
</TouchableOpacity>
);
}
}
AddressItem.propTypes = {
address: PropTypes.object,
style: ViewPropTypes.style
};
AddressItem.defaultProps = {
iconColor: "#fff",
iconBackgroundColor: Consts.colorSecondary
};
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
TouchableOpacity,
FlatList,
StyleSheet
} from "react-native";
import { connect } from "react-redux";
import {
getListingDetailNavigation,
changeListingDetailNavigation,
getListingDescription,
getListingBoxCustom,
getListingListFeature,
getListingPhotos,
getListingVideos,
getListingReviews,
getListingEvents,
getScrollTo
} from "../../actions";
import * as Consts from "../../constants/styleConstants";
import _ from "lodash";
import { bottomBarHeight, FontIcon } from "../../wiloke-elements";
class ListingDetailNavContainer extends Component {
static defaultProps = {
colorPrimary: Consts.colorPrimary
};
static propTypes = {
colorPrimary: PropTypes.string
};
state = {
imageIndex: 0,
isImageViewVisible: false,
loadOnly: true
};
componentDidMount() {
const { data } = this.props;
const { getListingDetailNavigation } = this.props;
getListingDetailNavigation(data);
}
componentDidUpdate(prevProps) {
if (_.isEqual(prevProps.data, this.props.data)) return false;
this.props.getListingDetailNavigation(this.props.data);
}
_handlePress = (item, index) => {
const {
listingId,
changeListingDetailNavigation,
getListingDescription,
getListingBoxCustom,
getListingListFeature,
getListingReviews,
getListingPhotos,
getListingVideos,
getListingEvents,
listingDetailNav
} = this.props;
const checkCurrent = listingDetailNav.filter(_item => _item.current)[0];
if (!_.isEqual(checkCurrent, item)) {
changeListingDetailNavigation(item.key);
this.props.getScrollTo(0);
}
if (!item.loaded) {
switch (item.category) {
case "content":
return getListingDescription(listingId, item.key, null);
case "text":
return getListingBoxCustom(listingId, item.key, null);
case "tags":
case "boxIcon":
return getListingListFeature(listingId, item.key, null);
case "reviews":
return getListingReviews(listingId, item.key, null);
case "photos":
return getListingPhotos(listingId, item.key, null);
case "videos":
return getListingVideos(listingId, item.key, null);
case "events":
return getListingEvents(listingId, item.key, null);
default:
return false;
}
}
};
// _getIcon = category => {
// switch (category) {
// case "home":
// return "home";
// case "photos":
// return "image";
// case "videos":
// return "video";
// case "events":
// return "calendar";
// case "reviews":
// return "star";
// case "content":
// return "file-text";
// case "tags":
// return "list";
// default:
// return "check";
// }
// };
renderItemNav = ({ item, index }) => {
return (
<View>
<TouchableOpacity
activeOpacity={0.5}
onPress={() => this._handlePress(item, index)}
style={[
styles.itemNav,
{
borderTopWidth: 2,
borderTopColor: item.current
? this.props.colorPrimary
: "transparent"
}
]}
>
<FontIcon
name={item.icon}
size={16}
color={item.current ? this.props.colorPrimary : Consts.colorDark3}
/>
<View style={{ width: 5 }} />
<Text
style={{
fontSize: 12,
fontWeight: "600",
color: item.current ? this.props.colorPrimary : Consts.colorDark3
}}
>
{item.name}
</Text>
</TouchableOpacity>
</View>
);
};
// _getTabEmpty = () => {
// const {
// listingVideosAll,
// listingPhotosAll,
// listingEventsAll,
// listingListFeatureAll,
// listingDescriptionAll
// } = this.props;
// return [
// isEmpty(listingVideosAll) ? "videos" : null,
// isEmpty(listingPhotosAll) ? "photos" : null,
// isEmpty(listingEventsAll) ? "events" : null,
// isEmpty(listingListFeatureAll) ? "tags" : null,
// isEmpty(listingDescriptionAll) ? "content" : null
// ];
// };
render() {
const { listingDetailNav } = this.props;
return (
<FlatList
style={styles.navigation}
// data={listingDetailNav.filter(
// item => !this._getTabEmpty().includes(item.category)
// )}
data={listingDetailNav}
keyExtractor={(item, index) => index.toString()}
renderItem={this.renderItemNav}
horizontal={true}
showsHorizontalScrollIndicator={false}
/>
);
}
}
const styles = StyleSheet.create({
navigation: {
position: "absolute",
left: 0,
right: 0,
bottom: 0,
zIndex: 999,
backgroundColor: "#fff",
borderTopWidth: 1,
borderTopColor: Consts.colorGray1,
paddingBottom: bottomBarHeight
},
itemNav: {
height: 43,
paddingHorizontal: 12,
flexDirection: "row",
justifyContent: "center",
alignItems: "center"
}
});
const mapStateToProps = state => ({
listingDetailNav: state.listingDetailNav
// listingVideosAll: state.listingVideosAll,
// listingPhotosAll: state.listingPhotosAll,
// listingEventsAll: state.listingEventsAll,
// listingListFeatureAll: state.listingListFeatureAll,
// listingDescriptionAll: state.listingDescriptionAll
});
export default connect(
mapStateToProps,
{
getListingDetailNavigation,
changeListingDetailNavigation,
getListingDescription,
getListingBoxCustom,
getListingListFeature,
getListingPhotos,
getListingVideos,
getListingReviews,
getListingEvents,
getScrollTo
}
)(ListingDetailNavContainer);
<file_sep>import getSlideFromRightTransition from "react-navigation-slide-from-right-transition";
import * as Consts from "../constants/styleConstants";
const RootTabNavOpts = colorPrimary => ({
tabBarPosition: "bottom",
animationEnabled: false,
swipeEnabled: false,
tabBarOptions: {
showIcon: true,
showLabel: true,
upperCaseLabel: false,
lazy: true,
activeTintColor: colorPrimary,
inactiveTintColor: Consts.colorDark3,
style: {
backgroundColor: "#fff",
borderTopWidth: 0,
borderTopColor: colorPrimary
},
labelStyle: {
borderRadius: 100,
fontSize: 10,
fontWeight: "500",
padding: 0,
paddingLeft: 3,
paddingRight: 3,
paddingBottom: 2,
margin: 0
},
indicatorStyle: {
backgroundColor: "transparent"
}
}
});
export default RootTabNavOpts;
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
Image,
Modal,
FlatList,
TouchableOpacity,
PanResponder,
Animated,
Easing,
StatusBar,
ActivityIndicator,
Keyboard,
Dimensions,
StyleSheet
} from "react-native";
import { Constants } from "expo";
import { Feather } from "@expo/vector-icons";
import * as Consts from "../../../constants/styleConstants";
import stylesBase from "../../../stylesBase";
const { width: screenWidth, height: screenHeight } = Dimensions.get("window");
export default class GalleryLightBox extends Component {
constructor(props) {
super(props);
this.state = {
gallery: [],
modalVisible: false,
loadingVisible: false,
showModal: new Animated.Value(0),
position: new Animated.ValueXY(),
containerLayout: null,
itemActiveLayout: {},
isMoveX: false,
isMoveY: false,
isActiveIndex: null,
isMove: new Animated.Value(false)
};
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: (event, gestureState) => true,
onStartShouldSetPanResponderCapture: (event, gestureState) => true,
onMoveShouldSetPanResponder: (event, gestureState) => true,
onMoveShouldSetPanResponderCapture: (event, gestureState) => true,
onPanResponderGrant: (event, gestureState) => {
this.state.position.setOffset({
x: 0,
y: this.state.position.y._value
});
this.state.position.setValue({
x: 0,
y: 0
});
},
onPanResponderMove: (evt, gestureState) => {
const { position } = this.state;
position.setValue({
x: 0,
y:
!this.state.isMoveX &&
Math.abs(gestureState.dx) < Math.abs(gestureState.dy)
? gestureState.dy
: 0
});
},
onPanResponderTerminationRequest: (evt, gestureState) => false,
onPanResponderRelease: (event, gestureState) => {
const { position, showModal } = this.state;
position.flattenOffset();
this.state.isMove.setValue(false);
if (
!this.state.isMoveX &&
Math.abs(gestureState.dx) < Math.abs(gestureState.dy)
) {
if (gestureState.dy > 150) {
Animated.spring(position, {
toValue: {
x: 0,
y: screenHeight / 1.5
},
duration: 300,
userNativeDriver: true
}).start(() => {
this.setState(
{
modalVisible: false
},
() => {
position.setValue({
x: 0,
y: 0
});
}
);
});
Animated.timing(showModal, {
toValue: 0,
duration: 500
}).start();
StatusBar.setHidden(false, "fade");
} else if (gestureState.dy < -150) {
Animated.spring(position, {
toValue: {
x: 0,
y: -screenHeight / 1.5
},
duration: 300,
userNativeDriver: true
}).start(() => {
this.setState(
{
modalVisible: false
},
() => {
position.setValue({
x: 0,
y: 0
});
}
);
});
Animated.timing(showModal, {
toValue: 0,
duration: 500
}).start();
StatusBar.setHidden(false, "fade");
} else {
Animated.spring(position, {
toValue: {
x: 0,
y: 0
},
duration: 300,
userNativeDriver: true
}).start(() => {
position.setValue({
x: 0,
y: 0
});
});
}
}
},
onShouldBlockNativeResponder: (evt, gestureState) => true
});
this.opacity = this.state.position.y.interpolate({
inputRange: [-screenHeight / 2, 0, screenHeight / 2],
outputRange: [0, 1, 0],
extrapolate: "clamp"
});
this.scale = this.state.position.y.interpolate({
inputRange: [-screenHeight, 0, screenHeight],
outputRange: [0.3, 1, 0.3],
extrapolate: "clamp"
});
}
// componentDidUpdate(prevProps, prevState, snapshot) {
// console.log("componentDidUpdate");
// }
_onOpenModal = index => {
// this._item.measure((fx, fy, width, height, px, py) => {
// });
this.setState({
modalVisible: true,
loadingVisible: true,
isActiveIndex: index
});
StatusBar.setHidden(true, "fade");
Keyboard.dismiss();
};
_onCloseModal = () => {
const { showModal } = this.state;
Animated.timing(showModal, {
toValue: 0,
duration: 500
}).start(() => {
this.setState({
modalVisible: false
});
StatusBar.setHidden(false, "fade");
});
};
_onShowModal = () => {
const { isActiveIndex, showModal } = this.state;
this._flatListModal.scrollToIndex({
animated: false,
index: isActiveIndex
});
Animated.timing(showModal, {
toValue: 300,
duration: 500
}).start(() => {
this.setState({
loadingVisible: false
});
});
};
componentDidMount() {
this.setState({
gallery: this.props.renderGallery()
});
}
_onLayoutContainer = event => {
this.setState({
containerLayout: event.nativeEvent.layout
});
};
renderModal() {
const { modalVisible, gallery, showModal, itemActiveLayout } = this.state;
const { renderLightBox, renderThumbnail } = this.props;
const ITEM_OPACITY = showModal.interpolate({
inputRange: [0, 300],
outputRange: [0, 1],
extrapolate: "clamp"
});
// console.log(this.state.isMoveX);
return (
<Modal
animationType="fade"
transparent={true}
visible={modalVisible}
style={styles.modal}
onShow={this._onShowModal}
onRequestClose={() => {}}
>
<View style={styles.modalView}>
<View style={styles.close}>
<TouchableOpacity
activeOpacity={0.6}
onPress={this._onCloseModal}
style={{
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
height: 40,
opacity: 0.7
}}
>
<Feather name="x-circle" size={30} color={Consts.colorGray1} />
</TouchableOpacity>
</View>
<FlatList
data={gallery}
ref={c => (this._flatListModal = c)}
renderItem={({ item }) => (
<View
style={{
position: "relative",
width: screenWidth
}}
>
<Animated.View
ref={c => (this._imageLightBox = c)}
{...this._panResponder.panHandlers}
style={{
position: "relative",
zIndex: 2,
overflow: "hidden",
opacity: ITEM_OPACITY
// transform: this.state.position.getTranslateTransform()
// transform: [
// ...this.state.position.getTranslateTransform(),
// {
// scale: this.scale
// }
// ]
}}
>
<Image
source={{
uri: item.uri
}}
resizeMode="contain"
style={{
width: screenWidth,
height: screenHeight
}}
/>
</Animated.View>
<View
style={{
position: "absolute",
zIndex: 1,
height: 50,
top: "50%",
left: 0,
right: 0,
marginTop: -25,
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
opacity: this.state.loadingVisible ? 1 : 0
}}
>
<ActivityIndicator
size="small"
color={this.props.activityIndicatorColor}
/>
</View>
</View>
)}
pagingEnabled={true}
keyExtractor={item => item.id}
numColumns={1}
horizontal={true}
showsHorizontalScrollIndicator={false}
// scrollEnabled={this.state.isMoveX ? false : true}
onScrollBeginDrag={() => {
this.setState({
isMoveX: true
});
}}
onScrollEndDrag={() => {
this.setState({
isMoveX: false
});
}}
/>
</View>
<Animated.View
style={[
stylesBase.absFull,
{
backgroundColor: this.props.underlayColor,
opacity: this.opacity
}
]}
/>
</Modal>
);
}
renderThumbnail() {
const { column, itemGap } = this.props;
const { gallery, containerLayout } = this.state;
return containerLayout !== null ? (
<FlatList
data={gallery}
renderItem={({ item, index }) => (
<View
ref={c => (this._item = c)}
style={[
styles.gridItem,
{
padding: itemGap / 2,
width: containerLayout.width / column,
height: containerLayout.width / column
}
]}
>
<TouchableOpacity
activeOpacity={0.5}
onPress={() => this._onOpenModal(index)}
>
<Image
source={{
uri: item.thumbnail
}}
style={{
width: containerLayout.width / column - itemGap,
height: containerLayout.width / column - itemGap
}}
/>
</TouchableOpacity>
</View>
)}
keyExtractor={item => item.id}
numColumns={column}
showsHorizontalScrollIndicator={false}
/>
) : (
<Text>Loading...</Text>
);
}
render() {
const { itemGap } = this.props;
const { modalVisible } = this.state;
return (
<View
style={[
styles.container,
{
margin: -itemGap / 2
}
]}
onLayout={this._onLayoutContainer}
>
{this.renderThumbnail()}
{this.renderModal()}
</View>
);
}
}
GalleryLightBox.defaultProps = {
renderThumbnail: () => {},
renderGallery: () => [],
underlayColor: "#000",
column: 3,
itemGap: 10,
activityIndicatorColor: Consts.colorPrimary
};
GalleryLightBox.propTypes = {
renderThumbnail: PropTypes.func,
renderLightBox: PropTypes.func,
underlayColor: PropTypes.string
};
const styles = StyleSheet.create({
container: {
flexDirection: "row"
},
gridItem: {
width: "25%"
},
modal: {
position: "relative",
justifyContent: "center",
alignItems: "center"
},
modalView: {
position: "absolute",
zIndex: 2,
left: 0,
right: 0,
top: 0,
bottom: 0,
flex: 1,
justifyContent: "center",
paddingTop: Constants.statusBarHeight
},
close: {
position: "absolute",
bottom: 40,
left: 0,
right: 0,
zIndex: 9
}
});
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, Animated, Image, StyleSheet, Dimensions } from "react-native";
import { ParallaxScreen, ImageCover } from "../../wiloke-elements";
import Heading from "./Heading";
const LOGO_SIZE = 80;
const WAVE_SIZE = 168;
const { height: SCREEN_HEIGHT } = Dimensions.get("window");
export default class ParallaxListingScreen extends Component {
static propTypes = {
renderContent: PropTypes.func,
logo: PropTypes.string,
title: PropTypes.string,
tagline: PropTypes.string,
renderNavigation: PropTypes.func
};
static defaultProps = {
renderContent: () => {},
renderNavigation: () => {}
};
state = {
scrollY: new Animated.Value(0),
headerMaxHeight: 0,
headerMinHeight: 0
};
_handleGetScrollYAnimation = (scrollY, headerMeasure) => {
const { headerMaxHeight, headerMinHeight } = headerMeasure;
this.setState({ scrollY, headerMaxHeight, headerMinHeight });
};
_getHeaderDistance = () => {
const { headerMaxHeight, headerMinHeight } = this.state;
return headerMaxHeight - headerMinHeight;
};
_getLogoWrapperInnerStyle = () => {
const { scrollY } = this.state;
const scale = scrollY.interpolate({
inputRange: [0, this._getHeaderDistance()],
outputRange: [1, 0],
extrapolate: "clamp"
});
const opacity = scrollY.interpolate({
inputRange: [this._getHeaderDistance(), this._getHeaderDistance() + 1],
outputRange: [1, 0],
extrapolate: "clamp"
});
return {
transform: [{ scale }],
opacity
};
};
_getLogoWrapperStyle = () => {
const { scrollY, headerMinHeight } = this.state;
const opacity = scrollY.interpolate({
inputRange: [headerMinHeight, headerMinHeight + 1],
outputRange: [1, 0],
extrapolate: "clamp"
});
return { opacity: 1 };
};
renderAfterImage = () => {
return (
<Animated.View
style={[styles.logoWrapper, this._getLogoWrapperInnerStyle()]}
>
<Animated.View style={[styles.logoWrapInner]}>
<ImageCover
src={this.props.logo}
width={LOGO_SIZE}
borderRadius={LOGO_SIZE / 2}
styles={styles.logo}
/>
<Image
source={require("../../../assets/wave.png")}
style={styles.wave}
/>
</Animated.View>
</Animated.View>
);
};
renderContent = () => {
const { title, tagline } = this.props;
return (
<View style={{ paddingTop: 8 }}>
<Heading
title={title}
text={tagline}
titleSize={16}
align="center"
style={{ paddingHorizontal: 15 }}
/>
<View style={{ height: 10 }} />
{this.props.renderContent()}
</View>
);
};
render() {
return (
<View style={styles.container}>
<ParallaxScreen
{...this.props}
renderAfterImage={this.renderAfterImage}
renderContent={this.renderContent}
onGetScrollYAnimation={this._handleGetScrollYAnimation}
afterImageMarginTop={-40}
/>
{this.props.renderNavigation()}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
position: "relative",
height: SCREEN_HEIGHT
},
logoWrapper: {
position: "relative",
alignItems: "center",
zIndex: 9999
},
logoWrapInner: {
position: "relative",
width: LOGO_SIZE
},
logo: {
marginTop: 4
},
wave: {
position: "absolute",
top: 0,
left: -WAVE_SIZE / 2 + LOGO_SIZE / 2,
tintColor: "#fff",
width: WAVE_SIZE,
height: (WAVE_SIZE * 131) / 317
}
});
<file_sep># Dromo React-Native
## About
* This repository is an initiative by [Dromo](https://www.dromo.club/): a platform build for package pooling by Appendly. We are inviting. Maintainers, Owners, Developers to contribute to the project.
## How should I join?
* You are just a minute away from becoming a member. Fill up this [form](https://forms.gle/Hd9i7kiiPpGfTugZ8), and we'll add to our repository. You have to accept our request and it's done.

<file_sep>import getSlideFromRightTransition from "react-navigation-slide-from-right-transition";
export default (StackNavOpts = {
transitionConfig: getSlideFromRightTransition,
headerMode: "none"
});
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { View, ViewPropTypes } from "react-native";
const MAX_COLUMN = 6;
export class Row extends PureComponent {
render() {
const { props } = this;
return (
<View
{...props}
style={[
{
flexWrap: "wrap",
flexDirection: "row",
alignItems: "flex-start",
margin: -props.gap / 2,
marginVertical: -props.gapVertical / 2,
marginHorizontal: -props.gapHorizontal / 2
},
props.style
]}
>
{props.children}
</View>
);
}
}
Row.defaultProps = {
gap: 10
};
Row.propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.element),
PropTypes.element,
PropTypes.bool,
PropTypes.array
]),
gap: PropTypes.number,
style: ViewPropTypes.style
};
export class Col extends PureComponent {
render() {
const { props } = this;
return (
<View
{...props}
style={[
{
width: `${100 / props.column}%`,
padding: props.gap / 2,
paddingVertical: props.gapVertical / 2,
paddingHorizontal: props.gapHorizontal / 2
},
props.style
]}
>
{props.children}
</View>
);
}
}
Col.defaultProps = {
column: 1,
gap: 10
};
Col.propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.element),
PropTypes.element,
PropTypes.bool,
PropTypes.array
]),
column: PropTypes.number,
gap: PropTypes.number,
style: ViewPropTypes.style
};
<file_sep>import ListingsContainer from "./ListingsContainer";
import MenuContainer from "./MenuContainer";
import ListingSearchResultsContainer from "./ListingSearchResultsContainer";
import ListingByCatContainer from "./ListingByCatContainer";
import LocationModalPickerContainer from "./LocationModalPickerContainer";
import NearbyContainer from "./NearbyContainer";
import ListingDescriptionContainer from "./ListingDescriptionContainer";
import ListingListFeatureContainer from "./ListingListFeatureContainer";
import ListingPhotosContainer from "./ListingPhotosContainer";
import ListingReviewsContainer from "./ListingReviewsContainer";
import ListingDetailNavContainer from "./ListingDetailNavContainer";
import ListingEventsContainer from "./ListingEventsContainer";
import ListingVideosContainer from "./ListingVideosContainer";
import ListingSidebarContainer from "./ListingSidebarContainer";
import AverageDetailReviewContainer from "./AverageDetailReviewContainer";
import EventsContainer from "./EventsContainer";
import EventDetailContainer from "./EventDetailContainer";
import EventDiscussionContainer from "./EventDiscussionContainer";
import EventSearchResultsContainer from "./EventSearchResultsContainer";
import ArticleContainer from "./ArticleContainer";
import ArticleDetailContainer from "./ArticleDetailContainer";
import PageContainer from "./PageContainer";
import LoginFormContainer from "./LoginFormContainer";
export {
MenuContainer,
NearbyContainer,
ListingsContainer,
ListingSearchResultsContainer,
ListingByCatContainer,
LocationModalPickerContainer,
ListingDescriptionContainer,
ListingListFeatureContainer,
ListingPhotosContainer,
ListingReviewsContainer,
ListingDetailNavContainer,
ListingEventsContainer,
ListingVideosContainer,
ListingSidebarContainer,
AverageDetailReviewContainer,
EventsContainer,
EventDetailContainer,
EventDiscussionContainer,
EventSearchResultsContainer,
ArticleContainer,
ArticleDetailContainer,
PageContainer,
LoginFormContainer
};
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, Text } from "react-native";
import { connect } from "react-redux";
import { getListingSidebar } from "../../actions";
import {
ViewWithLoading,
ContentBox,
isEmpty,
RequestTimeoutWrapped,
P,
HtmlViewer
} from "../../wiloke-elements";
import * as Consts from "../../constants/styleConstants";
import {
ListingHours,
ListingBusinessInfo,
PriceRange,
ListingCatList,
ListingStatistic,
ListingTagList
} from "../dumbs";
class ListingSidebarContainer extends Component {
static propTypes = {
navigation: PropTypes.object
};
state = {
isLoading: true
};
_getListingSidebar = async () => {
const { getListingSidebar, listingId } = this.props;
await getListingSidebar(listingId);
this.setState({ isLoading: false });
};
componentDidMount() {
this._getListingSidebar();
}
// _getIcon = key => {
// switch (key) {
// case "businessHours":
// return "clock";
// case "categories":
// return "layers";
// case "statistic":
// return "bar-chart-2";
// case "tags":
// return "tag";
// case "businessInfo":
// return "repeat";
// default:
// return "check-circle";
// }
// };
_checkItemContent = item => {
const { navigation, translations, settings } = this.props;
switch (item.aSettings.key) {
case "businessHours":
return (
<ListingHours
data={item.oContent}
alwaysOpenText={translations.always_open}
/>
);
case "priceRange":
return (
<View>
{!!item.oContent.desc && (
<P style={{ paddingBottom: 5 }}>{item.oContent.desc}</P>
)}
<PriceRange
data={item.oContent}
colorPrimary={settings.colorPrimary}
/>
</View>
);
case "categories":
return <ListingCatList data={item.oContent} />;
case "statistic":
return <ListingStatistic data={item.oContent} />;
case "tags":
return <ListingTagList data={item.oContent} />;
case "businessInfo":
return (
<ListingBusinessInfo data={item.oContent} navigation={navigation} />
);
case "được_tài_trợ":
return (
<View style={{ marginLeft: -10 }}>
<HtmlViewer
html={item.aSettings.content}
htmlWrapCssString={`font-size: 13px; color: ${
Consts.colorDark2
}; line-height: 1.4em`}
containerMaxWidth={Consts.screenWidth - 22}
containerStyle={{ paddingLeft: 10, paddingRight: 0 }}
/>
</View>
);
default:
return false;
}
};
renderStatusHours = item => {
if (!item.oContent.oDetails) {
return false;
}
const { status, text } = item.oContent.oDetails.oCurrent;
return (
<View
style={{
borderWidth: 1,
borderColor:
status === "closed" || status === "close" || status === "day_off"
? Consts.colorQuaternary
: Consts.colorSecondary,
borderRadius: 2,
paddingVertical: 3,
paddingHorizontal: 8
}}
>
<Text
style={{
fontSize: 12,
color:
status === "closed" || status === "close" || status === "day_off"
? Consts.colorQuaternary
: Consts.colorSecondary
}}
>
{text}
</Text>
</View>
);
};
renderItem = (item, index) => {
const { settings } = this.props;
if (typeof item === "object") {
const { key, name, icon } = item.aSettings;
return (
item.oContent.mode !== "no_hours_available" && (
<ContentBox
key={key}
headerTitle={name ? name : ""}
headerIcon={icon}
renderRight={() => {
return key === "businessHours" && this.renderStatusHours(item);
}}
style={{ marginBottom: 10 }}
colorPrimary={settings.colorPrimary}
>
{this._checkItemContent(item)}
</ContentBox>
)
);
}
};
render() {
const { isLoading } = this.state;
const {
listingSidebar,
isListingDetailSidebarRequestTimeout,
translations
} = this.props;
return (
<RequestTimeoutWrapped
isTimeout={isListingDetailSidebarRequestTimeout}
onPress={this._getListingSidebar}
text={translations.networkError}
buttonText={translations.retry}
>
<ViewWithLoading isLoading={isLoading}>
{!isEmpty(listingSidebar) && listingSidebar.map(this.renderItem)}
</ViewWithLoading>
</RequestTimeoutWrapped>
);
}
}
const mapStateToProps = state => ({
listingSidebar: state.listingSidebar,
translations: state.translations,
isListingDetailSidebarRequestTimeout:
state.isListingDetailSidebarRequestTimeout,
settings: state.settings
});
export default connect(
mapStateToProps,
{ getListingSidebar }
)(ListingSidebarContainer);
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import {
Text,
View,
ActivityIndicator,
Modal,
StyleSheet,
Dimensions
} from "react-native";
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get("window");
const LoadingFull = ({ ...props }) => {
return (
<Modal
{...props}
animationType="fade"
transparent={true}
onRequestClose={() => {}}
>
<View style={styles.modal}>
<View style={styles.icon}>
<ActivityIndicator size="small" color="#fff" />
</View>
<View style={styles.underlay} />
</View>
</Modal>
);
};
LoadingFull.propTypes = {
...Object.keys(Modal.propTypes).reduce((acc, cur) => {
return {
...acc,
...(cur !== "onRequestClose" ? { [cur]: Modal.propTypes[cur] } : {})
};
}, {})
};
const styles = StyleSheet.create({
modal: {
position: "relative",
flex: 1,
justifyContent: "center",
alignItems: "center",
width: SCREEN_WIDTH,
height: SCREEN_HEIGHT
},
icon: {
width: 60,
height: 60,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#000",
borderRadius: 10
},
underlay: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
backgroundColor: "rgba(255,255,255,0.7)",
zIndex: -1
}
});
export default LoadingFull;
<file_sep>import React, { PureComponent } from "react";
import { View, StyleSheet, Animated, ActivityIndicator } from "react-native";
import * as Consts from "../../../constants/styleConstants";
import ImageProgress from "react-native-image-progress";
export default class MessageTyping extends PureComponent {
state = {
animation: new Animated.Value(0)
};
_createAnimation = _ => {
this.state.animation.setValue(0);
Animated.timing(this.state.animation, {
toValue: 100,
duration: 1600,
useNativeDriver: true
}).start(_ => this._createAnimation());
};
componentDidMount() {
this._createAnimation();
}
_getAnimation = _ => {
return this.state.animation.interpolate({
inputRange: [0, 50, 100],
outputRange: [1, 0.4, 1],
extrapolate: "clamp"
});
};
render() {
const { image, style } = this.props;
return (
<View style={[style, styles.container]}>
<View
style={[
styles.imageWrap,
{
borderRadius: 12,
width: 24,
height: 24
}
]}
>
<ImageProgress
source={{ uri: image }}
resizeMode="cover"
style={{
width: 24,
height: 24
}}
indicator={ActivityIndicator}
/>
</View>
<View style={styles.iconWrap}>
<Animated.View
style={[styles.item, { opacity: this._getAnimation() }]}
/>
<Animated.View
style={[styles.item, { opacity: this._getAnimation() }]}
/>
<Animated.View
style={[styles.item, { opacity: this._getAnimation() }]}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: "row",
alignItems: "flex-end"
},
imageWrap: {
overflow: "hidden",
marginBottom: 4,
marginRight: 5
},
iconWrap: {
width: 50,
height: 30,
borderRadius: 15,
backgroundColor: Consts.colorGray2,
flexDirection: "row",
justifyContent: "center",
alignItems: "center"
},
item: {
width: 8,
height: 8,
borderRadius: 5,
backgroundColor: Consts.colorDark4,
marginHorizontal: 2
}
});
<file_sep>import * as types from "../constants/actionTypes";
const reducers = type => (state = [], action) => {
switch (action.type) {
case type:
return action.payload;
case types.RESET_LISTING_DETAIL:
return [];
default:
return state;
}
};
export const listingDetail = reducers(types.GET_LISTING_DETAIL);
export const listingDescription = reducers(types.GET_LISTING_DESTINATION);
export const listingDescriptionAll = reducers(
types.GET_LISTING_DESTINATION_ALL
);
export const listingListFeature = reducers(types.GET_LISTING_LIST_FEATURE);
export const listingListFeatureAll = reducers(
types.GET_LISTING_LIST_FEATURE_ALL
);
export const listingVideos = reducers(types.GET_LISTING_VIDEOS);
export const listingVideosAll = reducers(types.GET_LISTING_VIDEOS_ALL);
export const listingReviews = reducers(types.GET_LISTING_REVIEWS);
export const listingReviewsAll = reducers(types.GET_LISTING_REVIEWS_ALL);
export const listingEvents = reducers(types.GET_LISTING_EVENTS);
export const listingEventsAll = reducers(types.GET_LISTING_EVENTS_ALL);
export const commentInReviews = reducers(types.GET_COMMENT_IN_REVIEWS);
export const listingSidebar = reducers(types.GET_LISTING_SIDEBAR);
const photoInitState = {
large: [],
medium: []
};
export const listingPhotos = (state = photoInitState, action) => {
switch (action.type) {
case types.GET_LISTING_PHOTOS:
return action.payload;
case types.RESET_LISTING_DETAIL:
return photoInitState;
default:
return state;
}
};
export const listingPhotosAll = (state = photoInitState, action) => {
switch (action.type) {
case types.GET_LISTING_PHOTOS_ALL:
return action.payload;
case types.RESET_LISTING_DETAIL:
return photoInitState;
default:
return state;
}
};
export const listingDetailNav = (state = [], action) => {
switch (action.type) {
case types.GET_LISTING_DETAIL_NAV:
return action.detailNav;
case types.CHANGE_LISTING_DETAIL_NAV:
return state.map(item => {
const condition = item.key === action.key;
return {
...item,
current: condition ? true : false,
loaded: condition ? true : item.loaded
};
});
case types.RESET_LISTING_DETAIL:
return [];
default:
return state;
}
};
export const listingCustomBox = (state = [], action) => {
switch (action.type) {
case types.GET_LISTING_BOX_CUSTOM:
case types.GET_LISTING_BOX_CUSTOM_ALL:
return {
...state,
[action.payload.key]:
typeof action.payload.data === "object"
? action.payload.data
: [action.payload.data]
};
case types.RESET_LISTING_DETAIL:
return {};
default:
return state;
}
};
<file_sep>import {
GET_NOTIFICATION_SETTING,
SET_NOTIFICATION_SETTING,
GET_NOTIFICATION_ADMIN_SETTING
} from "../constants/actionTypes";
import axios from "axios";
import _ from "lodash";
const encodeId = id => `___${id}___`;
const decodeId = id => id.replace(/___/g, "");
export const getNotificationAdminSettings = () => dispatch => {
return axios
.get("notification-settings")
.then(({ data }) => {
if (data.status === "success") {
const settings = data.aSettings.reduce((obj, item, index) => {
return {
...obj,
[item.key]: {
...item,
id: index
}
};
}, {});
dispatch({
type: GET_NOTIFICATION_ADMIN_SETTING,
payload: settings
});
}
})
.catch(console.log);
};
export const getNotificationSettings = myID => async (dispatch, getState) => {
try {
const { db } = getState();
if (!db) return;
const snapshot = await db
.ref(`deviceTokens/${encodeId(myID)}/pushNotificationSettings`)
.once("value");
const settings = snapshot.val();
if (settings) {
dispatch({
type: GET_NOTIFICATION_SETTING,
payload: settings
});
}
} catch (err) {
console.log(err);
}
};
export const setNotificationSettings = (
myID,
notificationSettings,
type
) => async (dispatch, getState) => {
const { db } = getState();
if (!db) return;
const dbNotificationSettings = db.ref(
`deviceTokens/${encodeId(myID)}/pushNotificationSettings`
);
if (type === "start") {
const flatten = Object.keys(notificationSettings).reduce(
(obj, item) => ({
...obj,
[item]: true
}),
{}
);
const snap = await dbNotificationSettings.once("value");
const val = snap.val();
const payload = val
? _.pick({ ...flatten, ...val }, Object.keys(flatten))
: flatten;
try {
await db
.ref(`deviceTokens/${encodeId(myID)}/pushNotificationSettings`)
.set(payload);
dispatch({
type: SET_NOTIFICATION_SETTING,
payload
});
} catch (err) {
console.log(err);
}
} else {
await db
.ref(`deviceTokens/${encodeId(myID)}/pushNotificationSettings`)
.set(notificationSettings);
dispatch({
type: SET_NOTIFICATION_SETTING,
payload: notificationSettings
});
}
};
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Dimensions
} from "react-native";
import { Feather } from "@expo/vector-icons";
import { Constants } from "expo";
import * as Consts from "../../../constants/styleConstants";
import stylesBase from "../../../stylesBase";
const { width: SCREEN_WIDTH } = Dimensions.get("window");
const ICON_WIDTH = 50;
const ICON_HEIGHT = 30;
const PADDING_HORIZONTAL = 10;
export default class HeaderHasBack extends PureComponent {
static propTypes = {
renderRight: PropTypes.func,
goBack: PropTypes.func,
renderCenter: PropTypes.func,
goBackIconName: PropTypes.string,
title: PropTypes.string,
headerBackgroundColor: PropTypes.string,
headerHeight: PropTypes.number
};
static defaultProps = {
renderRight: () => <Text />,
goBackIconName: "chevron-left",
headerBackgroundColor: Consts.colorPrimary,
headerHeight: 52,
tintColor: "#fff"
};
render() {
return (
<View
style={[
styles.container,
{
height: this.props.headerHeight + Constants.statusBarHeight,
backgroundColor: this.props.headerBackgroundColor
}
]}
>
<TouchableOpacity activeOpacity={0.8} onPress={this.props.goBack}>
<View
style={[
styles.icon,
{
alignItems: "flex-start"
}
]}
>
<Feather
name={this.props.goBackIconName}
size={26}
color={this.props.tintColor}
/>
</View>
</TouchableOpacity>
<View
style={{
width: SCREEN_WIDTH - (ICON_WIDTH + PADDING_HORIZONTAL) * 2,
alignItems: "center"
}}
>
{this.props.renderCenter ? (
this.props.renderCenter()
) : (
<Text
style={[
stylesBase.h5,
{ color: this.props.tintColor, fontWeight: "500" }
]}
numberOfLines={1}
>
{this.props.title}
</Text>
)}
</View>
<View
style={[
styles.icon,
{
alignItems: "flex-end"
}
]}
>
{this.props.renderRight()}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingHorizontal: PADDING_HORIZONTAL,
paddingTop: Constants.statusBarHeight
},
icon: {
width: ICON_WIDTH,
height: ICON_HEIGHT,
justifyContent: "center",
alignItems: "center"
}
});
<file_sep>import React, { PureComponent, Fragment } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
Animated,
TouchableOpacity,
Keyboard,
StyleSheet,
ViewPropTypes
} from "react-native";
import { Feather } from "@expo/vector-icons";
import * as Consts from "../../../constants/styleConstants";
import stylesBase from "../../../stylesBase";
export default class CheckBox extends PureComponent {
state = {
isChecked: this.props.checked || false,
animatedValue: new Animated.Value(0)
};
handleChecked = () => {
this.setState({
isChecked: !this.state.isChecked
});
this.props.onPress(this.props.name, !this.state.isChecked);
Keyboard.dismiss();
};
renderCircleAnimated(opts) {
const { circleAnimatedSize, size, borderWidth } = this.props;
return (
<Animated.View
style={[
styles.circleAnimated,
{
width: circleAnimatedSize,
height: circleAnimatedSize,
borderRadius: circleAnimatedSize / 2,
top: (size - borderWidth * 2 - circleAnimatedSize) / 2,
left: (size - borderWidth * 2 - circleAnimatedSize) / 2
},
{
opacity: opts.opacity(),
transform: [
{
scaleX: opts.scale()
},
{
scaleY: opts.scale()
}
],
backgroundColor: opts.backgroundColor
}
]}
/>
);
}
renderIcon() {
const { animatedValue, isChecked } = this.state;
const {
size,
radius,
borderWidth,
iconColor,
iconBackgroundColor
} = this.props;
const ANIMATED_ICON = animatedValue.interpolate({
inputRange: [0, 100],
outputRange: [0, 1],
extrapolate: "clamp"
});
return (
<Animated.View
style={[
styles.icon,
{
opacity: ANIMATED_ICON,
width: size,
height: size,
marginLeft: -borderWidth,
marginTop: -borderWidth,
borderRadius: radius,
backgroundColor: iconBackgroundColor
}
]}
>
<Feather name="check" size={size - 4} color={iconColor} />
</Animated.View>
);
}
renderContent() {
const { animatedValue, isChecked } = this.state;
const {
size,
radius,
borderWidth,
borderColor,
circleAnimatedColor
} = this.props;
Animated.timing(animatedValue, {
toValue: isChecked ? 100 : 0,
duration: 300,
useNativeDriver: true
}).start();
const ANIMATED_CIRCLE_OPACITY = outputRange => {
return animatedValue.interpolate({
inputRange: [0, 20, 40, 80],
outputRange,
extrapolate: "clamp"
});
};
const ANIMATED_CIRCLE_SCALE = outputRange => {
return animatedValue.interpolate({
inputRange: [0, 80],
outputRange,
extrapolate: "clamp"
});
};
return (
<View
style={[
styles.inner,
{
width: size,
height: size,
borderRadius: radius,
borderWidth: borderWidth,
borderColor: borderColor
}
]}
>
{this.renderIcon()}
{this.renderCircleAnimated({
opacity: () => ANIMATED_CIRCLE_OPACITY([0, 0, 1, 0]),
scale: () => ANIMATED_CIRCLE_SCALE([0, 1]),
backgroundColor: isChecked ? circleAnimatedColor[0] : "transparent"
})}
{this.renderCircleAnimated({
opacity: () => ANIMATED_CIRCLE_OPACITY([0, 0.4, 0.7, 1]),
scale: () => ANIMATED_CIRCLE_SCALE([1, 0]),
backgroundColor: isChecked ? "transparent" : circleAnimatedColor[1]
})}
</View>
);
}
renderLabel() {
const { label, labelStyle } = this.props;
return (
<View style={{ width: "80%" }}>
<Text
style={[
{
color: Consts.colorDark3
},
labelStyle
]}
>
{label}
</Text>
</View>
);
}
render() {
const { size, style, disabled, label, reverse } = this.props;
return (
<Fragment>
{disabled ? (
<View
style={[
{
width: !label ? size : "auto",
height: !label ? size : "auto",
alignItems: "center",
flexDirection: reverse ? "row-reverse" : "row",
justifyContent: reverse ? "flex-end" : "space-between",
opacity: 0.5
},
style
]}
>
{!!label && this.renderLabel()}
{!!label && <View style={{ width: 5 }} />}
{this.renderContent()}
</View>
) : (
<TouchableOpacity
activeOpacity={1}
onPress={this.handleChecked}
style={[
{
width: !label ? size : "auto",
height: !label ? size : "auto",
alignItems: "center",
flexDirection: reverse ? "row-reverse" : "row",
justifyContent: reverse ? "flex-end" : "space-between"
},
style
]}
>
{!!label && this.renderLabel()}
{!!label && <View style={{ width: 5 }} />}
{this.renderContent()}
</TouchableOpacity>
)}
</Fragment>
);
}
}
CheckBox.defaultProps = {
size: 22,
radius: Consts.round,
borderWidth: 2,
borderColor: "#c5cbd8",
circleAnimatedSize: 50,
checked: false,
disabled: false,
circleAnimatedColor: [Consts.colorDark4, Consts.colorPrimary],
iconColor: "#fff",
iconBackgroundColor: Consts.colorPrimary,
onPress: () => {}
};
CheckBox.propTypes = {
size: PropTypes.number,
radius: PropTypes.number,
borderWidth: PropTypes.number,
borderColor: PropTypes.string,
circleAnimatedSize: PropTypes.number,
checked: PropTypes.bool,
disabled: PropTypes.bool,
circleAnimatedColor: PropTypes.arrayOf(PropTypes.string),
style: ViewPropTypes.style,
iconColor: PropTypes.string,
iconBackgroundColor: PropTypes.string,
onPress: PropTypes.func,
name: PropTypes.string,
label: PropTypes.string,
labelStyle: Text.propTypes.style,
reverse: PropTypes.bool
};
const styles = StyleSheet.create({
inner: {
position: "relative",
zIndex: 9,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center"
},
icon: {
position: "relative",
zIndex: 2,
justifyContent: "center",
alignItems: "center"
},
circleAnimated: {
position: "absolute",
zIndex: 1
}
});
<file_sep>import {
LOADING,
GET_LISTING_BY_CAT,
GET_LISTING_BY_CAT_LOADMORE
} from "../constants/actionTypes";
import axios from "axios";
const POSTS_PER_PAGE = 12;
export const getListingByCat = (
categoryId,
taxonomy,
endpointAPI
) => dispatch => {
dispatch({
type: LOADING,
loading: true
});
axios
.get(endpointAPI, {
params: {
page: 1,
postsPerPage: POSTS_PER_PAGE,
[taxonomy]: categoryId
}
})
.then(res => {
dispatch({
type: GET_LISTING_BY_CAT,
payload: res.data
});
dispatch({
type: LOADING,
loading:
(res.data.oResults && res.data.oResults.length > 0) ||
res.data.status === "error"
? false
: true
});
})
.catch(err => console.log(err.message));
};
export const getListingByCatLoadmore = (
next,
categoryId,
taxonomy,
endpointAPI
) => dispatch => {
return axios
.get(endpointAPI, {
params: {
page: next,
postsPerPage: POSTS_PER_PAGE,
[taxonomy]: categoryId
}
})
.then(res => {
dispatch({
type: GET_LISTING_BY_CAT_LOADMORE,
payload: res.data
});
})
.catch(err => console.log(err.message));
};
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { View, Animated, StyleSheet } from "react-native";
import * as Consts from "../../../constants/styleConstants";
const TRACK_COLOR_DEFAULT = Consts.colorPrimary;
const PROGRESS_COLOR_DEFAULT = Consts.colorGray1;
export default class ProgressBar extends PureComponent {
static propTypes = {
tintColorTrack: PropTypes.string,
tintColorProgress: PropTypes.string,
duration: PropTypes.number,
value: PropTypes.number,
maxValue: PropTypes.number,
onLayout: PropTypes.func
};
static defaultProps = {
tintColorTrack: TRACK_COLOR_DEFAULT,
tintColorProgress: PROGRESS_COLOR_DEFAULT,
onLayout: () => {},
value: 50,
maxValue: 100,
duration: 1000
};
state = {
width: 0,
animation: new Animated.Value(0)
};
_handleLayout = event => {
const { width } = event.nativeEvent.layout;
this.setState({ width });
this.props.onLayout(event);
};
_handleAnimation = () => {
const { value, maxValue, duration } = this.props;
const { animation } = this.state;
this._container.measure((x, y, width) => {
Animated.timing(animation, {
toValue: (value * width) / maxValue,
duration,
userNativeDriver: true
}).start();
});
};
componentDidMount() {
setTimeout(this._handleAnimation, 1000);
}
render() {
const { tintColorTrack, tintColorProgress } = this.props;
const { animation } = this.state;
return (
<View
ref={ref => (this._container = ref)}
style={[
styles.container,
{ backgroundColor: tintColorProgress, height: 5 }
]}
>
<Animated.View
style={[
styles.bar,
{
backgroundColor: tintColorTrack,
transform: [{ translateX: animation }]
}
]}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
position: "relative",
overflow: "hidden"
},
bar: {
position: "absolute",
width: "100%",
height: "100%",
top: 0,
left: "-100%"
}
});
<file_sep>import React from "react";
import PropTypes from "prop-types";
import { View } from "react-native";
import { Feather, FontAwesome } from "@expo/vector-icons";
import { convertFontIcon } from "../../../wiloke-elements";
const FontIcon = props => {
return (
<View>
{props.name.search(/^fa\s*fa-/g) !== -1 ||
!convertFontIcon(props.name) ? (
<View>
{!/rutube|odnoklassniki|livejournal|bloglovin|map-pint|three-line|write|dollar/.test(
props.name
) ? (
<FontAwesome
name={props.name.replace(/^((f|l)a\s*|)(f|l)a-/g, "")}
size={props.size}
color={props.color}
/>
) : (
<Feather name="check" size={props.size} color={props.color} />
)}
</View>
) : (
<Feather
name={convertFontIcon(props.name)}
size={props.size}
color={props.color}
/>
)}
</View>
);
};
FontIcon.propTypes = {
name: PropTypes.string,
size: PropTypes.number,
color: PropTypes.string
};
export default FontIcon;
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { View, Text } from "react-native";
import * as Consts from "../../../constants/styleConstants";
const styleGeneral = {
color: Consts.colorDark1,
marginBottom: 8,
fontWeight: "600"
};
const propTypesGeneral = {
...Text.propTypes
};
export const H1 = props => (
<Text {...props} style={[styleGeneral, { fontSize: 40 }, props.style]}>
{props.children}
</Text>
);
H1.propTypes = propTypesGeneral;
export const H2 = props => (
<Text {...props} style={[styleGeneral, { fontSize: 30 }, props.style]}>
{props.children}
</Text>
);
H2.propTypes = propTypesGeneral;
export const H3 = props => (
<Text {...props} style={[styleGeneral, { fontSize: 26 }, props.style]}>
{props.children}
</Text>
);
H3.propTypes = propTypesGeneral;
export const H4 = props => (
<Text {...props} style={[styleGeneral, { fontSize: 22 }, props.style]}>
{props.children}
</Text>
);
H4.propTypes = propTypesGeneral;
export const H5 = props => (
<Text {...props} style={[styleGeneral, { fontSize: 18 }, props.style]}>
{props.children}
</Text>
);
H5.propTypes = propTypesGeneral;
export const H6 = props => (
<Text {...props} style={[styleGeneral, { fontSize: 14 }, props.style]}>
{props.children}
</Text>
);
H6.propTypes = propTypesGeneral;
export const P = props => (
<Text
{...props}
style={[
styleGeneral,
{
fontSize: 13,
fontWeight: "400",
lineHeight: 19,
color: Consts.colorDark2
},
props.style
]}
>
{props.children}
</Text>
);
P.propTypes = propTypesGeneral;
<file_sep>import { GET_DEVICE_TOKEN } from "../constants/actionTypes";
export const getDeviceToken = token => dispatch => {
return new Promise(resolve => {
dispatch({
type: GET_DEVICE_TOKEN,
payload: token
});
resolve();
});
};
<file_sep>import React, { PureComponent } from "react";
import { View } from "react-native";
import { connect } from "react-redux";
import { getArticleDetail } from "../../actions";
import {
isEmpty,
ViewWithLoading,
IconTextSmall,
HtmlViewer
} from "../../wiloke-elements";
import * as Consts from "../../constants/styleConstants";
class ArticleDetailContainer extends PureComponent {
state = {
isLoading: true
};
_getArticleDetail = async () => {
try {
const { navigation } = this.props;
const { params } = navigation.state;
await this.props.getArticleDetail(params.id);
this.setState({ isLoading: false });
} catch (err) {
console.log(err);
}
};
componentDidMount() {
this._getArticleDetail();
}
renderMeta = () => {
const { articleDetail, translations, settings } = this.props;
return (
<View
style={{
flexDirection: "row",
alignItems: "center",
paddingHorizontal: 10,
paddingTop: 8,
backgroundColor: "#fff"
}}
>
<IconTextSmall
iconName="calendar"
text={articleDetail.postDate}
iconSize={14}
textSize={12}
iconColor={settings.colorPrimary}
/>
<View style={{ width: 10 }} />
<IconTextSmall
iconName="message-square"
text={`${articleDetail.countComments} ${translations.comments}`}
iconSize={14}
textSize={12}
iconColor={settings.colorPrimary}
/>
</View>
);
};
render() {
const { articleDetail } = this.props;
const { isLoading } = this.state;
return (
<View
style={{
marginHorizontal: -10,
marginBottom: isLoading ? -10 : 0,
paddingTop: isLoading ? 10 : 5,
backgroundColor: "#fff"
}}
>
<ViewWithLoading isLoading={isLoading} contentLoader="content">
{this.renderMeta()}
{!isEmpty(articleDetail) && (
<View style={{ backgroundColor: "#fff" }}>
<HtmlViewer
html={articleDetail.postContent}
htmlWrapCssString={`font-size: 13px; color: ${
Consts.colorDark2
}; line-height: 1.4em`}
/>
</View>
)}
</ViewWithLoading>
</View>
);
}
}
const mapStateToProps = state => ({
articleDetail: state.articleDetail,
translations: state.translations,
settings: state.settings
});
const mapDispatchToProps = {
getArticleDetail
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ArticleDetailContainer);
<file_sep>import { NEAR_BY_FOCUS } from "../constants/actionTypes";
export const getNearByFocus = _ => dispatch => {
dispatch({
type: NEAR_BY_FOCUS
});
};
<file_sep>import { createStackNavigator } from "react-navigation";
import stackOpts from "./stackOpts";
import ListingScreen from "../components/screens/ListingScreen";
const listingStack = createStackNavigator(
{
ListingScreen: {
screen: ListingScreen,
navigationOptions: ({ navigation }) => {
// navigation.setParams({ otherParam: "Updated!" });
// return {
// title: navigation.getParam('otherParam', 'A Nested Details Screen'),
// };
}
// navigationOptions: {
// title: 'Wilcity',
// headerStyle: {
// backgroundColor: Consts.colorDark,
// },
// headerTintColor: Consts.colorPrimary,
// headerTitleStyle: {
// fontWeight: '400',
// fontSize: 14,
// },
// }
}
// LISTING_DETAIL: {
// screen: ListingDetail
// },
},
stackOpts
);
export default listingStack;
<file_sep>import React, { Component } from "react";
import {
View,
FlatList,
TouchableOpacity,
Alert,
Platform,
Dimensions,
Text
} from "react-native";
import * as Consts from "../../constants/styleConstants";
import { Layout } from "../dumbs";
import {
ViewWithLoading,
ImageCircleAndText,
LoadingFull,
Toast,
Button,
getTime,
P,
bottomBarHeight,
CameraRollSelect
} from "../../wiloke-elements";
import { connect } from "react-redux";
import {
getUsersFromFirebase,
getMessageChatNewCount,
deleteUserListMessageChat,
removeItemInUsersError,
getCurrentSendMessageScreen
} from "../../actions";
import _ from "lodash";
import he from "he";
import Swipeout from "react-native-swipeout";
import { Feather } from "@expo/vector-icons";
import { Constants } from "expo";
const END_REACHED_THRESHOLD = Platform.OS === "ios" ? 0 : 1;
const HEADER_HEIGHT = 52 + Constants.statusBarHeight;
const { height: SCREEN_HEIGHT } = Dimensions.get("window");
const CONTENT_HEIGHT = SCREEN_HEIGHT - HEADER_HEIGHT;
class NotificationsScreen extends Component {
state = {
isScrollEnabled: true,
isDeleteLoading: false,
startLoadmore: false
};
_getUsersFromFirebase = async _ => {
try {
const { shortProfile } = this.props;
const myID = shortProfile.userID;
await this.props.removeItemInUsersError(myID);
await this.props.getUsersFromFirebase(myID);
} catch (err) {
console.log(err);
}
};
componentDidMount() {
this._getUsersFromFirebase();
this.props.getCurrentSendMessageScreen(false);
}
shouldComponentUpdate(nextProps, nextState) {
if (!_.isEqual(nextProps.usersFromFirebase, this.props.usersFromFirebase)) {
return true;
}
if (!_.isEqual(nextProps.userConnections, this.props.userConnections)) {
return true;
}
if (
!_.isEqual(
nextProps.usersFromFirebaseLoading,
this.props.usersFromFirebaseLoading
)
) {
return true;
}
if (!_.isEqual(nextState.isScrollEnabled, this.state.isScrollEnabled)) {
return true;
}
if (!_.isEqual(nextState.isDeleteLoading, this.state.isDeleteLoading)) {
return true;
}
return false;
}
_handleListItem = item => _ => {
const { navigation, getMessageChatNewCount, shortProfile } = this.props;
const { userID, displayName, key } = item;
const myID = shortProfile.userID;
navigation.navigate("SendMessageScreen", {
userID,
displayName,
key
});
getMessageChatNewCount(myID);
};
_deleteUserListMessageChat = key => async _ => {
const { shortProfile } = this.props;
const myID = shortProfile.userID;
await this.setState({ isDeleteLoading: true });
await this.props.deleteUserListMessageChat(myID, key);
this.setState({ isDeleteLoading: false });
};
// _handleEndReached = next => {
// const { startLoadmore } = this.state;
// const { getMyNotificationsLoadmore } = this.props;
// !!next && startLoadmore && getMyNotificationsLoadmore(next);
// };
_handleAddMessageScreen = _ => {
this.props.navigation.navigate("AddMessageScreen");
};
_handleSwipeDelete = key => _ => {
const { translations } = this.props;
Alert.alert(
translations.delete,
translations.deleteMessage,
[
{
text: translations.cancel,
style: "cancel"
},
{
text: translations.ok,
onPress: this._deleteUserListMessageChat(key)
}
],
{ cancelable: false }
);
};
renderItem = ({ item, index }) => {
const { translations, userConnections } = this.props;
const message =
item.message.search(/longitude|latitude/g) !== -1 ? "📍" : item.message;
return (
<Swipeout
right={[
{
text: translations.delete,
type: "delete",
onPress: this._handleSwipeDelete(item.key)
}
]}
autoClose={true}
scroll={event => this.setState({ isScrollEnabled: event })}
style={{
borderBottomWidth: 1,
borderColor: Consts.colorGray1,
backgroundColor: "#fff",
borderTopWidth: index === 0 ? 1 : 0
}}
>
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleListItem(item)}
style={{
paddingVertical: 12,
paddingHorizontal: 10,
backgroundColor: item.new ? "#f6f6f8" : "#fff"
}}
>
<ImageCircleAndText
image={item.avatar}
title={item.displayName}
message={message}
time={!!item.timestamp ? getTime(item.timestamp) : ""}
horizontal={true}
messageNumberOfLines={1}
imageSize={44}
dotEnabled={!!userConnections[item.userID]}
dotTintColor={Consts.colorSecondary}
dotPosition={true}
/>
</TouchableOpacity>
</Swipeout>
);
};
renderContent = () => {
const {
usersFromFirebase,
usersFromFirebaseLoading,
usersFromFirebaseError,
settings,
translations
} = this.props;
const { isDeleteLoading } = this.state;
return (
<ViewWithLoading
isLoading={usersFromFirebaseLoading}
contentLoader="headerAvatar"
avatarSize={44}
contentLoaderItemLength={10}
gap={0}
>
{usersFromFirebaseError === "error" && _.isEmpty(usersFromFirebase) && (
<View style={{ alignItems: "center", padding: 30, marginTop: 20 }}>
<P style={{ textAlign: "center" }}>
{translations.startConversation}
</P>
<Button
backgroundColor="primary"
color="light"
size="md"
radius="round"
colorPrimary={settings.colorPrimary}
onPress={this._handleAddMessageScreen}
>
{translations.searchAuthor}
</Button>
</View>
)}
<FlatList
data={usersFromFirebase}
renderItem={this.renderItem}
keyExtractor={(_, index) => index.toString()}
scrollEnabled={this.state.isScrollEnabled}
ListFooterComponent={() => (
<View
style={{
paddingBottom: bottomBarHeight
}}
/>
)}
// onEndReachedThreshold={END_REACHED_THRESHOLD}
// onEndReached={() => this._handleEndReached(next)}
// ListFooterComponent={() => {
// return (
// <View>
// {!!next &&
// status === "success" &&
// startLoadmore && (
// <ViewWithLoading
// isLoading={true}
// contentLoader="headerAvatar"
// avatarSize={44}
// contentLoaderItemLength={1}
// gap={0}
// />
// )}
// {status === "error" && (
// <MessageError message={translations[msg]} />
// )}
// <View style={{ height: 30 }} />
// </View>
// );
// }}
/>
<LoadingFull visible={isDeleteLoading} />
<Toast ref={c => (this._toast = c)} />
</ViewWithLoading>
);
};
render() {
const { navigation, settings, translations, auth } = this.props;
const { isLoggedIn } = auth;
const { name } = navigation.state.params;
return (
<Layout
navigation={navigation}
headerType="headerHasBack"
title={name}
goBack={() => navigation.goBack()}
renderRight={() => (
<TouchableOpacity
activeOpacity={0.5}
onPress={this._handleAddMessageScreen}
style={{ width: 25, alignItems: "flex-end" }}
>
<Feather name="edit" size={20} color={settings.colorPrimary} />
</TouchableOpacity>
)}
renderContent={this.renderContent}
colorPrimary={settings.colorPrimary}
textSearch={translations.search}
isLoggedIn={isLoggedIn}
scrollViewEnabled={false}
scrollViewStyle={{
backgroundColor: "#fff"
}}
tintColor={Consts.colorDark1}
colorPrimary={Consts.colorGray2}
statusBarStyle="dark-content"
contentHeight={CONTENT_HEIGHT}
/>
);
}
}
const mapStateToProps = state => ({
usersFromFirebase: state.usersFromFirebase,
settings: state.settings,
translations: state.translations,
auth: state.auth,
shortProfile: state.shortProfile,
usersFromFirebaseLoading: state.usersFromFirebaseLoading,
usersFromFirebaseError: state.usersFromFirebaseError,
userConnections: state.userConnections
});
const mapDispatchToProps = {
getUsersFromFirebase,
getMessageChatNewCount,
deleteUserListMessageChat,
removeItemInUsersError,
getCurrentSendMessageScreen
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(NotificationsScreen);
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, Text } from "react-native";
import { Location, Permissions } from "expo";
import Button from "./Button";
import { H5, P } from "./Typography";
export default class PermissionsLocation extends Component {
static propTypes = {
title: PropTypes.string,
text: PropTypes.string,
buttonText: PropTypes.string
};
static defaultProps = {
buttonText: "Turn on location"
};
constructor(props) {
super(props);
this.state = {
subscriber: "",
location: null,
errorMessage: ""
};
}
componentDidMount() {
// Location.getProviderStatusAsync()
// .then(status => {
// console.log("Getting status");
// if (!status.locationServicesEnabled) {
// throw new Error("Location services disabled");
// }
// })
// .then(_ => Permissions.askAsync(Permissions.LOCATION))
// .then(permissions => {
// console.log("Getting permissions");
// if (permissions.status !== "granted") {
// throw new Error("Ask for permissions");
// }
// })
// .then(_ => {
// console.log("Have permissions");
// const subscriber = Location.watchPositionAsync(
// {
// timeInterval: 1000
// },
// location => {
// console.log("Location change: ", location);
// this.setState({ location });
// }
// );
// this.setState({ subscriber });
// })
// .catch(error => {
// console.log(error);
// this.setState({
// errorMessage: "Permission to access location was denied"
// });
// });
}
_getLocationAsync = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== "granted") {
this.setState({
errorMessage: "Permission to access location was denied"
});
}
let location = await Location.getCurrentPositionAsync({
enableHighAccuracy: true
});
this.setState({ location });
};
// componentDidUpdate() {
// const { location, errorMessage } = this.state;
// this.props.onPress(location, errorMessage);
// }
render() {
const { location } = this.state;
console.log(
location && location.coords.latitude,
location && location.coords.longitude
);
return (
<View
style={{
paddingHorizontal: 10,
alignItems: "center"
}}
>
<H5>{this.props.title}</H5>
<P>{this.props.text}</P>
<Button size="md" radius="round" onPress={this._getLocationAsync}>
{this.props.buttonText}
</Button>
</View>
);
}
}
<file_sep>import * as Consts from "./constants/styleConstants";
import { StyleSheet } from "react-native";
const stylesBase = StyleSheet.create({
text: {
fontSize: 13,
color: Consts.colorDark2,
lineHeight: 19
},
h1: {
fontSize: 30,
fontWeight: "bold",
color: Consts.colorDark1
},
h2: {
fontSize: 26,
fontWeight: "bold",
color: Consts.colorDark1
},
h3: {
fontSize: 22,
fontWeight: "bold",
color: Consts.colorDark1
},
h4: {
fontSize: 18,
fontWeight: "bold",
color: Consts.colorDark1
},
h5: {
fontSize: 15,
fontWeight: "bold",
color: Consts.colorDark1
},
h6: {
fontSize: 13,
fontWeight: "bold",
color: Consts.colorDark1
},
mb5: {
marginBottom: 5
},
mb10: {
marginBottom: 10
},
mb20: {
marginBottom: 20
},
mb30: {
marginBottom: 30
},
mt5: {
marginTop: 5
},
pd5: {
padding: 10
},
pd10: {
padding: 10
},
pd15: {
padding: 10
},
pv10: {
paddingVertical: 10
},
pv20: {
paddingVertical: 20
},
pv30: {
paddingVertical: 30
},
pv40: {
paddingVertical: 40
},
bgLight: {
backgroundColor: "#fff"
},
bgGray: {
backgroundColor: Consts.colorGray2
},
divider: {
borderTopWidth: 1,
borderTopColor: Consts.colorGray2
},
absFull: {
position: "absolute",
width: "100%",
height: "100%",
top: 0,
left: 0,
zIndex: 1
},
colorPrimary: {
color: Consts.colorPrimary
},
colorSecondary: {
color: Consts.colorSecondary
},
colorTertiary: {
color: Consts.colorTertiary
},
colorQuaternary: {
color: Consts.colorQuaternary
}
});
export default stylesBase;
<file_sep>import { NEAR_BY_FOCUS } from "../constants/actionTypes";
export const nearByFocus = (state = false, action) => {
switch (action.type) {
case NEAR_BY_FOCUS:
return !state;
default:
return state;
}
};
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { Animated, ScrollView } from "react-native";
export default class ScrollViewAnimated extends Component {
static propTypes = {
...ScrollView.propTypes,
onScroll: PropTypes.func,
onScrollAnimation: PropTypes.func
};
static defaultProps = {
onScroll: () => {},
onScrollAnimation: () => {}
};
render() {
const {
children,
onScroll,
onScrollAnimation,
...myScrollViewProps
} = this.props;
return (
<Animated.ScrollView {...myScrollViewProps}>
{children}
</Animated.ScrollView>
);
}
}
<file_sep>import { GET_LISTING_STATUS, GET_EVENT_STATUS } from "../constants/actionTypes";
import axios from "axios";
const getStatus = allText => dispatch => (endpoint, type) => {
return axios
.get(endpoint)
.then(res => {
const { data } = res;
data.status === "success" &&
dispatch({
type,
payload: [
{
id: "all",
name: allText,
selected: true
},
...data.oResults.map(item => ({
id: item.post_status,
name: `${item.status} (${item.total})`,
selected: false
}))
]
});
})
.catch(err => console.log(err));
};
export const getListingStatus = allText => dispatch => {
return getStatus(allText)(dispatch)("get-listing-status", GET_LISTING_STATUS);
};
export const getEventStatus = allText => dispatch => {
return getStatus(allText)(dispatch)("get-event-status", GET_EVENT_STATUS);
};
<file_sep>import React, { PureComponent, Fragment } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
ImageBackground,
Dimensions,
Animated,
StyleSheet
} from "react-native";
import { LinearGradient } from "expo";
import * as Consts from "../../../constants/styleConstants";
import stylesBase from "../../../stylesBase";
export default class Overlay extends PureComponent {
static propTypes = {
backgroundColor: PropTypes.string,
opacity: PropTypes.oneOfType([PropTypes.object, PropTypes.number]),
zIndex: PropTypes.number,
linearGradient: PropTypes.object,
modifier: PropTypes.oneOf(["dark", "light"]),
animated: PropTypes.bool
};
static defaultProps = {
modifier: "dark",
opacity: 0.6,
animated: false
};
render() {
return (
<Fragment>
{this.props.animated ? (
<Animated.View
style={[
stylesBase.absFull,
{
backgroundColor: this.props.backgroundColor
? this.props.backgroundColor
: this.props.modifier === "dark"
? Consts.colorDark1
: "#fff",
opacity: this.props.opacity,
zIndex: this.props.zIndex
}
]}
/>
) : (
<Fragment>
{typeof this.props.linearGradient === "object" ? (
<LinearGradient
colors={this.props.linearGradient}
start={{ x: 0.0, y: 1.0 }}
end={{ x: 1.0, y: 1.0 }}
style={[
stylesBase.absFull,
{
opacity: this.props.opacity,
zIndex: this.props.zIndex
}
]}
/>
) : (
<View
style={[
stylesBase.absFull,
{
backgroundColor: this.props.backgroundColor
? this.props.backgroundColor
: this.props.modifier === "dark"
? Consts.colorDark1
: "#fff",
opacity: this.props.opacity,
zIndex: this.props.zIndex
}
]}
/>
)}
</Fragment>
)}
</Fragment>
);
}
}
<file_sep>import * as types from "../constants/actionTypes";
export const loading = (state = true, action) => {
switch (action.type) {
case types.LOADING:
return action.loading;
default:
return state;
}
};
export const loadingListingDetail = (state = true, action) => {
switch (action.type) {
case types.LOADING_LISTING_DETAIL:
return action.loading;
default:
return state;
}
};
export const loadingReview = (state = true, action) => {
switch (action.type) {
case types.LOADING_REVIEW:
return action.loading;
default:
return state;
}
};
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, Text, StyleSheet } from "react-native";
import * as Consts from "../../constants/styleConstants";
import stylesBase from "../../stylesBase";
import _ from "lodash";
export default class Heading extends Component {
render() {
const titleStyles = {
fontSize: this.props.titleSize,
fontWeight: "bold",
color: this.props.titleColor,
textAlign: this.props.align
};
const textStyles = {
fontSize: this.props.textSize,
color: this.props.textColor,
textAlign: this.props.align
};
return (
<View
style={[
{
flex: 1,
marginTop: 0,
padding: 0,
marginBottom: this.props.mb,
alignItems: this.props.align
},
this.props.style
]}
>
<Text
style={[stylesBase.h6, titleStyles]}
numberOfLines={this.props.titleNumberOfLines}
>
{this.props.title}
</Text>
{!_.isEmpty(this.props.text) && (
<Text
style={[stylesBase.text, textStyles]}
numberOfLines={this.props.textNumberOfLines}
>
{this.props.text}
</Text>
)}
</View>
);
}
}
Heading.propTypes = {
titleSize: PropTypes.number,
textSize: PropTypes.number,
mb: PropTypes.number,
textNumberOfLines: PropTypes.number,
titleNumberOfLines: PropTypes.number,
titleColor: PropTypes.string,
textColor: PropTypes.string,
align: PropTypes.string,
title: PropTypes.string,
text: PropTypes.string
};
Heading.defaultProps = {
titleSize: 24,
titleColor: Consts.colorDark1,
textSize: 12,
textColor: Consts.colorDark3
};
<file_sep>import {
SEARCH_USERS,
SEARCH_USERS_ERROR,
GET_USER,
GET_USERS_FROM_FIREBASE,
GET_USERS_FROM_FIREBASE_LOADING,
GET_USERS_FROM_FIREBASE_ERROR,
GET_KEY_FIREBASE,
GET_KEY_FIREBASE2,
USER_CONNECTION,
POST_USER_CONNECTION
} from "../constants/actionTypes";
import axios from "axios";
import _ from "lodash";
import * as firebase from "firebase";
const getArrValue = obj => {
return Object.keys(obj).reduce((arr, item) => {
return [...arr, { ...obj[item], ...{ key: item } }];
}, []);
};
const encodeId = id => `___${id}___`;
const decodeId = id => id.replace(/___/g, "");
export const searchUsers = username => dispatch => {
return axios
.get("search-users", {
params: {
s: username
}
})
.then(({ data }) => {
if (data.status === "success") {
dispatch({
type: SEARCH_USERS,
payload: data.aResults
});
} else if (data.status === "error") {
dispatch({
type: SEARCH_USERS_ERROR,
message: data.msg
});
}
})
.catch(err => console.log(err));
};
export const getUser = userID => dispatch => {
return axios
.get(`users/${userID}`)
.then(({ data }) => {
if (data.status === "success") {
dispatch({
type: GET_USER,
payload: data.oInfo
});
}
})
.catch(err => console.log(err));
};
const addToList = (db, id, firebaseID1) => async (
id2,
displayName,
message,
type,
firebaseID2
) => {
const dbInfo = db.ref(`messages/users/${encodeId(id)}`);
const snapshotOderByUserID = await dbInfo
.orderByChild("userID")
.equalTo(id2)
.once("value");
const snapshotOderByActive = await dbInfo
.orderByChild("active")
.equalTo(true)
.once("value");
const valOrderByUserID = snapshotOderByUserID.val();
const valOrderByActive = snapshotOderByActive.val();
if (valOrderByUserID) {
const key = Object.keys(valOrderByUserID)[0];
db.ref(`messages/users/${encodeId(id)}/${key}/message`).set(message);
db.ref(`messages/users/${encodeId(id)}/${key}/timestamp`).set(
firebase.database.ServerValue.TIMESTAMP
);
if (firebaseID1) {
db.ref(`messages/users/${encodeId(id)}/${key}/fUser`).set(firebaseID1);
}
if (firebaseID2) {
db.ref(`messages/users/${encodeId(id)}/${key}/sUser`).set(firebaseID2);
}
if (type === "setNew") {
if (valOrderByActive) {
db.ref(`messages/users/${encodeId(id)}/${key}/new`).set(
Object.keys(valOrderByActive)[0] !== key
);
} else {
db.ref(`messages/users/${encodeId(id)}/${key}/new`).set(true);
}
}
} else {
dbInfo.push({
userID: id2,
displayName,
message,
timestamp: firebase.database.ServerValue.TIMESTAMP,
new: type === "setNew" ? true : false,
active: false,
...(firebaseID1 ? { fUser: firebaseID1 } : {}),
...(firebaseID2 ? { sUser: firebaseID2 } : {})
});
}
};
export const addUsersToFirebase = (
userID,
displayName,
myID,
myDisplayName,
message,
firebaseID
) => async (dispatch, getState) => {
try {
const { db } = getState();
if (!db || !myID || !userID || !firebaseID) return;
await Promise.all([
addToList(db, myID, firebaseID)(userID, displayName, message),
addToList(db, userID)(myID, myDisplayName, message, "setNew", firebaseID)
]);
const snapConnections = await db
.ref(`connections/${encodeId(userID)}`)
.once("value");
if (snapConnections.val()) {
dispatch({
type: POST_USER_CONNECTION,
payload: { [userID]: true }
});
}
} catch (err) {
console.log(err);
}
};
export const getUsersFromFirebase = myID => (dispatch, getState) => {
dispatch({
type: GET_USERS_FROM_FIREBASE_LOADING,
payload: true
});
const { db } = getState();
if (!db || !myID) return;
const dbUsers = db.ref(`messages/users/${encodeId(myID)}`);
return new Promise(resolve => {
dbUsers.off("value");
dbUsers.on("value", snapshot => {
const val = snapshot.val();
if (val) {
axios
.get("list-users", {
params: {
s: getArrValue(val)
.map(item => item.userID)
.join(",")
}
})
.then(({ data }) => {
if (data.status === "success") {
dispatch({
type: GET_USERS_FROM_FIREBASE,
payload: getArrValue(val)
.map((item, index) => {
return {
...item,
avatar: data.aResult[index].avatar
};
})
.sort((x, y) => y.timestamp - x.timestamp)
});
dispatch({
type: GET_USERS_FROM_FIREBASE_LOADING,
payload: false
});
resolve(val);
}
})
.catch(err => console.log(err));
} else {
dispatch({
type: GET_USERS_FROM_FIREBASE_ERROR
});
dispatch({
type: GET_USERS_FROM_FIREBASE_LOADING,
payload: false
});
}
});
});
// dbUsers
// .orderByChild("new")
// .equalTo(false)
// .once("value", snapshot => {
// const val = snapshot.val();
// if (val) {
// dbUsers
// .orderByChild("new")
// .equalTo(true)
// .once("value", snapshotNew => {
// const valNew = snapshotNew.val();
// const valAll = { ...val, ...(valNew !== null ? valNew : {}) };
// axios
// .get("list-users", {
// params: {
// s: getArrValue(valAll)
// .map(item => item.userID)
// .join(",")
// }
// })
// .then(({ data }) => {
// if (data.status === "success") {
// dispatch({
// type: GET_USERS_FROM_FIREBASE,
// payload: getArrValue(valAll)
// .map((item, index) => ({
// ...item,
// avatar: data.aResult[index].avatar,
// key: Object.keys(valAll)[index]
// }))
// .reverse()
// });
// dispatch({
// type: GET_USERS_FROM_FIREBASE_LOADING,
// payload: false
// });
// }
// })
// .catch(err => console.log(err));
// });
// } else {
// dispatch({
// type: GET_USERS_FROM_FIREBASE_ERROR
// });
// dispatch({
// type: GET_USERS_FROM_FIREBASE_LOADING,
// payload: false
// });
// }
// });
};
export const getKeyFirebase = (myID, userID, type) => async (
dispatch,
getState
) => {
try {
const { db } = getState();
if (!db || !myID || !userID) return;
const snapshot = await db
.ref(`messages/users/${encodeId(myID)}`)
.orderByChild("userID")
.equalTo(userID)
.once("value");
const val = snapshot.val();
if (val) {
dispatch({
type:
type === "forPushNotification" ? GET_KEY_FIREBASE2 : GET_KEY_FIREBASE,
payload: Object.keys(val)[0]
});
}
} catch (err) {
console.log(err);
}
};
export const setUserConnection = (myID, connection) => async (
dispatch,
getState
) => {
const { db } = getState();
if (!db || !myID) return;
await db
.ref(`connections/${encodeId(myID)}`)
.set(connection ? connection : null);
const usersSnap = await db
.ref(`messages/users/${encodeId(myID)}`)
.once("value");
const usersVal = usersSnap.val();
const friends = usersVal
? Object.values(usersVal).map(item => item.userID.toString())
: [];
return new Promise(resolve => {
db.ref("connections").on("value", snapshot => {
const val = {};
snapshot.forEach(child => {
const childVal = child.val();
const childKey = decodeId(child.key);
if (childVal && friends.includes(childKey)) {
val[childKey] = childVal;
}
});
dispatch({
type: USER_CONNECTION,
payload: val
});
resolve(val);
});
});
};
export const getUserConnection = userID => (__, getState) => {
const { db } = getState();
if (!db || !userID) return;
db.ref(`connections/${encodeId(userID)}`).on("value", snapshot => {
const val = snapshot.val();
if (val) {
console.log(val);
}
});
};
export const deleteUserListMessageChat = (myID, key) => async (
__,
getState
) => {
const { db } = getState();
if (!db || !myID) return;
await db.ref(`messages/users/${encodeId(myID)}/${key}`).set(null);
};
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { View, Text, ViewPropTypes } from "react-native";
import * as Consts from "../../constants/styleConstants";
export default class RatedSmall extends PureComponent {
static propTypes = {
rate: PropTypes.number,
max: PropTypes.number,
text: PropTypes.string,
style: ViewPropTypes.style,
horizontal: PropTypes.bool
};
static defaultProps = {
max: 10
};
setColor = () => {
const { rate, max } = this.props;
if (rate >= 0 && rate < max / 5) {
return { color: "#e03d3d" };
} else if (rate >= max / 5 && rate < max / 2.5) {
return { color: "#e68145" };
} else if (rate >= max / 2.5 && rate < max / 1.66666667) {
return { color: "#f4b34d" };
} else if (rate >= max / 1.66666667 && rate < max / 1.25) {
return { color: "#8dda62" };
} else if (rate >= max / 1.25 && rate <= max) {
return { color: "#3ece7e" };
}
};
render() {
const { rate, max, text, horizontal } = this.props;
return rate > 0 ? (
<View
style={[
this.props.style,
horizontal
? {
flexDirection: "row",
justifyContent: "space-between"
}
: {}
]}
>
<View>
{text && (
<Text style={{ color: Consts.colorDark2, fontSize: 12 }}>
{text}
</Text>
)}
</View>
<View style={{ height: 3 }} />
<Text style={this.setColor()}>
{rate < 10 && rate.toString().length === 1 ? rate + ".0" : rate}
</Text>
</View>
) : (
<View />
);
}
}
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
TextInput,
WebView,
Dimensions,
TouchableOpacity,
StyleSheet,
StatusBar
} from "react-native";
import { HeaderHasBack, Loader } from "../../wiloke-elements";
import { Constants } from "expo";
import { Feather } from "@expo/vector-icons";
import * as Consts from "../../constants/styleConstants";
import * as Progress from "react-native-progress";
import { MapView } from "expo";
const HEADER_HEIGHT = 36 + Constants.statusBarHeight;
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get("window");
export default class WebViewScreen extends PureComponent {
state = {
text: "",
url: "",
isLoading: true
};
componentDidMount() {
const { navigation } = this.props;
const { params } = navigation.state;
const { url } = params;
this.setState({ url, text: url });
}
_handleLoadEnd = () => {
this.setState({ isLoading: false });
};
_handleChangeText = text => {
this.setState({ text });
};
renderTextInput = () => {
const { url } = this.state;
return (
typeof url !== "object" &&
url.search("google.com/maps") === -1 && (
<View style={styles.inputWrapper}>
<TextInput
value={url}
onChangeText={this._handleChangeText}
underlineColorAndroid="transparent"
autoCorrect={false}
dataDetectorTypes="link"
style={styles.input}
/>
</View>
)
);
};
_handleReload = () => {
const { text, url } = this.state;
typeof url !== "object" &&
this.setState({
url: text.search(/^http/g) !== -1 ? text : `http://${text}`
});
};
renderButtonReload = () => {
const { url } = this.state;
return (
typeof url !== "object" &&
url.search("google.com/maps") === -1 && (
<TouchableOpacity activeOpacity={0.5} onPress={this._handleReload}>
<Feather name="corner-up-right" size={20} color="#fff" />
</TouchableOpacity>
)
);
};
render() {
const { navigation } = this.props;
const { params } = navigation.state;
const { url, isLoading } = this.state;
const { title, description, lat, lng } = url;
return (
<View
style={{
position: "relative",
width: SCREEN_WIDTH,
height: SCREEN_HEIGHT
}}
>
<StatusBar barStyle="light-content" />
<HeaderHasBack
renderRight={this.renderButtonReload}
renderCenter={this.renderTextInput}
goBack={() => navigation.goBack()}
headerHeight={36}
headerBackgroundColor={Consts.colorDark1}
/>
{typeof url !== "object" ? (
<WebView
ref={ref => (this._webView = ref)}
source={{ uri: url }}
onLoadEnd={this._handleLoadEnd}
style={{
width: SCREEN_WIDTH,
height: SCREEN_HEIGHT - HEADER_HEIGHT,
borderWidth: 10
}}
/>
) : (
<MapView
style={{
flex: 1,
width: SCREEN_WIDTH,
height: SCREEN_HEIGHT - HEADER_HEIGHT
}}
initialRegion={{
latitude: Number(lat),
longitude: Number(lng),
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}}
>
<MapView.Marker
coordinate={{
latitude: Number(lat),
longitude: Number(lng)
}}
title={title}
description={description}
/>
</MapView>
)}
{typeof url !== "object" && isLoading && (
<View style={styles.loading}>
<Loader size="small" />
</View>
)}
</View>
);
}
}
const styles = StyleSheet.create({
inputWrapper: {
width: "100%",
backgroundColor: "rgba(255,255,255,0.1)",
borderRadius: 3
},
input: {
color: Consts.colorGray1,
paddingVertical: 3,
paddingHorizontal: 8,
width: "100%"
},
loading: {
backgroundColor: "#fff",
width: SCREEN_WIDTH,
height: SCREEN_HEIGHT - HEADER_HEIGHT,
position: "absolute",
top: HEADER_HEIGHT,
left: 0,
zIndex: 9
}
});
<file_sep>import { GET_SETTINGS } from "../constants/actionTypes";
import { configureApp } from "../../configureApp";
const initialState = {
colorPrimary: configureApp.colorPrimary,
oSingleListing: {
contentPosition: "above_sidebar"
}
};
export const settings = (state = initialState, action) => {
switch (action.type) {
case GET_SETTINGS:
return {
...action.payload,
colorPrimary: !action.payload.colorPrimary
? colorPrimary
: action.payload.colorPrimary
};
default:
return state;
}
};
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
StatusBar,
TouchableOpacity,
Dimensions,
StyleSheet
} from "react-native";
import { Feather } from "@expo/vector-icons";
import { Constants } from "expo";
import * as Consts from "../../constants/styleConstants";
import stylesBase from "../../stylesBase";
import { connect } from "react-redux";
import { getCountNotifications, getMessageChatNewCount } from "../../actions";
import _ from "lodash";
const { width: SCREEN_WIDTH } = Dimensions.get("window");
const HEADER_HEIGHT = 52 + Constants.statusBarHeight;
const FORM_HEIGHT = 32;
class Header extends Component {
static propTypes = {
renderRight: PropTypes.func,
renderLeft: PropTypes.func,
backgroundColor: PropTypes.string,
textSearch: PropTypes.string
};
static defaultProps = {
backgroundColor: Consts.colorPrimary
};
componentDidMount() {
const { shortProfile, auth, getMessageChatNewCount } = this.props;
const myID = shortProfile.userID;
auth.isLoggedIn && getMessageChatNewCount(myID);
}
_getCountNotifications = _ => {
const { getCountNotifications } = this.props;
if (this.props.auth.isLoggedIn) {
getCountNotifications();
}
};
_handleHeaderRightPress = _ => {
const { navigation, translations } = this.props;
this._getCountNotifications();
navigation.navigate("NotificationsScreenInAccount", {
name: translations.notifications
});
};
_handleHeaderLeftPress = () => {
const { navigation, translations, shortProfile } = this.props;
!_.isEmpty(shortProfile) &&
navigation.navigate("MessageScreen", {
name: translations.messages
});
};
render() {
const {
navigation,
isLoggedIn,
countNotify,
countNotifyRealTimeFaker,
messageNewCount
} = this.props;
const notifyNewCount = countNotifyRealTimeFaker - countNotify;
return (
<View>
<StatusBar barStyle="light-content" />
<View
style={[
styles.container,
{
backgroundColor: this.props.backgroundColor
}
]}
>
{isLoggedIn && (
<View style={styles.headerIcon}>
{this.props.renderLeft ? (
this.props.renderLeft()
) : (
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleHeaderRightPress}
style={styles.headerIcon}
>
<Feather name="bell" size={20} color="#fff" />
{notifyNewCount > 0 && (
<View style={styles.count}>
<Text style={{ color: "#fff", fontSize: 10 }}>
{notifyNewCount > 50 ? 50 : notifyNewCount}
</Text>
</View>
)}
</TouchableOpacity>
)}
</View>
)}
<TouchableOpacity
activeOpacity={0.4}
onPress={() => navigation.navigate("SearchScreen")}
>
<View
style={[
styles.formItem,
{
width: SCREEN_WIDTH - (isLoggedIn ? 100 : 20)
}
]}
>
<Feather
style={styles.formItemIcon}
name="search"
size={16}
color="#fff"
/>
<Text style={[stylesBase.text, styles.search]}>
{this.props.textSearch}
</Text>
</View>
</TouchableOpacity>
{isLoggedIn &&
(this.props.renderRight ? (
this.props.renderRight()
) : (
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleHeaderLeftPress}
style={styles.headerIcon}
>
<Feather name="message-square" size={20} color="#fff" />
{messageNewCount > 0 && (
<View style={styles.count}>
<Text style={{ color: "#fff", fontSize: 10 }}>
{messageNewCount}
</Text>
</View>
)}
</TouchableOpacity>
))}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingHorizontal: 10,
height: HEADER_HEIGHT,
paddingTop: Constants.statusBarHeight
},
formItem: {
flexDirection: "row",
backgroundColor: "rgba(0,0,0,0.1)",
borderRadius: FORM_HEIGHT / 2,
height: FORM_HEIGHT,
alignItems: "center",
justifyContent: "center"
},
formItemIcon: {
marginRight: 5
},
search: {
color: "#fff",
fontSize: 14
},
headerIcon: {
width: 30,
height: 30,
justifyContent: "center",
alignItems: "center"
},
count: {
width: 16,
height: 16,
borderRadius: 8,
backgroundColor: Consts.colorQuaternary,
justifyContent: "center",
alignItems: "center",
position: "absolute",
top: 0,
right: 0
}
});
const mapStateToProps = state => ({
translations: state.translations,
auth: state.auth,
countNotify: state.countNotify,
countNotifyRealTimeFaker: state.countNotifyRealTimeFaker,
shortProfile: state.shortProfile,
messageNewCount: state.messageNewCount
});
const mapDispatchToProps = {
getCountNotifications,
getMessageChatNewCount
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Header);
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { Row, Col, IconTextMedium } from "../../wiloke-elements";
import he from "he";
export default class ListingStatistic extends PureComponent {
static propTypes = {
data: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string,
count: PropTypes.number,
key: PropTypes.string
})
)
};
_getIcon = key => {
switch (key) {
case "views":
return "eye";
case "reviews":
return "star";
case "favorites":
return "heart";
case "shares":
return "share";
default:
return "check";
}
};
render() {
const { data } = this.props;
return (
<Row gap={15}>
{data.length > 0 &&
data.map((item, index) => (
<Col key={index.toString()} column={2} gap={15}>
<IconTextMedium
iconName={this._getIcon(item.key)}
iconSize={30}
text={`${item.count} ${he.decode(item.name)}`}
texNumberOfLines={1}
/>
</Col>
))}
</Row>
);
}
}
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, Dimensions, FlatList, StyleSheet } from "react-native";
import he from "he";
import ListingCat from "./ListingCat";
export default class ListingLayoutCat extends Component {
static propTypes = {
renderItem: PropTypes.func
};
static defaultProps = {
renderItem: () => {}
};
renderItemLoader = () => (
<View style={styles.grid}>
<ListingCat contentLoader={true} />
</View>
);
render() {
const { data } = this.props;
return (
<View style={styles.container}>
{data.length > 0 ? (
<FlatList
data={data}
renderItem={this.props.renderItem}
keyExtractor={item => item.oTerm.term_id.toString()}
numColumns={this.props.layout === "horizontal" ? 1 : 2}
horizontal={this.props.layout === "horizontal" ? true : false}
showsHorizontalScrollIndicator={false}
/>
) : (
<FlatList
data={[{ id: "1" }, { id: "2" }, { id: "3" }]}
renderItem={this.renderItemLoader}
keyExtractor={item => item.id}
horizontal={true}
showsHorizontalScrollIndicator={false}
/>
)}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "row",
padding: 5
},
grid: {
margin: 5
}
});
<file_sep>import React, { PureComponent } from "react";
import { Text, View, TouchableOpacity } from "react-native";
import { connect } from "react-redux";
import { Layout } from "../dumbs";
import { Feather } from "@expo/vector-icons";
import { ListItemTouchable } from "../../wiloke-elements";
class SettingScreen extends PureComponent {
constructor(props) {
super(props);
const { translations } = this.props;
this.data = [
{
iconName: "bell",
text: `${translations.notifications} ${translations.settings}`,
screen: "NotificationSettingScreen"
},
{
iconName: "edit",
text: translations.editProfile,
screen: "EditProfile"
}
];
}
_renderItem = (item, index) => {
return (
<ListItemTouchable
key={item.text}
iconName={item.iconName}
text={item.text}
onPress={() => {
this.props.navigation.navigate(item.screen);
}}
/>
);
};
_renderContent = () => {
return this.data.map(this._renderItem);
};
render() {
const { navigation, settings, translations } = this.props;
const { name } = navigation.state.params;
return (
<Layout
navigation={navigation}
headerType="headerHasBack"
title={name}
goBack={() => navigation.goBack()}
renderRight={() => (
<TouchableOpacity
activeOpacity={0.5}
onPress={() => navigation.navigate("SearchScreen")}
>
<Feather name="search" size={20} color="#fff" />
</TouchableOpacity>
)}
renderContent={this._renderContent}
colorPrimary={settings.colorPrimary}
textSearch={translations.search}
/>
);
}
}
const mapStateToProps = state => ({
settings: state.settings,
translations: state.translations
});
const mapDispatchToProps = {};
export default connect(
mapStateToProps,
mapDispatchToProps
)(SettingScreen);
<file_sep>import React, { PureComponent } from "react";
import { connect } from "react-redux";
import {
ListItemTouchable,
ViewWithLoading,
isEmpty,
RequestTimeoutWrapped
} from "../../wiloke-elements";
import { getStackNavigator } from "../../actions";
class MenuContainer extends PureComponent {
state = {
isLoading: true
};
_getStackNavigator = async () => {
try {
await this.props.getStackNavigator();
this.setState({ isLoading: false });
} catch (err) {
this.setState({ isLoading: false });
}
};
componentDidMount() {
this._getStackNavigator();
}
_handlePress = (stackNavListing, item) => () => {
const { navigation } = this.props;
console.log(item.navigation);
navigation.navigate(item.navigation, {
name: item.name,
key: item.key
});
};
renderItem = stackNavListing => item => (
<ListItemTouchable
key={item.key}
iconName={item.iconName}
text={item.name}
onPress={this._handlePress(stackNavListing, item)}
/>
);
render() {
const { stackNavigator, isMenuRequestTimeout, translations } = this.props;
const { isLoading } = this.state;
const stackNavListing = stackNavigator
.filter(item => item.screen === "listingStack")
.map(item => item.key);
return (
<ViewWithLoading
isLoading={isLoading}
contentLoader="header"
contentLoaderItemLength={4}
gap={0}
>
<RequestTimeoutWrapped
isTimeout={isMenuRequestTimeout}
onPress={this._getStackNavigator}
fullScreen={true}
text={translations.networkError}
buttonText={translations.retry}
>
{!isEmpty(stackNavigator) &&
stackNavigator.map(this.renderItem(stackNavListing))}
</RequestTimeoutWrapped>
</ViewWithLoading>
);
}
}
const mapStateToProps = state => ({
stackNavigator: state.stackNavigator,
isMenuRequestTimeout: state.isMenuRequestTimeout,
translations: state.translations
});
const mapDispatchToProps = {
getStackNavigator
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(MenuContainer);
<file_sep>export const validEmail = email => {
const regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return email.length > 0 && regex.test(String(email).toLowerCase());
};
export const validPhone = phone => {
const regex = /^(\+|)\d*$/;
return phone.length > 0 && regex.test(String(phone));
};
export const validUrl = url => {
const regex = /^(ftp|http|https):\/\/[^ "]+$/;
return url.length > 0 && regex.test(String(url));
};
export const validPassword = password => {
const regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
return password.length > 0 && regex.test(String(password));
};
<file_sep>import React, { PureComponent } from "react";
import { TouchableOpacity, View, Text, StyleSheet } from "react-native";
import * as Consts from "../../constants/styleConstants";
import { ParallaxScreen, ActionSheet } from "../../wiloke-elements";
import { Feather } from "@expo/vector-icons";
import { ArticleDetailContainer } from "../smarts";
import { Heading } from "../dumbs";
import { connect } from "react-redux";
class EventDetailScreen extends PureComponent {
renderHeaderLeft = () => {
const { navigation } = this.props;
return (
<TouchableOpacity activeOpacity={0.5} onPress={() => navigation.goBack()}>
<View
style={{
width: 30,
height: 30,
justifyContent: "center",
alignItems: "center"
}}
>
<Feather name="chevron-left" size={26} color="#fff" />
</View>
</TouchableOpacity>
);
};
renderHeaderCenter = () => {
const { navigation } = this.props;
const { params } = navigation.state;
return (
<Text style={{ color: "#fff" }} numberOfLines={1}>
{params.name}
</Text>
);
};
renderHeaderRight() {
return (
<ActionSheet
options={["Cancel", "Remove", "Report", "Write a review"]}
destructiveButtonIndex={1}
cancelButtonIndex={0}
onPressButtonItem={() => {
console.log("press");
}}
renderButtonItem={() => (
<View
style={{
width: 40,
height: 40,
justifyContent: "center",
alignItems: "center"
}}
>
<Feather name="more-horizontal" size={24} color="#fff" />
</View>
)}
onAction={buttonIndex => {
console.log(buttonIndex);
if (buttonIndex === 1) {
// code
}
}}
/>
);
}
render() {
const { navigation, settings } = this.props;
const { params } = navigation.state;
return (
<ParallaxScreen
headerImageSource={params.image}
overlayRange={[0, 0.9]}
overlayColor={settings.colorPrimary}
renderHeaderLeft={this.renderHeaderLeft}
renderHeaderCenter={this.renderHeaderCenter}
renderHeaderRight={this.renderHeaderRight}
renderContent={() => (
<View style={{ padding: 10 }}>
<Heading title={params.name} titleSize={18} textSize={12} />
<View
style={{
marginHorizontal: -10,
paddingHorizontal: 10,
backgroundColor: Consts.colorGray2
}}
>
<ArticleDetailContainer navigation={navigation} />
</View>
</View>
)}
/>
);
}
}
const mapStateToProps = state => ({
settings: state.settings
});
export default connect(mapStateToProps)(EventDetailScreen);
<file_sep>import React from "react";
import { View, Text, Platform } from "react-native";
import { Layout } from "../dumbs";
import { MenuContainer } from "../smarts";
import { connect } from "react-redux";
import { Modal } from "../../wiloke-elements";
import { Feather } from "@expo/vector-icons";
const MenuScreen = props => {
const { navigation, translations, settings, auth } = props;
const { isLoggedIn } = auth;
return (
<Layout
navigation={navigation}
textSearch={translations.search}
renderContent={() => <MenuContainer navigation={navigation} />}
colorPrimary={settings.colorPrimary}
isLoggedIn={isLoggedIn}
/>
);
};
const mapStateToProps = state => ({
settings: state.settings,
translations: state.translations,
auth: state.auth
});
export default connect(mapStateToProps)(MenuScreen);
<file_sep>import { createStackNavigator } from "react-navigation";
import { Dimensions } from "react-native";
import stackOpts from "./stackOpts";
import SearchScreen from "../components/screens/SearchScreen";
import ListingSearchResultScreen from "../components/screens/ListingSearchResultScreen";
const { width } = Dimensions.get("window");
const searchStack = createStackNavigator(
{
SearchScreen: {
screen: SearchScreen,
navigationOptions: {
gesturesEnabled: true
}
},
ListingSearchResultScreen: {
screen: ListingSearchResultScreen,
navigationOptions: {
gesturesEnabled: true
}
}
},
stackOpts
);
export default searchStack;
<file_sep>import { createStackNavigator } from "react-navigation";
import stackOpts from "./stackOpts";
import * as Consts from "../constants/styleConstants";
import ArticleScreen from "../components/screens/ArticleScreen";
const articleStack = createStackNavigator(
{
ArticleScreen: {
screen: ArticleScreen
}
},
stackOpts
);
export default articleStack;
<file_sep>import React from "react";
import PropTypes from "prop-types";
import {
View,
ActivityIndicator,
ViewPropTypes,
StyleSheet
} from "react-native";
import ImageProgress from "react-native-image-progress";
import { H6, P } from "../../wiloke-elements";
import * as Consts from "../../constants/styleConstants";
import he from "he";
const ListingSmallCard = props => {
const { image, title, text, style, renderRate } = props;
return (
<View style={[styles.container, style]}>
<View style={styles.imageWrapped}>
<ImageProgress
source={{ uri: image }}
resizeMode="cover"
style={styles.image}
indicator={ActivityIndicator}
/>
</View>
<View style={{ paddingRight: 70 }}>
{renderRate()}
<H6 numberOfLines={1}>{he.decode(title)}</H6>
<P style={{ marginTop: -5 }} numberOfLines={1}>
{he.decode(text)}
</P>
</View>
</View>
);
};
ListingSmallCard.propTypes = {
image: PropTypes.string,
title: PropTypes.string,
text: PropTypes.string,
style: ViewPropTypes.style,
renderRate: PropTypes.func
};
ListingSmallCard.defaultProps = {
renderRate: () => {}
};
const styles = StyleSheet.create({
container: {
flexDirection: "row",
alignItems: "center",
borderBottomWidth: 1,
borderBottomColor: Consts.colorGray1,
padding: 10
},
imageWrapped: {
marginRight: 10,
width: 60,
height: 60,
backgroundColor: Consts.colorGray2
},
image: {
width: "100%",
height: "100%"
}
});
export default ListingSmallCard;
<file_sep>import React from "react";
import PropTypes from "prop-types";
import {
View,
Text,
ImageBackground,
Dimensions,
StyleSheet
} from "react-native";
import { LinearGradient } from "expo";
import * as Consts from "../../constants/styleConstants";
import stylesBase from "../../stylesBase";
import { Overlay } from "../../wiloke-elements";
const { height } = Dimensions.get("window");
const Hero = props => {
return (
<View>
<ImageBackground source={{ uri: props.src }} style={styles.background}>
<Overlay opacity={1} backgroundColor={props.overlayColor} />
<View style={styles.content}>
<Text
style={[stylesBase.h2, { color: props.titleColor }, styles.title]}
>
{props.title}
</Text>
<Text
style={[stylesBase.text, { color: props.textColor }, styles.text]}
>
{props.text}
</Text>
</View>
</ImageBackground>
</View>
);
};
Hero.propTypes = {
titleColor: PropTypes.string,
textColor: PropTypes.string,
title: PropTypes.string,
text: PropTypes.string,
src: PropTypes.string,
overlayColor: PropTypes.string
};
Hero.defaultProps = {
titleColor: Consts.colorPrimary,
textColor: Consts.colorGray1,
overlayColor: "rgba(0,0,0,0.4)"
};
const styles = StyleSheet.create({
background: {
position: "relative",
width: "100%",
height: height / 3.5
},
content: {
position: "relative",
zIndex: 9,
flex: 1,
alignItems: "center",
justifyContent: "center",
padding: 20
},
title: {
marginBottom: 5,
textAlign: "center"
},
text: {
textAlign: "center",
fontSize: 15,
lineHeight: 20
}
});
export default Hero;
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import {
Text,
View,
FlatList,
StyleSheet,
TouchableOpacity,
ViewPropTypes,
Dimensions,
StatusBar
} from "react-native";
import ImageCover from "../atoms/ImageCover";
import CameraRollHOC from "../molecules/CameraRollHOC";
import { bottomBarHeight } from "../../functions/bottomBarHeight";
import { Feather } from "@expo/vector-icons";
import _ from "lodash";
import { Constants } from "expo";
const { height: SCREEN_HEIGHT } = Dimensions.get("window");
const STATUS_BAR_HEIGHT = Constants.statusBarHeight;
const IMAGE_BG_COLOR = "#f0f0f3";
const BORDER_BOTTOM_COLOR = "#e7e7ed";
const HEADER_HEIGHT = 52 + STATUS_BAR_HEIGHT;
const CONTENT_HEIGHT = SCREEN_HEIGHT - HEADER_HEIGHT;
const TEXT_COLOR = "#70778b";
class CameraRollSelect extends Component {
static propTypes = {
...FlatList.propTypes, // lấy lại propTypes của Flatlist
numGap: PropTypes.number, // khoảng cách giữa các item
data: PropTypes.array, // mảng dữ liệu truyền vào
customIconSelected: PropTypes.func, // tạo lại icon khi check
iconColorSelected: PropTypes.string, // màu icon
containerStyle: ViewPropTypes.style, // style cho container
itemSelectedMaximum: PropTypes.number, // select được nhiều nhất là bao nhiêu item,
itemWidth: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
itemHeight: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
buttonHeaderLeft: PropTypes.shape({
color: PropTypes.string, // set color cho nút bên trái của header
text: PropTypes.string, // set text cho nút bên trái của header
onPress: PropTypes.func // có tham số là mảng kết quả
}),
buttonHeaderRight: PropTypes.shape({
color: PropTypes.string, // set color cho nút bên phải của header
text: PropTypes.string, // set text cho nút bên phải của header
onPress: PropTypes.func // có tham số là mảng kết quả
}),
selectedText: PropTypes.func, // có tham số là count và return ra string
onSelectPhotos: PropTypes.func, // có tham số là mảng kết quả
statusBarStyle: StatusBar.propTypes.barStyle, // style cho status bar
headerEnabled: PropTypes.bool, // bật / tắt header,
headerStyle: ViewPropTypes.style, // style cho header
contentStyle: ViewPropTypes.style, // style cho content
selectedPhotos: PropTypes.array // ảnh đc chọn lúc đầu
};
static defaultProps = {
numColumns: 1,
numGap: 6,
horizontal: false,
onEndReached: () => {},
onSelectPhotos: () => {},
renderHeaderCenter: count => (
<View>
<Text style={styles.headerCenterText}>{count} selected</Text>
</View>
),
iconColorSelected: "red",
itemSelectedMaximum: Infinity,
buttonHeaderLeft: {
color: "#666",
text: "Button left",
onPress: () => {}
},
buttonHeaderRight: {
color: "#666",
text: "Button right",
onPress: () => {}
},
statusBarStyle: "dark-content",
headerEnabled: true,
selectedPhotos: []
};
state = {
results: this.props.selectedPhotos
};
_handleItemPress = item => async () => {
await this.setState(prevState => ({
results: _.some(prevState.results, item) // nếu mảng có chứa item này rồi
? prevState.results.filter(_item => !_.isEqual(_item, item)) // thì bấm vào sẽ xoá nó
: prevState.results.length < this.props.itemSelectedMaximum // còn không nếu mà số item nhỏ hơn max
? [...prevState.results, item] // thì thêm item này vào
: prevState.results // còn không thì không thêm item nữa
}));
// tạo props onSelectPhotos và truyền tham số là kết quả mảng đã selected
this.props.onSelectPhotos(this.state.results);
};
// bấm vào button 2 bên của header
_handleHeaderPress = type => () => {
const { buttonHeaderLeft, buttonHeaderRight } = this.props;
const { results } = this.state;
if (type === "left") {
buttonHeaderLeft.onPress && buttonHeaderLeft.onPress(results);
} else {
buttonHeaderRight.onPress && buttonHeaderRight.onPress(results);
}
};
_getStyleForIcon = itemSelected => {
const { iconColorSelected } = this.props;
return {
backgroundColor: itemSelected ? iconColorSelected : "transparent",
borderColor: itemSelected ? iconColorSelected : "rgba(255, 255, 255, 0.7)"
};
};
_renderIconSelected = item => {
const { customIconSelected } = this.props;
const { results } = this.state;
const itemSelected = _.some(results, item);
return customIconSelected ? ( // nếu set cho custom lại icon
customIconSelected(itemSelected) // thì gọi hàm và truyền tham số itemSelected trả về true nếu item selected còn k là false
) : (
// nếu k thì sẽ render ra icon selected có sẵn
<View style={[styles.iconSelected, this._getStyleForIcon(itemSelected)]}>
{itemSelected && <Feather name="check" color={"#fff"} size={20} />}
</View>
);
};
_renderItem = ({ item }) => {
const { numColumns, numGap, itemWidth, itemHeight } = this.props;
return (
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleItemPress(item)}
style={[
styles.itemWrap,
{
width: !!itemWidth ? itemWidth : `${100 / numColumns}%`,
padding: numGap / 2
}
]}
>
<View
style={[
styles.itemInnerWrap,
{
width: "100%",
height: itemHeight
}
]}
>
<ImageCover
src={item.node.image.uri}
{...(!!itemHeight ? { height: itemHeight } : {})}
/>
{this._renderIconSelected(item)}
</View>
</TouchableOpacity>
);
};
_renderHeader = () => {
const { results } = this.state;
const {
renderHeaderCenter,
buttonHeaderLeft,
buttonHeaderRight,
headerStyle
} = this.props;
const selectedCount = results.length;
return (
<View style={[styles.header, headerStyle]}>
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleHeaderPress("left")}
style={styles.headerLeft}
>
<Text
style={[styles.headerLeftText, { color: buttonHeaderLeft.color }]}
>
{buttonHeaderLeft.text}
</Text>
</TouchableOpacity>
{renderHeaderCenter(selectedCount)}
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleHeaderPress("right")}
style={styles.headerRight}
>
<Text
style={[styles.headerRightText, { color: buttonHeaderRight.color }]}
>
{buttonHeaderRight.text}
</Text>
</TouchableOpacity>
</View>
);
};
render() {
const {
data,
numGap,
containerStyle,
statusBarStyle,
headerEnabled,
contentStyle
} = this.props;
return (
<View style={[styles.container, containerStyle]}>
<StatusBar barStyle={statusBarStyle} />
{headerEnabled && this._renderHeader()}
<FlatList
{...this.props}
data={data}
keyExtractor={(_, index) => index.toString()}
renderItem={this._renderItem}
onEndReachedThreshold={1}
style={[styles.flatList, contentStyle, { margin: -(numGap / 2) }]}
/>
<View style={{ height: bottomBarHeight }} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: "#fff"
},
flatList: {
height: CONTENT_HEIGHT,
padding: 5
},
itemWrap: {
height: "100%"
},
itemInnerWrap: {
position: "relative",
zIndex: 9,
overflow: "hidden",
backgroundColor: IMAGE_BG_COLOR
},
iconSelected: {
width: 30,
height: 30,
borderRadius: 15,
borderWidth: 1,
position: "absolute",
top: 4,
right: 4,
zIndex: 9,
alignItems: "center",
justifyContent: "center"
},
header: {
position: "relative",
zIndex: 9,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
height: HEADER_HEIGHT,
paddingTop: STATUS_BAR_HEIGHT,
paddingHorizontal: 10,
borderBottomWidth: 1,
borderBottomColor: BORDER_BOTTOM_COLOR,
backgroundColor: "#f6f6f8"
},
headerLeft: {
width: 100
},
headerLeftText: {
textAlign: "left"
},
headerRight: {
width: 100
},
headerRightText: {
textAlign: "right"
},
headerCenterText: {
fontSize: 12,
color: TEXT_COLOR
}
});
export default CameraRollHOC(CameraRollSelect);
<file_sep>import * as types from "../constants/actionTypes";
import axios from "axios";
const initialState = {
isLoggedIn: false,
token: null,
message: ""
};
export const auth = (state = initialState, action) => {
switch (action.type) {
case types.LOGIN:
const { token } = action.payload;
if (token)
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
return {
isLoggedIn: token ? true : false,
token,
message: ""
};
case types.LOGOUT:
if (!token) delete axios.defaults.headers.common["Authorization"];
return {
isLoggedIn: false,
token: null,
message: action.message
};
default:
return state;
}
};
export const loginError = (state = null, action) => {
switch (action.type) {
case types.LOGIN_ERROR:
return action.err;
case types.LOGIN:
return null;
default:
return state;
}
};
export const isLoginLoading = (state = false, action) => {
switch (action.type) {
case types.LOGIN_LOADING:
return action.loading;
default:
return state;
}
};
<file_sep>import {
GET_MY_EVENTS,
GET_MY_EVENTS_LOADMORE,
GET_MY_EVENT_ERROR
} from "../constants/actionTypes";
export const myEvents = (state = { oResults: [] }, action) => {
switch (action.type) {
case GET_MY_EVENTS:
return action.payload;
case GET_MY_EVENTS_LOADMORE:
return {
...state,
next: action.payload.next,
oResults: [...state.oResults, ...action.payload.oResults]
};
case GET_MY_EVENT_ERROR:
return { oResults: [] };
default:
return state;
}
};
export const myEventError = (state = "", action) => {
switch (action.type) {
case GET_MY_EVENT_ERROR:
return action.messageError;
default:
return state;
}
};
<file_sep>import { GET_SIGNUP_FORM } from "../constants/actionTypes";
import { ctlGet } from "./reducerController";
export const signUpForm = (state = [], action) => {
return ctlGet(state, action)(GET_SIGNUP_FORM);
};
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import {
Text,
View,
StatusBar,
Keyboard,
TouchableWithoutFeedback
} from "react-native";
import he from "he";
import { NewGallery } from "../../wiloke-elements";
import { CommentReview } from "../dumbs";
import stylesBase from "../../stylesBase";
import { connect } from "react-redux";
import { getCommentInReviews } from "../../actions";
const TIME_FAKE = 4000;
class CommentListingScreen extends PureComponent {
state = {
isLoading: true
};
async componentDidMount() {
const { navigation, getCommentInReviews } = this.props;
const { params } = navigation.state;
const { item } = params;
const commentId = item.ID;
await getCommentInReviews(commentId);
this.setState({ isLoading: false });
// RealTime Faker
// this._realTimeFaker = setInterval(() => {
// getCommentInReviews(commentId);
// }, TIME_FAKE);
}
// componentWillUnmount() {
// clearInterval(this._realTimeFaker);
// }
_handleGoBack = () => {
const { navigation } = this.props;
Keyboard.dismiss();
navigation.goBack();
};
renderReviewGallery = item => {
const { settings } = this.props;
return (
item.oGallery !== false && (
<View style={{ paddingTop: 8 }}>
<NewGallery
thumbnails={item.oGallery.medium}
modalSlider={item.oGallery.large}
colorPrimary={settings.colorPrimary}
/>
</View>
)
);
};
render() {
// console.log(this.props.navigation);
const { navigation, translations, commentInReviews } = this.props;
const { params } = navigation.state;
const { id, key, item, autoFocus, mode } = params;
const { isLoading } = this.state;
const dataComments =
commentInReviews.length > 0
? commentInReviews.map((item, index) => ({
id: index.toString() + item.postContent,
image: item.oUserInfo.avatar,
title: item.oUserInfo.displayName,
message: item.postContent,
text: item.postDate
}))
: [];
return (
<View>
{/* <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}> */}
<View>
<StatusBar barStyle="dark-content" />
<CommentReview
fullScreen={true}
colorPrimary={this.props.settings.colorPrimary}
inputAutoFocus={autoFocus ? true : false}
headerActionSheet={{
options: [
"Cancel",
"Remove",
"Report review",
"Comment",
"Pin to Top of Review",
"Write a review",
"Edit review"
],
title: he.decode(item.postTitle),
message: he.decode(`${item.postContent.substr(0, 40)}...`),
destructiveButtonIndex: 1,
cancelButtonIndex: 0,
onPressButtonItem: () => {
console.log("press");
},
onAction: buttonIndex => {
console.log(buttonIndex);
if (buttonIndex === 1) {
// code
}
}
}}
rated={item.oReviews.average}
ratedMax={mode}
ratedText={item.oReviews.quality ? item.oReviews.quality : ""}
headerAuthor={{
image: item.oUserInfo.avatar,
title: he.decode(item.oUserInfo.displayName),
text: item.postDate
}}
renderContent={() => (
<View>
<Text style={[stylesBase.h5, { marginBottom: 3 }]}>
{he.decode(item.postTitle)}
</Text>
<Text style={stylesBase.text}>
{he.decode(item.postContent)}
</Text>
{this.renderReviewGallery(item)}
<View style={{ height: 3 }} />
</View>
)}
shares={{
count: item.countShared,
text:
item.countShared > 1 ? translations.shares : translations.share
}}
comments={{
data: dataComments.reverse(),
count: item.countDiscussions,
isLoading,
text:
item.countDiscussions > 1
? translations.comments
: translations.comment
}}
likes={{
count: item.countLiked,
text: item.countLiked > 1 ? translations.likes : translations.like
}}
commentsActionSheet={{
options: ["Cancel", "Remove", "Edit", "Report"],
title: "Comment by <NAME>",
destructiveButtonIndex: 1,
cancelButtonIndex: 0,
onPressButtonItem: () => {
console.log("press");
},
onAction: buttonIndex => {
console.log(buttonIndex);
if (buttonIndex === 1) {
// code
}
}
}}
goBack={this._handleGoBack}
style={{ borderWidth: 0 }}
/>
</View>
{/* </TouchableWithoutFeedback> */}
</View>
);
}
}
const mapStateToProps = state => ({
translations: state.translations,
commentInReviews: state.commentInReviews,
settings: state.settings
});
export default connect(
mapStateToProps,
{ getCommentInReviews }
)(CommentListingScreen);
<file_sep>import { createStore, applyMiddleware, compose } from "redux";
import logger from "redux-logger";
import thunk from "redux-thunk";
import rootReducers from "./app/reducers";
import storage from "redux-persist/lib/storage";
import { persistStore, persistReducer } from "redux-persist";
const persistConfig = {
key: "root",
storage,
whitelist: [
"translations",
"settings",
"auth",
"countNotify",
"countNotifyRealTimeFaker",
"homeScreen",
"listings",
"events",
"stackNavigator",
"tabNavigator",
"deviceToken"
]
};
const reducers = persistReducer(persistConfig, rootReducers);
const middlewares = [thunk];
// if (__DEV__) middlewares.push(logger);
const store = createStore(
reducers,
undefined,
compose(applyMiddleware(...middlewares))
);
const persistor = persistStore(store);
export { store, persistor };
<file_sep>import {
GET_COUNT_MESSAGES,
GET_COUNT_NOTIFICATIONS,
GET_COUNT_NOTIFICATIONS_REALTIMEFAKER
} from "../constants/actionTypes";
import { ctlGet } from "./reducerController";
export const countNotify = (state = 0, action) => {
return ctlGet(state, action)(GET_COUNT_NOTIFICATIONS);
};
export const countNotifyRealTimeFaker = (state = 0, action) => {
return ctlGet(state, action)(GET_COUNT_NOTIFICATIONS_REALTIMEFAKER);
};
<file_sep>import * as types from "../constants/actionTypes";
import axios from "axios";
const POSTS_PER_PAGE = 10;
const LATEST = 3;
export const getEventDiscussion = (eventId, type) => dispatch => {
return axios
.get(`event-detail/${eventId}/discussions`, {
params: {
page: 1,
postsPerPage: type === "latest" ? LATEST : POSTS_PER_PAGE
}
})
.then(res => {
if (type === "latest") {
dispatch({
type: types.GET_EVENT_DISCUSSION_LATEST,
payload: res.data
});
} else {
dispatch({
type: types.GET_EVENT_DISCUSSION,
payload: res.data
});
}
})
.catch(err => console.log(err.message));
};
export const getEventDiscussionLoadmore = (eventId, next) => dispatch => {
return axios
.get(`event-detail/${eventId}/discussions`, {
params: {
page: next,
postsPerPage: POSTS_PER_PAGE
}
})
.then(res => {
dispatch({
type: types.GET_EVENT_DISCUSSION_LOADMORE,
payload: res.data
});
})
.catch(err => console.log(err.message));
};
export const getCommentInDiscussionEvent = discussionId => dispatch => {
return axios
.get(`event-detail/${discussionId}/discussions`)
.then(res => {
dispatch({
type: types.GET_COMMENT_DISCUSSION_EVENT,
payload: res.data
});
})
.catch(err => console.log(err.message));
};
<file_sep>import React, { PureComponent, Fragment } from "react";
import PropTypes from "prop-types";
import { View, Animated, ActivityIndicator } from "react-native";
import { LinearGradient } from "expo";
import ImageProgress from "react-native-image-progress";
import * as Consts from "../../../constants/styleConstants";
export default class ImageCover extends PureComponent {
static propTypes = {
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
borderRadius: PropTypes.number,
blurRadius: PropTypes.number,
overlay: PropTypes.number,
animated: PropTypes.bool,
src: PropTypes.string
};
static defaultProps = {
width: "100%",
animated: false
};
renderOverlay = () => (
<Fragment>
{typeof this.props.linearGradient === "object" ? (
<LinearGradient
colors={this.props.linearGradient}
start={{ x: 0.0, y: 1.0 }}
end={{ x: 1.0, y: 1.0 }}
style={{
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
zIndex: 1,
opacity: this.props.overlay
}}
/>
) : (
<View
style={{
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
zIndex: 1,
backgroundColor: Consts.colorDark,
opacity: this.props.overlay
}}
/>
)}
</Fragment>
);
_getPadding = modifier => {
switch (modifier) {
case "16by9":
return { paddingTop: "56.25%" };
case "4by3":
return { paddingTop: "75%" };
default:
return { paddingTop: "100%" };
}
};
renderContent = () => {
const { src, blurRadius, overlay, modifier, height } = this.props;
return (
<Fragment>
<ImageProgress
source={{ uri: src }}
style={{
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0
}}
blurRadius={blurRadius}
indicator={ActivityIndicator}
/>
<View style={height ? { height } : this._getPadding(modifier)} />
{typeof overlay === "number" && this.renderOverlay()}
</Fragment>
);
};
render() {
const { width, styles } = this.props;
const styleView = [
{ width },
styles,
{
position: "relative",
zIndex: 1,
overflow: "hidden",
borderRadius: this.props.borderRadius
}
];
return (
<Fragment>
{this.props.animated ? (
<Animated.View style={styleView}>
{this.renderContent()}
</Animated.View>
) : (
<View style={styleView}>{this.renderContent()}</View>
)}
</Fragment>
);
}
}
<file_sep>import { GET_REVIEW_FIELDS } from "../constants/actionTypes";
import { ctlGet } from "./reducerController";
export const reviewFields = (state = {}, action) => {
return ctlGet(state, action)(GET_REVIEW_FIELDS);
};
<file_sep>import React from "react";
import PropTypes from "prop-types";
import { TouchableOpacity, ViewPropTypes } from "react-native";
import { IconTextMedium } from "../../wiloke-elements";
import * as Consts from "../../constants/styleConstants";
import { WebBrowser } from "expo";
export const WebItem = props => {
const { url, navigation, style, iconColor, iconBackgroundColor } = props;
return (
<TouchableOpacity
activeOpacity={0.5}
onPress={() => WebBrowser.openBrowserAsync(url)}
style={style}
>
<IconTextMedium
iconName="globe"
iconSize={30}
iconColor={iconColor}
iconBackgroundColor={iconBackgroundColor}
text={url}
/>
</TouchableOpacity>
);
};
WebItem.propTypes = {
url: PropTypes.string,
style: ViewPropTypes.style
};
WebItem.defaultProps = {
iconColor: "#fff",
iconBackgroundColor: Consts.colorQuaternary
};
<file_sep>export const FIREBASE = "FIREBASE";
export const LOADING = "LOADING";
export const LOADING_LISTING_DETAIL = "LOADING_LISTING_DETAIL";
export const LOADING_REVIEW = "LOADING_REVIEW";
export const SCROLL_TO = "SCROLL_TO";
export const REQUEST_TIMEOUT = "REQUEST_TIMEOUT";
export const HOME_REQUEST_TIMEOUT = "HOME_REQUEST_TIMEOUT";
export const ARTICLE_REQUEST_TIMEOUT = "ARTICLE_REQUEST_TIMEOUT";
export const LISTING_REQUEST_TIMEOUT = "LISTING_REQUEST_TIMEOUT";
export const LISTING_SEARCH_REQUEST_TIMEOUT = "LISTING_SEARCH_REQUEST_TIMEOUT";
export const EVENT_SEARCH_REQUEST_TIMEOUT = "EVENT_SEARCH_REQUEST_TIMEOUT";
export const EVENT_REQUEST_TIMEOUT = "EVENT_REQUEST_TIMEOUT";
export const LISTING_DETAIL_DES_REQUEST_TIMEOUT =
"LISTING_DETAIL_DES_REQUEST_TIMEOUT";
export const LISTING_DETAIL_PHOTOS_REQUEST_TIMEOUT =
"LISTING_DETAIL_PHOTOS_REQUEST_TIMEOUT";
export const LISTING_DETAIL_VID_REQUEST_TIMEOUT =
"LISTING_DETAIL_VID_REQUEST_TIMEOUT";
export const LISTING_DETAIL_LIST_REQUEST_TIMEOUT =
"LISTING_DETAIL_LIST_REQUEST_TIMEOUT";
export const LISTING_DETAIL_REVIEWS_REQUEST_TIMEOUT =
"LISTING_DETAIL_REVIEWS_REQUEST_TIMEOUT";
export const LISTING_DETAIL_EVENT_REQUEST_TIMEOUT =
"LISTING_DETAIL_EVENT_REQUEST_TIMEOUT";
export const LISTING_DETAIL_SIDEBAR_REQUEST_TIMEOUT =
"LISTING_DETAIL_SIDEBAR_REQUEST_TIMEOUT";
export const MENU_REQUEST_TIMEOUT = "MENU_REQUEST_TIMEOUT";
export const NEAR_BY_FOCUS = "NEAR_BY_FOCUS";
export const GET_TAB_NAVIGATOR = "GET_TAB_NAVIGATOR";
export const GET_STACK_NAVIGATOR = "GET_STACK_NAVIGATOR";
export const GET_TRANSLATIONS = "GET_TRANSLATIONS";
export const GET_LISTINGS = "GET_LISTINGS";
export const GET_LISTINGS_LOADMORE = "GET_LISTINGS_LOADMORE";
export const GET_LISTING_SEARCH_RESULTS = "GET_LISTING_SEARCH_RESULTS";
export const GET_LISTING_SEARCH_RESULTS_LOADMORE =
"GET_LISTING_SEARCH_RESULTS_LOADMORE";
export const GET_LISTING_BY_CAT = "GET_LISTING_BY_CAT";
export const GET_LISTING_BY_CAT_LOADMORE = "GET_LISTING_BY_CAT_LOADMORE";
export const GET_LISTING_NEARBY = "GET_LISTING_NEARBY";
export const GET_HOME_SCREEN = "GET_HOME_SCREEN";
export const GET_LISTING_FILTERS = "GET_LISTING_FILTERS";
export const GET_LOCATION_LIST = "GET_LOCATION_LIST";
export const GET_CATEGORY_LIST = "GET_CATEGORY_LIST";
export const RESET_SELECTED_CATEGORY_LIST = "RESET_SELECTED_CATEGORY_LIST";
export const RESET_SELECTED_LOCATION_LIST = "RESET_SELECTED_LOCATION_LIST";
export const CHANGE_CATEGORY_LIST = "CHANGE_CATEGORY_LIST";
export const CHANGE_LOCATION_LIST = "CHANGE_LOCATION_LIST";
export const GET_LOCATION = "GET_LOCATION";
export const GET_LISTING_BOX_CUSTOM = "GET_LISTING_BOX_CUSTOM";
export const GET_LISTING_BOX_CUSTOM_ALL = "GET_LISTING_BOX_CUSTOM_ALL";
export const GET_LISTING_DETAIL = "GET_LISTING_DETAIL";
export const RESET_LISTING_DETAIL = "RESET_LISTING_DETAIL";
export const GET_LISTING_DESTINATION = "GET_LISTING_DESTINATION";
export const GET_LISTING_DESTINATION_ALL = "GET_LISTING_DESTINATION_ALL";
export const GET_LISTING_LIST_FEATURE = "GET_LISTING_LIST_FEATURE";
export const GET_LISTING_LIST_FEATURE_ALL = "GET_LISTING_LIST_FEATURE_ALL";
export const GET_LISTING_PHOTOS = "GET_LISTING_PHOTOS";
export const GET_LISTING_PHOTOS_ALL = "GET_LISTING_PHOTOS_ALL";
export const GET_LISTING_REVIEWS = "GET_LISTING_REVIEWS";
export const GET_LISTING_REVIEWS_ALL = "GET_LISTING_REVIEWS_ALL";
export const GET_LISTING_EVENTS = "GET_LISTING_EVENTS";
export const GET_LISTING_EVENTS_ALL = "GET_LISTING_EVENTS_ALL";
export const GET_LISTING_VIDEOS = "GET_LISTING_VIDEOS";
export const GET_LISTING_VIDEOS_ALL = "GET_LISTING_VIDEOS_ALL";
export const GET_LISTING_DETAIL_NAV = "GET_LISTING_DETAIL_NAV";
export const CHANGE_LISTING_DETAIL_NAV = "CHANGE_LISTING_DETAIL_NAV";
export const GET_COMMENT_IN_REVIEWS = "GET_COMMENT_IN_REVIEWS";
export const GET_LISTING_SIDEBAR = "GET_LISTING_SIDEBAR";
export const GET_REPORT_FORM = "GET_REPORT_FORM";
export const GET_REPORT_MESSAGE = "GET_REPORT_MESSAGE";
export const GET_EVENTS = "GET_EVENTS";
export const GET_EVENT_DETAIL = "GET_EVENT_DETAIL";
export const GET_EVENTS_LOADMORE = "GET_EVENTS_LOADMORE";
export const GET_EVENT_DISCUSSION = "GET_EVENT_DISCUSSION";
export const GET_EVENT_DISCUSSION_LATEST = "GET_EVENT_DISCUSSION_LATEST";
export const GET_EVENT_DISCUSSION_LOADMORE = "GET_EVENT_DISCUSSION_LOADMORE";
export const GET_COMMENT_DISCUSSION_EVENT = "GET_COMMENT_DISCUSSION_EVENT";
export const GET_EVENT_SEARCH_RESULTS = "GET_EVENT_SEARCH_RESULTS";
export const GET_EVENT_SEARCH_RESULTS_LOADMORE =
"GET_EVENT_SEARCH_RESULTS_LOADMORE";
export const GET_ARTICLES = "GET_ARTICLES";
export const GET_ARTICLES_LOADMORE = "GET_ARTICLES_LOADMORE";
export const GET_ARTICLE_DETAIL = "GET_ARTICLE_DETAIL";
export const GET_PAGE = "GET_PAGE";
export const GET_SETTINGS = "GET_SETTINGS";
export const IS_POPUP_LOGIN = "IS_POPUP_LOGIN";
export const LOGIN = "LOGIN";
export const LOGOUT = "LOGOUT";
export const CHECK_TOKEN = "CHECK_TOKEN";
export const LOGIN_LOADING = "LOGIN_LOADING";
export const LOGIN_ERROR = "LOGIN_ERROR";
export const GET_MY_FAVORITES = "GET_MY_FAVORITES";
export const TOGGLE_MY_FAVORITES = "TOGGLE_MY_FAVORITES";
export const RESET_MY_FAVORITES = "RESET_MY_FAVORITES";
export const GET_MY_PROFILE = "GET_MY_PROFILE";
export const POST_MY_PROFILE = "POST_MY_PROFILE";
export const POST_MY_PROFILE_ERROR = "POST_MY_PROFILE_ERROR";
export const GET_SHORT_PROFILE = "GET_SHORT_PROFILE";
export const CHANGE_PASSWORD_SUCCESS = "CHANGE_PASSWORD_SUCCESS";
export const ADD_LISTING_DETAIL_FAVORITES = "ADD_LISTING_DETAIL_FAVORITES";
export const GET_ACCOUNT_NAV = "GET_ACCOUNT_NAV";
export const GET_PROFILE_FORM = "GET_PROFILE_FORM";
export const GET_MY_LISTINGS = "GET_MY_LISTINGS";
export const GET_MY_LISTINGS_LOADMORE = "GET_MY_LISTINGS_LOADMORE";
export const GET_MY_LISTING_ERROR = "GET_MY_LISTING_ERROR";
export const GET_LISTING_STATUS = "GET_LISTING_STATUS";
export const GET_EVENT_STATUS = "GET_EVENT_STATUS";
export const GET_POST_TYPES = "GET_POST_TYPES";
export const GET_MY_EVENTS = "GET_MY_EVENTS";
export const GET_MY_EVENTS_LOADMORE = "GET_MY_EVENTS_LOADMORE";
export const GET_MY_EVENT_ERROR = "GET_MY_EVENT_ERROR";
export const GET_MY_NOTIFICATIONS = "GET_MY_NOTIFICATIONS";
export const GET_MY_NOTIFICATIONS_LOADMORE = "GET_MY_NOTIFICATIONS_LOADMORE";
export const GET_MY_NOTIFICATION_ERROR = "GET_MY_NOTIFICATION_ERROR";
export const DELETE_MY_NOTIFICATION = "DELETE_MY_NOTIFICATION";
export const DELETE_MY_NOTIFICATION_ERROR = "DELETE_MY_NOTIFICATION_ERROR";
export const GET_MESSAGE_LIST = "GET_MESSAGE_LIST";
export const GET_MESSAGE_CHAT = "GET_MESSAGE_CHAT";
export const GET_MESSAGE_CHAT_LOADMORE = "GET_MESSAGE_CHAT_LOADMORE";
export const PUT_MESSAGE_CHAT = "PUT_MESSAGE_CHAT";
export const PUT_MESSAGE_CHAT_LISTENER = "PUT_MESSAGE_CHAT_LISTENER";
export const DELETE_MESSAGE_CHAT = "DELETE_MESSAGE_CHAT";
export const EDIT_MESSAGE_CHAT = "EDIT_MESSAGE_CHAT";
export const RESET_MESSAGE_CHAT = "RESET_MESSAGE_CHAT";
export const WRITING_MESSAGE_CHAT = "WRITING_MESSAGE_CHAT";
export const GET_MESSAGE_NEW_COUNT = "GET_MESSAGE_NEW_COUNT";
export const GET_CURRENT_SEND_MESSAGE_SCREEN =
"GET_CURRENT_SEND_MESSAGE_SCREEN";
export const GET_SIGNUP_FORM = "GET_SIGNUP_FORM";
export const SIGNUP = "SIGNUP";
export const SIGNUP_ERROR = "SIGNUP_ERROR";
export const SIGNUP_LOADING = "SIGNUP_LOADING";
export const GET_COUNT_MESSAGES = "GET_COUNT_MESSAGES";
export const GET_COUNT_NOTIFICATIONS = "GET_COUNT_NOTIFICATIONS";
export const GET_COUNT_NOTIFICATIONS_REALTIMEFAKER =
"GET_COUNT_NOTIFICATIONS_REALTIMEFAKER";
export const SEARCH_USERS = "SEARCH_USERS";
export const SEARCH_USERS_ERROR = "SEARCH_USERS_ERROR";
export const GET_USER = "GET_USER";
export const GET_USERS_FROM_FIREBASE = "GET_USERS_FROM_FIREBASE";
export const GET_USERS_FROM_FIREBASE_LOADING =
"GET_USERS_FROM_FIREBASE_LOADING";
export const GET_USERS_FROM_FIREBASE_ERROR = "GET_USERS_FROM_FIREBASE_ERROR";
export const GET_KEY_FIREBASE = "GET_KEY_FIREBASE";
export const GET_KEY_FIREBASE2 = "GET_KEY_FIREBASE2";
export const USER_CONNECTION = "USER_CONNECTION";
export const POST_USER_CONNECTION = "POST_USER_CONNECTION";
export const GET_DEVICE_TOKEN = "GET_DEVICE_TOKEN";
export const GET_NOTIFICATION_SETTING = "GET_NOTIFICATION_SETTING";
export const SET_NOTIFICATION_SETTING = "SET_NOTIFICATION_SETTING";
export const GET_NOTIFICATION_ADMIN_SETTING = "GET_NOTIFICATION_ADMIN_SETTING";
export const GET_REVIEW_FIELDS = "GET_REVIEW_FIELDS";
<file_sep>import { GET_LISTING_STATUS, GET_EVENT_STATUS } from "../constants/actionTypes";
import { ctlGet } from "./reducerController";
export const listingStatus = (state = [], action) => {
return ctlGet(state, action)(GET_LISTING_STATUS);
};
export const eventStatus = (state = [], action) => {
return ctlGet(state, action)(GET_EVENT_STATUS);
};
<file_sep>import {
GET_MESSAGE_CHAT,
PUT_MESSAGE_CHAT,
GET_MESSAGE_CHAT_LOADMORE,
RESET_MESSAGE_CHAT,
WRITING_MESSAGE_CHAT,
GET_MESSAGE_NEW_COUNT,
GET_CURRENT_SEND_MESSAGE_SCREEN,
DELETE_MESSAGE_CHAT,
EDIT_MESSAGE_CHAT
} from "../constants/actionTypes";
import axios from "axios";
import { Audio } from "expo";
import { Platform } from "react-native";
const soundSendMessage = require("../../assets/sendMessage.mp3");
const soundPushMessage = require("../../assets/pushMessage.mp3");
const soundWritingMessage = require("../../assets/writingMessage.mp3");
const PAGESIZE = 40;
const soundObject = new Audio.Sound();
// export const getMessageList = _ => dispatch => {
// return axios
// .get("get-author-messages")
// .then(({ data }) => {
// console.log(data);
// // if (data.status === 'success') {
// // dispatch({
// // type: GET_MESSAGE_LIST,
// // })
// // }
// })
// .catch(err => console.log(err));
// };
import * as firebase from "firebase";
const getChatItemId = (id1, id2) => `___${id1}___${id2}___`;
const getArrValue = obj => {
return Object.keys(obj).reduce((arr, item) => {
return [...arr, { ...obj[item], ...{ key: item } }];
}, []);
};
const encodeId = id => `___${id}___`;
const decodeId = id => id.replace(/___/g, "");
const setSendMessageSound = async (soundObject, sound) => {
try {
soundObject.setOnPlaybackStatusUpdate(async playbackStatus => {
if (playbackStatus.didJustFinish) {
try {
await soundObject.stopAsync();
} catch (err) {
console.log(err);
}
}
});
await soundObject.loadAsync(sound);
await soundObject.playAsync();
} catch (err) {
setSendMessageSound(new Audio.Sound(), sound);
}
};
const checkOpenSound = async (db, myID, chatId) => {
try {
const soundObject = new Audio.Sound();
const snapshot = await db
.ref(`messages/chats/${chatId}/lists`)
.orderByKey()
.limitToLast(1)
.once("value");
db.ref(`messages/chats/${chatId}/lists`)
.orderByKey()
.limitToLast(1)
.on("child_added", async childSnapshot => {
try {
const val = childSnapshot.val();
const _val = snapshot.val();
if (_val) {
const { timestamp } = Object.values(_val)[0];
if (timestamp !== val.timestamp) {
if (val.userID !== myID) {
soundObject.setOnPlaybackStatusUpdate(async playbackStatus => {
if (playbackStatus.didJustFinish) {
try {
await soundObject.stopAsync();
} catch (err) {
console.log(err);
}
}
});
await soundObject.loadAsync(soundPushMessage);
await soundObject.playAsync();
}
}
}
} catch (err) {}
});
} catch (err) {
console.log(err);
}
};
export const getMessageChat = (myID, userID) => (dispatch, getState) => {
const { db } = getState();
if (!db || !myID || !userID) return;
const id = getChatItemId(myID, userID);
const idReverse = getChatItemId(userID, myID);
const dbChat = db
.ref(`messages/chats/${id}/lists`)
.orderByKey()
.limitToLast(PAGESIZE);
const dbChat2 = db
.ref(`messages/chats/${idReverse}/lists`)
.orderByKey()
.limitToLast(PAGESIZE);
return new Promise(resolve => {
// checkOpenSound(db, myID, id);
// checkOpenSound(db, myID, idReverse);
dbChat.on("value", async snapshot => {
const val = snapshot.val();
if (val === null) {
dbChat2.on("value", snapshot2 => {
const val2 = snapshot2.val();
if (val2 === null) {
dispatch({
type: GET_MESSAGE_CHAT,
payload: {
firstKey: null,
chats: [],
chatId: id
}
});
return false;
} else {
dispatch({
type: GET_MESSAGE_CHAT,
payload: {
firstKey: Object.keys(val2)[0],
chats: getArrValue(val2).reverse(),
chatId: idReverse
}
});
resolve();
}
});
} else {
dispatch({
type: GET_MESSAGE_CHAT,
payload: {
firstKey: Object.keys(val)[0],
chats: getArrValue(val).reverse(),
chatId: id
}
});
resolve();
}
});
});
// dbChat.on("child_added", snapshot => {
// const val = snapshot.val();
// console.log(snapshot);
// if (val !== null) {
// dispatch({
// type: PUT_MESSAGE_CHAT,
// payload: val
// });
// }
// });
};
export const getMessageChatLoadmore = (firstKey, chatId) => async (
dispatch,
getState
) => {
const { db } = getState();
if (!db || !chatId) return;
const dbChat = db.ref(`messages/chats/${chatId}/lists`).orderByKey();
const snapshotLimitOne = await dbChat.limitToFirst(1).once("value");
const arrFirstKey = snapshotLimitOne.val()
? Object.keys(snapshotLimitOne.val())
: [firstKey];
return new Promise(resolve => {
if (!arrFirstKey.includes(firstKey)) {
dbChat
.endAt(firstKey)
.limitToLast(PAGESIZE)
.once("value", snapshot => {
const val = snapshot.val();
if (val) {
dispatch({
type: GET_MESSAGE_CHAT_LOADMORE,
payload: {
firstKey: Object.keys(val)[0],
chats: getArrValue(val)
.reverse()
.filter((_, index) => index !== 0),
chatId
}
});
resolve(true);
}
});
} else {
resolve(false);
}
});
};
export const putMessageChatOff = (
myID,
myName,
chatId,
message
) => async dispatch => {
const newItem = {
userID: myID,
displayName: myName,
message,
timestamp: "timestamp"
};
try {
await setSendMessageSound(new Audio.Sound(), soundSendMessage);
dispatch({
type: PUT_MESSAGE_CHAT,
payload: { chatId, newItem }
});
} catch (err) {}
};
export const putMessageChat = (
myID,
myName,
chatId,
message,
firebaseID
) => async (__, getState) => {
try {
const { db } = getState();
if (!db || !myID || !chatId) return;
const timestamp = firebase.database.ServerValue.TIMESTAMP;
const newItem = {
userID: myID,
displayName: myName,
message,
timestamp,
firebaseID
};
const snap = await db.ref(`messages/chats/${chatId}/fUser`).once("value");
await db.ref(`messages/chats/${chatId}/lists`).push(newItem);
const val = snap.val();
if (!val) {
await db.ref(`messages/chats/${chatId}/fUser`).set(firebaseID);
} else {
if (val !== firebaseID) {
await db.ref(`messages/chats/${chatId}/sUser`).set(firebaseID);
}
}
} catch (err) {
console.log(err);
}
};
// export const putMessageChatListener = (event, firstKey, chatId) => dispatch => {
// const dbLists = db.ref(`messages/chats/${chatId}/lists`).limitToLast(1);
// return new Promise(resolve => {
// if (event === "on") {
// dbLists.on("child_added", snapshot => {
// const val = snapshot.val();
// const { key } = snapshot;
// console.log({ ...val, key });
// if (val) {
// dispatch({
// type: PUT_MESSAGE_CHAT_LISTENER,
// payload: {
// firstKey,
// chatId,
// chat: {
// ...val,
// key
// }
// }
// });
// resolve();
// }
// });
// } else if (event === "off") {
// dbLists.off("child_added");
// }
// });
// };
export const resetMessageChat = chatId => (dispatch, getState) => {
const { db } = getState();
if (!db || !chatId) return;
db.ref(`messages/chats/${chatId}/lists`).off("value");
dispatch({
type: RESET_MESSAGE_CHAT
});
};
export const postWritingMessageChat = (myID, chatId, message) => async (
__,
getState
) => {
try {
const { db } = getState();
if (!db || !myID || !chatId) return;
const dbMyWriting = db.ref(`messages/chats/${chatId}/writings/${myID}`);
await dbMyWriting.set(!!message ? true : false);
} catch (err) {
console.log(err);
}
};
export const checkDispatchWritingMessageChat = (
event,
chatId,
userID
) => async (dispatch, getState) => {
const { db } = getState();
if (!db || !chatId || !userID) return;
const dbUserWriting = db.ref(`messages/chats/${chatId}/writings/${userID}`);
try {
soundObject.setOnPlaybackStatusUpdate(async playbackStatus => {
if (playbackStatus.didJustFinish) {
try {
await soundObject.stopAsync();
} catch (err) {
console.log(err);
}
}
});
await soundObject.loadAsync(soundWritingMessage);
} catch (err) {
console.log(err);
}
if (event === "on") {
dbUserWriting.on("value", async snapshot => {
const val = snapshot.val();
try {
if (val) {
await soundObject.playAsync();
}
} catch (err) {
console.log(err);
}
dispatch({
type: WRITING_MESSAGE_CHAT,
payload: {
[chatId]: val ? true : false
}
});
});
} else if (event === "off") {
dbUserWriting.off("value");
}
// if (event === "off") {
// console.log('off')
// dbUserWriting.off("value", test);
// }
};
export const readNewMessageChat = (id, key) => async (__, getState) => {
const { db } = getState();
if (!db || !id || !key) return;
await db.ref(`messages/users/${encodeId(id)}/${key}/new`).set(false);
};
export const messageChatActive = (id, key, val) => async (__, getState) => {
const { db } = getState();
if (!db || !id || !key) return;
await db.ref(`messages/users/${encodeId(id)}/${key}/active`).set(val);
};
export const getMessageChatNewCount = id => async (dispatch, getState) => {
const { db } = getState();
if (!db || !id) return;
return new Promise(resolve => {
db.ref(`messages/users/${encodeId(id)}`)
.orderByChild("new")
.equalTo(true)
.on("value", snapshot => {
const val = snapshot.val();
const count = val ? Object.keys(val).length : 0;
dispatch({
type: GET_MESSAGE_NEW_COUNT,
payload: count
});
resolve(val);
});
});
};
export const resetMessageActive = (id, key, isActive) => (__, getState) => {
const { db } = getState();
if (!db || !id || !key) return;
db.ref(`messages/users/${encodeId(id)}/${key}/active`).set(isActive);
};
export const resetMessageActiveAll = id => (__, getState) => {
const { db } = getState();
if (!db || !id) return;
db.ref(`messages/users/${encodeId(id)}`)
.orderByChild("active")
.equalTo(true)
.on("value", snapshot => {
const val = snapshot.val();
if (val) {
const valArr = getArrValue(val);
valArr.forEach(item => {
db.ref(`messages/users/${encodeId(id)}/${item.key}/active`).set(
false
);
});
}
});
};
export const removeItemInUsersError = id => (__, getState) => {
const { db } = getState();
if (!db || !id) return;
return new Promise(resolve => {
db.ref(`messages/users/${encodeId(id)}`).on("value", snapshot => {
const val = snapshot.val();
if (val) {
const valArr = getArrValue(val);
valArr.forEach(item => {
if (!item.userID) {
db.ref(`messages/users/${encodeId(id)}/${item.key}`).set(null);
}
});
}
resolve();
});
});
};
export const deleteChatItem = (chatId, key) => async (dispatch, getState) => {
try {
const { db } = getState();
if (!db || !chatId || !key) return;
dispatch({
type: DELETE_MESSAGE_CHAT,
key
});
await db.ref(`messages/chats/${chatId}/lists/${key}`).set(null);
} catch (err) {
console.log(err);
}
};
export const editChatItem = (myID, chatId, key, message) => async (
dispatch,
getState
) => {
try {
const { db } = getState();
if (!db || !myID || !chatId || !key) return;
dispatch({
type: EDIT_MESSAGE_CHAT,
payload: {
key,
message
}
});
await Promise.all([
db.ref(`messages/chats/${chatId}/lists/${key}/message`).set(message),
db
.ref(`messages/chats/${chatId}/lists/${key}/timestamp`)
.set(firebase.database.ServerValue.TIMESTAMP),
db.ref(`messages/chats/${chatId}/writings/${myID}`).set(false)
]);
} catch (err) {
console.log(err);
}
};
export const getCurrentSendMessageScreen = val => async dispatch => {
try {
await dispatch({
type: GET_CURRENT_SEND_MESSAGE_SCREEN,
payload: val
});
} catch (err) {
console.log(err);
}
};
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import {
View,
PanResponder,
Animated,
Easing,
Text,
StyleSheet,
ViewPropTypes
} from "react-native";
import * as Consts from "../../../constants/styleConstants";
import * as Progress from "react-native-progress";
const ANIMATION_MAX = 100;
const ANIMATION_DURATION = 1000;
const TIME_TAB_DOUBLE = 300;
const COLOR_PRIMARY = Consts.colorPrimary;
const COLOR_SECONDARY = Consts.colorSecondary;
const COLOR_TERTIARY = Consts.colorTertiary;
const COLOR_QUATERNARY = Consts.colorQuaternary;
const COLOR_DARK = Consts.colorDark;
const COLOR_GRAY2 = Consts.colorGray2;
const COLOR_DARK1 = Consts.colorDark1;
const COLOR_DARK3 = Consts.colorDark3;
const ROUND = Consts.round;
export default class Button extends PureComponent {
static propTypes = {
block: PropTypes.bool,
animation: PropTypes.bool,
isLoading: PropTypes.bool,
backgroundColor: PropTypes.oneOf([
"primary",
"secondary",
"tertiary",
"quaternary",
"dark",
"gray",
"light"
]),
color: PropTypes.oneOf(["dark", "dark3", "primary", "light"]),
size: PropTypes.oneOf(["lg", "md", "sm", "xs"]),
radius: PropTypes.oneOf(["round", "pill"]),
children: PropTypes.oneOfType([
PropTypes.element,
PropTypes.string,
PropTypes.bool
]),
title: PropTypes.oneOfType([
PropTypes.element,
PropTypes.string,
PropTypes.bool
]),
onPress: PropTypes.func,
onPressIn: PropTypes.func,
onPressOut: PropTypes.func,
onDoublePress: PropTypes.func,
style: ViewPropTypes.style,
textStyle: Text.propTypes.style,
colorPrimary: PropTypes.string
};
static defaultProps = {
block: false,
animation: true,
isLoading: false,
title: "Button",
colorPrimary: COLOR_PRIMARY,
onPress: () => {},
onPressIn: () => {},
onPressOut: () => {},
onDoublePress: () => {}
};
constructor(props) {
super(props);
this.state = {
width: 0,
height: 0,
prevTimestamp: 0,
animation: new Animated.Value(0),
position: new Animated.ValueXY(),
isLoading: false
};
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: (event, gestureState) => true,
onStartShouldSetPanResponderCapture: (event, gestureState) => true,
onMoveShouldSetPanResponder: (event, gestureState) => true,
onMoveShouldSetPanResponderCapture: (event, gestureState) => true,
onPanResponderGrant: this._handlePanResponderGrant,
onPanResponderRelease: this._handlePanResponderRelease,
onPanResponderTerminationRequest: (evt, gestureState) => false,
onShouldBlockNativeResponder: (evt, gestureState) => true
});
}
componentDidMount() {
const { isLoading } = this.props;
this.setState({ isLoading });
}
componentDidUpdate(prevProps) {
const { isLoading } = this.props;
if (isLoading !== prevProps.isLoading) {
this.setState({ isLoading });
}
}
_boundingCheck = (lx, ly, w, h) => {
return lx > 0 && lx < w && ly > 0 && ly < h;
};
_handlePanResponderGrant = (event, gestureState) => {
const { locationX, locationY } = event.nativeEvent;
const { position, animation, width, height } = this.state;
const { onPressIn } = this.props;
position.setValue({
x: locationX,
y: locationY
});
Animated.timing(animation, {
toValue: ANIMATION_MAX,
duration: ANIMATION_DURATION,
easing: Easing.inOut(Easing.ease),
userNativeDriver: true
}).start(() => {
animation.setValue(0);
});
// onPressIn
onPressIn(event);
};
_handlePanResponderRelease = (event, gestureState) => {
const { onPress, onDoublePress, onPressOut } = this.props;
const { width, height, prevTimestamp } = this.state;
const { locationX, locationY, timestamp } = event.nativeEvent;
if (this._boundingCheck(locationX, locationY, width, height)) {
this.setState({ prevTimestamp: timestamp });
if (timestamp - prevTimestamp <= TIME_TAB_DOUBLE) {
onDoublePress(event);
} else {
onPress(event);
}
// onPressOut
onPressOut(event);
}
};
_setBackgroundColor = modifier => {
switch (modifier) {
case "primary":
return { backgroundColor: this.props.colorPrimary };
case "secondary":
return { backgroundColor: COLOR_SECONDARY };
case "tertiary":
return { backgroundColor: COLOR_TERTIARY };
case "quaternary":
return { backgroundColor: COLOR_QUATERNARY };
case "dark":
return { backgroundColor: COLOR_DARK };
case "gray":
return { backgroundColor: COLOR_GRAY2 };
case "light":
return { backgroundColor: "#fff" };
default:
return {};
}
};
_setColor = modifier => {
switch (modifier) {
case "dark":
return { color: COLOR_DARK };
case "dark3":
return { color: COLOR_DARK3 };
case "primary":
return { color: this.props.colorPrimary };
case "light":
return { color: "#fff" };
default:
return {};
}
};
_setPaddingSize = modifier => {
switch (modifier) {
case "lg":
return styles.lg;
case "md":
return styles.md;
case "sm":
return styles.sm;
case "xs":
return styles.xs;
default:
return {};
}
};
_setFontSize = modifier => {
switch (modifier) {
case "lg":
return { fontSize: 14 };
case "md":
return { fontSize: 14 };
case "sm":
return { fontSize: 13 };
case "xs":
return { fontSize: 12 };
default:
return {};
}
};
_radius = modifier => {
switch (modifier) {
case "round":
return { borderRadius: ROUND };
case "pill":
return { borderRadius: 50 };
default:
return {};
}
};
_getSizeButton = event => {
const { width, height } = event.nativeEvent.layout;
this.setState({ width, height });
};
renderAnimated() {
const { width, height, position, animation } = this.state;
const SCALE = animation.interpolate({
inputRange: [0, ANIMATION_MAX],
outputRange: [0.3, 1],
extrapolate: "clamp"
});
const OPACITY = animation.interpolate({
inputRange: [0, ANIMATION_MAX / 3, ANIMATION_MAX],
outputRange: [0, 0.4, 0],
extrapolate: "clamp"
});
return (
<Animated.View
pointerEvents="none"
style={{
position: "absolute",
width: width * 2,
height: width * 2,
top: -width,
left: -width,
borderRadius: width,
backgroundColor: "#fff",
opacity: OPACITY,
transform: [
...position.getTranslateTransform(),
{
scale: SCALE
}
]
}}
/>
);
}
renderText() {
const { children, title, color, size, textStyle } = this.props;
return (
<Text
style={[
styles.text,
this._setColor(color),
this._setFontSize(size),
textStyle
]}
>
{children ? children : title}
</Text>
);
}
render() {
const {
block,
backgroundColor,
radius,
size,
style,
animation
} = this.props;
const { width, height, isLoading } = this.state;
return (
<View style={styles.container}>
<View
style={[
styles.row,
this._setBackgroundColor(backgroundColor),
this._setPaddingSize(size),
this._radius(radius),
{
width: block ? "100%" : "auto"
},
style,
{
position: "relative",
overflow: "hidden"
}
]}
onLayout={this._getSizeButton}
{...this._panResponder.panHandlers}
>
{isLoading ? (
<View style={{ alignItems: "center", justifyContent: "center" }}>
<Progress.CircleSnail
size={18}
duration={800}
spinDuration={2000}
thickness={2}
color="#fff"
/>
</View>
) : (
this.renderText()
)}
{animation && this.renderAnimated()}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexWrap: "wrap",
alignItems: "flex-start",
flexDirection: "row"
},
row: {
flexDirection: "column",
paddingVertical: 10,
paddingHorizontal: 20,
borderRadius: 0,
minWidth: 130
},
text: {
fontSize: 13,
fontWeight: "600",
color: "#fff",
textAlign: "center"
},
lg: {
paddingVertical: 15,
paddingHorizontal: 20
},
md: {
paddingVertical: 11,
paddingHorizontal: 20
},
sm: {
paddingVertical: 9,
paddingHorizontal: 18,
minWidth: 100
},
xs: {
paddingVertical: 5,
paddingHorizontal: 15,
minWidth: 80
}
});
<file_sep>import { GET_REVIEW_FIELDS } from "../constants/actionTypes";
import axios from "axios";
export const getReviewFields = id => async dispatch => {
try {
const res = await axios.get(`review-fields/${id}`);
const { data } = res;
if (data.status === "success") {
dispatch({
type: GET_REVIEW_FIELDS,
payload: data.oFields
});
}
} catch (err) {
console.log(err);
}
};
<file_sep>import React, { Component, PureComponent } from "react";
import {
Text,
View,
TouchableOpacity,
Dimensions,
StyleSheet,
Platform,
FlatList,
ActivityIndicator,
AppState,
Keyboard
} from "react-native";
import LinkPreview from "react-native-link-preview";
import { Feather } from "@expo/vector-icons";
import * as Consts from "../../constants/styleConstants";
import { connect } from "react-redux";
import { Constants, WebBrowser, MapView } from "expo";
import {
InputAccessoryLayoutFullScreen,
ImageCircleAndText,
MessageTyping,
ActionSheet,
P,
OfflineNotice,
getEmoijFromString
} from "../../wiloke-elements";
import ImageProgress from "react-native-image-progress";
import {
getMessageChat,
getMessageChatLoadmore,
putMessageChat,
putMessageChatOff,
resetMessageChat,
getUser,
addUsersToFirebase,
postWritingMessageChat,
checkDispatchWritingMessageChat,
messageChatActive,
readNewMessageChat,
resetMessageActive,
deleteChatItem,
editChatItem,
messagePushNotification,
getCurrentSendMessageScreen
} from "../../actions";
import _ from "lodash";
const { height: SCREEN_HEIGHT, width: SCREEN_WIDTH } = Dimensions.get("window");
const HEADER_HEIGHT = 52 + Constants.statusBarHeight;
const CONTENT_HEIGHT = SCREEN_HEIGHT - HEADER_HEIGHT;
const END_REACHED_THRESHOLD = Platform.OS === "ios" ? 0 : 1;
const PAGESIZE = 40;
class MyMapView extends Component {
shouldComponentUpdate(nextProps) {
return false;
}
render() {
const { latitude, longitude } = this.props;
return (
<MapView
style={{
width: "100%",
height: "100%"
}}
initialRegion={{
latitude,
longitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}}
>
<MapView.Marker
coordinate={{
latitude,
longitude
}}
/>
</MapView>
);
}
}
class SendMessageScreen extends Component {
state = {
isLoadMore: true,
message: "",
isEditing: false,
itemEditing: {},
linkPreviews: {}
};
_handleAppStateChange = (myID, key) => nextAppState => {
this.props.resetMessageActive(myID, key, nextAppState !== "active");
};
async componentDidMount() {
const {
navigation,
getMessageChat,
getUser,
shortProfile,
checkDispatchWritingMessageChat,
messageChatActive,
readNewMessageChat,
getCurrentSendMessageScreen
} = this.props;
const { params } = navigation.state;
const { userID, key } = params;
const myID = shortProfile.userID;
getUser(userID);
this.setState({ isLoadMore: false });
await getMessageChat(myID, userID);
const { messageChat } = this.props;
checkDispatchWritingMessageChat("on", messageChat.chatId, userID);
getCurrentSendMessageScreen(true);
!!key && messageChatActive(myID, key, true);
!!key && readNewMessageChat(myID, key);
!!key &&
AppState.addEventListener(
"change",
this._handleAppStateChange(myID, key)
);
this._setLinkPreviews(messageChat.chats);
}
componentDidUpdate(prevProps) {
if (!_.isEqual(prevProps.messageChat.chats, this.props.messageChat.chats)) {
this._setLinkPreviews(this.props.messageChat.chats);
}
}
async componentWillUnmount() {
const {
navigation,
messageChat,
shortProfile,
postWritingMessageChat,
resetMessageChat,
messageChatActive,
checkDispatchWritingMessageChat
} = this.props;
const myID = shortProfile.userID;
const { chatId } = messageChat;
const { params } = navigation.state;
const { key, userID } = params;
resetMessageChat(chatId);
postWritingMessageChat(myID, chatId, "");
checkDispatchWritingMessageChat("off", messageChat.chatId, userID);
this.setState({ isLoadMore: false });
!!key && messageChatActive(myID, key, false);
!!key &&
AppState.removeEventListener(
"change",
this._handleAppStateChange(myID, key)
);
}
_handleSendMessage = async () => {
const {
messageChat,
putMessageChat,
putMessageChatOff,
addUsersToFirebase,
navigation,
shortProfile,
postWritingMessageChat,
editChatItem,
messagePushNotification
} = this.props;
const { params } = navigation.state;
const { userID, displayName, key } = params;
const {
userID: myID,
displayName: myDisplayName,
firebaseID
} = shortProfile;
const { chatId } = messageChat;
const { isEditing, itemEditing, message } = this.state;
if (message.length > 0) {
try {
this.setState({ message: "" });
if (isEditing) {
await editChatItem(myID, chatId, itemEditing.key, message);
} else {
await putMessageChatOff(myID, myDisplayName, chatId, message);
await postWritingMessageChat(myID, chatId, "");
await putMessageChat(
myID,
myDisplayName,
chatId,
message,
firebaseID
);
messagePushNotification(userID, myDisplayName, message, myID, key);
addUsersToFirebase(
userID,
displayName,
myID,
myDisplayName,
message,
firebaseID
);
}
this._setLinkPreviews([{ message }]);
} catch (err) {
console.log(err);
}
}
this.setState({ isEditing: false });
};
_handleChangeMessage = message => {
const { shortProfile, messageChat, postWritingMessageChat } = this.props;
const myID = shortProfile.userID;
const { chatId } = messageChat;
postWritingMessageChat(myID, chatId, message);
this.setState({ message });
};
_handleEndReached = (firstKey, chatId) => async _ => {
const { messageChat } = this.props;
const { length } = messageChat.chats;
try {
if (length >= PAGESIZE) {
const isLoadMore = await this.props.getMessageChatLoadmore(
firstKey,
chatId
);
this.setState({ isLoadMore });
this._setLinkPreviews(messageChat.chats);
}
} catch (err) {
console.log(err);
}
};
_renderHeader = () => {
const { navigation, user, userConnections, translations } = this.props;
const { params } = navigation.state;
const { userID, displayName } = params;
return (
<View style={styles.header}>
<View style={{ flexDirection: "row", alignItems: "center" }}>
<TouchableOpacity
activeOpacity={0.6}
onPress={() => navigation.goBack()}
style={{ marginRight: 10 }}
>
<Feather name="chevron-left" size={30} color={Consts.colorDark2} />
</TouchableOpacity>
<ImageCircleAndText
title={displayName}
text={
userConnections[userID]
? translations.online
: translations.offline
}
image={user.avatar}
horizontal={true}
dotEnabled={true}
dotTintColor={
userConnections[userID]
? Consts.colorSecondary
: Consts.colorQuaternary
}
/>
</View>
</View>
);
};
_renderImageCircleSmall = img => {
return (
<View style={styles.imageCircleSmall}>
<ImageProgress
source={{ uri: img }}
resizeMode="cover"
style={styles.imageCircleSmallImage}
indicator={ActivityIndicator}
/>
</View>
);
};
_handleChatItemDelete = async key => {
const { messageChat } = this.props;
const { chatId } = messageChat;
this.props.deleteChatItem(chatId, key);
await this.setState({
message: "",
isEditing: false,
itemEditing: {}
});
};
_handleChatItemEdit = item => {
this.setState({
message: item.message,
isEditing: true,
itemEditing: item
});
};
_handleCancelChatEdit = _ => {
this.setState({
message: "",
isEditing: false,
itemEditing: {}
});
};
_actionSheetMoreOptions = item => {
const { translations } = this.props;
return {
options: [translations.cancel, translations.delete, translations.edit],
destructiveButtonIndex: 1,
cancelButtonIndex: 0,
// onPressButtonItem: () => {
// console.log(item);
// },
onAction: buttonIndex => {
switch (buttonIndex) {
case 1:
return this._handleChatItemDelete(item.key);
case 2:
return this._handleChatItemEdit(item);
default:
break;
}
}
};
};
_renderChatItemText = (myID, item, index) => () => {
const { settings, messageChat, translations } = this.props;
const { isEditing, itemEditing } = this.state;
const checkForMe = item.userID === myID;
const intersectAtTheEnd =
index >= 1 &&
messageChat.chats[index].displayName !==
messageChat.chats[index - 1].displayName;
const intersectAtTheStart =
index < messageChat.chats.length - 1 &&
messageChat.chats[index].displayName !==
messageChat.chats[index + 1].displayName;
const styleMe = {
borderTopLeftRadius: 10,
borderBottomLeftRadius: 10,
borderTopRightRadius:
intersectAtTheStart || index === messageChat.chats.length - 1 ? 10 : 3,
borderBottomRightRadius: intersectAtTheEnd || index === 0 ? 10 : 3
};
const styleOrther = {
borderTopRightRadius: 10,
borderBottomRightRadius: 10,
borderTopLeftRadius:
intersectAtTheStart || index === messageChat.chats.length - 1 ? 10 : 3,
borderBottomLeftRadius: intersectAtTheEnd || index === 0 ? 10 : 3,
marginRight: 20,
marginLeft: 5
};
const { message } = item;
return (
<View>
{message.length === 2 && getEmoijFromString(message).length > 0 ? (
<View style={{ marginBottom: -6 }}>
<Text style={{ fontSize: 50 }}>{getEmoijFromString(message)}</Text>
</View>
) : (
<View
style={[
{
paddingHorizontal: 10,
paddingVertical: 5,
backgroundColor: checkForMe
? isEditing && item.key === itemEditing.key
? Consts.colorTertiary
: settings.colorPrimary
: Consts.colorGray1
},
checkForMe ? styleMe : styleOrther
]}
>
<Text
style={{
color: item.userID === myID ? "#fff" : Consts.colorDark1,
lineHeight: 20
}}
{...message.search("http") !== -1 && { numberOfLines: 2 }}
>
{message.search(/longitude|latitude/g) !== -1
? `${translations.showMap} ↓`
: message}
</Text>
</View>
)}
</View>
);
};
_handleUrlPreview = url => () => {
WebBrowser.openBrowserAsync(url);
};
_renderUrlPreview = url => {
const { linkPreviews } = this.state;
const data = !_.isEmpty(linkPreviews) && linkPreviews[url];
const imageWidth = SCREEN_WIDTH / 2;
const imageHeight = (imageWidth * 56.25) / 100;
return !_.isEmpty(linkPreviews) ? (
!!data && (
<View style={styles.urlPreview}>
{!_.isEmpty(linkPreviews[url].images) && (
<ImageProgress
source={{ uri: linkPreviews[url].images[0] }}
resizeMode="cover"
style={{
width: imageWidth,
height: imageHeight
}}
indicator={ActivityIndicator}
/>
)}
<View style={styles.urlPreviewContent}>
<P style={{ lineHeight: 18, fontWeight: "500" }}>
{linkPreviews[url].title}
</P>
<View style={{ marginTop: -5 }}>
<P
style={{
fontSize: 11,
color: Consts.colorDark4,
lineHeight: 15
}}
numberOfLines={1}
>
{linkPreviews[url].url.replace(/\/$/g, "")}
</P>
</View>
</View>
</View>
)
) : (
<View style={styles.urlPreview}>
<View
style={{
width: imageWidth,
height: imageHeight
}}
/>
<View style={styles.urlPreviewContent} />
</View>
);
};
_getLinkPreview = async chats => {
const messageUrls = chats.reduce((arr, item) => {
return [
...arr,
...(item.message &&
item.message
.split(" ")
.filter(
item =>
item.search(/http(s|):\/\/(.*www\..*(?=\.)|(?!www).*\.)/g) !==
-1
))
];
}, []);
const messageUrlPromises = messageUrls.map(LinkPreview.getPreview);
const newMessageUrlPreviews = await Promise.all(messageUrlPromises);
return messageUrls.reduce((obj, messageUrl) => {
const pattern = /http.*\/\/(www\.|)/g;
return {
...obj,
[messageUrl]: newMessageUrlPreviews.filter(
item =>
messageUrl.search(
item.url.replace(/\/$/g, "").replace(pattern, "")
) !== -1
)[0]
};
}, {});
};
_setLinkPreviews = async chats => {
const newLinkPreviews = await this._getLinkPreview(chats);
this.setState(prevState => {
return {
linkPreviews: {
...prevState.linkPreviews,
...newLinkPreviews
}
};
});
};
_handleDragMapEnd = coordinate => {
this.setState({
message: JSON.stringify(coordinate)
});
};
_handleOpenMapView = coordinate => {
this.setState({
message: JSON.stringify(coordinate)
});
};
_handleEmoijSelected = async icon => {
const { message } = this.state;
await this.setState({
message: message.length > 0 ? `${message}${icon}` : icon
});
if (this.state.message.length === 2) this._handleSendMessage();
};
_handleOpenMapViewScreen = (longitude, latitude) => () => {
this.props.navigation.navigate("WebViewScreen", {
url: {
title: "",
description: "",
lat: latitude,
lng: longitude
}
});
};
_renderUrl = position => (item, index) => {
return (
<TouchableOpacity
key={index.toString()}
activeOpacity={0.6}
onPress={this._handleUrlPreview(item)}
style={position === "end" ? { alignItems: "flex-end" } : {}}
>
{this._renderUrlPreview(item)}
</TouchableOpacity>
);
};
_renderMapView = (message, position) => {
const latlng = JSON.parse(message);
const { longitude, latitude } = latlng;
const width = SCREEN_WIDTH / 5;
return (
<View style={position === "end" ? { alignItems: "flex-end" } : {}}>
<View
style={[
{
width,
height: width
},
styles.mapView
]}
>
<MyMapView latitude={latitude} longitude={longitude} />
<TouchableOpacity
activeOpacity={0.6}
style={styles.mapViewOverlay}
onPress={this._handleOpenMapViewScreen(longitude, latitude)}
/>
</View>
</View>
);
};
_renderChatItem = ({ item, index }) => {
const {
shortProfile,
user,
translations,
messageChat,
settings
} = this.props;
const myID = shortProfile.userID;
const { isEditing, itemEditing } = this.state;
const checkDisplayNameCoincident =
index >= 1 &&
messageChat.chats[index].displayName !==
messageChat.chats[index - 1].displayName;
// messageChat.chats[index - 1].timestamp -
// messageChat.chats[index].timestamp >
// 20000;
return (
<View
style={{
flexDirection: "row",
alignItems: "flex-end",
justifyContent: item.userID === myID ? "flex-end" : "flex-start",
paddingLeft: 15,
marginBottom: checkDisplayNameCoincident ? 15 : 3
}}
>
{item.userID !== myID && (
<View
style={{
opacity: checkDisplayNameCoincident || index === 0 ? 1 : 0
}}
>
{this._renderImageCircleSmall(user.avatar)}
</View>
)}
{item.userID === myID ? (
<View
style={{
maxWidth: "80%",
position: "relative",
paddingRight: 15
}}
>
<ActionSheet
{...this._actionSheetMoreOptions(item)}
renderButtonItem={this._renderChatItemText(myID, item, index)}
/>
{isEditing && item.key === itemEditing.key && (
<TouchableOpacity
style={{ alignItems: "flex-end", paddingBottom: 10 }}
onPress={this._handleCancelChatEdit}
>
<P style={{ color: Consts.colorQuaternary }}>
{translations.cancel}
</P>
</TouchableOpacity>
)}
{!item.key && (
<View
style={[
styles.iconLoadingSend,
{ borderColor: settings.colorPrimary }
]}
/>
)}
{item.message.search("http") !== -1 &&
item.message
.split(" ")
.filter(item => item.search("http") !== -1)
.map(this._renderUrl("end"))}
{item.message.search(/longitude|latitude/g) !== -1 &&
this._renderMapView(item.message, "end")}
</View>
) : (
<View
style={{
maxWidth: "80%"
}}
>
{this._renderChatItemText(myID, item, index)()}
{item.message.search("http") !== -1 &&
item.message
.split(" ")
.filter(item => item.search("http") !== -1)
.map(this._renderUrl("start"))}
{item.message.search(/longitude|latitude/g) !== -1 &&
this._renderMapView(item.message, "start")}
</View>
)}
</View>
);
};
_renderListFooterComponent = _ => {
const { isLoadMore } = this.state;
return (
<View
style={{
opacity: isLoadMore ? 1 : 0,
alignItems: "center",
padding: 10
}}
>
<ActivityIndicator size="small" />
</View>
);
};
_renderListHeaderComponent = () => {
const { isWritingMessageChat, messageChat, user } = this.props;
const { chatId } = messageChat;
return (
!!isWritingMessageChat[chatId] && (
<MessageTyping
image={user.avatar}
style={{ paddingVertical: 5, paddingHorizontal: 15 }}
/>
)
);
};
render() {
const { messageChat, settings, navigation, translations } = this.props;
// const { params } = navigation.state;
// const { userID, key } = params;
// db.ref(`messages/chats/${messageChat.chatId}/writings/${userID}`).on(
// "value",
// snapshot => {
// console.log(snapshot.val());
// }
// );
return (
<InputAccessoryLayoutFullScreen
translations={translations}
groupButtonItemColorActive={settings.colorPrimary}
contentScrollViewEnabled={false}
renderHeader={() => (
<View>
<View
style={{
height: Constants.statusBarHeight,
backgroundColor: "#fff"
}}
/>
{this._renderHeader()}
</View>
)}
renderContent={() => (
<View style={{ backgroundColor: "#fff", paddingBottom: 5 }}>
<OfflineNotice />
<FlatList
data={messageChat.chats}
inverted={true}
renderItem={this._renderChatItem}
keyExtractor={(_, index) => index.toString()}
keyboardShouldPersistTaps="always"
keyboardDismissMode="on-drag"
onEndReachedThreshold={END_REACHED_THRESHOLD}
onEndReached={this._handleEndReached(
messageChat.firstKey,
messageChat.chatId
)}
ListFooterComponent={this._renderListFooterComponent}
ListHeaderComponent={this._renderListHeaderComponent}
style={{ minHeight: "100%" }}
/>
</View>
)}
textInputProps={{
placeholder: "Aa",
multiline: true,
autoFocus: true,
autoCorrect: false,
value: this.state.message,
onPressText: this._handleSendMessage,
onChangeText: this._handleChangeMessage,
colorPrimary: settings.colorPrimary,
iconName: "fa fa-paper-plane"
}}
groupActionEnabled={true}
onDragMapEnd={this._handleDragMapEnd}
onEmoijSeleted={this._handleEmoijSelected}
onOpenMapView={this._handleOpenMapView}
/>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: "#fff",
borderColor: Consts.colorGray1
},
header: {
position: "relative",
zIndex: 9,
borderBottomWidth: 1,
borderBottomColor: Consts.colorGray1,
paddingHorizontal: 10,
paddingVertical: 10,
flexDirection: "row",
justifyContent: "space-between",
backgroundColor: "#fff"
},
iconLoadingSend: {
width: 10,
height: 10,
borderRadius: 5,
borderWidth: 1,
justifyContent: "center",
alignItems: "center",
position: "absolute",
bottom: 2,
right: 3
},
urlPreview: {
width: SCREEN_WIDTH / 2,
borderWidth: 1,
borderColor: Consts.colorGray1,
borderRadius: 10,
overflow: "hidden",
marginTop: 3,
marginLeft: 5,
backgroundColor: Consts.colorGray2
},
urlPreviewContent: {
padding: 10,
paddingBottom: 0,
backgroundColor: "#fff",
minHeight: 50
},
mapView: {
position: "relative",
borderWidth: 1,
borderColor: Consts.colorGray1,
borderRadius: 10,
overflow: "hidden",
marginTop: 3,
marginLeft: 5,
backgroundColor: Consts.colorGray2
},
mapViewOverlay: {
position: "absolute",
width: "100%",
height: "100%",
top: 0,
left: 0,
zIndex: 9
},
imageCircleSmall: {
borderRadius: 12,
width: 24,
height: 24,
overflow: "hidden",
marginBottom: 2
},
imageCircleSmallImage: {
width: 24,
height: 24
}
});
const mapStateToProps = state => ({
settings: state.settings,
translations: state.translations,
messageChat: state.messageChat,
user: state.user,
shortProfile: state.shortProfile,
isWritingMessageChat: state.isWritingMessageChat,
userConnections: state.userConnections
});
const mapDispatchToProps = {
getMessageChat,
getMessageChatLoadmore,
putMessageChat,
putMessageChatOff,
resetMessageChat,
getUser,
addUsersToFirebase,
postWritingMessageChat,
checkDispatchWritingMessageChat,
messageChatActive,
readNewMessageChat,
resetMessageActive,
deleteChatItem,
editChatItem,
messagePushNotification,
getCurrentSendMessageScreen
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(SendMessageScreen);
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, Text, StyleSheet } from "react-native";
import * as Consts from "../../constants/styleConstants";
export default class TextBox extends Component {
static defaultProps = {
titleStyles: {
fontSize: 13,
color: Consts.colorDark1
},
textStyles: {
fontSize: 11,
color: Consts.colorDark3
}
};
static propTypes = {
titleStyles: PropTypes.any,
textStyles: PropTypes.any,
align: PropTypes.string,
title: PropTypes.string,
text: PropTypes.string
};
render() {
return (
<View
style={{
flex: 1,
marginBottom: 5,
alignItems: this.props.align
}}
>
<Text style={this.props.titleStyles}>{this.props.title}</Text>
<Text style={this.props.textStyles}>{this.props.text}</Text>
</View>
);
}
}
<file_sep>import {
LOGIN,
LOGOUT,
LOGIN_ERROR,
LOGIN_LOADING,
CHECK_TOKEN,
SIGNUP,
SIGNUP_ERROR,
SIGNUP_LOADING
} from "../constants/actionTypes";
import axios from "axios";
export const login = user => dispatch => {
dispatch({
type: LOGIN_LOADING,
loading: true
});
return axios
.post("auth", user)
.then(({ data }) => {
const { token, status, msg } = data;
if (status === "loggedIn") {
dispatch({
type: LOGIN,
payload:
status && status !== "error"
? {
token
}
: {}
});
} else if (status === "error") {
dispatch({
type: LOGIN_ERROR,
err: msg
});
}
dispatch({
type: LOGIN_LOADING,
loading: false
});
})
.catch(err => {
dispatch({
type: LOGIN_LOADING,
loading: false
});
console.log(err);
});
};
export const logout = _ => dispatch => {
dispatch({
type: LOGOUT,
message: "logout"
});
};
export const checkToken = _ => dispatch => {
return axios
.get("is-token-living")
.then(({ data }) => {
dispatch({
type: CHECK_TOKEN,
isLoggedIn: data.status === "success" ? true : false,
message: !!data.msg ? data.msg : ""
});
})
.catch(err => console.log(err));
};
export const register = user => dispatch => {
dispatch({
type: SIGNUP_LOADING,
loading: true
});
return axios
.post("signup", user)
.then(({ data }) => {
const { token } = data;
console.log(data);
if (data.status === "success") {
dispatch({
type: SIGNUP,
payload: { token }
});
} else if (data.status === "error") {
dispatch({
type: SIGNUP_ERROR,
err: data.msg
});
}
dispatch({
type: SIGNUP_LOADING,
loading: false
});
})
.catch(err => {
dispatch({
type: SIGNUP_LOADING,
loading: false
});
console.log(err);
});
};
<file_sep>import React, { Component } from "react";
import { View, Text, StyleSheet } from "react-native";
import { connect } from "react-redux";
import _ from "lodash";
import he from "he";
import {
getListingBoxCustom,
getListingDescription,
changeListingDetailNavigation,
getScrollTo
} from "../../actions";
import stylesBase from "../../stylesBase";
import {
ViewWithLoading,
ContentBox,
isEmpty,
RequestTimeoutWrapped,
HtmlViewer
} from "../../wiloke-elements";
import { ButtonFooterContentBox } from "../dumbs";
import * as Consts from "../../constants/styleConstants";
class ListingDescriptionContainer extends Component {
state = {
isLoading: true
};
_getListingDescription = async () => {
try {
const {
params,
getListingDescription,
getListingBoxCustom,
type
} = this.props;
const { id, item, max } = params;
type === null &&
(await (item.key === "content"
? getListingDescription(id, item.key, max)
: getListingBoxCustom(id, item.key, max)));
this.setState({ isLoading: false });
} catch (err) {
console.log(err);
}
};
componentDidMount() {
this._getListingDescription();
}
renderContent = (id, item, isLoading, descriptions, type) => {
const {
isListingDetailDesRequestTimeout,
translations,
settings
} = this.props;
return (
<ViewWithLoading isLoading={isLoading} contentLoader="contentHeader">
{!isEmpty(descriptions) && (
<ContentBox
headerTitle={item.name}
headerIcon="file-text"
style={{ marginBottom: type !== "all" ? 10 : 50 }}
renderFooter={
item.status &&
item.status === "yes" &&
this.renderFooterContentBox(id, item.key)
}
colorPrimary={settings.colorPrimary}
>
<RequestTimeoutWrapped
isTimeout={isListingDetailDesRequestTimeout}
onPress={this._getListingDescription}
text={translations.networkError}
buttonText={translations.retry}
>
{descriptions[0].search(/<(img|div|p|span|strong|i|a|br)/g) !==
-1 ? (
<View style={{ marginLeft: -10 }}>
<HtmlViewer
html={descriptions[0]}
htmlWrapCssString={`font-size: 13px; color: ${
Consts.colorDark2
}; line-height: 1.4em`}
containerMaxWidth={Consts.screenWidth - 22}
containerStyle={{ paddingLeft: 10, paddingRight: 0 }}
/>
</View>
) : (
<Text style={stylesBase.text}>
{he.decode(descriptions[0])}
</Text>
)}
</RequestTimeoutWrapped>
</ContentBox>
)}
</ViewWithLoading>
);
};
renderFooterContentBox = (listingId, key) => {
const {
translations,
changeListingDetailNavigation,
getListingDescription,
getScrollTo
} = this.props;
return (
<ButtonFooterContentBox
text={translations.viewAll.toUpperCase()}
onPress={() => {
changeListingDetailNavigation(key);
getListingDescription(listingId, key, null);
getScrollTo(0);
}}
/>
);
};
render() {
const {
listingCustomBox,
listingDescription,
listingDescriptionAll,
loadingListingDetail,
type,
params
} = this.props;
const { id, item } = params;
const { isLoading } = this.state;
return type === "all"
? this.renderContent(
id,
item,
loadingListingDetail,
item.key === "content"
? listingDescriptionAll
: listingCustomBox[item.key],
"all"
)
: this.renderContent(
id,
item,
isLoading,
item.key === "content"
? listingDescription
: listingCustomBox[item.key]
);
}
}
const htmlViewStyles = StyleSheet.create({
div: {
fontSize: 13,
color: Consts.colorDark2,
lineHeight: 19
},
a: {
textDecorationLine: "underline"
},
blockquote: {
fontSize: 14,
fontStyle: "italic",
color: Consts.colorDark3,
marginVertical: 10
},
strong: {
display: "flex"
}
});
const mapStateToProps = state => ({
translations: state.translations,
listingCustomBox: state.listingCustomBox,
listingDescription: state.listingDescription,
listingDescriptionAll: state.listingDescriptionAll,
loadingListingDetail: state.loadingListingDetail,
isListingDetailDesRequestTimeout: state.isListingDetailDesRequestTimeout,
settings: state.settings
});
const mapDispatchToProps = {
getListingBoxCustom,
getListingDescription,
changeListingDetailNavigation,
getScrollTo
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ListingDescriptionContainer);
<file_sep>import { GET_LOCATION } from "../constants/actionTypes";
export const getLocations = location => dispatch => {
dispatch({
type: GET_LOCATION,
locations: {
location
}
});
};
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import {
Text,
View,
StyleSheet,
TouchableOpacity,
Dimensions
} from "react-native";
import { ModalPicker, InputMaterial, Button, FontIcon } from "../../";
import _ from "lodash";
import * as Consts from "../../../constants/styleConstants";
const { width: SCREEN_WIDTH } = Dimensions.get("window");
export default class SocialField extends Component {
static propTypes = {
buttonAddText: PropTypes.string,
defaultResults: PropTypes.array,
socials: PropTypes.array,
modalPickerLabel: PropTypes.string,
colorPrimary: PropTypes.string
};
static defaultProps = {
buttonAddText: "+ Add social",
modalPickerLabel: "Social",
colorPrimary: Consts.colorPrimary
};
state = {
results: []
};
componentDidMount() {
const { defaultResults, onChangeResults } = this.props;
this.setState({
results: defaultResults
});
onChangeResults(defaultResults);
}
_handleAdd = async () => {
await this.setState({
results: [
...this.state.results,
{
url: "",
id: ""
}
]
});
};
_handleRemoveItem = index => () => {
const { onChangeResults } = this.props;
const results = this.state.results.filter(
(_item, _index) => _index !== index
);
this.setState({ results });
onChangeResults(results.filter(item => item.url !== "" && item.id !== ""));
};
_handleModalPickerChange = index => (newOptions, itemSelected) => {
const { onChangeResults } = this.props;
const results = this.state.results.map((_item, _index) => {
return {
..._item,
id:
_index === index && !_.isEmpty(itemSelected)
? itemSelected[0].id
: _item.id
};
});
this.setState({ results });
onChangeResults(results.filter(item => item.url !== "" && item.id !== ""));
};
_handleChangeUrl = index => text => {
const { onChangeResults } = this.props;
const results = this.state.results.map((_item, _index) => {
return {
..._item,
url: _index === index ? text : _item.url
};
});
this.setState({ results });
onChangeResults(results.filter(item => item.url !== "" && item.id !== ""));
};
_renderItem = (item, index, results) => {
const { modalPickerLabel, colorPrimary } = this.props;
return (
<View key={index.toString()} style={styles.item}>
<View style={{ width: SCREEN_WIDTH / 2.5 - 30 - 20, marginRight: 15 }}>
<ModalPicker
options={item.socials}
label={modalPickerLabel}
matterial={true}
onChangeOptions={this._handleModalPickerChange(index)}
textResultNumberOfLines={1}
colorPrimary={colorPrimary}
clearSelectEnabled={false}
containerStyle={{
marginTop: -6
}}
/>
</View>
<View
style={{
width: (SCREEN_WIDTH * 1.5) / 2.5 - 30 - 20,
marginRight: 15
}}
>
<InputMaterial
value={item.url}
placeholder={item.id}
clearTextEnabled={false}
colorPrimary={colorPrimary}
onChangeText={this._handleChangeUrl(index)}
/>
</View>
{results.length - 1 === index && (
<TouchableOpacity
activeOpacity={0.6}
style={styles.remove}
onPress={this._handleRemoveItem(index)}
>
<FontIcon name="x" size={18} color={Consts.colorQuaternary} />
</TouchableOpacity>
)}
</View>
);
};
render() {
const { results } = this.state;
const { socials, buttonAddText } = this.props;
const _results = results.map(item => {
return {
...item,
socials: socials.map(socialItem => {
return {
...socialItem,
selected: item.id === socialItem.id ? true : false
};
})
};
});
return (
<View>
{!_.isEmpty(_results) && _results.map(this._renderItem)}
<Button
backgroundColor="gray"
color="dark"
onPress={this._handleAdd}
radius="round"
>
{buttonAddText}
</Button>
</View>
);
}
}
const styles = StyleSheet.create({
item: {
flexDirection: "row",
alignItems: "center"
},
remove: {
width: 30,
height: 30,
justifyContent: "center",
alignItems: "center",
backgroundColor: Consts.colorGray2,
borderRadius: 3,
position: "relative",
top: 4
}
});
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
PanResponder,
Animated,
Easing,
StyleSheet,
ViewPropTypes
} from "react-native";
import * as Consts from "../../../constants/styleConstants";
const THUMB_TINTCOLOR_DEFAULT = Consts.colorPrimary;
const FILL_LOWER_TINTCOLOR_DEFAULT = Consts.colorPrimary;
const TRACK_TINTCOLOR_DEFAULT = Consts.colorDark5;
const LABEL_TINTCOLOR_DEFAULT = Consts.colorDark3;
const RESULT_TINTCOLOR_DEFAULT = Consts.colorDark2;
export default class RangeSlider extends Component {
static propTypes = {
minValue: PropTypes.number,
maxValue: PropTypes.number,
defaultValue: PropTypes.number,
thumbSize: PropTypes.number,
onChangeValue: PropTypes.func,
onBeginChangeValue: PropTypes.func,
onEndChangeValue: PropTypes.func,
disabled: PropTypes.bool,
showLabel: PropTypes.bool,
showResult: PropTypes.bool,
label: PropTypes.string,
trackTintColor: PropTypes.string,
thumbTintColor: PropTypes.string,
fillLowerTintColor: PropTypes.string,
fillLowerStyle: ViewPropTypes.style,
trackStyle: ViewPropTypes.style,
sliderStyle: ViewPropTypes.style
};
static defaultProps = {
minValue: 0,
maxValue: 500,
defaultValue: 0,
thumbSize: 24,
onChangeValue: () => {},
onBeginChangeValue: () => {},
onEndChangeValue: () => {},
disabled: false,
showLabel: true,
showResult: true,
label: "Slider",
thumbTintColor: THUMB_TINTCOLOR_DEFAULT,
trackTintColor: TRACK_TINTCOLOR_DEFAULT,
fillLowerTintColor: FILL_LOWER_TINTCOLOR_DEFAULT
};
constructor(props) {
super(props);
this.state = {
position: new Animated.ValueXY(),
maxWidth: 1,
minWidth: 0,
value: 0,
trackHeight: 0,
isLoading: true
};
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: (event, gestureState) => true,
onStartShouldSetPanResponderCapture: (event, gestureState) => true,
onMoveShouldSetPanResponder: (event, gestureState) => true,
onMoveShouldSetPanResponderCapture: (event, gestureState) => true,
onPanResponderGrant: this._onPanResponderGrant,
onPanResponderMove: this._onPanResponderMove,
onPanResponderRelease: this._onPanResponderRelease,
onPanResponderTerminationRequest: (evt, gestureState) => false,
onShouldBlockNativeResponder: (evt, gestureState) => true
});
}
_startUpdate = () => {
const { position, minWidth } = this.state;
const { defaultValue, maxValue, minValue, thumbSize } = this.props;
this._track.measureInWindow((fx, fy, width, height) => {
const maxWidth = width > thumbSize ? width - thumbSize : width;
const x =
minWidth +
((defaultValue - minValue) * maxWidth) / (maxValue - minValue);
this.setState(
{
value: defaultValue,
maxWidth,
trackHeight: height
},
() => {
position.setValue({
x,
y: 0
});
}
);
});
};
componentDidMount() {
setTimeout(() => {
this._startUpdate();
this.setState({
isLoading: false
});
}, 1000);
}
_onPanResponderGrant = (event, gestureState) => {
const { position, value } = this.state;
const { onBeginChangeValue } = this.props;
const { _value } = position.x;
position.setOffset({
x: _value,
y: 0
});
position.setValue({
x: 0,
y: 0
});
// Called when the user drag the thumb
onBeginChangeValue(event, value, gestureState);
};
_onPanResponderMove = (event, gestureState) => {
const { position, maxWidth, minWidth } = this.state;
const { minValue, maxValue, disabled, onChangeValue } = this.props;
const { dx: x, dy: y } = gestureState;
if (!disabled) {
position.setValue({ x, y: 0 });
const { _offset, _value } = position.x;
const currentX = _offset + _value;
let value = Math.floor((currentX * (maxValue - minValue)) / maxWidth);
if (value < minWidth) {
value = minWidth;
} else if (value > maxValue - minValue) {
value = maxValue - minValue;
}
this.setState({
value: value + minValue
});
// Called when the user drag the thumb
onChangeValue(value + minValue);
}
};
_onPanResponderRelease = (event, gestureState) => {
const { position, maxWidth, minWidth, value } = this.state;
const { onEndChangeValue, minValue } = this.props;
position.flattenOffset();
const { _value } = position.x;
let x = _value;
if (_value < minWidth) {
x = minWidth;
} else if (_value > maxWidth) {
x = maxWidth;
}
position.setValue({
x,
y: 0
});
// Called when the user stops dragging
onEndChangeValue(event, value, gestureState);
};
_ANIMATED_TRANSLATE_X = () => {
const { maxWidth, position } = this.state;
if (maxWidth !== 0)
return position.x.interpolate({
inputRange: [0, maxWidth],
outputRange: [0, maxWidth],
extrapolate: "clamp"
});
else return 10;
};
renderLabel() {
const { label, labelTextStyle, labelStyle } = this.props;
return (
<View
style={[
{
marginBottom: 4
},
labelStyle
]}
>
<Text
style={[
{
fontSize: 13,
color: LABEL_TINTCOLOR_DEFAULT
},
labelTextStyle
]}
>
{label}
</Text>
</View>
);
}
renderResult() {
const { value } = this.state;
const { thumbSize, resultTextStyle, resultStyle } = this.props;
return (
<View
style={[
resultStyle,
{
paddingBottom: thumbSize / 2 + 5
}
]}
>
<Text
style={[
{
color: RESULT_TINTCOLOR_DEFAULT,
fontSize: 14
},
resultTextStyle
]}
>
{value}
</Text>
</View>
);
}
renderHeader() {
const { value } = this.state;
const { showLabel, showResult, customHeader } = this.props;
if (customHeader) return customHeader(value);
return (
<View>
<View>
{showLabel && this.renderLabel()}
{showResult && this.renderResult()}
</View>
</View>
);
}
renderThumb() {
const { trackHeight, isLoading } = this.state;
const { thumbSize, thumbTintColor } = this.props;
return (
<Animated.View
{...this._panResponder.panHandlers}
style={[
{
position: "absolute",
top: -(thumbSize - trackHeight) / 2,
left: 0,
zIndex: 5,
width: thumbSize,
height: thumbSize,
borderRadius: thumbSize / 2,
opacity: isLoading ? 0 : 1,
transform: [
{
translateX: this._ANIMATED_TRANSLATE_X()
}
]
}
]}
>
<View
style={{
position: "absolute",
width: "100%",
height: "100%",
top: 0,
left: 0,
borderRadius: thumbSize / 2,
backgroundColor: thumbTintColor,
opacity: 0.5
}}
/>
<View
style={{
position: "absolute",
width: "50%",
height: "50%",
top: "25%",
left: "25%",
borderRadius: thumbSize / 4,
backgroundColor: thumbTintColor
}}
/>
</Animated.View>
);
}
renderFillLower() {
const { fillLowerStyle, thumbSize, fillLowerTintColor } = this.props;
return (
<View style={styles.fillLowerWrapper}>
<Animated.View
style={[
styles.fillLower,
fillLowerStyle,
{
marginLeft: thumbSize / 2,
backgroundColor: fillLowerTintColor,
transform: [{ translateX: this._ANIMATED_TRANSLATE_X() }]
}
]}
/>
</View>
);
}
renderTrack() {
const { trackStyle, trackTintColor, disabled, thumbSize } = this.props;
const { isLoading } = this.state;
return (
<View
style={{
position: "relative"
}}
>
{this.renderThumb()}
<View
ref={ref => (this._track = ref)}
style={[
styles.track,
trackStyle,
{
backgroundColor: trackTintColor,
marginBottom: thumbSize / 2,
opacity: disabled ? 0.6 : 1,
zIndex: 4
}
]}
>
{!isLoading && this.renderFillLower()}
</View>
</View>
);
}
render() {
const { sliderStyle } = this.props;
return (
<View style={[styles.slider, sliderStyle]}>
{this.renderHeader()}
{this.renderTrack()}
</View>
);
}
}
const styles = StyleSheet.create({
slider: {
marginBottom: 15
},
track: {
position: "relative",
height: 2
},
fillLowerWrapper: {
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%",
overflow: "hidden",
zIndex: -1
},
fillLower: {
position: "absolute",
top: 0,
left: "-100%",
width: "100%",
height: "100%"
}
});
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { View, ActivityIndicator, StyleSheet } from "react-native";
import { CircleSnail } from "react-native-progress";
import * as Consts from "../../../constants/styleConstants";
export default class Loader extends PureComponent {
static propTypes = {
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
color: PropTypes.oneOfType([PropTypes.array, PropTypes.string]),
height: PropTypes.number
};
static defaultProps = {
size: "large",
color: [
Consts.colorSecondary,
Consts.colorTertiary,
Consts.colorQuanternary
],
height: 200
};
_handleSize = () => {
const { size } = this.props;
switch (size) {
case "small":
return 30;
case "medium":
return 35;
case "large":
return 40;
default:
return size;
}
};
render() {
const { color, height } = this.props;
return (
<View style={[styles.loader, { height: height }]}>
<CircleSnail
size={this._handleSize()}
duration={800}
spinDuration={2000}
thickness={2}
color={color}
/>
</View>
);
}
}
const styles = StyleSheet.create({
loader: {
flex: 1,
justifyContent: "center",
alignItems: "center"
}
});
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, FlatList, StyleSheet, Dimensions } from "react-native";
import _ from "lodash";
import he from "he";
import { connect } from "react-redux";
import { getArticles, getArticlesLoadmore } from "../../actions";
import { PostCard } from "../dumbs";
import {
MessageError,
RequestTimeoutWrapped,
ViewWithLoading,
ContentLoader,
Row,
Col,
IconTextSmall,
isEmpty
} from "../../wiloke-elements";
const { width: SCREEN_WIDTH } = Dimensions.get("window");
const END_REACHED_THRESHOLD = 0;
class ArticleContainer extends Component {
static defaultProps = {
horizontal: false
};
static propTypes = {
horizontal: PropTypes.bool
};
state = {
startLoadmore: false
};
// _getId = () => {
// const { categoryList, locationList } = this.props;
// const getId = arr => arr.filter(item => item.selected)[0].id;
// const categoryId =
// categoryList.length > 0 && getId(categoryList) !== "wilokeListingCategory"
// ? getId(categoryList)
// : null;
// const locationId =
// locationList.length > 0 && getId(locationList) !== "wilokeListingLocation"
// ? getId(locationList)
// : null;
// return { categoryId, locationId };
// };
_getArticles = async () => {
try {
const { getArticles } = this.props;
// const { categoryId, locationId } = this._getId();
await getArticles();
this.setState({ startLoadmore: true });
} catch (err) {
console.log(err);
}
};
componentDidMount() {
this._getArticles();
}
_handleEndReached = next => {
const { navigation, getArticlesLoadmore } = this.props;
const { params } = navigation.state;
const { startLoadmore } = this.state;
startLoadmore && next !== false && getArticlesLoadmore(next);
};
renderItem = ({ item, index }) => {
const { navigation, translations, settings } = this.props;
return (
<Col column={2} gap={10}>
<PostCard
image={item.oFeaturedImg.medium}
title={he.decode(item.postTitle)}
text={he.decode(item.postContent)}
renderMeta={() => (
<View>
<IconTextSmall
iconName="calendar"
text={item.postDate}
iconColor={settings.colorPrimary}
/>
<View style={{ height: 6 }} />
<IconTextSmall
iconName="message-square"
text={`${item.countComments} ${translations.comments}`}
iconColor={settings.colorPrimary}
/>
<View style={{ height: 3 }} />
</View>
)}
style={{
width: "100%"
}}
onPress={() =>
navigation.navigate("ArticleDetailScreen", {
id: item.postID,
name: he.decode(item.postTitle),
image:
SCREEN_WIDTH > 420
? item.oFeaturedImg.large
: item.oFeaturedImg.medium
})
}
/>
</Col>
);
};
_getWithLoadingProps = loading => ({
isLoading: loading,
contentLoader: "content",
contentHeight: 90,
contentLoaderItemLength: 6,
featureRatioWithPadding: "56.25%",
column: 2,
gap: 10,
containerPadding: 10
});
renderContentSuccess(loading, articles) {
const { startLoadmore } = this.state;
return (
<ViewWithLoading {...this._getWithLoadingProps(loading)}>
<FlatList
data={articles.oResults}
renderItem={this.renderItem}
keyExtractor={(item, index) => index.toString()}
numColumns={2}
horizontal={false}
showsHorizontalScrollIndicator={false}
onEndReachedThreshold={END_REACHED_THRESHOLD}
onEndReached={() => this._handleEndReached(articles.next)}
ListFooterComponent={() =>
startLoadmore && articles.next !== false ? (
<View style={{ padding: 5 }}>
<Row gap={10}>
{Array(2)
.fill(null)
.map((_, index) => (
<Col key={index.toString()} column={2} gap={10}>
<ContentLoader
featureRatioWithPadding="56.25%"
contentHeight={90}
content={true}
/>
</Col>
))}
</Row>
</View>
) : (
<View style={{ paddingBottom: 20 }} />
)
}
style={{ padding: 5 }}
/>
</ViewWithLoading>
);
}
renderContentError(loading, articles) {
return (
<ViewWithLoading {...this._getWithLoadingProps(loading)}>
<MessageError message={articles.msg} />
</ViewWithLoading>
);
}
render() {
const {
articles,
isArticleRequestTimeout,
loading,
translations
} = this.props;
return (
<RequestTimeoutWrapped
isTimeout={isArticleRequestTimeout}
onPress={this._getArticles}
fullScreen={true}
style={styles.container}
text={translations.networkError}
buttonText={translations.retry}
>
{!_.isEmpty(articles) && articles.oResults
? this.renderContentSuccess(loading, articles)
: this.renderContentError(loading, articles)}
</RequestTimeoutWrapped>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "row"
}
});
const mapStateToProps = state => ({
articles: state.articles,
loading: state.loading,
translations: state.translations,
isArticleRequestTimeout: state.isArticleRequestTimeout,
settings: state.settings
});
const mapDispatchToProps = {
getArticles,
getArticlesLoadmore
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ArticleContainer);
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { Text, View, StyleSheet } from "react-native";
import { isEmpty } from "../../";
export default class NavList extends Component {
state = {
list: []
};
componentDidMount() {
this.setState({
list: this.props.data
});
}
renderItem = item => {
return (
<View>
<Text>item.text</Text>
</View>
);
};
renderLoading = () => {
return (
<View>
<Text>item.text</Text>
</View>
);
};
render() {
const { list } = this.state;
return (
<View style={styles.container}>
{!isEmpty(list) ? list.map(this.renderItem) : this.renderLoading}
</View>
);
}
}
const styles = StyleSheet.create({
container: {}
});
<file_sep>import React, { Component } from "react";
import {
View,
FlatList,
TouchableOpacity,
Alert,
Platform
} from "react-native";
import * as Consts from "../../constants/styleConstants";
import { Layout } from "../dumbs";
import {
ViewWithLoading,
ImageCircleAndText,
LoadingFull,
Toast,
MessageError
} from "../../wiloke-elements";
import { connect } from "react-redux";
import {
getMyNotifications,
getMyNotificationsLoadmore,
deleteMyNotifications
} from "../../actions";
import _ from "lodash";
import he from "he";
import Swipeout from "react-native-swipeout";
const END_REACHED_THRESHOLD = Platform.OS === "ios" ? 0 : 1;
class NotificationsScreen extends Component {
state = {
isLoading: true,
isScrollEnabled: true,
isDeleteLoading: false,
startLoadmore: false
};
_getMyNotifications = async _ => {
await this.setState({ isLoading: true });
await this.props.getMyNotifications();
this.setState({ isLoading: false, startLoadmore: true });
};
componentDidMount() {
this._getMyNotifications();
}
shouldComponentUpdate(nextProps, nextState) {
if (!_.isEqual(nextProps.myNotifications, this.props.myNotifications)) {
return true;
}
if (!_.isEqual(nextState.isLoading, this.state.isLoading)) {
return true;
}
if (!_.isEqual(nextState.isScrollEnabled, this.state.isScrollEnabled)) {
return true;
}
if (!_.isEqual(nextState.isDeleteLoading, this.state.isDeleteLoading)) {
return true;
}
return false;
}
_handleListItem = item => _ => {
const { navigation } = this.props;
!!item.screen &&
navigation.navigate(item.screen, {
id: null,
key: null,
item: item.oDetails,
autoFocus: false,
mode: item.mode
});
};
_deleteListItem = ID => async _ => {
const { translations, deleteMyNotificationError } = this.props;
await this.setState({ isDeleteLoading: true });
await this.props.deleteMyNotifications(ID);
this.setState({ isDeleteLoading: false });
!!deleteMyNotificationError &&
setTimeout(
() => this._toast.show(translations[deleteMyNotificationError], 3000),
500
);
};
_handleEndReached = next => {
const { startLoadmore } = this.state;
const { getMyNotificationsLoadmore } = this.props;
!!next && startLoadmore && getMyNotificationsLoadmore(next);
};
renderNotifyItem = ({ item }) => {
const { translations } = this.props;
return (
<Swipeout
right={[
{
text: translations.delete,
type: "delete",
onPress: () => {
Alert.alert(
translations.delete,
translations.confirmDeleteNotification,
[
{
text: translations.cancel,
style: "cancel"
},
{
text: translations.ok,
onPress: this._deleteListItem(item.ID)
}
],
{ cancelable: false }
);
}
}
]}
autoClose={true}
scroll={event => this.setState({ isScrollEnabled: event })}
style={{
borderBottomWidth: 1,
borderColor: Consts.colorGray1,
backgroundColor: "#fff"
}}
>
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleListItem(item)}
style={{
paddingVertical: 12,
paddingHorizontal: 10
}}
>
<ImageCircleAndText
image={item.image}
title={item.name}
message={item.message}
time={item.time}
horizontal={true}
messageNumberOfLines={1}
imageSize={44}
/>
</TouchableOpacity>
</Swipeout>
);
};
renderContent = () => {
const { myNotifications, translations } = this.props;
const { oResults, next, status, msg } = myNotifications;
const { isLoading, isDeleteLoading, startLoadmore } = this.state;
const _oResults = !_.isEmpty(oResults)
? oResults.map(item => ({
ID: item.ID,
oDetails: item.oDetails,
screen: item.screen,
time: item.time,
type: item.type,
image: item.oFeaturedImg.thumbnail,
name: he.decode(item.postTitle),
message: he.decode(item.postContent)
}))
: [];
return (
<ViewWithLoading
isLoading={isLoading}
contentLoader="headerAvatar"
avatarSize={44}
contentLoaderItemLength={10}
gap={0}
>
<FlatList
data={_oResults}
renderItem={this.renderNotifyItem}
keyExtractor={(_, index) => index.toString()}
scrollEnabled={this.state.isScrollEnabled}
onEndReachedThreshold={END_REACHED_THRESHOLD}
onEndReached={() => this._handleEndReached(next)}
ListFooterComponent={() => {
return (
<View>
{!!next &&
status === "success" &&
startLoadmore && (
<ViewWithLoading
isLoading={true}
contentLoader="headerAvatar"
avatarSize={44}
contentLoaderItemLength={1}
gap={0}
/>
)}
{status === "error" && (
<MessageError message={translations[msg]} />
)}
<View style={{ height: 30 }} />
</View>
);
}}
/>
<LoadingFull visible={isDeleteLoading} />
<Toast ref={c => (this._toast = c)} />
</ViewWithLoading>
);
};
render() {
const { navigation, settings, translations, auth } = this.props;
const { isLoggedIn } = auth;
const { name } = navigation.state.params;
return (
<Layout
navigation={navigation}
headerType="headerHasBack"
title={name}
goBack={() => navigation.goBack()}
renderContent={this.renderContent}
textSearch={translations.search}
isLoggedIn={isLoggedIn}
scrollViewEnabled={false}
scrollViewStyle={{
backgroundColor: "#fff"
}}
tintColor={Consts.colorDark1}
colorPrimary={Consts.colorGray2}
statusBarStyle="dark-content"
/>
);
}
}
const mapStateToProps = state => ({
myNotifications: state.myNotifications,
settings: state.settings,
translations: state.translations,
auth: state.auth,
deleteMyNotificationError: state.deleteMyNotificationError
});
const mapDispatchToProps = {
getMyNotifications,
deleteMyNotifications,
getMyNotificationsLoadmore
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(NotificationsScreen);
<file_sep>import React from "react";
import { TouchableOpacity, Text } from "react-native";
import { Feather } from "@expo/vector-icons";
import * as Consts from "../../constants/styleConstants";
import { withNavigationFocus, FlatListRedux } from "../../wiloke-elements";
import {
ListingsContainer,
LocationModalPickerContainer,
NearbyContainer
} from "../smarts";
import { Layout } from "../dumbs";
import { connect } from "react-redux";
const Listing = props => {
const { navigation, isFocused, settings } = props;
const { state } = navigation;
const nextRoute = navigation.dangerouslyGetParent().state;
const postType = state.params ? state.params.key : nextRoute.key;
return (
<Layout
navigation={navigation}
headerType="headerHasFilter"
renderLeft={() => <NearbyContainer postType={postType} />}
renderCenter={() => (
<LocationModalPickerContainer
postType={postType}
isFocused={isFocused}
/>
)}
renderRight={() => (
<TouchableOpacity
activeOpacity={0.5}
onPress={() => navigation.navigate("SearchScreen")}
style={{ width: 25, alignItems: "flex-end" }}
>
<Feather name="search" size={20} color="#fff" />
</TouchableOpacity>
)}
renderContent={() => <ListingsContainer navigation={navigation} />}
// renderContent={() => {
// return (
// <FlatListRedux
// componentDidMount={() => {
// this.props.getListings();
// }}
// onEndReached={params => {
// this.props.getListingLoadmore(params)
// }}
// data={["test", "sdfsdf"]}
// keyExtractor={(item, index) => index.toString()}
// renderItem={({ item, index }) => {
// return <Text>{item}</Text>;
// }}
// />
// );
// }}
scrollViewEnabled={false}
scrollViewStyle={{
backgroundColor: Consts.colorGray2
}}
colorPrimary={settings.colorPrimary}
/>
);
};
const mapStateToProps = state => ({
settings: state.settings
});
export default connect(mapStateToProps)(withNavigationFocus(Listing));
<file_sep>import { GET_SETTINGS } from "../constants/actionTypes";
import axios from "axios";
export const getSettings = _ => dispatch => {
return axios
.get("general-settings")
.then(res => {
dispatch({
type: GET_SETTINGS,
payload: res.data
});
})
.catch(err => console.log(err));
};
<file_sep>import React from "react";
import { StyleSheet, View } from "react-native";
import { Constants } from "expo";
export default (MyComponent = () => {
<View>
<View style={styles.statusBar} />
</View>;
});
const styles = StyleSheet.create({
statusBar: {
backgroundColor: "#fff",
height: Constants.statusBarHeight
}
});
<file_sep>import React, { Component } from "react";
import { View } from "react-native";
import { connect } from "react-redux";
import he from "he";
import {
changeListingDetailNavigation,
getListingListFeature,
getListingBoxCustom,
getScrollTo
} from "../../actions";
import {
isEmpty,
Row,
Col,
IconTextMedium,
ViewWithLoading,
ContentBox,
RequestTimeoutWrapped
} from "../../wiloke-elements";
import { ButtonFooterContentBox } from "../dumbs";
import * as Consts from "../../constants/styleConstants";
class ListingListFeatureContainer extends Component {
state = {
isLoading: true
};
async _getListingFeature() {
try {
const {
params,
getListingListFeature,
getListingBoxCustom,
type
} = this.props;
const { id, item, max } = params;
type === null &&
(await (item.key === "tags"
? getListingListFeature(id, item.key, max)
: getListingBoxCustom(id, item.key, max)));
this.setState({ isLoading: false });
} catch (err) {
console.log(err);
}
}
componentDidMount() {
this._getListingFeature();
}
renderContent = (id, item, isLoading, listFeature, type) => {
const {
isListingDetailListRequestTimeout,
translations,
settings
} = this.props;
return (
<ViewWithLoading isLoading={isLoading} contentLoader="contentHeader">
{!isEmpty(listFeature) && (
<ContentBox
headerTitle={item.name}
headerIcon="list"
style={{ marginBottom: type !== "all" ? 10 : 50 }}
renderFooter={
item.status &&
item.status === "yes" &&
this.renderFooterContentBox(id, item.key)
}
colorPrimary={settings.colorPrimary}
>
<RequestTimeoutWrapped
isTimeout={isListingDetailListRequestTimeout}
onPress={this._getListingFeature}
text={translations.networkError}
buttonText={translations.retry}
>
<Row gap={15}>
{listFeature.map((item, index) => (
<Col key={index.toString()} column={2} gap={15}>
<IconTextMedium
iconName={item.oIcon.icon}
iconSize={30}
text={he.decode(item.name)}
texNumberOfLines={1}
iconBackgroundColor={
item.oIcon.color && item.oIcon.color !== ""
? item.oIcon.color
: Consts.colorGray2
}
iconColor={
item.oIcon.color && item.oIcon.color !== ""
? "#fff"
: Consts.colorDark2
}
/>
</Col>
))}
</Row>
</RequestTimeoutWrapped>
</ContentBox>
)}
</ViewWithLoading>
);
};
renderFooterContentBox = (listingId, key) => {
const {
translations,
changeListingDetailNavigation,
getListingListFeature,
getScrollTo
} = this.props;
return (
<ButtonFooterContentBox
text={translations.viewAll.toUpperCase()}
onPress={() => {
changeListingDetailNavigation(key);
getListingListFeature(listingId, key, null);
getScrollTo(0);
}}
/>
);
};
render() {
const {
listingListFeature,
listingListFeatureAll,
loadingListingDetail,
listingCustomBox,
type,
params
} = this.props;
const { id, item } = params;
const { isLoading } = this.state;
return type === "all"
? this.renderContent(
id,
item,
loadingListingDetail,
item.key === "tags"
? listingListFeatureAll
: listingCustomBox[item.key],
"all"
)
: this.renderContent(
id,
item,
isLoading,
item.key === "tags" ? listingListFeature : listingCustomBox[item.key]
);
}
}
const mapStateToProps = state => ({
listingListFeature: state.listingListFeature,
listingListFeatureAll: state.listingListFeatureAll,
loadingListingDetail: state.loadingListingDetail,
translations: state.translations,
isListingDetailListRequestTimeout: state.isListingDetailListRequestTimeout,
settings: state.settings,
listingCustomBox: state.listingCustomBox
});
const mapDispatchToProps = {
changeListingDetailNavigation,
getListingListFeature,
getListingBoxCustom,
getScrollTo
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ListingListFeatureContainer);
<file_sep>import * as types from "../constants/actionTypes";
export const eventDiscussionLatest = (state = { oResults: [] }, action) => {
switch (action.type) {
case types.GET_EVENT_DISCUSSION_LATEST:
return action.payload;
default:
return state;
}
};
export const eventDiscussion = (state = { oResults: [] }, action) => {
switch (action.type) {
case types.GET_EVENT_DISCUSSION:
return action.payload;
case types.GET_EVENT_DISCUSSION_LOADMORE:
return {
...state,
next: action.payload.next,
oResults: [...state.oResults, ...action.payload.oResults]
};
default:
return state;
}
};
export const commentInDiscussionEvent = (state = { oResults: [] }, action) => {
switch (action.type) {
case types.GET_COMMENT_DISCUSSION_EVENT:
return action.payload;
default:
return state;
}
};
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import {
Text,
View,
Dimensions,
LayoutAnimation,
UIManager,
ViewPropTypes,
Keyboard,
ScrollView,
Platform,
StyleSheet,
StatusBar,
TouchableOpacity,
ActivityIndicator,
FlatList
} from "react-native";
import { bottomBarHeight } from "../../functions/bottomBarHeight";
import InputHasButton from "../atoms/InputHasButton";
import { emoij } from "../../functions/emoij";
import * as Consts from "../../../constants/styleConstants";
import { Permissions, Location, IntentLauncherAndroid, MapView } from "expo";
import { Entypo } from "@expo/vector-icons";
/**
* Constants
*/
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get("window");
const IOS = Platform.OS === "ios";
/**
* Create Component InputAccessoryLayoutFullScreen
*/
export default class InputAccessoryLayoutFullScreen extends Component {
/**
* Prop Types
*/
static propTypes = {
renderHeader: PropTypes.func,
renderContent: PropTypes.func.isRequired,
textInputProps: PropTypes.shape({
...InputHasButton.propTypes
}),
textInputEnabled: PropTypes.bool,
style: ViewPropTypes.style,
keyboardDismissMode: PropTypes.oneOf(["none", "on-drag"]),
contentScrollViewEnabled: PropTypes.bool,
statusBarStyle: PropTypes.string,
onDragMapEnd: PropTypes.func,
onEmoijSeleted: PropTypes.func,
onOpenMapView: PropTypes.func,
translations: PropTypes.object,
groupButtonItemColorActive: PropTypes.string,
groupActionEnabled: PropTypes.bool
};
/**
* Default Props
*/
static defaultProps = {
renderHeader: __ => {},
onDragMapEnd: __ => {},
onEmoijSeleted: __ => {},
onOpenMapView: __ => {},
contentScrollViewEnabled: true,
statusBarStyle: "dark-content",
textInputEnabled: true,
groupActionEnabled: false
};
/**
* Constructor
*/
constructor(props) {
super(props);
this.state = {
isKeyboardOpened: false,
keyboardHeight: 0,
keyboardHeightPermanent: 0,
headerHeight: 0,
inputHeight: 0,
contentHeight: 1,
layoutHeight: 0,
targetContentOffsetY: 0,
groupButtonActive: false,
groupButtonCurrentIndex: null,
coordinate: {
latitude: 41.032234,
longitude: 29.031939
}
};
if (IOS) {
this.keyboardWillShowListener = Keyboard.addListener(
"keyboardWillShow",
this._keyboardShow
);
this.keyboardWillHideListener = Keyboard.addListener(
"keyboardWillHide",
this._keyboardHide
);
} else {
UIManager.setLayoutAnimationEnabledExperimental &&
UIManager.setLayoutAnimationEnabledExperimental(true);
}
}
/**
* Keyboard Listener For Android
*/
componentDidMount() {
if (!IOS) {
this.keyboardDidShowListener = Keyboard.addListener(
"keyboardDidShow",
this._keyboardShow
);
this.keyboardDidHideListener = Keyboard.addListener(
"keyboardDidHide",
this._keyboardHide
);
}
}
/**
* Configure for LayoutAnimation
* @param {*event KeyBoard} event
*/
_configureLayoutAnimation = event => {
return LayoutAnimation.configureNext({
duration: IOS ? event.duration : 300,
create: {
type: IOS
? LayoutAnimation.Types.keyboard
: LayoutAnimation.Types.easeInEaseOut,
property: LayoutAnimation.Properties.opacity
},
update: {
type: IOS
? LayoutAnimation.Types.keyboard
: LayoutAnimation.Types.easeInEaseOut
}
});
};
_getButtomKeyBoardIphoneX = number => {
return bottomBarHeight === 0 ? 0 : bottomBarHeight + number;
};
/**
* Event Keyboard Show
* @param {*event KeyBoard} event
*/
_keyboardShow = event => {
const { contentHeight, layoutHeight, targetContentOffsetY } = this.state;
const isBottom =
Math.floor(contentHeight - layoutHeight) ===
Math.floor(targetContentOffsetY);
const keyboardHeight =
(IOS ? event.startCoordinates.height : event.endCoordinates.height) +
this._getButtomKeyBoardIphoneX(35);
this._configureLayoutAnimation(event);
this.setState(
{
keyboardHeight,
keyboardHeightPermanent: keyboardHeight,
isKeyboardOpened: true
},
() => {
isBottom &&
setTimeout(() => this._scrollView.scrollToEnd({ animated: true }), 0);
}
);
};
/**
* Event Keyboard Hide
* @param {*event KeyBoard} event
*/
_keyboardHide = event => {
const { keyboardHeight, groupButtonActive } = this.state;
if (!groupButtonActive) {
this._configureLayoutAnimation(event);
this.setState({
keyboardHeight: this._getButtomKeyBoardIphoneX(0),
isKeyboardOpened: false
});
}
};
/**
* Get header height
* @param {*event Header component} event
*/
_getHeaderHeight = event => {
this.setState({ headerHeight: event.nativeEvent.layout.height });
};
/**
* Get input wrapper height
* @param {*event Input wrapper} event
*/
_getInputHeight = event => {
this.setState({ inputHeight: event.nativeEvent.layout.height });
};
/**
* Get contentHeight, layoutHeight, targetContentOffsetY
* @param {*event ScrollView Component} event
*/
_handleScrollEndDrag = event => {
const { nativeEvent } = event;
this.setState({
contentHeight: nativeEvent.contentSize.height,
layoutHeight: nativeEvent.layoutMeasurement.height,
targetContentOffsetY: IOS
? nativeEvent.targetContentOffset.y
: nativeEvent.contentOffset.y
});
};
/**
* Remove KeyBoard Listener
*/
componentWillUnmount() {
if (IOS) {
this.keyboardWillShowListener.remove();
this.keyboardWillHideListener.remove();
} else {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
}
/**
* Update Scroll (ScrollView Component)
* @param {*Previous props} prevProps
* @param {*Previous state} prevState
* @param {*} snapshot
*/
componentDidUpdate(prevProps, prevState, snapshot) {
const {
contentHeight,
layoutHeight,
targetContentOffsetY,
inputHeight
} = this.state;
const isBottom =
Math.floor(contentHeight - layoutHeight) ===
Math.floor(targetContentOffsetY);
const isIncrementInputHeight = prevState.inputHeight < inputHeight;
if (isBottom && isIncrementInputHeight) {
setTimeout(() => this._scrollView.scrollToEnd({ animated: false }), 0);
}
}
// get location
_getLocationAsync = async index => {
try {
const { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status === "granted") {
const location = await Location.getCurrentPositionAsync({
enableHighAccuracy: true
});
const { latitude, longitude } = location.coords;
await this.setState({
coordinate: { longitude, latitude }
});
this.setState({
groupButtonCurrentIndex: index
});
this.props.onOpenMapView({ latitude, longitude });
} else {
throw new Error("Location permission not granted");
}
} catch (err) {
const { translations } = this.props;
this.setState({
isMapView: true
});
Platform === "android"
? IntentLauncherAndroid.startActivityAsync(
IntentLauncherAndroid.ACTION_LOCATION_SOURCE_SETTINGS
)
: Alert.alert(
he.decode(translations.askForAllowAccessingLocationTitle),
he.decode(translations.askForAllowAccessingLocationDesc),
[
{
text: "Cancel",
style: "cancel"
},
{
text: "OK",
onPress: () => Linking.openURL("app-settings:")
}
],
{ cancelable: false }
);
}
};
/**
* Render Header
*/
renderHeader() {
return (
<View
style={styles.header}
renderToHardwareTextureAndroid={true}
onLayout={this._getHeaderHeight}
>
{this.props.renderHeader()}
</View>
);
}
/**
* Render Content
*/
renderContent() {
const { keyboardHeight, inputHeight, headerHeight } = this.state;
const {
keyboardDismissMode,
renderContent,
contentScrollViewEnabled
} = this.props;
return (
<View style={styles.content}>
{contentScrollViewEnabled ? (
<ScrollView
ref={ref => (this._scrollView = ref)}
keyboardDismissMode={keyboardDismissMode}
keyboardShouldPersistTaps="always"
onScrollEndDrag={this._handleScrollEndDrag}
renderToHardwareTextureAndroid={true}
scrollEnabled={true}
style={[
styles.content,
{
height:
SCREEN_HEIGHT - inputHeight - headerHeight - keyboardHeight
}
]}
>
{renderContent()}
</ScrollView>
) : (
<View
style={[
styles.content,
{
height:
SCREEN_HEIGHT - inputHeight - headerHeight - keyboardHeight
}
]}
>
{renderContent()}
</View>
)}
</View>
);
}
_handleButtonItem = index => async () => {
const { keyboardHeightPermanent } = this.state;
Keyboard.dismiss();
this.setState({
groupButtonActive: true,
keyboardHeight: keyboardHeightPermanent
});
if (index === 0) {
await this._getLocationAsync(index);
} else if (index === 1) {
this.setState({
groupButtonCurrentIndex: index
});
}
};
_renderGroupButtonItem = ({ item, index }) => {
const { groupButtonCurrentIndex } = this.state;
const { groupButtonItemColorActive } = this.props;
return (
<TouchableOpacity onPress={this._handleButtonItem(index)}>
<Entypo
name={item}
size={18}
color={
groupButtonCurrentIndex === index
? groupButtonItemColorActive
: Consts.colorDark3
}
/>
</TouchableOpacity>
);
};
/**
* Render Input Accessory
*/
renderInputAccessory() {
const { keyboardHeight } = this.state;
const { textInputProps } = this.props;
return (
<View
style={[
styles.input,
{
bottom: keyboardHeight
}
]}
renderToHardwareTextureAndroid={true}
onLayout={this._getInputHeight}
>
<InputHasButton
{...textInputProps}
groupButtonData={["location", "emoji-happy"]}
onFocus={() => {
this.setState({
groupButtonActive: false,
groupButtonCurrentIndex: null
});
}}
renderGroupButtonItem={this._renderGroupButtonItem}
/>
</View>
);
}
_handleMapDragEnd = event => {
const { coordinate } = event.nativeEvent;
this.setState({ coordinate });
this.props.onDragMapEnd(coordinate);
};
_handleEmoijPress = item => () => {
this.props.onEmoijSeleted(item);
};
_renderEmoijItem = ({ item, index }) => {
return (
<View style={styles.emoijWrap}>
<View style={{ paddingTop: "100%" }} />
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleEmoijPress(item)}
style={styles.emoij}
>
<Text style={{ fontSize: 50 }}>{item}</Text>
</TouchableOpacity>
</View>
);
};
_checkRenderGroupContent = () => {
const { coordinate, groupButtonCurrentIndex, keyboardHeight } = this.state;
const { longitude, latitude } = coordinate;
switch (groupButtonCurrentIndex) {
case 0:
return (
<MapView
style={{
width: "100%",
height: "100%"
}}
initialRegion={{
latitude,
longitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}}
>
<MapView.Marker
draggable
onDragEnd={this._handleMapDragEnd}
coordinate={{
latitude,
longitude
}}
/>
</MapView>
);
case 1:
return (
<View
style={{
width: "100%",
height: "100%"
}}
>
<FlatList
data={emoij}
keyExtractor={(item, index) => index.toString()}
renderItem={this._renderEmoijItem}
numColumns={6}
/>
<View />
</View>
);
default:
return (
keyboardHeight !== bottomBarHeight && (
<ActivityIndicator size="small" color={Consts.colorDark3} />
)
);
}
};
renderGroupContent = () => {
const { keyboardHeight } = this.state;
return (
<View
style={{
position: "absolute",
left: 0,
bottom: 0,
width: "100%",
height: keyboardHeight,
justifyContent: "center",
alignItems: "center"
}}
>
{this._checkRenderGroupContent()}
</View>
);
};
/**
* Render Component
*/
render() {
const { textInputEnabled, groupActionEnabled } = this.props;
return (
<View style={[styles.container, this.props.style]}>
<StatusBar barStyle={this.props.statusBarStyle} />
{this.renderHeader()}
{this.renderContent()}
{textInputEnabled && this.renderInputAccessory()}
{groupActionEnabled && this.renderGroupContent()}
</View>
);
}
}
/**
* Style for component
*/
const styles = StyleSheet.create({
container: {
position: "relative",
zIndex: 99999,
height: SCREEN_HEIGHT,
backgroundColor: Consts.colorGray3
},
header: {
position: "relative",
zIndex: 9
},
content: {
position: "relative"
},
input: {
position: "absolute",
left: 0,
right: 0,
zIndex: 9
},
emoijWrap: {
position: "relative",
width: `${100 / 6}%`,
justifyContent: "center",
alignItems: "center"
},
emoij: {
position: "absolute",
margin: "auto",
width: "100%",
height: "100%",
top: 0,
left: 0,
justifyContent: "center",
alignItems: "center"
}
});
<file_sep>import * as types from "../constants/actionTypes";
import axios from "axios";
export const getEventDetail = eventId => dispatch => {
return axios
.get(`event-detail/${eventId}`)
.then(res => {
dispatch({
type: types.GET_EVENT_DETAIL,
payload: res.data.oResults
});
})
.catch(err => console.log(err.message));
};
<file_sep>import React, { Component, Fragment } from "react";
import PropTypes from "prop-types";
import { View, Platform, FlatList, StyleSheet, Dimensions } from "react-native";
import _ from "lodash";
import he from "he";
import { connect } from "react-redux";
import { getListings, getListingsLoadmore } from "../../actions";
import ListingItem from "../dumbs/ListingItem";
import {
MessageError,
RequestTimeoutWrapped,
ViewWithLoading,
ContentLoader,
Row,
Col,
bottomBarHeight
} from "../../wiloke-elements";
const RADIUS = 10;
const END_REACHED_THRESHOLD = Platform.OS === "ios" ? 0 : 1;
const { with: SCREEN_WIDTH } = Dimensions.get("window");
class ListingsContainer extends Component {
static defaultProps = {
horizontal: false
};
static propTypes = {
horizontal: PropTypes.bool
};
state = {
refreshing: false,
startLoadmore: false,
postType: null
};
_getId = postType => {
const { categoryList, locationList } = this.props;
const getId = arr => arr.filter(item => item.selected)[0].id;
const categoryId =
typeof categoryList[postType] !== "undefined" &&
categoryList[postType].length > 0 &&
getId(categoryList[postType]) !== "wilokeListingCategory"
? getId(categoryList[postType])
: null;
const locationId =
typeof locationList[postType] !== "undefined" &&
locationList[postType].length > 0 &&
getId(locationList[postType]) !== "wilokeListingLocation"
? getId(locationList[postType])
: null;
return { categoryId, locationId };
};
_getListing = async () => {
try {
const { locations, getListings, navigation, nearByFocus } = this.props;
const { coords } = locations.location;
const nearby = {
lat: coords.latitude,
lng: coords.longitude,
unit: "km",
radius: RADIUS
};
const { state } = navigation;
const nextRoute = navigation.dangerouslyGetParent().state;
const postType = state.params ? state.params.key : nextRoute.key;
const { categoryId, locationId } = this._getId(postType);
await this.setState({ postType });
await getListings(
categoryId,
locationId,
postType,
nearByFocus ? nearBy : {}
);
this.setState({ startLoadmore: true });
} catch (err) {
console.log(err);
}
};
componentDidMount() {
this._getListing();
}
_handleRefresh = async () => {
try {
this.setState({ refreshing: true });
await this._getListing();
this.setState({ refreshing: false });
} catch (err) {
console.log(err);
}
};
_handleEndReached = next => {
const { locations, getListingsLoadmore, nearByFocus } = this.props;
const { coords } = locations.location;
const nearby = {
lat: coords.latitude,
lng: coords.longitude,
unit: "km",
radius: RADIUS
};
const { postType } = this.state;
const { startLoadmore } = this.state;
const { categoryId, locationId } = this._getId(postType);
startLoadmore &&
next !== false &&
getListingsLoadmore(
next,
categoryId,
locationId,
postType,
nearByFocus ? nearby : {}
);
};
renderItem = ({ item }) => {
const { navigation, settings } = this.props;
return (
<ListingItem
image={item.oFeaturedImg.medium}
title={he.decode(item.postTitle)}
tagline={item.tagLine ? he.decode(item.tagLine) : null}
logo={item.logo !== "" ? item.logo : item.oFeaturedImg.thumbnail}
location={he.decode(item.oAddress.address)}
reviewMode={item.oReview.mode}
reviewAverage={item.oReview.average}
businessStatus={item.businessStatus}
colorPrimary={settings.colorPrimary}
onPress={() =>
navigation.navigate("ListingDetailScreen", {
id: item.ID,
name: he.decode(item.postTitle),
tagline: !!item.tagLine ? he.decode(item.tagLine) : null,
link: item.postLink,
author: item.oAuthor,
image:
SCREEN_WIDTH > 420
? item.oFeaturedImg.large
: item.oFeaturedImg.medium,
logo: item.logo !== "" ? item.logo : item.oFeaturedImg.thumbnail
})
}
layout={this.props.horizontal ? "horizontal" : "vertical"}
/>
);
};
_getWithLoadingProps = loading => ({
isLoading: loading,
contentLoader: "content",
contentHeight: 90,
contentLoaderItemLength: 6,
featureRatioWithPadding: "56.25%",
column: 2,
gap: 10,
containerPadding: 10
});
renderContentSuccess(listings) {
const { startLoadmore } = this.state;
return (
<FlatList
data={listings.oResults}
renderItem={this.renderItem}
keyExtractor={(item, index) => item.ID.toString() + index.toString()}
numColumns={this.props.horizontal ? 1 : 2}
horizontal={this.props.horizontal}
showsHorizontalScrollIndicator={false}
onEndReachedThreshold={END_REACHED_THRESHOLD}
onEndReached={() => this._handleEndReached(listings.next)}
ListFooterComponent={() =>
startLoadmore && listings.next !== false ? (
<View style={{ padding: 5 }}>
<Row gap={10}>
{Array(2)
.fill(null)
.map((_, index) => (
<Col key={index.toString()} column={2} gap={10}>
<ContentLoader
featureRatioWithPadding="56.25%"
contentHeight={90}
content={true}
/>
</Col>
))}
</Row>
</View>
) : (
<View style={{ paddingBottom: 20 + bottomBarHeight }} />
)
}
style={{ padding: 5 }}
/>
);
}
renderContentError(listings) {
return listings && <MessageError message={listings.msg} />;
}
render() {
const {
listings,
isListingRequestTimeout,
loading,
translations
} = this.props;
const { postType } = this.state;
const condition =
!_.isEmpty(listings[postType]) && listings[postType].status === "success";
return (
<ViewWithLoading {...this._getWithLoadingProps(loading)}>
<RequestTimeoutWrapped
isTimeout={isListingRequestTimeout && _.isEmpty(listings[postType])}
onPress={this._getListing}
fullScreen={true}
style={styles.container}
text={translations.networkError}
buttonText={translations.retry}
>
{condition
? this.renderContentSuccess(listings[postType])
: this.renderContentError(listings[postType])}
</RequestTimeoutWrapped>
</ViewWithLoading>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "row"
}
});
const mapStateToProps = state => ({
listings: state.listings,
loading: state.loading,
locationList: state.locationList,
categoryList: state.categoryList,
isListingRequestTimeout: state.isListingRequestTimeout,
nearByFocus: state.nearByFocus,
locations: state.locations,
translations: state.translations,
settings: state.settings
});
const mapDispatchToProps = {
getListings,
getListingsLoadmore
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ListingsContainer);
<file_sep>import {
GET_NOTIFICATION_SETTING,
SET_NOTIFICATION_SETTING,
GET_NOTIFICATION_ADMIN_SETTING
} from "../constants/actionTypes";
export const notificationSettings = (state = {}, action) => {
switch (action.type) {
case GET_NOTIFICATION_SETTING:
case SET_NOTIFICATION_SETTING:
return { ...state, ...action.payload };
default:
return state;
}
};
export const notificationAdminSettings = (state = [], action) => {
switch (action.type) {
case GET_NOTIFICATION_ADMIN_SETTING:
return action.payload;
default:
return state;
}
};
<file_sep>export const getSocialColor = social => {
switch (social) {
case "facebook":
return "#325d94";
case "twitter":
return "#00aadb";
case "flickr":
return "#ff0084";
case "tumblr":
return "#2f4e6b";
case "dribbble":
return "#fb4087";
case "youtube-play":
case "youtube":
return "#df2e1c";
case "vk":
return "#4c75a3";
case "digg":
return "#1b5891";
case "reddit":
return "#ff4500";
case "medium":
return "#00ab6c";
case "tripadvisor":
return "#00af87";
case "wikipedia-w":
return "#636466";
case "skype":
return "#00aff0";
case "linkedin":
return "#1686b0";
case "whatsapp":
return "#25d366";
case "stumbleupon":
return "#eb4924";
case "google-plus":
return "#db4437";
case "vimeo-square":
case "vimeo":
return "#63b3e4";
case "instagram":
return "#517fa4";
case "pinterest":
return "#cc1d24";
case "behance":
return "#1478ff";
case "heart":
return "#4bd1fa";
case "github":
return "#24292e";
case "envelope":
return "#5540f7";
case "link":
return "#f06292";
case "odnoklassniki":
return "#ee8208";
default:
return "#222";
}
};
<file_sep>export const mapObjectToFormData = object =>
Object.keys(object).reduce((formData, key) => {
formData.append(key, JSON.stringify(object[key]));
return formData;
}, new FormData());
<file_sep>import React from "react";
import PropTypes from "prop-types";
import { View, Text, StyleSheet } from "react-native";
import { Feather } from "@expo/vector-icons";
import * as Consts from "../../constants/styleConstants";
import he from "he";
const PriceRange = props => {
const { data } = props;
return (
<View style={styles.container}>
<Text style={{ color: props.colorPrimary, fontSize: 26 }}>
{data.minPrice + he.decode(data.currencySymbol)}
</Text>
<Feather name="arrow-right" size={20} color={props.colorPrimary} />
<Text style={{ color: props.colorPrimary, fontSize: 26 }}>
{data.maxPrice + he.decode(data.currencySymbol)}
</Text>
</View>
);
};
PriceRange.propTypes = {
data: PropTypes.object,
colorPrimary: PropTypes.string
};
PriceRange.defaultProps = {
colorPrimary: Consts.colorPrimary
};
const styles = StyleSheet.create({
container: {
flexDirection: "row",
alignItems: "center"
}
});
export default PriceRange;
<file_sep>import * as types from "../constants/actionTypes";
export const eventSearchResults = (state = {}, action) => {
switch (action.type) {
case types.GET_EVENT_SEARCH_RESULTS:
return action.payload;
case types.GET_EVENT_SEARCH_RESULTS_LOADMORE:
return {
...state,
next: action.payload.next,
oResults: [...state.oResults, ...action.payload.oResults]
};
default:
return state;
}
};
<file_sep>import {
GET_COUNT_MESSAGES,
GET_COUNT_NOTIFICATIONS,
GET_COUNT_NOTIFICATIONS_REALTIMEFAKER
} from "../constants/actionTypes";
import axios from "axios";
export const getCountNotifications = _ => dispatch => {
return axios
.get("count-new-notifications")
.then(({ data }) => {
if (data.status === "success") {
dispatch({
type: GET_COUNT_NOTIFICATIONS,
payload: data.msg
});
}
})
.catch(err => console.log(err));
};
export const getCountNotificationsRealTimeFaker = _ => dispatch => {
return axios
.get("count-new-notifications")
.then(({ data }) => {
if (data.status === "success") {
dispatch({
type: GET_COUNT_NOTIFICATIONS_REALTIMEFAKER,
payload: data.msg
});
}
})
.catch(err => console.log(err));
};
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { View, StyleSheet, TouchableOpacity, Dimensions } from "react-native";
import { Input } from "../../wiloke-elements";
import { Feather } from "@expo/vector-icons";
import * as Consts from "../../constants/styleConstants";
/**
* Constants
*/
const ICON_SIZE = 34;
const { width: SCREEN_WIDTH } = Dimensions.get("window");
/**
* Start PureComponent
*/
export default class InputHasButton extends PureComponent {
/**
* PropTypes
*/
static propTypes = {
iconName: PropTypes.string,
colorPrimary: PropTypes.string,
onChangeText: PropTypes.func,
onPressText: PropTypes.func
};
/**
* Default Props
*/
static defaultProps = {
iconName: "arrow-up",
colorPrimary: Consts.colorPrimary,
onChangeText: _ => {},
onPressText: _ => {}
};
state = {
text: ""
};
_handleChangeText = text => {
this.setState({ text });
this.props.onChangeText(text);
};
_handlePress = event => {
const { text } = this.state;
this.props.onPressText(text, event);
this.setState({ text: "" });
};
/**
* Render
*/
render() {
return (
<View style={styles.container}>
<Input
{...this.props}
placeholderTextColor={Consts.colorDark4}
styleWrapper={styles.input}
value={this.state.text}
onChangeText={this._handleChangeText}
/>
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handlePress}
style={[
styles.iconWrap,
{
backgroundColor: this.props.colorPrimary
}
]}
>
<Feather name={this.props.iconName} size={20} color="#fff" />
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
position: "relative",
padding: 8,
borderTopWidth: 1,
borderTopColor: Consts.colorGray1,
backgroundColor: Consts.colorGray3,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center"
},
input: {
borderRadius: 26,
width: SCREEN_WIDTH - 60
},
iconWrap: {
width: ICON_SIZE,
height: ICON_SIZE,
borderRadius: ICON_SIZE / 2,
justifyContent: "center",
alignItems: "center"
}
});
<file_sep>// import React, { Component } from "react";
// import PropTypes from "prop-types";
// import {
// View,
// Dimensions,
// FlatList,
// Modal,
// TouchableOpacity,
// StatusBar,
// Animated,
// PanResponder,
// Text,
// Image,
// StyleSheet
// } from "react-native";
// import { Constants } from "expo";
// const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get("window");
// const ANIMATION_MAX = 100;
// const ANIMATION_DURATION = 200;
// const SWIPE_THRESHOLD = 120;
// const ANIMATED = {
// duration: ANIMATION_DURATION,
// userNativeDriver: true
// };
// export default class NewGallery extends Component {
// static propTypes = {
// gridColumn: PropTypes.number,
// gridGap: PropTypes.number,
// onClose: PropTypes.func,
// onOpen: PropTypes.func,
// onShow: PropTypes.func
// };
// static defaultProps = {
// gridColumn: 3,
// gridGap: 10,
// onClose: () => {},
// onOpen: () => {},
// onShow: () => {}
// };
// constructor(props) {
// super(props);
// this.state = {
// modalVisible: false,
// sliderVisible: false,
// sliderDrag: false,
// imageAnimationLoading: true,
// currentIndex: -1,
// measure: {},
// getSizeCurrentImage: null,
// position: new Animated.ValueXY(),
// animation: new Animated.Value(0)
// };
// this._panResponder = PanResponder.create({
// onStartShouldSetPanResponder: (evt, gestureState) => true,
// onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
// onMoveShouldSetPanResponder: (evt, gestureState) => true,
// onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
// // onPanResponderMove: this._onPanResponderMove,
// onPanResponderTerminationRequest: (evt, gestureState) => false
// // onPanResponderRelease: this._onPanResponderRelease
// });
// }
// _onPanResponderMove = (event, gestureState) => {
// const { position, sliderDrag } = this.state;
// const { dx, dy } = gestureState;
// position.setValue({
// x: 0,
// y: sliderDrag ? 0 : dy
// });
// };
// _onPanResponderRelease = (event, gestureState) => {
// const { position, sliderDrag } = this.state;
// const { dx, dy } = gestureState;
// if (!sliderDrag) {
// if (dy > SWIPE_THRESHOLD) {
// this._onCloseLightBox();
// } else if (dy < -SWIPE_THRESHOLD) {
// this._onCloseLightBox();
// } else {
// this._resetPosition();
// }
// }
// };
// _resetPosition = () => {
// const { position } = this.state;
// Animated.timing(position, {
// ...ANIMATED,
// toValue: {
// x: 0,
// y: 0
// }
// }).start(() => {
// position.setValue({
// x: 0,
// y: 0
// });
// });
// };
// _openLightBox = index => {
// const { lightBoxImages } = this.props;
// setTimeout(() => {
// this[`_gridItem_${index}`].measure((fx, fy, width, height, px, py) => {
// this.setState({
// modalVisible: true,
// currentIndex: index,
// measure: { width, height, px, py }
// });
// });
// Image.getSize(lightBoxImages[index].src, (width, height) => {
// this.setState({
// getSizeCurrentImage: { width, height }
// });
// });
// }, 0);
// StatusBar.setHidden(true, "fade");
// this.props.onOpen();
// };
// _sliderHidden = () => {
// this.setState({
// sliderVisible: false
// });
// };
// _sliderVisible = () => {
// this.setState({
// sliderVisible: true
// });
// };
// _onShowLightBox = () => {
// const { currentIndex, animation } = this.state;
// Animated.timing(animation, {
// ...ANIMATED,
// toValue: ANIMATION_MAX
// }).start(() => {
// this._lightBoxSlider.scrollToIndex({
// animated: false,
// index: currentIndex
// });
// this.setState({
// sliderVisible: true
// });
// });
// this.props.onShow();
// };
// _onCloseLightBox = () => {
// const { animation, position } = this.state;
// StatusBar.setHidden(false, "fade");
// this.setState(
// {
// sliderVisible: false
// },
// () => {
// Animated.timing(animation, {
// ...ANIMATED,
// toValue: 0
// }).start(() => {
// this.setState({
// currentIndex: -1,
// modalVisible: false
// });
// position.setValue({
// x: 0,
// y: 0
// });
// });
// }
// );
// this.props.onClose();
// };
// _setAnimatedMove = () => {
// const { animation, measure, getSizeCurrentImage } = this.state;
// const WIDTH = animation.interpolate({
// inputRange: [0, ANIMATION_MAX],
// outputRange: [measure.width, SCREEN_WIDTH],
// extrapolate: "clamp"
// });
// const HEIGHT = animation.interpolate({
// inputRange: [0, ANIMATION_MAX],
// outputRange: [
// measure.height,
// getSizeCurrentImage.height * SCREEN_WIDTH / getSizeCurrentImage.width
// ],
// extrapolate: "clamp"
// });
// const TRANSLATE_X = animation.interpolate({
// inputRange: [0, ANIMATION_MAX],
// outputRange: [measure.px, 0],
// extrapolate: "clamp"
// });
// const TRANSLATE_Y = animation.interpolate({
// inputRange: [0, ANIMATION_MAX],
// outputRange: [
// measure.py,
// this.state.position.y._value +
// (SCREEN_HEIGHT -
// getSizeCurrentImage.height *
// SCREEN_WIDTH /
// getSizeCurrentImage.width) /
// 2
// ],
// extrapolate: "clamp"
// });
// return {
// width: WIDTH,
// height: HEIGHT,
// transform: [
// {
// translateX: TRANSLATE_X
// },
// {
// translateY: TRANSLATE_Y
// }
// ]
// };
// };
// renderGridItem = ({ item, index }) => {
// const { gridGap } = this.props;
// const { currentIndex } = this.state;
// return (
// <TouchableOpacity
// activeOpacity={1}
// onPress={() => this._openLightBox(index)}
// style={styles.grid}
// >
// <View
// style={{
// position: "relative",
// opacity: index !== currentIndex ? 1 : 0
// }}
// >
// <Image
// ref={ref => (this[`_gridItem_${index}`] = ref)}
// source={{ uri: item.src }}
// resizeMode="cover"
// style={{
// position: "absolute",
// top: gridGap / 2,
// right: gridGap / 2,
// bottom: gridGap / 2,
// left: gridGap / 2,
// zIndex: 9
// }}
// />
// <View style={styles.setItemHeight} />
// </View>
// </TouchableOpacity>
// );
// };
// renderGrid() {
// const { thumbnailImages, gridColumn, gridGap } = this.props;
// return (
// <FlatList
// data={thumbnailImages}
// renderItem={this.renderGridItem}
// keyExtractor={(item, index) => index.toString()}
// numColumns={gridColumn}
// horizontal={false}
// showsHorizontalScrollIndicator={false}
// showsVerticalScrollIndicator={false}
// style={{
// margin: -gridGap / 2
// }}
// />
// );
// }
// renderLightBoxSliderItem = ({ item, index }) => {
// const { position } = this.state;
// return (
// <Animated.View
// style={{
// width: SCREEN_WIDTH,
// height: SCREEN_HEIGHT
// // transform: [...position.getTranslateTransform()]
// }}
// {...this._panResponder.panHandlers}
// >
// <Image
// source={{ uri: item.src }}
// resizeMode="contain"
// style={{
// width: "100%",
// height: "100%"
// }}
// />
// </Animated.View>
// );
// };
// renderLightBoxSlider() {
// const { lightBoxImages } = this.props;
// const { getSizeCurrentImage, sliderVisible } = this.state;
// if (getSizeCurrentImage !== null) {
// return (
// <FlatList
// ref={ref => (this._lightBoxSlider = ref)}
// onScrollToIndexFailed={() => {}}
// data={lightBoxImages}
// renderItem={this.renderLightBoxSliderItem}
// keyExtractor={(item, index) => index.toString()}
// horizontal={true}
// showsHorizontalScrollIndicator={false}
// pagingEnabled={true}
// style={{ opacity: sliderVisible ? 1 : 0 }}
// scrollEnabled={true}
// onScrollBeginDrag={event => {
// this.setState({
// sliderDrag: true
// });
// }}
// onScrollEndDrag={() => {
// this.setState({
// sliderDrag: false
// });
// }}
// />
// );
// }
// }
// renderLightBoxUnderlay() {
// const { animation, modalVisible, position, sliderVisible } = this.state;
// const OPACITY_SLIDER_VISIBLE = position.y.interpolate({
// inputRange: [-SCREEN_HEIGHT / 2, 0, SCREEN_HEIGHT / 2],
// outputRange: [0, 1, 0],
// extrapolate: "clamp"
// });
// const OPACITY_SLIDER_HIDDEN = animation.interpolate({
// inputRange: [0, ANIMATION_MAX],
// outputRange: [0, 1],
// extrapolate: "clamp"
// });
// return (
// <Animated.View
// style={[
// styles.underlay,
// {
// opacity: sliderVisible
// ? OPACITY_SLIDER_VISIBLE
// : OPACITY_SLIDER_HIDDEN
// }
// ]}
// />
// );
// }
// renderImageAnimation() {
// const { lightBoxImages } = this.props;
// const { currentIndex, getSizeCurrentImage, sliderVisible } = this.state;
// return (
// currentIndex !== -1 &&
// getSizeCurrentImage !== null && (
// <View
// style={{
// position: "absolute",
// top: 0,
// left: 0,
// zIndex: -1,
// width: SCREEN_WIDTH,
// height: SCREEN_HEIGHT,
// opacity: sliderVisible ? 0 : 1
// }}
// >
// <Animated.Image
// source={{ uri: lightBoxImages[currentIndex].src }}
// resizeMode="cover"
// onLoadStart={this._onLoadStartImageAnim}
// onLoadEnd={this._onLoadEndImageAnim}
// onLoad={this._onLoadImageAnim}
// style={this._setAnimatedMove()}
// />
// </View>
// )
// );
// }
// renderLightBox() {
// const { modalVisible } = this.state;
// return (
// <Modal
// animationType="none"
// transparent={true}
// visible={modalVisible}
// style={styles.modal}
// onShow={this._onShowLightBox}
// onRequestClose={this._onCloseLightBox}
// >
// <View style={styles.modalHeader}>
// <TouchableOpacity activeOpacity={0.6} onPress={this._onCloseLightBox}>
// <Text style={{ color: "red" }}>Close</Text>
// </TouchableOpacity>
// </View>
// {this.renderImageAnimation()}
// {this.renderLightBoxSlider()}
// {this.renderLightBoxUnderlay()}
// </Modal>
// );
// }
// render() {
// const { style } = this.props;
// return (
// <View style={styles.container} style={style}>
// {this.renderGrid()}
// {this.renderLightBox()}
// </View>
// );
// }
// }
// const styles = StyleSheet.create({
// container: {
// flex: 1,
// flexDirection: "row",
// flexWrap: "wrap"
// },
// grid: {
// flex: 1,
// position: "relative"
// },
// setItemHeight: {
// paddingTop: "100%"
// },
// modal: {
// position: "relative",
// zIndex: 9
// },
// underlay: {
// position: "absolute",
// top: 0,
// right: 0,
// bottom: 0,
// left: 0,
// zIndex: -5,
// backgroundColor: "#000"
// },
// modalHeader: {
// position: "absolute",
// top: 0,
// left: 0,
// height: 40,
// paddingHorizontal: 10,
// alignItems: "center",
// zIndex: 10
// }
// });
import React, { Component } from "react";
import { PropTypes } from "prop-types";
import {
View,
Text,
TouchableOpacity,
Modal,
StyleSheet,
StatusBar,
Dimensions,
ActivityIndicator,
Image
} from "react-native";
import { ImageCover, Row, Col, filterMax } from "../../";
import Swiper from "react-native-swiper";
import * as Consts from "../../../constants/styleConstants";
import { Feather } from "@expo/vector-icons";
import _ from "lodash";
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get("window");
const Slide = props => {
return (
<View style={styles.slide}>
<Image
onLoad={props.loadHandle.bind(null, props.i)}
resizeMode="contain"
style={styles.image}
source={{ uri: props.uri }}
/>
{!props.loaded && (
<View style={styles.loadingView}>
<ActivityIndicator size="small" />
</View>
)}
</View>
);
};
export default class NewGallery extends Component {
static propTypes = {
gap: PropTypes.number,
column: PropTypes.number,
thumbnailMax: PropTypes.oneOfType([PropTypes.number, PropTypes.bool]),
thumbnails: PropTypes.array,
modalSlider: PropTypes.array,
underlayColor: PropTypes.string,
colorPrimary: PropTypes.string
};
static defaultProps = {
gap: 5,
column: 3,
thumbnails: [],
modalSlider: [],
underlayColor: "#000",
thumbnailMax: 0,
colorPrimary: Consts.colorPrimary
};
state = {
modalVisible: false,
currentIndex: 0,
thumbnails: [],
modalSlider: [],
loadSwiper: false,
loadQueue: [0, 0, 0, 0]
};
componentDidMount() {
const { modalSlider, thumbnails } = this.props;
this.setState({ modalSlider, thumbnails });
}
componentDidUpdate(prevProps, prevState) {
const { modalSlider, thumbnails } = this.props;
if (!_.isEqual(prevProps.modalSlider, modalSlider)) {
this.setState({ modalSlider });
}
if (!_.isEqual(prevProps.thumbnails, thumbnails)) {
this.setState({ thumbnails });
}
}
// componentWillUnmount() {
// this.setState({ modalSlider: [], thumbnails: [] });
// }
loadHandle = i => {
let loadQueue = this.state.loadQueue;
loadQueue[i] = 1;
this.setState({
loadQueue
});
};
_handleOpenModal = index => {
this.setState({
modalVisible: true,
currentIndex: index
});
StatusBar.setHidden(true, "fade");
};
_handleShowModal = () => {
this.setState({ loadSwiper: true });
};
_handleCloseModal = () => {
this.setState({
modalVisible: false,
loadSwiper: false
});
StatusBar.setHidden(false, "fade");
};
renderGallery = () => {
const { gap, column, thumbnailMax } = this.props;
const { thumbnails } = this.state;
const _thumbnails =
thumbnailMax > 0 ? filterMax(thumbnails)(thumbnailMax) : thumbnails;
return thumbnails.length > 0 ? (
<Row gap={gap}>
{_thumbnails.map((item, index) => (
<Col key={index.toString()} column={column} gap={gap}>
<TouchableOpacity
activeOpacity={0.5}
onPress={() => this._handleOpenModal(index)}
style={{
position: "relative",
width: "100%",
backgroundColor: Consts.colorGray2
}}
>
<View style={{ paddingTop: "100%" }} />
<View style={styles.abs}>
<ImageCover src={item} />
{thumbnails.length > _thumbnails.length &&
_thumbnails.length - 1 === index && (
<View
style={[
styles.abs,
{
backgroundColor: "rgba(0,0,0,0.5)",
justifyContent: "center",
alignItems: "center"
}
]}
>
<Text
style={{
color: "#fff",
fontSize: 30,
fontWeight: "500"
}}
>{`+${thumbnails.length}`}</Text>
</View>
)}
</View>
</TouchableOpacity>
</Col>
))}
</Row>
) : (
<Row gap={gap}>
{Array(3)
.fill(null)
.map((_, index) => (
<Col key={index.toString()} column={column} gap={gap}>
<View
style={{
position: "relative",
width: "100%",
backgroundColor: Consts.colorGray2
}}
>
<View style={{ paddingTop: "100%" }} />
</View>
</Col>
))}
</Row>
);
};
renderItemSlider = (item, index) => (
<View
key={index.toString()}
style={{
width: SCREEN_WIDTH,
height: SCREEN_HEIGHT
}}
>
<Image
source={{ uri: item }}
resizeMode="contain"
style={{ width: "100%", height: "100%" }}
onLoad={props.loadHandle.bind(null, props.i)}
/>
</View>
);
renderSlider = () => {
const { currentIndex, modalSlider, loadSwiper } = this.state;
return (
loadSwiper && (
<Swiper
loadMinimal
loadMinimalSize={1}
loop={false}
showsButtons={false}
dotColor="rgba(255,255,255,0.2)"
activeDotColor={this.props.colorPrimary}
index={currentIndex}
>
{modalSlider.length > 0 &&
modalSlider.map((item, i) => (
<Slide
loadHandle={this.loadHandle}
loaded={!!this.state.loadQueue[i]}
uri={item}
i={i}
key={i}
/>
))}
</Swiper>
)
);
};
renderUnderlay = () => (
<View
style={[
styles.abs,
{ zIndex: -1, backgroundColor: this.props.underlayColor }
]}
/>
);
renderHeader = () => (
<View style={styles.modalHeader}>
<TouchableOpacity activeOpacity={0.6} onPress={this._handleCloseModal}>
<Feather name="x" size={24} color="#fff" />
</TouchableOpacity>
</View>
);
renderModal = () => {
const { modalVisible } = this.state;
return (
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
style={styles.modal}
onShow={this._handleShowModal}
onRequestClose={this._handleCloseModal}
>
{this.renderHeader()}
{this.renderSlider()}
{this.renderUnderlay()}
</Modal>
);
};
render() {
const { currentIndex, modalSlider } = this.state;
return (
<View>
{this.renderGallery()}
{this.renderModal()}
</View>
);
}
}
const styles = StyleSheet.create({
modal: {
position: "relative",
zIndex: 999
},
modalHeader: {
position: "absolute",
top: 0,
right: 0,
height: 50,
paddingHorizontal: 10,
justifyContent: "center",
zIndex: 10
},
abs: {
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: 9
},
slide: {
flex: 1,
justifyContent: "center",
backgroundColor: "transparent"
},
image: {
width: SCREEN_WIDTH,
flex: 1,
backgroundColor: "transparent"
},
loadingView: {
position: "absolute",
justifyContent: "center",
alignItems: "center",
left: 0,
right: 0,
top: 0,
bottom: 0,
backgroundColor: "rgba(0,0,0,.5)"
}
});
<file_sep>export const isEmpty = prop =>
prop === null ||
prop === undefined ||
(prop.hasOwnProperty("length") && prop.length === 0) ||
(prop.constructor === Object && Object.keys(prop).length === 0);
export const filterMax = arr => max => arr.filter((item, index) => index < max);
export const zeroPad = number =>
number < 10 && number > 0 ? `0${number}` : number;
export const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
export const toDataURL = url => {
return fetch(url)
.then(response => response.blob())
.then(blob => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
});
};
<file_sep>import * as types from "../constants/actionTypes";
import axios from "axios";
export const getArticleDetail = articleId => dispatch => {
return axios
.get(`posts/${articleId}`)
.then(res => {
dispatch({
type: types.GET_ARTICLE_DETAIL,
payload: res.data.oResult
});
})
.catch(err => console.log(err.message));
};
<file_sep>import {
GET_LISTINGS,
GET_LISTINGS_LOADMORE,
GET_LISTING_NEARBY
} from "../constants/actionTypes";
export const listings = (state = {}, action) => {
switch (action.type) {
case GET_LISTINGS:
return {
...state,
...action.payload
};
case GET_LISTING_NEARBY:
return action.payload;
case GET_LISTINGS_LOADMORE:
const postType = Object.keys(action.payload)[0];
return {
...state,
[postType]: {
status: action.payload[postType].status,
next: action.payload[postType].next,
oResults: [
...state[postType].oResults,
...action.payload[postType].oResults
]
}
};
default:
return state;
}
};
<file_sep>import { GET_POST_TYPES } from "../constants/actionTypes";
import axios from "axios";
export const getPostTypes = allText => dispatch => {
return axios
.get("get-listing-types")
.then(res => {
const { data } = res;
data.status === "success" &&
dispatch({
type: GET_POST_TYPES,
payload: [
{
id: "all",
name: allText,
selected: true
},
...data.oResults.map(item => ({
id: item.key,
name: `${item.name} (${item.total})`,
selected: false
}))
]
});
})
.catch(err => console.log(err));
};
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { Text, View, TouchableOpacity, FlatList, Platform } from "react-native";
import { connect } from "react-redux";
import { getEventDiscussion, getEventDiscussionLoadmore } from "../../actions";
import { CommentReview } from "../dumbs";
import * as Consts from "../../constants/styleConstants";
import stylesBase from "../../stylesBase";
import he from "he";
import { Button, ViewWithLoading, Loader } from "../../wiloke-elements";
const END_REACHED_THRESHOLD = Platform.OS === "ios" ? 0 : 1;
class EventDiscussionContainer extends PureComponent {
static defaultProps = {
colorPrimary: Consts.colorPrimary
};
static propTypes = {
colorPrimary: PropTypes.string
};
state = {
isLoading: true
};
_getEventDiscussion = async () => {
try {
const { getEventDiscussion, id, type } = this.props;
await getEventDiscussion(id, type);
this.setState({ isLoading: false });
} catch (err) {
console.log(err);
}
};
componentDidMount() {
this._getEventDiscussion();
}
_handleEndReached = next => {
this.props.getEventDiscussionLoadmore(next);
};
_handleCommentScreen = (item, autoFocus) => () => {
const { navigation } = this.props;
navigation.navigate("EventCommentDiscussionScreen", {
item,
autoFocus
});
};
renderItem = ({ item, index }) => {
const { translations } = this.props;
return (
<CommentReview
key={index.toString()}
colorPrimary={this.props.settings.colorPrimary}
// headerActionSheet={{
// options: [
// "Cancel",
// "Remove",
// "Report review",
// "Comment",
// "Pin to Top of Review",
// "Write a review",
// "Edit review"
// ],
// title: he.decode(item.postTitle),
// message: he.decode(`${item.postContent.substr(0, 40)}...`),
// destructiveButtonIndex: 1,
// cancelButtonIndex: 0,
// onPressButtonItem: () => {
// console.log("press");
// },
// onAction: buttonIndex => {
// console.log(buttonIndex);
// if (buttonIndex === 1) {
// // code
// }
// }
// }}
headerAuthor={{
image: item.oAuthor.avatar,
title: he.decode(item.oAuthor.displayName),
text: item.postDate
}}
renderContent={() => (
<View>
<Text style={stylesBase.text}>
{he.decode(
item.postContent.length > 200
? `${item.postContent.substr(0, 200)}...`
: item.postContent
)}
</Text>
{item.postContent.length > 200 && (
<TouchableOpacity
activeOpacity={0.5}
onPress={this._handleCommentScreen(item, false)}
style={{ marginTop: 4 }}
>
<Text style={[stylesBase.text, { color: Consts.colorDark4 }]}>
{translations.seeMoreReview}
</Text>
</TouchableOpacity>
)}
<View style={{ height: 3 }} />
</View>
)}
shares={{
count: item.countShared,
text: item.countShared > 1 ? translations.shares : translations.share
}}
comments={{
count: item.countDiscussions,
isLoading: false,
text:
item.countDiscussions > 1
? translations.comments
: translations.comment
}}
likes={{
count: item.countLiked,
text: item.countLiked > 1 ? translations.likes : translations.like
}}
onComment={this._handleCommentScreen(item, true)}
style={{ marginBottom: 10 }}
/>
);
};
render() {
const {
eventDiscussion,
eventDiscussionLatest,
type,
id,
translations,
navigation
} = this.props;
const _eventDiscussion =
type === "latest" ? eventDiscussionLatest : eventDiscussion;
const data = _eventDiscussion.oResults;
const { isLoading } = this.state;
return (
<View>
<ViewWithLoading
isLoading={isLoading}
contentLoader="contentHeaderAvatar"
contentLoaderItemLength={3}
>
{data && data.length > 0 && type === "latest" && (
<View
style={{
flexDirection: "row",
alignItems: "center",
marginBottom: 10,
marginTop: 10
}}
>
<Text
style={{
color: this.props.settings.colorPrimary,
fontSize: 24,
fontWeight: "500"
}}
>
{_eventDiscussion.countDiscussions}
</Text>
<Text
style={{
color: Consts.colorDark2,
fontSize: 18,
fontWeight: "500"
}}
>
{` ${
_eventDiscussion.countDiscussions === 1
? translations.discussion
: translations.discussions
}`}
</Text>
</View>
)}
{data && data.length > 0 && (
<FlatList
data={data}
renderItem={this.renderItem}
keyExtractor={item => item.ID.toString()}
showsVerticalScrollIndicator={false}
onEndReachedThreshold={END_REACHED_THRESHOLD}
onEndReached={() =>
_eventDiscussion &&
_eventDiscussion.next !== false &&
type !== "latest"
? this._handleEndReached(_eventDiscussion.next)
: {}
}
ListFooterComponent={() =>
_eventDiscussion &&
_eventDiscussion.next !== false &&
type !== "latest" && <Loader size={30} height={80} />
}
/>
)}
{data && data.length > 2 && type === "latest" && (
<View style={{ marginBottom: 20 }}>
<Button
size="lg"
block={true}
backgroundColor="light"
color="dark"
onPress={() => {
navigation.navigate("EventDiscussionAllScreen", {
id
});
}}
>
{translations.seeMoreDiscussions}
</Button>
</View>
)}
</ViewWithLoading>
</View>
);
}
}
const mapStateToProps = state => ({
eventDiscussion: state.eventDiscussion,
eventDiscussionLatest: state.eventDiscussionLatest,
translations: state.translations,
settings: state.settings
});
export default connect(
mapStateToProps,
{
getEventDiscussion,
getEventDiscussionLoadmore
}
)(EventDiscussionContainer);
<file_sep>import React, { Component } from "react";
import {
View,
Text,
Dimensions,
TouchableOpacity,
Alert,
StyleSheet
} from "react-native";
import { Layout, ListingSmallCard, Rated } from "../dumbs";
import {
ViewWithLoading,
ModalPicker,
isCloseToBottom,
MessageError
} from "../../wiloke-elements";
import { connect } from "react-redux";
import {
getMyEvents,
getMyEventsLoadmore,
getEventStatus
} from "../../actions";
import { Feather } from "@expo/vector-icons";
import _ from "lodash";
import he from "he";
import Swipeout from "react-native-swipeout";
const { width: SCREEN_WIDTH } = Dimensions.get("window");
const ICON_WIDTH = 30;
const ICON_HEIGHT = 30;
class MyEventsScreen extends Component {
state = {
isLoading: true,
isScrollEnabled: true,
postStatus: "all",
isLoadMore: true,
isFetch: false,
startLoadmore: false
};
_getMyEvents = async ({ postStatus }) => {
const { getMyEvents } = this.props;
await getMyEvents({ postStatus });
};
async componentDidMount() {
const { getEventStatus } = this.props;
await this.setState({ isLoading: true });
await getEventStatus("Status");
await this._getMyEvents({
postStatus: "all"
});
this.setState({ isLoading: false, startLoadmore: true });
}
componentDidUpdate(prevProps) {
if (!_.isEqual(prevProps.myEvents, this.props.myEvents)) {
this.setState({
isFetch: true
});
}
}
shouldComponentUpdate(nextProps, nextState) {
if (!_.isEqual(nextProps.myEvents, this.props.myEvents)) {
return true;
}
if (!_.isEqual(nextState.isLoading, this.state.isLoading)) {
return true;
}
return false;
}
_handlePressItem = item => _ => {
const { navigation, translations } = this.props;
navigation.navigate("EventDetailScreen", {
id: item.ID,
name: he.decode(item.postTitle),
image:
SCREEN_WIDTH > 420 ? item.oFeaturedImg.large : item.oFeaturedImg.medium,
address: he.decode(item.oAddress.address),
hosted: `${translations.hostedBy} ${item.oAuthor.displayName}`,
interested: `${item.oFavorite.totalFavorites} ${item.oFavorite.text}`
});
};
renderItem = (item, index) => {
return (
<TouchableOpacity
key={index.toString()}
activeOpacity={0.6}
onPress={this._handlePressItem(item)}
>
<ListingSmallCard
image={item.oFeaturedImg.thumbnail}
image={
SCREEN_WIDTH > 420
? item.oFeaturedImg.large
: item.oFeaturedImg.medium
}
title={item.postTitle}
text={item.tagLine}
renderRate={() => {
return (
item.oReview && (
<Rated
rate={item.oReview.average}
max={item.oReview.mode}
rateStyle={{ fontSize: 13, marginRight: 2 }}
maxStyle={{ fontSize: 9 }}
style={{ marginVertical: 5 }}
/>
)
);
}}
/>
</TouchableOpacity>
);
};
renderContent = () => {
const { myEvents, myEventError, translations } = this.props;
const { oResults, next } = myEvents;
const { isLoading, isLoadMore } = this.state;
console.log(oResults);
return (
<View>
<ViewWithLoading
isLoading={isLoading}
contentLoader="headerAvatar"
avatarSquare={true}
avatarSize={60}
contentLoaderItemLength={8}
gap={0}
>
{!_.isEmpty(oResults) && oResults.map(this.renderItem)}
</ViewWithLoading>
{next && (
<ViewWithLoading
isLoading={isLoadMore}
contentLoader="headerAvatar"
avatarSquare={true}
avatarSize={60}
contentLoaderItemLength={1}
gap={0}
/>
)}
{_.isEmpty(myEvents.oResults) &&
!!myEventError && (
<MessageError message={translations[myEventError]} />
)}
<View style={{ height: 30 }} />
</View>
);
};
_renderHeaderCenter = (options, onChangeOptions) => {
const { settings } = this.props;
return (
<View style={styles.headerCenterWrapper}>
{options.length > 0 ? (
<ModalPicker
options={options}
onChangeOptions={onChangeOptions}
underlayBorder={false}
textResultStyle={{
color: "#fff",
fontSize: 12,
marginRight: 4,
width: 120
}}
textResultNumberOfLines={1}
iconResultColor="#fff"
clearSelectEnabled={false}
colorPrimary={settings.colorPrimary}
/>
) : (
<View style={{ height: 46, width: 120, justifyContent: "center" }}>
<Text style={{ color: "#fff" }}>...</Text>
</View>
)}
<View style={styles.headerCenterBorder} />
</View>
);
};
_handleChangeOptions = modify => async (options, selected) => {
await this.setState({ isLoading: true });
await this.setState({
postStatus:
modify === "postStatus" ? selected[0].id : this.state.postStatus
});
await this._getMyEvents({
postStatus: this.state.postStatus
});
this.setState({ isLoading: false, startLoadmore: true });
};
_handleLoadmore = async _ => {
const { myEvents } = this.props;
const { next } = myEvents;
const { startLoadmore } = this.state;
this.setState({
isFetch: false
});
!!next &&
startLoadmore &&
this.state.isFetch &&
(await this.props.getMyEventsLoadmore({
next,
postStatus: this.state.postStatus
}));
this.setState({
isFetch: true
});
};
render() {
const {
navigation,
settings,
translations,
auth,
eventStatus
} = this.props;
const { isLoggedIn } = auth;
return (
<Layout
navigation={navigation}
headerType="headerHasFilter"
renderCenter={() => (
<View style={{ flexDirection: "row" }}>
{this._renderHeaderCenter(
eventStatus,
this._handleChangeOptions("postStatus")
)}
</View>
)}
renderLeft={() => (
<TouchableOpacity
activeOpacity={0.8}
onPress={() => navigation.goBack()}
>
<View
style={[
styles.icon,
{
alignItems: "flex-start"
}
]}
>
<Feather name="chevron-left" size={26} color="#fff" />
</View>
</TouchableOpacity>
)}
renderRight={() => (
<TouchableOpacity
activeOpacity={0.5}
onPress={() => navigation.navigate("SearchScreen")}
>
<Feather name="search" size={20} color="#fff" />
</TouchableOpacity>
)}
renderContent={this.renderContent}
colorPrimary={settings.colorPrimary}
textSearch={translations.search}
isLoggedIn={isLoggedIn}
scrollEnabled={this.state.isScrollEnabled}
scrollEventThrottle={16}
onMomentumScrollEnd={({ nativeEvent }) => {
isCloseToBottom(nativeEvent) && this._handleLoadmore();
}}
/>
);
}
}
const styles = StyleSheet.create({
headerCenterWrapper: {
position: "relative",
paddingLeft: 8,
paddingRight: 5,
zIndex: 9
},
headerCenterBorder: {
position: "absolute",
left: 0,
right: 0,
top: 12,
bottom: 12,
borderWidth: 1,
borderColor: "#fff",
opacity: 0.8,
borderRadius: 5,
zIndex: -1
},
container: {
flexDirection: "row"
},
lineVertical: {
position: "absolute",
top: 12,
bottom: 12,
left: 0,
width: 1,
backgroundColor: "#fff"
},
icon: {
width: ICON_WIDTH,
height: ICON_HEIGHT,
justifyContent: "center",
alignItems: "center"
}
});
const mapStateToProps = state => ({
myEvents: state.myEvents,
settings: state.settings,
translations: state.translations,
auth: state.auth,
myEventError: state.myEventError,
eventStatus: state.eventStatus
});
const mapDispatchToProps = {
getMyEvents,
getMyEventsLoadmore,
getEventStatus
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(MyEventsScreen);
<file_sep>import {
GET_CATEGORY_LIST,
CHANGE_CATEGORY_LIST,
RESET_SELECTED_CATEGORY_LIST
} from "../constants/actionTypes";
export const categoryList = (state = {}, action) => {
switch (action.type) {
case GET_CATEGORY_LIST:
return {
...state,
...action.payload
};
case CHANGE_CATEGORY_LIST:
return {
...state,
...action.payload
};
case RESET_SELECTED_CATEGORY_LIST:
return state.map((item, index) => {
return { ...item, selected: index === 0 ? true : false };
});
default:
return state;
}
};
<file_sep>import * as types from "../constants/actionTypes";
export const getScrollTo = scrollTo => dispatch => {
dispatch({
type: types.SCROLL_TO,
scrollTo
});
};
<file_sep>import React from "react";
import PropTypes from "prop-types";
import {
View,
Text,
TouchableOpacity,
StyleSheet,
ViewPropTypes
} from "react-native";
import { Feather } from "@expo/vector-icons";
import * as Consts from "../../../constants/styleConstants";
import stylesBase from "../../../stylesBase";
import { FontIcon } from "../../";
const ListItemTouchable = props => {
return (
<View style={[styles.container, props.style]}>
<TouchableOpacity activeOpacity={0.5} onPress={props.onPress}>
<View style={styles.inner}>
<View style={{ flexDirection: "row", alignItems: "center" }}>
<View
style={[
styles.iconWrapper,
{
width: props.iconSize,
height: props.iconSize,
borderRadius: props.iconSize / 2,
backgroundColor: props.iconBackgroundColor
}
]}
>
<FontIcon
name={props.iconName}
size={props.iconSize * (18 / 36)}
color={props.iconColor}
/>
</View>
<View style={{ width: 10 }} />
<Text style={[stylesBase.text, styles.text]}>{props.text}</Text>
</View>
<Feather
style={styles.icon}
name="chevron-right"
size={22}
color={Consts.colorDark4}
/>
</View>
</TouchableOpacity>
</View>
);
};
ListItemTouchable.propTypes = {
text: PropTypes.string,
iconName: PropTypes.string,
iconBackgroundColor: PropTypes.string,
iconColor: PropTypes.string,
iconSize: PropTypes.number,
onPress: PropTypes.func,
style: ViewPropTypes.style
};
ListItemTouchable.defaultProps = {
iconName: "check",
iconSize: 36,
iconColor: Consts.colorDark2,
iconBackgroundColor: Consts.colorGray2
};
const styles = StyleSheet.create({
container: {
borderBottomWidth: 1,
borderBottomColor: Consts.colorGray1,
backgroundColor: "#fff",
paddingVertical: 12,
paddingHorizontal: 10
},
inner: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center"
},
text: {
color: Consts.colorDark2,
fontSize: 14
},
iconWrapper: {
justifyContent: "center",
alignItems: "center"
}
});
export default ListItemTouchable;
<file_sep>import * as types from "../constants/actionTypes";
import axios from "axios";
import _ from "lodash";
const POSTS_PER_PAGE = 12;
export const getEvents = (
categoryId,
locationId,
postType,
nearBy
) => dispatch => {
dispatch({
type: types.LOADING,
loading: true
});
dispatch({
type: types.EVENT_REQUEST_TIMEOUT,
isTimeout: false
});
const params = _.pickBy(
{
page: 1,
postsPerPage: POSTS_PER_PAGE,
postType: postType === "all" ? "" : postType,
listing_cat: categoryId !== "wilokeListingCategory" ? categoryId : null,
listing_location:
locationId !== "wilokeListingLocation" ? locationId : null,
...nearBy
},
_.identity
);
return axios
.get("events", {
params
})
.then(res => {
dispatch({
type: types.GET_EVENTS,
payload: res.data
});
dispatch({
type: types.LOADING,
loading:
(res.data.oResults && res.data.oResults.length > 0) ||
res.data.status === "error"
? false
: true
});
dispatch({
type: types.EVENT_REQUEST_TIMEOUT,
isTimeout: false
});
})
.catch(err => {
dispatch({
type: types.LOADING,
loading: false
});
dispatch({
type: types.EVENT_REQUEST_TIMEOUT,
isTimeout: true
});
console.log(err.message);
});
};
export const getEventsLoadmore = (
next,
categoryId,
locationId,
postType,
nearBy
) => dispatch => {
const params = _.pickBy(
{
page: next,
postsPerPage: POSTS_PER_PAGE,
postType: postType === "all" ? "" : postType,
listing_cat: categoryId !== "wilokeListingCategory" ? categoryId : null,
listing_location:
locationId !== "wilokeListingLocation" ? locationId : null,
...nearBy
},
_.identity
);
return axios
.get(`events`, {
params
})
.then(res => {
dispatch({
type: types.GET_EVENTS_LOADMORE,
payload: res.data
});
})
.catch(err => console.log(err.message));
};
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { View, ViewPropTypes } from "react-native";
import { FontIcon, P } from "../../";
import * as Consts from "../../../constants/styleConstants";
export class AlertError extends PureComponent {
static propTypes = {
style: ViewPropTypes.style,
text: PropTypes.string
};
render() {
const { style, text } = this.props;
return (
<View style={[{ flexDirection: "row" }, style]}>
<View style={{ marginRight: 10 }}>
<FontIcon
name="alert-triangle"
size={16}
color={Consts.colorQuaternary}
/>
</View>
<P style={{ color: Consts.colorQuaternary }}>{text}</P>
</View>
);
}
}
<file_sep>import { createStackNavigator } from "react-navigation";
import stackOpts from "./stackOpts";
import * as Consts from "../constants/styleConstants";
import MenuScreen from "../components/screens/MenuScreen";
import EventScreen from "../components/screens/EventScreen";
import ListingScreen from "../components/screens/ListingScreen";
import BlogScreen from "../components/screens/ArticleScreen";
import PageScreen from "../components/screens/PageScreen";
import HomeScreen from "../components/screens/HomeScreen";
const menuStack = createStackNavigator(
{
MenuScreen: {
screen: MenuScreen
// navigationOptions: {
// title: "Wilcity",
// headerStyle: {
// backgroundColor: Consts.colorDark
// },
// headerTintColor: Consts.colorPrimary,
// headerTitleStyle: {
// fontWeight: "400",
// fontSize: 14
// }
// }
// navigationOptions: ({ navigation }) => ({
// header: false
// })
},
MenuHomeScreen: {
screen: HomeScreen
},
MenuEventScreen: {
screen: EventScreen
},
MenuListingScreen: {
screen: ListingScreen
},
MenuBlogScreen: {
screen: BlogScreen
},
MenuPageScreen: {
screen: PageScreen
}
},
stackOpts
);
export default menuStack;
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import {
View,
TouchableOpacity,
WebView,
Animated,
ImageBackground,
StyleSheet,
ViewPropTypes
} from "react-native";
import { Feather } from "@expo/vector-icons";
import stylesBase from "../../../stylesBase";
export default class Video extends PureComponent {
static propTypes = {
ratio: PropTypes.number,
source: PropTypes.string.isRequired,
style: ViewPropTypes.style,
thumbnail: PropTypes.string
};
static defaultProps = {
ratio: (9 / 16) * 100
};
state = {
width: 0,
opacity: new Animated.Value(1)
};
_handlePress = () => {
Animated.timing(this.state.opacity, {
toValue: 0,
duration: 400,
useNativeDriver: true
}).start();
};
_onLayout = event => {
const { width } = event.nativeEvent.layout;
this.setState({ width });
};
_handleSource = () => {
const { source } = this.props;
let _source = "";
const isYoutube =
source.search(/(w{3}\.|http(s|):\/\/.*)youtu(\.|)be/g) !== -1;
const isVimeo = source.search(/.*vimeo\.com\//g) !== -1;
if (isYoutube) {
_source = `https://www.youtube.com/embed/${source.replace(
/.*youtu(\.|)be.*(\/|watch\?v=|embed\/)/g,
""
)}?rel=0&showinfo=0&modestbranding=1`;
} else if (isVimeo) {
_source = `https://player.vimeo.com/video/${source.replace(
/.*vimeo\.com\/(video\/|)/g,
""
)}`;
}
return _source;
};
renderHtmlContent = () => {
const htmlStyles = {
wrapper: `
position: relative,
padding-top: ${this.props.ratio}%
`,
iframe: `
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
`
};
const htmlContent = `
<div style="${htmlStyles.wrapper}">
<iframe
style="${htmlStyles.iframe}"
src="${this._handleSource()}"
frameborder="0"
allow="autoplay; encrypted-media"
allowfullscreen
></iframe>
</div>
`;
return htmlContent;
};
render() {
const { width, opacity } = this.state;
const sizePlayButton = width / 4 < 60 ? width / 4 : 60;
return (
<View
onLayout={this._onLayout}
style={[styles.container, this.props.style]}
>
<TouchableOpacity
style={styles.container}
activeOpacity={1}
onPress={this._handlePress}
>
<WebView
source={{ html: this.renderHtmlContent() }}
scrollEnabled={false}
style={[{ paddingTop: `${this.props.ratio}%`, width }]}
/>
<Animated.View
style={[styles.placeholder, stylesBase.absFull, { opacity }]}
pointerEvents="none"
>
<ImageBackground
source={{ uri: this.props.thumbnail }}
style={styles.imageBg}
>
<View
style={[
styles.iconWrap,
{
width: sizePlayButton,
height: sizePlayButton,
borderRadius: sizePlayButton / 2,
backgroundColor: "rgba(255, 255, 255, 0.25)"
}
]}
>
<Feather name="play" size={sizePlayButton / 2} color="#fff" />
</View>
<View style={[styles.overlay, stylesBase.absFull]} />
</ImageBackground>
</Animated.View>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
position: "relative",
width: "100%"
},
placeholder: {
zIndex: 9
},
imageBg: {
justifyContent: "center",
alignItems: "center",
width: "100%",
height: "100%"
},
overlay: {
zIndex: -1,
backgroundColor: "#000",
opacity: 0.5
},
iconWrap: {
position: "relative",
zIndex: 9,
justifyContent: "center",
alignItems: "center"
}
});
<file_sep>import {
GET_MY_NOTIFICATIONS,
GET_MY_NOTIFICATIONS_LOADMORE,
GET_MY_NOTIFICATION_ERROR,
DELETE_MY_NOTIFICATION
} from "../constants/actionTypes";
import axios from "axios";
const POSTS_PER_PAGE = 14;
export const getMyNotifications = _ => dispatch => {
return axios
.get("get-my-notifications", {
params: {
postsPerPage: POSTS_PER_PAGE
}
})
.then(({ data }) => {
console.log(data);
if (data.status === "success") {
dispatch({
type: GET_MY_NOTIFICATIONS,
payload: data
});
} else if (data.status === "error") {
dispatch({
type: GET_MY_NOTIFICATION_ERROR,
messageError: data.msg
});
}
})
.catch(err => console.log(err));
};
export const getMyNotificationsLoadmore = next => async dispatch => {
return axios
.get("get-my-notifications", {
params: {
page: next,
postsPerPage: POSTS_PER_PAGE
}
})
.then(({ data }) => {
data.status === "success" &&
dispatch({
type: GET_MY_NOTIFICATIONS_LOADMORE,
payload: data
});
})
.catch(err => console.log(err));
};
export const deleteMyNotifications = id => dispatch => {
return axios
.delete(`delete-my-notification/${id}`)
.then(({ data }) => {
if (data.status === "success") {
dispatch({
type: DELETE_MY_NOTIFICATION,
id
});
} else if (data.status === "error") {
dispatch({
type: DELETE_MY_NOTIFICATION_ERROR,
message: data.msg
});
}
})
.catch(err => console.log(err));
};
<file_sep>import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import {
Text,
View,
StyleSheet,
ActivityIndicator,
TouchableOpacity,
Modal,
Image
} from "react-native";
import { ImagePicker, Permissions } from "expo";
import * as Consts from "../../../constants/styleConstants";
import { FontIcon } from "../../../wiloke-elements";
export default class ImageUpload extends PureComponent {
static propTypes = {
label: PropTypes.string,
text: PropTypes.string,
imageSize: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
onChange: PropTypes.func,
defaultUri: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
aspect: PropTypes.array,
uploadPhotoText: PropTypes.string,
takeAPhotoText: PropTypes.string,
cancelText: PropTypes.string
};
static defaultProps = {
label: "Image Upload",
text: "Click to upload image",
imageSize: 38,
onChange: () => {},
defaultUri: null,
aspect: [1, 1],
uploadPhotoText: "Upload photo from Library",
takeAPhotoText: "Take a Photo"
};
constructor(props) {
super(props);
this.state = {
image: this.props.defaultUri,
isModalVisible: false
};
}
_handleOpenModal = () => {
this.setState({
isModalVisible: true
});
};
_handleCloseModal = () => {
this.setState({
isModalVisible: false
});
};
_handleCameraRoll = async () => {
try {
const { status: cameraRollPermission } = await Permissions.askAsync(
Permissions.CAMERA_ROLL
);
if (cameraRollPermission === "granted") {
const result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: this.props.aspect,
base64: true
});
if (!result.cancelled) {
await this.setState({ image: result.uri });
this.state.image &&
this.setState({
isModalVisible: false
});
this.state.image && this.props.onChange(result);
}
}
} catch (err) {
console.log(err);
}
};
_handleCamera = async () => {
try {
const { status: cameraPermission } = await Permissions.askAsync(
Permissions.CAMERA
);
const { status: cameraRollPermission } = await Permissions.askAsync(
Permissions.CAMERA_ROLL
);
if (
cameraPermission === "granted" &&
cameraRollPermission === "granted"
) {
const result = await ImagePicker.launchCameraAsync({
allowsEditing: true,
aspect: this.props.aspect,
base64: true
});
if (!result.cancelled) {
this.setState({ image: result.uri });
this.state.image &&
this.setState({
isModalVisible: false
});
this.state.image && this.props.onChange(result);
}
}
} catch (err) {
console.log(err);
}
};
_renderModal = () => {
const { uploadPhotoText, takeAPhotoText, cancelText } = this.props;
return (
<Modal
animationType="slide"
transparent={true}
visible={this.state.isModalVisible}
onRequestClose={this._handleCloseModal}
>
<View style={styles.modalWrapInner}>
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleCameraRoll}
style={[
styles.button,
{
backgroundColor: Consts.colorSecondary
}
]}
>
<View style={styles.buttonIcon}>
<FontIcon name="fa fa-image" color="#fff" fontSize={18} />
</View>
<Text style={styles.buttonText}>{uploadPhotoText}</Text>
</TouchableOpacity>
<TouchableOpacity
activeOpacity={0.6}
onPress={this._handleCamera}
style={[
styles.button,
{
backgroundColor: Consts.colorSecondary
}
]}
>
<View style={styles.buttonIcon}>
<FontIcon name="fa fa-camera" color="#fff" fontSize={18} />
</View>
<Text style={styles.buttonText}>{takeAPhotoText}</Text>
</TouchableOpacity>
<TouchableOpacity
activeOpacity={0.6}
style={styles.button}
onPress={this._handleCloseModal}
>
<Text style={[styles.buttonText, { color: "#f00" }]}>
{cancelText}
</Text>
</TouchableOpacity>
</View>
</Modal>
);
};
render() {
const { label, text, imageSize } = this.props;
const { image } = this.state;
return (
<View>
<TouchableOpacity
style={styles.container}
activeOpacity={0.8}
onPress={this._handleOpenModal}
>
<View>
<Text style={styles.label}>{label}</Text>
<View style={{ height: 6 }} />
<Text style={styles.text}>{text}</Text>
</View>
{image ? (
<Image
source={{ uri: image }}
style={{
width: imageSize,
height: imageSize,
borderRadius: imageSize / 2
}}
indicator={ActivityIndicator}
/>
) : (
<View
style={{
width: imageSize,
height: imageSize,
borderRadius: imageSize / 2,
backgroundColor: Consts.colorGray2,
justifyContent: "center",
alignItems: "center"
}}
>
<FontIcon name="plus" size={18} color={Consts.colorDark3} />
</View>
)}
</TouchableOpacity>
{this._renderModal()}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingTop: 4,
paddingBottom: 5,
borderBottomWidth: 2,
borderBottomColor: Consts.colorGray1
},
modalWrapInner: {
flex: 1,
flexDirection: "column",
justifyContent: "flex-end",
backgroundColor: "rgba(0, 0, 0, 0.7)",
padding: 10
},
button: {
backgroundColor: "#fff",
paddingVertical: 10,
height: 46,
borderRadius: 8,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
marginBottom: 10
},
buttonIcon: {
width: 30,
height: 30,
borderRadius: 15,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
backgroundColor: "rgba(255, 255, 255, 0.2)",
marginRight: 10
},
buttonText: {
color: "#fff",
fontSize: 14
},
label: {
color: Consts.colorDark3,
fontSize: 12
},
text: {
color: Consts.colorDark2,
fontSize: 14
}
});
<file_sep>import React, { PureComponent } from "react";
import { Text, View, Dimensions } from "react-native";
import { ReviewForm, Layout } from "../dumbs";
import { connect } from "react-redux";
import { colorGray2, colorDark1 } from "../../constants/styleConstants";
import {
Button,
bottomBarHeight,
toDataURL,
Loader
} from "../../wiloke-elements";
import { Constants } from "expo";
import { submitReview, getReviewFields } from "../../actions";
import { ImageManipulator, FileSystem } from "expo";
import _ from "lodash";
const { height: SCREEN_HEIGHT } = Dimensions.get("window");
const HEADER_HEIGHT = 52 + Constants.statusBarHeight;
const CONTENT_HEIGHT = SCREEN_HEIGHT - HEADER_HEIGHT - 50 - bottomBarHeight;
class ReviewFormScreen extends PureComponent {
state = {
isScrollEnabled: true,
isSubmitLoading: false,
formResults: {},
isLoading: true
};
componentDidMount() {
const { navigation } = this.props;
const { params } = navigation.state;
this.props.getReviewFields(params.id);
this.setState({ isLoading: false });
}
_handleRangeSliderBeginChangeValue = () => {
this.setState({
isScrollEnabled: false
});
};
_handleSubmitReview = async () => {
try {
this.setState({ isSubmitLoading: true });
const { formResults } = this.state;
console.log(formResults);
const { gallery } = formResults;
if (!gallery) {
this.props.submitReview(formResults);
this.setState({ isSubmitLoading: false });
return;
}
const galleryPromise = gallery.map(uri => {
return ImageManipulator.manipulate(uri, [{ resize: { width: 1000 } }], {
base64: false
});
});
const newGalleryUri = await Promise.all(galleryPromise);
const newGallery = newGalleryUri.map(item => ({
uri: item.uri,
name: item.uri.replace(/^.*\//g, ""),
type: `image/${item.uri.replace(/^.*\./g, "")}`
}));
// const galleryUriBase64 = galleryBase64.map(
// item => `data:image/jpeg;base64,${item.base64}`
// );
const newFormResults = { ...formResults, gallery: newGallery };
this.setState({ isSubmitLoading: false });
this.props.submitReview(newFormResults);
} catch (err) {
console.log(err);
}
};
renderAfterContent = () => (
<Button
size="lg"
block={true}
backgroundColor="secondary"
style={{
paddingVertical: 0,
height: 50,
justifyContent: "center"
}}
isLoading={this.state.isSubmitLoading}
onPress={this._handleSubmitReview}
>
{"Review"}
</Button>
);
renderContent = () => {
const { settings, translations, navigation, reviewFields } = this.props;
const { params } = navigation.state;
const { isLoading } = this.state;
if (isLoading)
return (
<View style={{ height: 200 }}>
<Loader size="small" />
</View>
);
return (
!_.isEmpty(reviewFields) && (
<ReviewForm
data={reviewFields}
style={{ padding: 10 }}
onRangeSliderBeginChangeValue={
this._handleRangeSliderBeginChangeValue
}
settings={settings}
translations={translations}
mode={params.mode}
onResults={results => {
this.setState({
formResults: results
});
}}
/>
)
);
};
render() {
const { navigation, translations, auth } = this.props;
const { isLoggedIn } = auth;
return (
<Layout
navigation={navigation}
headerType="headerHasBack"
title={translations.yourReview}
goBack={() => navigation.goBack()}
renderContent={this.renderContent}
renderAfterContent={this.renderAfterContent}
isLoggedIn={isLoggedIn}
scrollViewStyle={{
backgroundColor: "#fff"
}}
tintColor={colorDark1}
colorPrimary={colorGray2}
statusBarStyle="dark-content"
scrollEnabled={this.state.isScrollEnabled}
contentHeight={CONTENT_HEIGHT}
/>
);
}
}
const mapStateFromProps = state => ({
translations: state.translations,
settings: state.settings,
auth: state.auth,
reviewFields: state.reviewFields
});
const mapDispatchFromProps = {
submitReview,
getReviewFields
};
export default connect(
mapStateFromProps,
mapDispatchFromProps
)(ReviewFormScreen);
<file_sep>import React, { Component, Fragment } from "react";
import PropTypes from "prop-types";
import {
View,
StyleSheet,
Animated,
Dimensions,
ActivityIndicator,
ViewPropTypes
} from "react-native";
import { Constants } from "expo";
import ImageProgress from "react-native-image-progress";
/**
* Constants
*/
const { height: SCREEN_HEIGHT } = Dimensions.get("window");
const STATUS_BAR_HEIGHT = Constants.statusBarHeight;
const SCROLL_EVENT_THROTTLE = 16;
const HEADER_MIN_HEIGHT = 52 + STATUS_BAR_HEIGHT;
/**
* Component
*/
export default class ParallaxScreen extends Component {
/**
* propTypes
*/
static propTypes = {
renderContent: PropTypes.func.isRequired,
renderHeaderLeft: PropTypes.func,
renderHeaderCenter: PropTypes.func,
renderHeaderRight: PropTypes.func,
renderAfterImage: PropTypes.func,
renderInsideImage: PropTypes.func,
onGetScrollYAnimation: PropTypes.func,
onScrollEndDrag: PropTypes.func,
headerImageSource: PropTypes.string,
overlayColor: PropTypes.string,
overlayRange: PropTypes.arrayOf(PropTypes.number),
containerStyle: ViewPropTypes.style,
afterImageMarginTop: PropTypes.number,
scrollViewRef: PropTypes.func,
headerMaxHeight: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
};
/**
* defaultProps
*/
static defaultProps = {
renderContent: () => {},
renderHeaderLeft: () => {},
renderHeaderCenter: () => {},
renderHeaderRight: () => {},
renderInsideImage: () => {},
onGetScrollYAnimation: () => {},
scrollViewRef: () => {},
onScrollEndDrag: () => {},
overlayRange: [0.3, 0.8],
overlayColor: "#000",
afterImageMarginTop: 0,
headerMaxHeight: SCREEN_HEIGHT / 2.5
};
/**
* State
*/
state = {
scrollY: new Animated.Value(0),
afterImageHeight: 80
};
componentDidMount() {
this.props.onGetScrollYAnimation(this.state.scrollY, {
headerMaxHeight: this.props.headerMaxHeight,
headerMinHeight: HEADER_MIN_HEIGHT
});
}
/**
* get header distance
*/
_getHeaderDistance = () => {
const { headerMaxHeight } = this.props;
return headerMaxHeight - HEADER_MIN_HEIGHT;
};
/**
* style and animation for imageWrapper
*/
_getImageWrapperStyles = () => {
const { scrollY } = this.state;
const translateY = scrollY.interpolate({
inputRange: [0, this._getHeaderDistance()],
outputRange: [0, -this._getHeaderDistance()],
extrapolate: "clamp"
});
return {
transform: [{ translateY }]
};
};
/**
* style and animation for overlay
*/
_getOverlayStyles = reverse => {
const { scrollY } = this.state;
const { overlayRange, overlayColor } = this.props;
const opacity = scrollY.interpolate({
inputRange: [0, this._getHeaderDistance()],
outputRange: reverse ? [0.3, 0] : overlayRange,
extrapolate: "clamp"
});
return {
opacity,
backgroundColor: reverse ? "#000" : overlayColor
};
};
_handleLayoutAfterImage = event => {
this.setState({
afterImageHeight: event.nativeEvent.layout.height
});
};
/**
* Render After Image
*/
renderAfterImage() {
const { renderAfterImage } = this.props;
return (
renderAfterImage && (
<View
style={{
position: "relative",
zIndex: 20,
marginTop: this.props.afterImageMarginTop
}}
onLayout={this._handleLayoutAfterImage}
renderToHardwareTextureAndroid={true}
pointerEvents="none"
>
{renderAfterImage()}
</View>
)
);
}
/**
* style and animation for image
*/
_getImageStyles = () => {
const { scrollY } = this.state;
const { headerMaxHeight } = this.props;
const translateY = scrollY.interpolate({
inputRange: [0, this._getHeaderDistance()],
outputRange: [0, this._getHeaderDistance() / 2],
extrapolate: "clamp"
});
const opacity = scrollY.interpolate({
inputRange: [0, this._getHeaderDistance()],
outputRange: [1, 0],
extrapolate: "clamp"
});
const scale = scrollY.interpolate({
inputRange: [-300, 0],
outputRange: [1.5, 1],
extrapolate: "clamp"
});
return {
width: "100%",
height: headerMaxHeight,
transform: [{ translateY }, { scale }],
opacity
};
};
/**
* Render Image
*/
renderImage() {
const { headerImageSource, renderInsideImage } = this.props;
const { isDrag } = this.state;
return (
<Animated.View
style={[styles.imageWrapper, this._getImageWrapperStyles()]}
pointerEvents={isDrag ? "none" : "box-none"}
>
<View
style={{
position: "relative",
overflow: "hidden",
backgroundColor: "#fff"
}}
>
<Animated.View
pointerEvents="none"
style={[styles.overlay, this._getOverlayStyles(false)]}
/>
<Animated.View
pointerEvents="none"
style={[
styles.overlay,
{ zIndex: 9 },
this._getOverlayStyles(true)
]}
/>
<Animated.View pointerEvents="none" style={this._getImageStyles()}>
<ImageProgress
source={{ uri: headerImageSource }}
resizeMode="cover"
style={{ width: "100%", height: "100%" }}
indicator={ActivityIndicator}
/>
</Animated.View>
<View style={styles.insideImage}>{renderInsideImage()}</View>
</View>
{this.renderAfterImage()}
</Animated.View>
);
}
/**
* style and animation for headerCenter
*/
_getHeaderCenterStyles = () => {
const { scrollY } = this.state;
const translateY = scrollY.interpolate({
inputRange: [
this._getHeaderDistance() - 10,
this._getHeaderDistance() + 50
],
outputRange: [HEADER_MIN_HEIGHT, 0],
extrapolate: "clamp"
});
const opacity = scrollY.interpolate({
inputRange: [
this._getHeaderDistance() - 10,
this._getHeaderDistance() + 50
],
outputRange: [0, 1],
extrapolate: "clamp"
});
return {
transform: [{ translateY }],
opacity
};
};
/**
* Render Header
*/
renderHeader() {
const {
renderHeaderLeft,
renderHeaderCenter,
renderHeaderRight
} = this.props;
return (
<Fragment>
{this.renderImage()}
<View style={styles.header}>
<View style={styles.headerLeft}>{renderHeaderLeft()}</View>
<Animated.View
style={[styles.headerCenter, this._getHeaderCenterStyles()]}
>
{renderHeaderCenter()}
</Animated.View>
<View style={styles.headerRight}>{renderHeaderRight()}</View>
</View>
</Fragment>
);
}
/**
* Render Content
*/
renderContent() {
const { scrollY, afterImageHeight } = this.state;
const {
renderAfterImage,
headerMaxHeight,
afterImageMarginTop
} = this.props;
const translate = scrollY.interpolate({
inputRange: [0, this._getHeaderDistance()],
outputRange: [0, -afterImageHeight / 2],
extrapolate: "clamp"
});
return (
<Animated.ScrollView
ref={this.props.scrollViewRef}
scrollEventThrottle={SCROLL_EVENT_THROTTLE}
showsVerticalScrollIndicator={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="always"
onScrollEndDrag={this.props.onScrollEndDrag}
onScroll={Animated.event(
[
{
nativeEvent: {
contentOffset: { y: scrollY }
}
}
],
{ useNativeDriver: true }
)}
style={{
transform: [
{
translateY: renderAfterImage
? afterImageMarginTop === 0
? afterImageHeight / 2
: translate
: 0
}
]
}}
>
<Animated.View
style={{
paddingTop:
headerMaxHeight + (renderAfterImage ? afterImageHeight / 2 : 0)
}}
/>
{this.props.renderContent()}
</Animated.ScrollView>
);
}
/**
* Render Component
*/
render() {
return (
<View style={[styles.container, this.props.containerStyle]}>
{this.renderHeader()}
{this.renderContent()}
</View>
);
}
}
/**
* Style for component
*/
const styles = StyleSheet.create({
container: {
position: "relative",
zIndex: 9,
backgroundColor: "#fff",
minHeight: SCREEN_HEIGHT
},
header: {
position: "absolute",
top: 0,
left: 0,
right: 0,
zIndex: 20,
paddingTop: STATUS_BAR_HEIGHT,
height: HEADER_MIN_HEIGHT,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center"
},
headerCenter: {
maxWidth: 200
},
imageWrapper: {
position: "absolute",
top: 0,
left: 0,
right: 0,
zIndex: 9,
overflow: "hidden"
},
overlay: {
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: 10
},
insideImage: {
position: "absolute",
left: 0,
bottom: 0,
zIndex: 11,
paddingTop: 100
}
});
<file_sep>import { createStackNavigator } from "react-navigation";
import { Dimensions } from "react-native";
import stackOpts from "./stackOpts";
import HomeScreen from "../components/screens/HomeScreen";
import ListingCategories from "../components/screens/ListingCategories";
const { width } = Dimensions.get("window");
const homeStack = createStackNavigator(
{
HomeScreen: {
screen: HomeScreen
},
ListingCategories: {
screen: ListingCategories,
navigationOptions: ({ navigation }) => ({
gesturesEnabled: true,
gestureResponseDistance: {
horizontal: width
}
})
}
},
stackOpts
);
export default homeStack;
<file_sep>import {
GET_MY_PROFILE,
POST_MY_PROFILE,
POST_MY_PROFILE_ERROR,
LOGOUT,
GET_SHORT_PROFILE
} from "../constants/actionTypes";
export const myProfile = (state = {}, action) => {
switch (action.type) {
case GET_MY_PROFILE:
return action.payload;
case POST_MY_PROFILE:
return action.payload;
case LOGOUT:
return {};
default:
return state;
}
};
export const myProfileError = (state = "", action) => {
switch (action.type) {
case POST_MY_PROFILE_ERROR:
return action.messageError;
default:
return state;
}
};
export const shortProfile = (state = {}, action) => {
switch (action.type) {
case GET_SHORT_PROFILE:
return action.payload;
case LOGOUT:
return {};
default:
return state;
}
};
<file_sep>// import { GET_LISTING_STATUS } from "../constants/actionTypes";
// import axios from "axios";
// export const ctlGet = () => dispatch => {
// return axios
// .get("get-listing-status")
// .then(res => {
// const { data } = res;
// data.status === "success" &&
// dispatch({
// type: GET_LISTING_STATUS,
// payload: data.oResults
// });
// })
// .catch(err => console.log(err));
// };
<file_sep>import { GET_TRANSLATIONS } from "../constants/actionTypes";
import translationDefault from "../utils/translationDefault";
export const translations = (state = translationDefault, action) => {
switch (action.type) {
case GET_TRANSLATIONS:
return action.payload;
default:
return state;
}
};
<file_sep>export * from "./listings";
export * from "./listingSearchResults";
export * from "./eventSearchResults";
export * from "./listingByCat";
export * from "./listingDetail";
export * from "./homeScreen";
export * from "./listingFilters";
export * from "./locationList";
export * from "./categoryList";
export * from "./locations";
export * from "./translations";
export * from "./scrollTo";
export * from "./events";
export * from "./eventDetail";
export * from "./eventDiscussion";
export * from "./articles";
export * from "./articleDetail";
export { getTabNavigator, getStackNavigator } from "./navigators";
export { getNearByFocus } from "./nearByFocus";
export * from "./page";
export { getSettings } from "./settings";
export { login, logout, checkToken, register } from "./actionAuth";
export {
getMyFavorites,
addMyFavorites,
resetMyFavorites
} from "./actionMyFavorites";
export {
getMyProfile,
postMyProfile,
getShortProfile
} from "./actionMyProfile";
export { getReportForm, postReport } from "./actionReportForm";
export { getAccountNav } from "./actionAccountNav";
export { getEditProfileForm } from "./actionEditProfileForm";
export { getMyListings, getMyListingsLoadmore } from "./actionMyListings";
export { getListingStatus, getEventStatus } from "./actionListingStatus";
export { getPostTypes } from "./actionPostTypes";
export {
getMyNotifications,
getMyNotificationsLoadmore,
deleteMyNotifications
} from "./actionNotifications";
export { getMyEvents, getMyEventsLoadmore } from "./actionMyEvents";
export {
getMessageChat,
getMessageChatLoadmore,
putMessageChat,
putMessageChatOff,
putMessageChatListener,
resetMessageChat,
postWritingMessageChat,
checkDispatchWritingMessageChat,
readNewMessageChat,
messageChatActive,
getMessageChatNewCount,
resetMessageActive,
resetMessageActiveAll,
removeItemInUsersError,
deleteChatItem,
editChatItem,
getCurrentSendMessageScreen,
checkDispatchWritingSound
} from "./actionMessage";
export { getSignUpForm } from "./actionGetSignupForm";
export {
getCountNotifications,
getCountNotificationsRealTimeFaker
} from "./actionCounts";
export {
searchUsers,
addUsersToFirebase,
getUser,
getUsersFromFirebase,
getKeyFirebase,
setUserConnection,
deleteUserListMessageChat
} from "./actionUsers";
export {
setDeviceTokenToFirebase,
messagePushNotification
} from "./actionPushNotificationDevice";
export { getDeviceToken } from "./actionDeviceToken";
export {
getNotificationSettings,
setNotificationSettings,
getNotificationAdminSettings
} from "./actionNotificationSettings";
export { submitReview } from "./actionSubmitReview";
export { firebaseInitApp } from "./actionFirebase";
export { getReviewFields } from "./actionReviewFields";
<file_sep>import React, { PureComponent } from "react";
import { Text, View, StyleSheet } from "react-native";
import { connect } from "react-redux";
import { getEventDetail } from "../../actions";
import { WebItem, PhoneItem, AddressItem } from "../dumbs";
import {
isEmpty,
ViewWithLoading,
IconTextMedium,
ContentBox
} from "../../wiloke-elements";
import * as Consts from "../../constants/styleConstants";
import stylesBase from "../../stylesBase";
import _ from "lodash";
import he from "he";
class EventDetailContainer extends PureComponent {
state = {
isLoading: true
};
_getEventDetail = async () => {
try {
const { navigation } = this.props;
const { params } = navigation.state;
await this.props.getEventDetail(params.id);
this.setState({ isLoading: false });
} catch (err) {
console.log(err);
}
};
componentDidMount() {
this._getEventDetail();
}
renderMetaMap = (item, index) => {
const { navigation } = this.props;
return (
<View key={index.toString()} style={styles.item}>
<AddressItem
address={item.value}
navigation={navigation}
iconColor={Consts.colorDark2}
iconBackgroundColor={Consts.colorGray2}
/>
</View>
);
};
renderMetaTerm = (item, index) => {
return (
<View
key={index.toString()}
style={[
styles.item,
{
paddingVertical: 4
}
]}
>
{item.value.map(cat => {
return (
<View
key={cat.slug}
style={{
flexDirection: "row",
marginVertical: 4,
marginRight: 15
}}
>
<IconTextMedium iconName="folder" iconSize={30} text={cat.name} />
</View>
);
})}
</View>
);
};
renderMetaWebsite = (item, index) => {
const { navigation } = this.props;
return (
<View key={index.toString()} style={styles.item}>
<WebItem
url={item.value}
navigation={navigation}
iconColor={Consts.colorDark2}
iconBackgroundColor={Consts.colorGray2}
/>
</View>
);
};
renderMetaPhone = (item, index) => {
return (
<View key={index.toString()} style={styles.item}>
<PhoneItem
phone={item.value}
iconColor={Consts.colorDark2}
iconBackgroundColor={Consts.colorGray2}
/>
</View>
);
};
renderMetaEmail = (item, index) => {
return (
<View key={index.toString()} style={styles.item}>
<IconTextMedium iconName="mail" iconSize={30} text={item.value} />
</View>
);
};
renderMeta = (item, index) => {
switch (item.type) {
case "map":
return this.renderMetaMap(item, index);
case "term":
return this.renderMetaTerm(item, index);
case "website":
return this.renderMetaWebsite(item, index);
case "email":
return this.renderMetaEmail(item, index);
case "phone":
return this.renderMetaPhone(item, index);
default:
return false;
}
};
renderBoxBorder = (text, hour) => {
return (
<View
style={{
borderWidth: 1,
borderColor: Consts.colorGray1,
paddingVertical: 5,
paddingHorizontal: 8,
borderRadius: Consts.round,
marginTop: 10
}}
>
<Text
style={{
fontSize: 12,
fontWeight: "500",
color: Consts.colorDark2
}}
>
{text}
</Text>
<View style={{ height: 4 }} />
<Text style={{ fontSize: 11, color: Consts.colorDark3 }}>{hour}</Text>
</View>
);
};
renderDescription = item => {
const { settings } = this.props;
return (
<ContentBox
key={item.type}
headerTitle={item.text}
headerIcon="file-text"
style={{ marginBottom: 10 }}
colorPrimary={settings.colorPrimary}
>
<Text style={stylesBase.text}>{he.decode(item.content)}</Text>
</ContentBox>
// <View
// key={item.type}
// style={{
// paddingVertical: 13,
// marginTop: 10,
// borderTopWidth: 1,
// borderTopColor: Consts.colorGray1
// }}
// >
// <Text style={stylesBase.text}>{item.content}</Text>
// </View>
);
};
renderTags = item => {
return (
<View key={item.type}>
{item.content.length > 0 &&
item.content.map(tag => (
<View key={tag.slug} style={{ marginRight: 15, marginBottom: 10 }}>
<IconTextMedium iconName="check" iconSize={30} text={tag.name} />
</View>
))}
</View>
);
};
renderSection = item => {
switch (item.type) {
case "listing_content":
return this.renderDescription(item);
case "listing_tag":
return this.renderTags(item);
default:
return false;
}
};
render() {
const { eventDetail } = this.props;
const { isLoading } = this.state;
return (
<View
style={{
marginHorizontal: -10
}}
>
<ViewWithLoading isLoading={isLoading} contentLoader="content">
{!isEmpty(eventDetail) && (
<View>
<View
style={{
backgroundColor: "#fff",
marginBottom: 10
}}
>
<View style={styles.item}>
{eventDetail.oCalendar && (
<IconTextMedium
iconName="calendar"
iconSize={30}
text={eventDetail.oCalendar.general}
/>
)}
{eventDetail.oCalendar && (
<View style={{ flexDirection: "row" }}>
{this.renderBoxBorder(
"Opening at",
eventDetail.oCalendar.oStarts.hour
)}
<View style={{ width: 5 }} />
{this.renderBoxBorder(
"Closed at",
eventDetail.oCalendar.oEnds.hour
)}
</View>
)}
</View>
{eventDetail.aMetaData.length > 0 &&
eventDetail.aMetaData.map(this.renderMeta)}
</View>
<View style={{ marginHorizontal: 10 }}>
{eventDetail.aSections.length > 0 &&
eventDetail.aSections.map(this.renderSection)}
</View>
</View>
)}
</ViewWithLoading>
</View>
);
}
}
const styles = StyleSheet.create({
item: {
padding: 8,
borderTopWidth: 1,
borderTopColor: Consts.colorGray2
}
});
const mapStateToProps = state => ({
eventDetail: state.eventDetail,
settings: state.settings
});
export default connect(
mapStateToProps,
{
getEventDetail
}
)(EventDetailContainer);
<file_sep>import React, { Component } from "react";
import {
Platform,
Image,
Dimensions,
Linking,
Alert,
AppState
} from "react-native";
import { connect } from "react-redux";
import {
Permissions,
Location,
Notifications,
IntentLauncherAndroid,
Updates
} from "expo";
import he from "he";
import _ from "lodash";
import axios from "axios";
import {
createBottomTabNavigator,
createStackNavigator
} from "react-navigation";
import getSlideFromRightTransition from "react-navigation-slide-from-right-transition";
import ListingDetailScreen from "../components/screens/ListingDetailScreen";
import CommentListingScreen from "../components/screens/CommentListingScreen";
import EventDetailScreen from "../components/screens/EventDetailScreen";
import EventDiscussionAllScreen from "../components/screens/EventDiscussionAllScreen";
import EventCommentDiscussionScreen from "../components/screens/EventCommentDiscussionScreen";
import WebViewScreen from "../components/screens/WebViewScreen";
import ArticleDetailScreen from "../components/screens/ArticleDetailScreen";
import SearchScreen from "../components/screens/SearchScreen";
import ListingSearchResultScreen from "../components/screens/ListingSearchResultScreen";
import EventSearchResultScreen from "../components/screens/EventSearchResultScreen";
import MessageScreen from "../components/screens/MessageScreen";
import SendMessageScreen from "../components/screens/SendMessageScreen";
import NotificationsScreen from "../components/screens/NotificationsScreen";
import AddMessageScreen from "../components/screens/AddMessageScreen";
import ReviewFormScreen from "../components/screens/ReviewFormScreen";
import {
getHomeScreen,
getTabNavigator,
getTranslations,
getLocations,
getSettings,
checkToken,
getCountNotificationsRealTimeFaker,
getShortProfile,
getMessageChatNewCount,
setUserConnection,
getDeviceToken,
setDeviceTokenToFirebase,
resetMessageActiveAll,
removeItemInUsersError,
setNotificationSettings,
getNotificationAdminSettings,
firebaseInitApp,
getAppState
} from "../actions";
import rootTabNavOpts from "./rootTabNavOpts";
import homeStack from "./homeStack";
import listingStack from "./listingStack";
import eventStack from "./eventStack";
import accountStack from "./accountStack";
import menuStack from "./menuStack";
import blogStack from "./articleStack";
import pageStack from "./pageStack";
import { FontIcon } from "../wiloke-elements";
const { width: SCREEN_WIDTH } = Dimensions.get("window");
const navigationOptions = {
gesturesEnabled: true
// gestureResponseDistance: {
// horizontal: SCREEN_WIDTH
// }
};
class RootStack extends Component {
constructor(props) {
super(props);
this.state = {
location: null,
errorMessage: null,
notification: {}
};
const { auth } = this.props;
const { token } = auth;
if (token)
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
}
_getLocationAsync = async () => {
try {
const { status } = await Permissions.askAsync(Permissions.LOCATION);
console.log(status);
// if (status !== "granted") {
// await this.setState({
// errorMessage: "Permission to access location was denied"
// });
// }
if (status === "granted") {
const location = await Location.getCurrentPositionAsync({
enableHighAccuracy: true
});
this.props.getLocations(location);
} else {
throw new Error("Location permission not granted");
}
// const location = await Location.getCurrentPositionAsync({});
} catch (err) {
const { translations } = await this.props;
Platform === "android"
? IntentLauncherAndroid.startActivityAsync(
IntentLauncherAndroid.ACTION_LOCATION_SOURCE_SETTINGS
)
: Alert.alert(
he.decode(translations.askForAllowAccessingLocationTitle),
he.decode(translations.askForAllowAccessingLocationDesc),
[
{
text: translations.cancel,
style: "cancel"
},
{
text: translations.ok,
onPress: () => Linking.openURL("app-settings:")
}
],
{ cancelable: false }
);
}
};
_checkToken = __ => {
const { checkToken, shortProfile, setUserConnection } = this.props;
const myID = shortProfile.userID;
if (this.props.auth.isLoggedIn) {
checkToken(myID);
}
this._checkTokenFaker = setInterval(__ => {
if (this.props.auth.isLoggedIn) {
checkToken(myID);
} else {
setUserConnection(myID, false);
}
}, 60000);
};
_getCountNotifications = __ => {
const { getCountNotificationsRealTimeFaker } = this.props;
if (this.props.auth.isLoggedIn) {
getCountNotificationsRealTimeFaker();
}
this._getCountNotificationFaker = setInterval(_ => {
if (this.props.auth.isLoggedIn) {
getCountNotificationsRealTimeFaker();
}
}, 10000);
};
_handleAppStateChange = myID => async nextAppState => {
this.props.setUserConnection(myID, nextAppState === "active");
this.props.getAppState(nextAppState);
};
registerForPushNotificationsAsync = async (isLoggedIn, myID, firebaseID) => {
const { status: existingStatus } = await Permissions.getAsync(
Permissions.NOTIFICATIONS
);
let finalStatus = existingStatus;
// only ask if permissions have not already been determined, because
// iOS won't necessarily prompt the user a second time.
if (existingStatus !== "granted") {
// Android remote notification permissions are granted during the app
// install, so this will only ask on iOS
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
// Stop here if the user did not grant permissions
if (finalStatus !== "granted") {
return;
}
// Get the token that uniquely identifies this device
let token = await Notifications.getExpoPushTokenAsync();
this.props.getDeviceToken(token);
// // POST the token to your backend server from where you can retrieve it to send push
if (isLoggedIn && myID) {
this.props.setDeviceTokenToFirebase(myID, firebaseID, token);
}
};
async componentDidMount() {
const {
firebaseInitApp,
getSettings,
getTranslations,
getHomeScreen,
getTabNavigator,
auth,
getMessageChatNewCount
} = this.props;
await firebaseInitApp();
await getSettings();
await getTranslations();
auth.isLoggedIn && (await this.props.getShortProfile());
getHomeScreen();
getTabNavigator();
this._checkToken();
this._getCountNotifications();
const { shortProfile } = this.props;
const { firebaseID, userID: myID } = shortProfile;
if (auth.isLoggedIn && myID) {
getMessageChatNewCount(myID);
this.props.setUserConnection(myID, true);
AppState.addEventListener("change", this._handleAppStateChange(myID));
this.props.resetMessageActiveAll(myID);
this.props.removeItemInUsersError(myID);
await this.props.getNotificationAdminSettings();
const { notificationAdminSettings } = this.props;
await this.props.setNotificationSettings(
myID,
notificationAdminSettings,
"start"
);
}
this.registerForPushNotificationsAsync(auth.isLoggedIn, myID, firebaseID);
// try {
// const update = await Updates.checkForUpdateAsync();
// if (update.isAvailable) {
// await Updates.fetchUpdateAsync();
// // ... notify user of update ...
// Updates.reloadFromCache();
// }
// } catch (e) {
// // handle or log error
// console.log(e);
// }
// Notifications.setBadgeNumberAsync(0);
// if (Platform.OS === "android" && !Constants.isDevice) {
// this.setState({
// errorMessage:
// "Oops, this will not work on Sketch in an Android emulator. Try it on your device!"
// });
// } else {
// this._getLocationAsync();
// }
}
componentWillUnmount() {
clearInterval(this._checkTokenFaker);
clearInterval(this._getCountNotificationFaker);
const { shortProfile, auth } = this.props;
const myID = shortProfile.userID;
if (auth.isLoggedIn && myID) {
AppState.addEventListener("change", this._handleAppStateChange(myID));
}
}
shouldComponentUpdate(nextProps) {
if (!_.isEqual(nextProps.homeScreen, this.props.homeScreen)) {
return true;
}
if (!_.isEqual(nextProps.translations, this.props.translations)) {
return true;
}
if (!_.isEqual(nextProps.settings, this.props.settings)) {
return true;
}
if (!_.isEqual(nextProps.tabNavigator, this.props.tabNavigator)) {
return true;
}
return false;
}
_checkScreen = screen => {
switch (screen) {
case "listingStack":
return listingStack;
case "eventStack":
return eventStack;
case "blogStack":
return blogStack;
case "accountStack":
return accountStack;
case "pageStack":
return pageStack;
case "menuStack":
return menuStack;
default:
return homeStack;
}
};
renderTabItem = ({ tabBarLabel, iconType, iconName }) => () => {
const { tabNavigator } = this.props;
// const tabBarListing = tabNavigator
// .filter(item => item.screen === "listingStack")
// .map(item => item.key);
return {
tabBarLabel,
tabBarIcon: ({ tintColor }) => {
switch (iconType) {
case "image":
return (
typeof iconName !== "undefined" && (
<Image
source={iconName}
style={{ width: 20, height: 20, tintColor: tintColor }}
/>
)
);
default:
return (
typeof iconName !== "undefined" && (
<FontIcon name={iconName} size={22} color={tintColor} />
)
);
}
}
// tabBarOnPress: ({ navigation, defaultHandler }) => {
// // const parentNavigation = navigation.dangerouslyGetParent();
// // const prevRoute =
// // parentNavigation.state.routes[parentNavigation.state.index];
// const nextRoute = navigation.state;
// const { routeName } = nextRoute;
// // if (isLoggedIn) {
// // defaultHandler();
// // } else {
// // togglePopupLogin();
// // }
// // } else {
// // defaultHandler();
// // }
// console.log(123, navigation);
// defaultHandler();
// // AsyncStorage.setItem(
// // "nextKey",
// // tabBarListing.length > 1 ? nextRoute.key : ""
// // );
// // AsyncStorage.setItem(
// // "prevKey",
// // tabBarListing.length > 1 ? prevRoute.key : ""
// // );
// // routeName === "ListingScreen" &&
// // AsyncStorage.setItem("postTypeFocus", nextRoute.key);
// }
};
};
render() {
const { tabNavigator, settings } = this.props;
const RootStack = createStackNavigator(
{
RootTab: {
screen: createBottomTabNavigator(
tabNavigator.length > 0
? tabNavigator.reduce((acc, cur) => {
return {
...acc,
[cur.key]: {
screen: this._checkScreen(cur.screen),
navigationOptions: this.renderTabItem({
tabBarLabel: cur.name,
iconType: "font",
iconName: cur.iconName
})
}
};
}, {})
: {
home: {
screen: homeStack,
navigationOptions: this.renderTabItem({
tabBarLabel: " "
})
}
},
rootTabNavOpts(settings.colorPrimary)
)
},
MessageScreen: {
screen: MessageScreen,
navigationOptions
},
SendMessageScreen: {
screen: SendMessageScreen,
navigationOptions
},
NotificationsScreen: {
screen: NotificationsScreen,
navigationOptions
},
SearchScreen: {
screen: SearchScreen,
navigationOptions
},
ListingSearchResultScreen: {
screen: ListingSearchResultScreen,
navigationOptions
},
EventSearchResultScreen: {
screen: EventSearchResultScreen,
navigationOptions
},
ListingDetailScreen: {
screen: ListingDetailScreen,
navigationOptions
},
CommentListingScreen: {
screen: CommentListingScreen,
navigationOptions
},
ReviewFormScreen: {
screen: ReviewFormScreen,
navigationOptions
},
EventDetailScreen: {
screen: EventDetailScreen,
navigationOptions
},
WebViewScreen: {
screen: WebViewScreen,
navigationOptions
},
EventDiscussionAllScreen: {
screen: EventDiscussionAllScreen,
navigationOptions
},
EventCommentDiscussionScreen: {
screen: EventCommentDiscussionScreen,
navigationOptions
},
ArticleDetailScreen: {
screen: ArticleDetailScreen,
navigationOptions
},
AddMessageScreen: {
screen: AddMessageScreen,
navigationOptions
}
},
{
transitionConfig: getSlideFromRightTransition,
headerMode: "none"
}
);
return <RootStack {...this.props} />;
}
}
const mapStateToProps = state => ({
tabNavigator: state.tabNavigator,
translations: state.translations,
settings: state.settings,
auth: state.auth,
isTokenExpired: state.isTokenExpired,
shortProfile: state.shortProfile,
notificationAdminSettings: state.notificationAdminSettings
});
const mapDispatchToProps = {
getTabNavigator,
getTranslations,
getLocations,
getSettings,
getHomeScreen,
checkToken,
getCountNotificationsRealTimeFaker,
getShortProfile,
getMessageChatNewCount,
setUserConnection,
getDeviceToken,
setDeviceTokenToFirebase,
resetMessageActiveAll,
removeItemInUsersError,
setNotificationSettings,
getNotificationAdminSettings,
firebaseInitApp,
getAppState
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(RootStack);
<file_sep>const convertFontIcon = (icon = "la ") => {
switch (icon.replace("la ", "")) {
case "la-line-chart":
case "activity":
return "activity";
case "la-exclamation-circle":
case "alert-circle":
return "alert-circle";
case "la-exclamation-triangle":
case "alert-triangle":
return "alert-triangle";
case "la-align-center":
case "align-center":
return "align-center";
case "la-align-justify":
case "align-justify":
return "align-justify";
case "la-align-left":
case "align-left":
return "align-left";
case "la-align-right":
case "align-right":
return "align-right";
case "la-anchor":
case "anchor":
return "anchor";
case "la-arrow-circle-down":
case "arrow-down-circle":
return "arrow-down-circle";
case "la-arrow-circle-up":
case "arrow-up-circle":
return "arrow-up-circle";
case "la-arrow-circle-left":
case "arrow-left-circle":
return "arrow-left-circle";
case "la-arrow-circle-right":
case "arrow-right-circle":
return "arrow-right-circle";
case "la-arrow-down":
case "arrow-down":
return "arrow-down";
case "la-arrow-up":
case "arrow-up":
return "arrow-up";
case "la-arrow-left":
case "arrow-left":
return "arrow-left";
case "la-arrow-right":
case "arrow-right":
return "arrow-right";
case "la-at":
case "at-sign":
return "at-sign";
case "la-bar-chart":
case "bar-chart":
return "bar-chart";
case "la-battery-three-quarters":
case "battery-charging":
return "battery-charging";
case "la-battery-0":
case "battery":
return "battery";
case "la-bell-slash":
case "la-bell-slash-o":
case "bell-off":
return "bell-off";
case "la-bell":
case "la-bell-o":
case "bell":
return "bell";
case "la-bold":
case "bold":
return "bold";
case "la-book":
case "book":
return "book";
case "la-bookmark":
case "la-bookmark-o":
case "bookmark":
return "bookmark";
case "la-briefcase":
case "briefcase":
return "briefcase";
case "la-calendar-check-o":
case "la-calendar-o":
case "la-calendar":
case "calendar":
return "calendar";
case "la-camera-retro":
case "la-camera":
case "camera":
return "camera";
case "la-check-circle":
case "la-check-circle-o":
case "check-circle":
return "check-circle";
case "la-check-square":
case "la-check-square-o":
case "check-square":
return "check-square";
case "la-check":
case "check":
return "check";
case "la-angle-down":
case "chevron-down":
return "chevron-down";
case "la-angle-up":
case "chevron-up":
return "chevron-up";
case "la-angle-left":
case "chevron-left":
return "chevron-left";
case "la-angle-right":
case "chevron-right":
return "chevron-right";
case "la-angle-double-down":
case "chevrons-down":
return "chevrons-down";
case "la-angle-double-up":
case "chevrons-up":
return "chevrons-up";
case "la-angle-double-left":
case "chevrons-left":
return "chevrons-left";
case "la-angle-double-right":
case "chevrons-right":
return "chevrons-right";
case "la-chrome":
case "chrome":
return "chrome";
case "la-circle":
case "circle":
return "circle";
case "la-archive":
case "la-clipboard":
case "clipboard":
return "clipboard";
case "la-clock-o":
case "clock":
return "clock";
case "la-cloud":
case "cloud":
return "cloud";
case "la-code":
case "code":
return "code";
case "la-codepen":
case "codepen":
return "codepen";
case "la-compass":
case "compass":
return "compass";
case "la-copy":
case "copy":
return "copy";
case "la-credit-card":
case "credit-card":
return "credit-card";
case "la-crop":
case "crop":
return "crop";
case "la-crosshairs":
case "crosshair":
return "crosshair";
case "la-database":
case "database":
return "database";
case "la-dot-circle-o":
case "disc":
return "disc";
case "la-cloud-download":
case "download-cloud":
return "download-cloud";
case "la-download":
case "download":
return "download1111";
case "la-edit":
case "edit":
return "edit";
case "la-external-link":
case "external-link":
return "external-link";
case "la-eye-slash":
case "eye-off":
return "eye-off";
case "la-eye":
case "eye":
return "eye";
case "la-facebook":
case "la-facebook-f":
case "la-facebook-official":
case "la-facebook-square":
case "facebook":
return "facebook";
case "la-forward":
case "fast-forward":
return "fast-forward";
case "la-file-text":
case "la-file-text-o":
case "file-text":
return "file-text";
case "la-file":
case "la-file-o":
case "file":
return "file";
case "la-film":
case "film":
return "film";
case "la-filter":
case "filter":
return "filter";
case "la-flag":
case "la-flag-o":
case "flag":
return "flag";
case "la-folder":
case "la-folder-o":
case "folder":
return "folder";
case "la-gift":
case "gift":
return "gift";
case "la-github":
case "la-github-alt":
case "la-github-square":
case "github":
return "github";
case "la-globe":
case "globe":
return "globe";
case "la-headphones":
case "headphones":
return "headphones";
case "la-heart":
case "heart":
return "heart";
case "la-question-circle":
case "help-circle":
return "help-circle";
case "la-home":
case "home":
return "home";
case "la-image":
case "image":
return "image";
case "la-image":
case "image":
return "image";
case "la-inbox":
case "inbox":
return "inbox";
case "la-info":
case "la-info-circle":
case "info":
return "info";
case "la-instagram":
case "instagram":
return "instagram";
case "la-italic":
case "italic":
return "italic";
case "la-database":
case "layers":
return "layers";
case "la-columns":
case "layout":
return "layout";
case "la-life-buoy":
case "life-buoy":
return "life-buoy";
case "la-link":
case "link":
return "link";
case "la-linkedin":
case "la-linkedin-square":
case "linkedin":
return "linkedin";
case "la-list":
case "la-list-alt":
case "la-list-ol":
case "la-list-ul":
case "list":
return "list";
case "la-spinner":
case "loader":
return "loader";
case "la-lock":
case "lock":
return "lock";
case "la-envelope":
case "la-envelope-o":
case "la-envelope-square":
case "mail":
return "mail";
case "la-map-marker":
case "la-map-pin":
case "map-pin":
return "map-pin";
case "la-map":
case "map":
return "map";
case "la-expand":
case "maximize-2":
return "maximize-2";
case "la-arrows-alt":
case "maximize":
return "maximize";
case "la-bars":
case "la-navicon":
case "menu":
return "menu";
case "la-comment":
case "la-comment-o":
case "la-commenting":
case "la-commenting-o":
case "la-comments":
case "la-comments-o":
case "message-square":
return "message-square";
case "la-microphone-slash":
case "mic-off":
return "mic-off";
case "la-la-microphone":
case "mic":
return "mic";
case "la-compress":
case "minimize-2":
return "minimize-2";
case "la-link":
case "link":
return "link";
case "la-minus-circle":
case "minus-circle":
return "minus-circle";
case "la-minus-square":
case "minus-square":
return "minus-square";
case "la-minus":
case "minus":
return "minus";
case "la-desktop":
case "monitor":
return "monitor";
case "la-moon-o":
case "moon":
return "moon";
case "la-ellipsis-h":
case "more-horizontal":
return "more-horizontal";
case "la-ellipsis-v":
case "more-vertical":
return "more-vertical";
case "la-cube":
case "package":
return "package";
case "la-paperclip":
case "paperclip":
return "paperclip";
case "la-music":
case "music":
return "music";
case "la-pause":
case "pause":
return "pause";
case "la-phone":
case "la-phone-square":
case "phone":
return "phone";
case "la-pie-chart":
case "piechart":
return "piechart";
case "la-play-circle":
case "la-play-circle-o":
case "play-circle":
return "play-circle";
case "la-play":
case "play":
return "play";
case "la-plus-circle":
case "plus-circle":
return "plus-circle";
case "la-plus-square":
case "plus-square":
return "plus-square";
case "la-plus":
case "plus":
return "plus";
case "la-get-pocket":
case "pocket":
return "pocket";
case "la-power-off":
case "power":
return "power";
case "la-print":
case "printer":
return "printer";
case "la-refresh":
case "refresh-cw":
return "refresh-cw";
case "la-repeat":
case "repeat":
return "repeat";
case "la-backward":
case "rewind":
return "rewind";
case "la-rotate-left":
case "rotate-ccw":
return "rotate-ccw";
case "la-rotate-right":
case "rotate-cw":
return "rotate-cw";
case "la-rss":
case "la-rss-square":
case "rss":
return "rss";
case "la-save":
case "save":
return "save";
case "la-scissors":
case "la-cut":
case "scissors":
return "scissors";
case "la-search":
case "la-search-plus":
case "search":
return "search";
case "la-send":
case "la-send-o":
case "la-paper-plane-o":
case "send":
return "send";
case "la-server":
case "server":
return "server";
case "la-wrench":
case "la-cog":
case "la-cogs":
case "settings":
return "settings";
case "la-share":
case "la-share-square":
case "la-share-square-o":
case "share-2":
return "share-2";
case "la-share-alt":
case "la-share-alt-square":
case "share":
return "share";
case "la-shield":
case "shield":
return "shield";
case "la-shopping-cart":
case "shopping-cart":
return "shopping-cart";
case "la-step-backward":
case "skip-back":
return "skip-back";
case "la-step-forward":
case "skip-forward":
return "skip-forward";
case "la-slack":
case "slack":
return "slack";
case "la-sliders":
case "sliders":
return "sliders";
case "la-mobile":
case "la-mobile-phone":
case "smartphone":
return "smartphone";
case "la-star":
case "la-star-o":
case "star":
return "star";
case "la-stop":
case "stop-circle":
return "stop-circle";
case "la-sun-o":
case "sun":
return "sun";
case "la-tablet":
case "tablet":
return "tablet";
case "la-tag":
case "la-tags":
case "tag":
return "tag";
case "la-bullseye":
case "target":
return "target";
case "la-terminal":
case "terminal":
return "terminal";
case "la-thumbs-down":
case "la-thumbs-o-down":
case "thumbs-down":
return "thumbs-down";
case "la-thumbs-up":
case "la-thumbs-o-up":
case "thumbs-up":
return "thumbs-up";
case "la-toggle-off":
case "toggle-left":
return "toggle-left";
case "la-toggle-on":
case "toggle-right":
return "toggle-right";
case "la-trash":
case "la-trash-o":
case "trash-2":
return "trash-2";
case "la-flash":
case "la-bolt":
case "trending-down":
return "trending-down";
case "la-truck":
case "truck":
return "truck";
case "la-pause":
case "pause":
return "pause";
case "la-tv":
case "tv":
return "tv";
case "la-twitter":
case "la-twitter-square":
case "twitter":
return "twitter";
case "la-umbrella":
case "umbrella":
return "umbrella";
case "la-underline":
case "underline":
return "underline";
case "la-unlock":
case "la-unlock-alt":
case "unlock":
return "unlock";
case "la-cloud-upload":
case "upload-cloud":
return "upload-cloud";
case "la-upload":
case "upload":
return "upload";
case "la-user-plus":
case "user-plus":
return "user-plus";
case "la-user-times":
case "user-x":
return "user-x";
case "la-user":
case "user":
return "user";
case "la-users":
case "users":
return "users";
case "la-video-camera":
case "video":
return "video";
case "la-volume-down":
case "volume-1":
return "volume-1";
case "la-volume-up":
case "volume-2":
return "volume-2";
case "la-volume-off":
case "volume-x":
return "volume-x";
case "la-wifi":
case "wifi":
return "wifi";
case "la-times-circle":
case "la-times-circle-o":
case "la-close":
case "x-circle":
return "x-circle";
case "la-times":
case "la-times-o":
case "x":
return "x";
case "la-youtube-play":
case "youtube":
return "youtube";
case "la-search-plus":
case "zoom-in":
return "zoom-in";
case "la-search-minus":
case "zoom-out":
return "zoom-out";
default:
return false;
}
};
export default convertFontIcon;
<file_sep>import { Dimensions } from "react-native";
const { width } = Dimensions.get("window");
// export const colorPrimary = '#f06292'
export const colorPrimary = "#ff5790";
export const colorSecondary = "#3ece7e";
export const colorTertiary = "#f4b34d";
export const colorQuaternary = "#fc6363";
export const colorDark = "#252c41";
export const colorDark1 = "#252c41";
export const colorDark2 = "#485273";
export const colorDark3 = "#70778b";
export const colorDark4 = "#9ea6ba";
export const colorDark5 = "#dfdfe4";
export const colorGray1 = "#e7e7ed";
export const colorGray2 = "#f0f0f3";
export const colorGray3 = "#fafafb";
export const colorGray4 = "#fbfbfc";
export const colorLight = "#fff";
export const round = 3;
export const screenWidth = width < 600 ? width : 600;
<file_sep>import React from "react";
import PropTypes from "prop-types";
import { View, Text, StyleSheet } from "react-native";
import { isEmpty } from "../../wiloke-elements";
import * as Consts from "../../constants/styleConstants";
const _getCurrentDayColor = (item, oCurrent) => {
if (item.is !== oCurrent.is) return Consts.colorDark2;
return oCurrent.status === "closed" ||
oCurrent.status === "close" ||
oCurrent.status === "day_off"
? Consts.colorQuaternary
: Consts.colorSecondary;
};
const Item = oCurrent => (item, index) => (
<View
key={index.toString()}
style={[styles.spaceBetween, { paddingVertical: 8 }]}
>
<View style={styles.left}>
<Text
style={[styles.text, { color: _getCurrentDayColor(item, oCurrent) }]}
>
{item.is}
</Text>
</View>
{item.status === "day_off" ? (
<View style={styles.spaceBetween}>
<Text
style={[styles.text, { color: _getCurrentDayColor(item, oCurrent) }]}
>
{item.text}
</Text>
</View>
) : (
<View style={styles.spaceBetween}>
{item.firstOpenHour &&
item.firstCloseHour && (
<Text
style={[
styles.text,
{ color: _getCurrentDayColor(item, oCurrent) }
]}
>
{item.firstOpenHour} - {item.firstCloseHour}
</Text>
)}
{item.firstOpenHour &&
item.firstCloseHour &&
item.secondOpenHour &&
item.secondCloseHour && <View style={{ width: 15 }} />}
{item.secondOpenHour &&
item.secondCloseHour && (
<Text
style={[
styles.text,
{ color: _getCurrentDayColor(item, oCurrent) }
]}
>
{item.secondOpenHour} - {item.secondCloseHour}
</Text>
)}
</View>
)}
</View>
);
const AlwayOpenItem = props => (
<View
style={{
padding: 10,
backgroundColor: Consts.colorSecondary,
flexDirection: "column",
alignItems: "center",
borderRadius: Consts.round
}}
>
<Text
style={{
color: "#fff",
fontSize: 13
}}
>
{props.alwaysOpenText}
</Text>
</View>
);
const ListingHours = props => {
const { data, alwaysOpenText } = props;
const { mode } = data;
switch (mode) {
case "rest":
const { oDetails } = data;
const { oCurrent } = oDetails;
const { oAllBusinessHours } = oDetails;
return (
<View>
{oAllBusinessHours &&
!isEmpty(oAllBusinessHours) &&
oAllBusinessHours.map(Item(oCurrent))}
</View>
);
case "always_open":
return <AlwayOpenItem alwaysOpenText={alwaysOpenText} />;
default:
return false;
}
};
ListingHours.propTypes = {
currentDay: PropTypes.object,
data: PropTypes.object
};
const styles = StyleSheet.create({
spaceBetween: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center"
},
text: {
color: Consts.colorDark2,
fontSize: 11
}
});
export default ListingHours;
<file_sep>import React, { PureComponent } from "react";
import { TouchableOpacity, Dimensions } from "react-native";
import { Feather } from "@expo/vector-icons";
import * as Consts from "../../constants/styleConstants";
import { ListingSearchResultsContainer } from "../smarts";
import { Layout } from "../dumbs";
import { Constants } from "expo";
import { connect } from "react-redux";
const { height: SCREEN_HEIGHT } = Dimensions.get("window");
const HEADER_HEIGHT = 52 + Constants.statusBarHeight;
const CONTENT_HEIGHT = SCREEN_HEIGHT - HEADER_HEIGHT;
class ListingSearchResultScreen extends PureComponent {
renderContent = () => {
const { navigation } = this.props;
return <ListingSearchResultsContainer navigation={navigation} />;
};
render() {
const { navigation, translations, settings } = this.props;
return (
<Layout
navigation={navigation}
headerType="headerHasBack"
title={translations.searchResults}
goBack={() => navigation.goBack()}
renderRight={() => (
<TouchableOpacity
activeOpacity={0.5}
onPress={() => navigation.goBack()}
>
<Feather name="search" size={20} color="#fff" />
</TouchableOpacity>
)}
renderContent={this.renderContent}
scrollViewEnabled={false}
scrollViewStyle={{
backgroundColor: Consts.colorGray2
}}
contentHeight={CONTENT_HEIGHT}
colorPrimary={settings.colorPrimary}
/>
);
}
}
const mapStateToProps = state => ({
translations: state.translations,
settings: state.settings
});
export default connect(mapStateToProps)(ListingSearchResultScreen);
<file_sep>import { createStackNavigator } from "react-navigation";
import stackOpts from "./stackOpts";
import PageScreen from "../components/screens/PageScreen";
const pageStack = createStackNavigator(
{
PageScreen: {
screen: PageScreen
}
},
stackOpts
);
export default pageStack;
<file_sep>import React from "react";
import PropTypes from "prop-types";
import { View, Text } from "react-native";
import { Feather } from "@expo/vector-icons";
import * as Consts from "../../constants/styleConstants";
import { Row, Col, IconTextMedium } from "../../wiloke-elements";
import he from "he";
const ListingCatList = props => {
const { data } = props;
return (
<Row gap={15}>
{data.length > 0 &&
data.map((item, index) => (
<Col key={index.toString()} column={2} gap={15}>
<IconTextMedium
iconName={item.icon}
iconSize={30}
iconColor={item.color ? "#fff" : Consts.colorDark2}
iconBackgroundColor={item.color ? item.color : Consts.colorGray2}
text={he.decode(item.name)}
texNumberOfLines={1}
/>
</Col>
))}
</Row>
);
};
ListingCatList.propTypes = {
data: PropTypes.array
};
export default ListingCatList;
<file_sep>import * as types from "../constants/actionTypes";
export const events = (state = { oResults: [] }, action) => {
switch (action.type) {
case types.GET_EVENTS:
return action.payload;
case types.GET_EVENTS_LOADMORE:
return {
...state,
next: action.payload.next,
oResults: [...state.oResults, ...action.payload.oResults]
};
default:
return state;
}
};
<file_sep>import {
GET_MY_LISTINGS,
GET_MY_LISTINGS_LOADMORE,
GET_MY_LISTING_ERROR
} from "../constants/actionTypes";
import axios from "axios";
const POSTS_PER_PAGE = 12;
export const getMyListings = ({ postType, postStatus }) => dispatch => {
return axios
.get("get-my-listings", {
params: {
postType,
postStatus,
postsPerPage: POSTS_PER_PAGE
}
})
.then(({ data }) => {
if (data.status === "success") {
dispatch({
type: GET_MY_LISTINGS,
payload: data
});
} else if (data.status === "error") {
dispatch({
type: GET_MY_LISTING_ERROR,
messageError: data.msg
});
}
})
.catch(err => console.log(err));
};
export const getMyListingsLoadmore = ({
next,
postType,
postStatus
}) => async dispatch => {
return axios
.get("get-my-listings", {
params: {
postType,
postStatus,
page: next,
postsPerPage: POSTS_PER_PAGE
}
})
.then(({ data }) => {
data.status === "success" &&
dispatch({
type: GET_MY_LISTINGS_LOADMORE,
payload: data
});
})
.catch(err => console.log(err));
};
<file_sep>import { SCROLL_TO } from "../constants/actionTypes";
export const scrollTo = (state = -1, action) => {
switch (action.type) {
case SCROLL_TO:
return action.scrollTo;
default:
return state;
}
};
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
TextInput,
InputAccessoryView,
ScrollView,
Keyboard,
UIManager,
Platform
} from "react-native";
const IOS = Platform.OS === "ios";
export default class AccessoryView extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<View style={{ flex: 1 }}>
<ScrollView
keyboardDismissMode="interactive"
keyboardShouldPersistTaps="always"
renderToHardwareTextureAndroid={true}
style={{
flex: 1
}}
>
<TextInput
style={{
padding: 10,
paddingTop: 50
}}
autoCorrect={false}
placeholder="type"
inputAccessoryViewID={"regular"}
/>
</ScrollView>
<InputAccessoryView nativeID={"regular"} style={{ width: "100%" }}>
<View
style={{
height: 200,
backgroundColor: "#fff",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center"
}}
>
<TextInput
style={{
width: "100%"
}}
autoCorrect={false}
autoFocus={true}
multiline={true}
placeholder="type"
/>
</View>
</InputAccessoryView>
</View>
);
}
}
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
TouchableOpacity,
StyleSheet,
ViewPropTypes
} from "react-native";
import { Feather } from "@expo/vector-icons";
import * as Consts from "../../constants/styleConstants";
import stylesBase from "../../stylesBase";
export default class TextBoxColor extends Component {
render() {
return (
<View
style={[this.props.style, { backgroundColor: this.props.colorPrimary }]}
>
<TouchableOpacity activeOpacity={0.5} onPress={this.props.onPress}>
<View style={styles.inner}>
<Feather
name={this.props.iconName}
size={this.props.iconSize}
color={this.props.color}
style={styles.icon}
/>
<Text
style={[stylesBase.h6, { fontSize: 10, color: this.props.color }]}
>
{this.props.text.toUpperCase()}
</Text>
</View>
</TouchableOpacity>
</View>
);
}
}
TextBoxColor.defaultProps = {
iconSize: 26,
color: "#fff",
colorPrimary: Consts.colorPrimary
};
TextBoxColor.propTypes = {
iconSize: PropTypes.number,
color: PropTypes.string,
iconName: PropTypes.string,
colorPrimary: PropTypes.string,
text: PropTypes.string,
onPress: PropTypes.func,
style: ViewPropTypes.style
};
const styles = StyleSheet.create({
inner: {
paddingHorizontal: 10,
paddingVertical: 30,
justifyContent: "center",
alignItems: "center"
},
icon: {
marginBottom: 10
}
});
|
ce240dd44b4ddb131c1f157e735f31728212a90d
|
[
"JavaScript",
"Markdown"
] | 161 |
JavaScript
|
appendly/react-native
|
b2f2def5c81583bd2834e1b687de9920fa4effa9
|
a99d17902f48dc346c05ce6abcdf0300f51d72ed
|
refs/heads/master
|
<file_sep>const express = require('express');
const app = express.Router();
const post = require('../Controllers/postController');
const uploadArray = require('../Middlewares/music');
app.get('/', post.getAllPost);
app.post('/searchPost', post.searchPost);
app.get('/popularPost', post.popularPost);
app.get('/threePopularPost', post.threePopularPost);
app.post('/addPost', uploadArray, post.savePost);
app.delete('/delete/:post_id', post.deletePost);
app.get('/single/:post_id', post.getPostById);
app.get('/:sub_category_id', post.getPosts);
module.exports = app;<file_sep>const mongoose = require('mongoose');
const subCategorySchema = mongoose.Schema({
sub_category_name: {
type: String,
required: [true, 'Sub Category name is required']
},
image:
{
type: String,
required: [true, 'Image is required']
}
},
);
const categorySchema = mongoose.Schema({
category_name: {
type: String,
required: [true, 'Category name is required']
},
image:
{
type: String,
required: [true, 'Image is required']
},
sub_categories: [subCategorySchema],
},
{
timestamps: true
}
);
module.exports = mongoose.model('Category', categorySchema);<file_sep>const User = require('../Models/User');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
var otpGenerator = require('otp-generator');
const nodemailer = require('nodemailer');
const LoginVerification = require('../Models/LoginVerification');
exports.getAllUsers = (req, res) => {
User.find()
.then((result) => {
res.status(200).json({
success: true,
msg: 'Users received',
users: result
});
})
.catch(msg => {
res.status(422).json({
success: false,
msg
});
})
}
exports.getArtists = (req, res) => {
User.find({role: "Artist"})
.then((result) => {
res.status(200).json({
success: true,
msg: 'Users received',
users: result
});
})
.catch(msg => {
res.status(422).json({
success: false,
msg
});
})
}
exports.resetPassword = (req, res) => {
console.log(req.body.email)
if (!req.body.email) {
return res.status(422).json({
success: false,
msg: 'Please enter the email',
});
}
bcrypt.hash(req.body.password, 12, (err, hashPassword) => {
if (err) {
console.log(err)
return res.status(422).json({
success: false,
msg: err
});
}
User.findOneAndUpdate({
email: req.body.email
}, {
password: <PASSWORD>
})
.then(_ => {
res.status(201).json({
success: true,
msg: 'Password resetted'
});
})
.catch(msg => {
res.status(422).json({
success: false,
msg
});
});
})
}
exports.checkOtp = (req, res) => {
LoginVerification.find({
email: req.body.email,
otp: req.body.otp
})
.then(user => {
if (!user || user.length <= 0) {
return res.status(422).json({
success: false,
msg: "Access Denied",
});
}
res.status(200).json({
success: true,
msg: 'User Verified',
email: user.email
});
})
.catch(msg => {
res.status(422).json({
success: false,
msg
});
})
}
exports.forgotPassword = (req, res) => {
const {
email
} = req.body;
if (!email) {
return res.status(422).json({
success: false,
msg: 'Please enter the email',
});
}
User.find({
email: req.body.email
}).then(user => {
if (!user || user.length <= 0) {
return res.status(422).json({
success: false,
msg: "User doesn't exist",
});
}
})
.catch(msg => {
res.status(422).json({
success: false,
msg
});
})
const otp = otpGenerator.generate(6, {
alphabets: true,
upperCase: true,
specialChars: false
});
const loginVerfication = new LoginVerification({
email: req.body.email,
otp: otp
});
loginVerfication.save()
.then(_ => {
let transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: '<EMAIL>',
pass: '<PASSWORD>'
}
});
let mailOptions = {
from: "<<EMAIL>>",
to: req.body.email,
subject: 'OTP ',
text: `OTP to create new password:-${otp}`,
// html: '<b>Hello World</b>'
}
transporter.sendMail(mailOptions)
.then(info => {
res.status(201).json({
success: true,
msg: 'OTP sent to your Email id',
});
})
.catch(msg => {
res.status(422).json({
success: false,
msg
});
});
}).catch(msg => {
res.status(422).json({
success: false,
msg
});
});
}
exports.saveUser = (req, res) => {
const {
email,
password
} = req.body;
if (!email) {
return res.status(422).json({
success: false,
msg: 'Please enter the email',
});
}
User.find({
email: email
})
.then(user => {
if (user.length >= 1) {
return res.status(422).json({
success: false,
msg: 'User already exist'
});
} else if (!password) {
return res.status(422).json({
success: false,
msg: 'Password not found'
});
}
bcrypt.hash(password, 12, (err, hashPassword) => {
if (err) {
return res.status(422).json({
success: false,
msg: err
});
}
const user = new User({
...req.body,
password: <PASSWORD>,
});
user.save()
.then(_ => {
res.status(201).json({
success: true,
msg: 'User saved'
});
})
.catch(msg => {
res.status(422).json({
success: false,
msg
});
});
})
})
}
exports.loginUser = (req, res) => {
const {
email,
password,
} = req.body;
if (!email) {
console.log(req.body.email)
return res.status(422).json({
success: false,
msg: 'Access Denied'
});
}
User.findOne({
email: email
}).then(user => {
if (!user || user.length > 1) {
return res.status(422).json({
success: false,
msg: 'Access Denied'
});
} else {
bcrypt.compare(password, user.password, (err, result) => {
if (err) {
return res.status(422).json({
success: false,
msg: err
});
} else if (result) {
const token = jwt.sign({
email: email,
userId: user._id,
role: user.role
}, "324324ui24hkb2k4b231k4k12kkfbdkbi24bib21", {
expiresIn: '1d'
});
return res.status(200).json({
success: true,
msg: 'Auth successful',
access_token: token,
role: user.role,
});
} else {
return res.status(422).json({
success: false,
msg: 'Access Denied'
});
}
})
}
})
}
exports.artistLogin = (req, res) => {
const {
email,
password,
} = req.body;
if (!email) {
console.log(req.body.email)
return res.status(422).json({
success: false,
msg: 'Access Denied'
});
}
User.findOne({
email: email , role : "Artist"
}).then(user => {
if (!user || user.length > 1 || user === null) {
return res.status(422).json({
success: false,
msg: 'Access Denied'
});
} else {
bcrypt.compare(password, user.password, (err, result) => {
if (err) {
return res.status(422).json({
success: false,
msg: err
});
} else if (result) {
const token = jwt.sign({
email: email,
userId: user._id,
role: user.role
}, "<PASSWORD>", {
expiresIn: '1d'
});
return res.status(200).json({
success: true,
msg: 'Auth successful',
access_token: token,
role: user.role,
});
} else {
return res.status(422).json({
success: false,
msg: 'Access Denied'
});
}
})
}
})
}<file_sep>const express = require('express');
const app = express.Router();
const category = require('../Controllers/categoryController');
const uploadFile = require('../Middlewares/file');
const uploadArray = require('../Middlewares/music');
app.get('/', category.getAllCategories);
app.post('/addCategory', uploadFile, category.saveCategory);
app.post('/edit/:category_id', uploadFile, category.editCategory);
app.get('/getAllSubCategories', uploadArray, category.getAllSubCategories);
app.post('/addSubCategory', uploadArray, category.saveSubCategory);
app.get('/:category_id', category.getSubCategoryById);
app.post('/editSubCategory/:sub_category_id', uploadFile, category.editSubCategory);
module.exports = app;<file_sep>const multer = require('multer');
const GET_EXT = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/jpg': 'jpg'
};
let img = "";
let error;
const config = multer.diskStorage({
destination: (req, file, cb) => {
let erAuthenticateRequestr = "";
if (!(GET_EXT[file.mimetype]))
error = new Error("Image not detected");
cb(error, 'images');
},
filename: (req, file, cb) => {
const filename = file.originalname.split(".");
const ext = GET_EXT[file.mimetype];
img = filename[0] + Date.now() + "." + ext;
cb(null, img);
}
});
module.exports = multer({ storage: config }).single('image')<file_sep>const mongoose = require('mongoose');
const postSchema = mongoose.Schema({
post_name: {
type: String,
required: [true, 'Post name is required']
},
is_active: {
type: Boolean,
default: true
},
image: {
type: String,
required: [true, 'image is required']
},
category_id: {
type: mongoose.Schema.ObjectId,
ref: 'Category',
required: [true, 'Category Id is required']
},
sub_category_id: {
type: mongoose.Schema.ObjectId,
required: [true, 'Sub Category Id is required']
},
views: {
type: String,
default: "0"
},
price: {
type: String,
default: "0"
},
file_type: {
type: String,
default: "image"
}
}, {
timestamps: true
});
// postSchema.index({post_name: 'text', 'post_name':'text'});
// postSchema.index({'$**': 'text'});
module.exports = mongoose.model('Post', postSchema);<file_sep>const express = require('express');
const app = express.Router();
const user = require('../Controllers/userController');
app.get('/', user.getAllUsers);
app.post('/artists/login', user.artistLogin);
app.get('/artists', user.getArtists);
app.post('/signup', user.saveUser);
app.post('/login', user.loginUser);
app.post('/forgot', user.forgotPassword);
app.post('/checkotp', user.checkOtp);
app.post('/resetpassword', user.resetPassword);
module.exports = app;
|
5889bb2b3781f201eab015e9ee345f8b8f6b86e7
|
[
"JavaScript"
] | 7 |
JavaScript
|
joravkumar/hackathon_api
|
5bdfc14b933e5899499a21761632e1f3d20db2c4
|
e9426232f1c02531d1172dde9bffde283ddf357a
|
refs/heads/master
|
<repo_name>braveheuel/prniotlet<file_sep>/extra/get_and_parse.sh
#! /bin/sh
#
# get_and_parse.sh
# Copyright (C) 2017 ch <<EMAIL>>
#
# Distributed under terms of the MIT license.
#
DOKPATH="$HOME/Dokumente/advent/2017"
if [ -z "$1" ]
then
START=1
else
START=$1
fi
mkdir -p out/
wget --http-user=ch --ask-password https://www.heuel-web.de/owncloud/remote.php/dav/calendars/ch/adventskalender?export -O calendar.ics
if [ -f calendar.ics ]
then
./parseICS.py --start $START calendar.ics "$DOKPATH"
rsync -avze ssh $DOKPATH/ raspberrypi:$DOKPATH/
else
echo "Error Retrieving Calendar!"
exit 1
fi
<file_sep>/scripts/prniotlet-text
#!/usr/bin/env python3
#
"""Print Text through python-escpos"""
from escpos import printer
import click
import asyncio
import prniotlet
@click.command()
@click.option("--caption", required=False)
@click.option("--text", required=True)
@click.option("--center/--no-center", default=True)
@click.option("--blocktext/--no-blocktext", default=True)
def print_data(text, caption, center, blocktext):
"""Print the specified data
:param caption: Title
:param text: Text to print
"""
escpos_printer = prniotlet.PrnIOTlet()
escpos_printer.proxy.hw("init")
if caption:
escpos_printer.proxy.set(align="center", bold=True, width=2, height=2)
escpos_printer.proxy.block_text(caption, columns=16)
escpos_printer.proxy.print_and_feed(1)
escpos_printer.proxy.print_and_feed()
escpos_printer.proxy.set(align="center" if blocktext else "left", bold=False, width=1, height=1)
if blocktext:
escpos_printer.proxy.block_text(text, font='a', columns=16)
else:
escpos_printer.proxy.text(text)
escpos_printer.proxy.print_and_feed(4)
escpos_printer.final_print()
if __name__ == "__main__":
print_data()
<file_sep>/prniotlet/__init__.py
import aiomas
import asyncio
from escpos import printer
import configparser
from xdg import BaseDirectory
import os
class PrnIOTlet:
def __init__(self, cfg_file=None):
self.proxy = printer.Dummy()
self.config = configparser.ConfigParser()
if cfg_file:
self.config.read(cfg_file)
else:
self.config.read(os.path.join(BaseDirectory.xdg_config_home, "prniotlet", "config"))
async def _final_print(self):
rpc_con = await aiomas.rpc.open_connection((self.config["connection"]["host"],
self.config.getint("connection", "port", fallback=5555)),
codec=aiomas.MsgPack)
try:
session = await rpc_con.remote.start_session()
await rpc_con.remote.raw_data(session, self.proxy.output)
await rpc_con.remote.final_print(session)
self.proxy.clear()
except Exception as e:
print("Error occurred!", e)
finally:
await rpc_con.remote.close_session(session)
await rpc_con.close()
def final_print(self):
aiomas.run(self._final_print())
<file_sep>/scripts/prniotlet-party
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 ch <<EMAIL>>
#
# Distributed under terms of the MIT license.
"""
Print party gag after keypress
"""
from escpos import *
from PIL import Image
import subprocess
import pigpio
import logging
import prniotlet
print_width = 384
printer_file = "/dev/usb/lp0"
logo = "/home/ch/Bilder/party-logo.png"
underline = "/home/ch/Bilder/underline.png"
TASTER = 4
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
def Umlaut_toASCII(s):
s = s.replace('ä', "ae")
s = s.replace('Ä', "Ae")
s = s.replace('ö', "oe")
s = s.replace('Ö', "Oe")
s = s.replace('ü', "ue")
s = s.replace('Ü', "Ue")
s = s.replace('ß', "ss")
return s
def print_note(ep, header, footer):
logging.info("Call fortune...")
fortprocess = subprocess.Popen("fortune -e /home/ch/Dokumente/fortune/ruhrpott /home/ch/Dokumente/fortune/ruhrpott-trilogie", stdout=subprocess.PIPE, shell=True)
(output, err) = fortprocess.communicate()
## Wait for date to terminate. Get return returncode ##
p_status = fortprocess.wait()
logging.info("fortune finished")
if p_status == 0:
ep.hw("init")
logging.debug("Printing header...")
ep.image(header)
ep.text("\n")
text = Umlaut_toASCII(output.decode("utf-8"))
logging.info("Printing text")
ep.block_text(text)
ep.text("\n")
logging.debug("Printing footer")
ep.image(footer)
ep.text("\n\n\n\n")
ep.flush()
logging.info("Printing finished")
else:
ep.text("Fehler: Kein Spruch verfuegbar")
ep.text("\n\n\n\n")
def main():
"""Main Function"""
logging.info("Starting... Loading Logo...")
img = Image.open(logo)
logging.info("Loading footer...")
img_underline = Image.open(underline)
ep = printer.File(printer_file)
pi = pigpio.pi()
pi.set_mode(TASTER, pigpio.INPUT)
logging.info("Going into loop...")
while True:
if pi.wait_for_edge(TASTER):
logging.info("Taster was pressed!")
print_note(ep, img, img_underline)
else:
logging.info("wait_for_edge timeout occurred.")
logging.debug("Left the loop!")
if __name__ == "__main__":
main()
<file_sep>/README.md
# PRNIoTlet
This project should result in small python scripts, which use a thermo printer to print out different information/images etc.
The main entry point is the prniotlet-server. The server offers the
functionality to print raw data. You have to request a session id before starting to print.
To print all at once, you can use the class PrnIOTlet. This sets up a dummy printer class. When you are finished with composing the print, you can call the final printing, which will send the whole data at once to the print-server.
<file_sep>/extra/parseICS.py
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 cheuel <<EMAIL>>
"""
Adventskalendar Parser
"""
import icalendar
import click
from os import path
def write_file(day, directory, text):
if text:
with open(path.join(directory, "{0}.txt".format(day)), 'wb') as txtfile:
txtfile.write(text.encode(encoding='UTF-8'))
def handle_event(x, lower_limit, directory):
a_day = x['dtstart'].dt.day
if a_day >= lower_limit:
a_summary = x['summary']
if 'DESCRIPTION' in x:
a_description = x['description']
else:
a_description = None
if 'location' in x:
a_loc = x['location']
else:
a_loc = None
print("{0}: {1}\n{2}\n{3}".format(a_day, a_summary, a_description, a_loc))
print("------------------------")
write_file(a_day, directory, a_description)
@click.command()
@click.argument("icsfile", type=click.File('rb'))
@click.argument("directory", type=click.Path(exists=True))
@click.option("--start", default=1)
def main(icsfile, directory, start):
ics = icalendar.Calendar.from_ical(icsfile.read())
for i in ics.walk():
if type(i) == icalendar.Event:
handle_event(i, start, directory)
if __name__ == "__main__":
main()
<file_sep>/scripts/prniotlet-server
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 ch <<EMAIL>>
#
# Distributed under terms of the MIT license.
"""
aimoas print server
"""
from escpos import printer, config
import aiomas
import uuid
import time
class SessionException(Exception):
"""
Exception Class showing another that an other session is active/in use
"""
pass
class PrnIOLetSession(object):
"""
Class for Session Objects
"""
def __init__(self):
self._session_string = uuid.uuid4().__str__()
self._timestamp = time.time()
def is_active(self):
"""
Returns if a session is active. This means, that the delta is smaller
than 180 secs
"""
return ((time.time() - self._timestamp) <= 3*60)
def is_same(self, session_id):
"""
Compare session string with internal
"""
return self._session_string == session_id
def update(self):
"""
Update timestamp
"""
self._timestamp = time.time()
def __str__(self):
"""
Return Session String
"""
return self._session_string
class ESCPOSServer(printer.Dummy):
router = aiomas.rpc.Service()
printer_real = config.Config().printer()
active_session = None
def __init__(self):
super().__init__()
@aiomas.expose
def start_session(self):
"""
Start a Session for the server. If a session is active, no other
requests can be done
"""
if not ESCPOSServer.active_session:
ESCPOSServer.active_session = PrnIOLetSession()
print("Starting Session ", ESCPOSServer.active_session)
return str(ESCPOSServer.active_session)
elif not ESCPOSServer.active_session.is_active():
print("Session expired ", ESCPOSServer.active_session)
ESCPOSServer.active_session = PrnIOLetSession()
print("Starting Session ", ESCPOSServer.active_session)
return str(ESCPOSServer.active_session)
else:
raise SessionException("Another Session is active")
@aiomas.expose
def close_session(self, session_id):
"""
Close a existing session
"""
if ESCPOSServer.active_session.is_same(session_id) or not ESCPOSServer.active_session.is_active():
print("Closing Session ", ESCPOSServer.active_session)
ESCPOSServer.active_session = None
self._output_list.clear()
else:
print("Wrong Session:", session_id, "Active One:",
ESCPOSServer.active_session)
raise SessionException("Wrong Session")
@aiomas.expose
def raw_data(self, session_id, msg):
"""
Print raw data to the Dummy Device
"""
if ESCPOSServer.active_session.is_same(session_id):
print("Receiving Raw Data")
super()._raw(msg)
ESCPOSServer.active_session.update()
else:
print("Wrong Session:", session_id, "Active One:",
ESCPOSServer.active_session)
raise SessionException("Wrong Session")
@aiomas.expose
def final_print(self, session_id):
"""
Print to the actual server
"""
if ESCPOSServer.active_session.is_same(session_id):
print("Printing...")
ESCPOSServer.printer_real._raw(self.output)
self._output_list.clear()
ESCPOSServer.active_session.update()
else:
print("Wrong Session:", session_id, "Active One:",
ESCPOSServer.active_session)
raise SessionException("Wrong Session")
if __name__ == "__main__":
server = aiomas.run(aiomas.rpc.start_server(('0.0.0.0', 5555),
ESCPOSServer(),
codec=aiomas.codecs.MsgPack))
aiomas.run(server.wait_closed())
<file_sep>/scripts/prniotlet-xkcd
#!/usr/bin/env python3
#
"""Print xkcd comics through python-escpos"""
import requests
from lxml import html
import argparse
import os
import io
from PIL import Image
import shutil
import pickle
import qrcode
import asyncio
import prniotlet
CACHE_DIR = os.path.expanduser("~") + "/.cache/xkcd/"
PICKLE_FILENAME = "data.pickle"
PRINT_WIDTH = 384
class XkcdDataStructure(object):
"""Datastructure for pickling"""
description = None
name = None
image_source = None
instance = None
directory = None
image = None
def get_image(self):
"""Return image data
:returns: PIL image data
"""
if self.image:
return Image.frombytes(**self.image)
def set_image(self, image):
"""Set the Image data"""
self.image = dict(
data=image.tobytes(),
size=image.size,
mode=image.mode
)
def load(number="", overwrite=False):
"""Download a comic from website
:param number: Specified number to download. Default: empty
:param overwrite: Set this to re-download the a comic
:returns: tuple of meta_data and bolean value if new
"""
response = requests.get('http://xkcd.com/{0!s}'.format(number))
parsed_body = html.fromstring(response.text)
meta_data = XkcdDataStructure()
meta_data.description = parsed_body.xpath(
'//*[@id="comic"]//img/@title')[0].__str__()
meta_data.name = parsed_body.xpath(
'//*[@id="comic"]//img/@alt')[0].__str__()
meta_data.image_source = "http:{0!s}".format((parsed_body.xpath(
'//*[@id="comic"]//img/@src')[0]))
meta_data.instance = os.path.split(
os.path.splitext(meta_data.image_source)[0])[1]
meta_data.directory = "{0!s}{1!s}".format(CACHE_DIR, meta_data.instance)
is_new = True
if os.path.isdir(meta_data.directory) and overwrite:
print("Already downloaded {0!s}, removing first...".format(meta_data.instance))
shutil.rmtree(meta_data.directory)
if os.path.isdir(meta_data.directory):
print("Already downloaded: {0!s}".format(meta_data.instance))
print("Using pickled variant")
meta_data = _load_from_file(meta_data.directory)
is_new = False
else:
os.makedirs(meta_data.directory)
image = _download_image(meta_data)
_convert_image(image, meta_data)
_save_meta_data(meta_data)
return (meta_data, is_new)
def _save_meta_data(data):
"""Save the data to a file
:param data: data to be written to file
"""
with open("{0!s}{1!s}{2!s}".format(data.directory, os.sep, PICKLE_FILENAME),
"wb") as outfile:
pickle.dump(data, outfile)
def _convert_image(image, data):
"""Convert specified image
:param image: Image to edit
:param data: data to edit
"""
# Rotate if width > height (always have stripe)
if image.size[0] > image.size[1]:
image = image.rotate(270, expand=1)
# Resize
if image.size[0] <= 1.5*PRINT_WIDTH:
ratio = float(PRINT_WIDTH) / float(image.size[0])
new_height = int(float(image.size[1])*float(ratio))
image = image.resize((PRINT_WIDTH, new_height))
else:
# Create QR code
qr = qrcode.QRCode()
qr.add_data(data.image_source)
image = qr.make_image(size=PRINT_WIDTH)._img
image = image.resize((PRINT_WIDTH, PRINT_WIDTH))
# Dither
converted_image = image.convert("1", dither=Image.FLOYDSTEINBERG)
converted_image.save("{0!s}{1!s}{2!s}".format(data.directory, os.sep,
"converted.png"), "PNG")
data.set_image(converted_image)
def _download_image(data):
"""Retrieve image
:param data: Specified data to download
:returns: Downloaded image
:raises Exception: Raised if request can't be done.
"""
print("Downloading image...")
url2retrieve = data.image_source
requested = requests.get(url2retrieve)
if not requested.status_code == 200:
raise Exception("Could not retrieve image! Status code {0:d}".format(
requested.status_code))
raw_image = Image.open(io.BytesIO(requested.content))
raw_image.save("{0!s}{1!s}{2!s}".
format(data.directory, os.sep, "image.png"), "PNG")
return raw_image
def _load_from_file(path):
"""Load pickeled data from file
:param path: Filename to load from
:returns: Data retrieved from pickle file
"""
with open("{0!s}{1!s}{2!s}".format(path, os.sep,
PICKLE_FILENAME), "rb") as infile:
pckl = pickle.load(infile)
return pckl
def print_data(data):
"""Print the specified data
:param data: Data to print
"""
escpos_printer = prniotlet.PrnIOTlet()
escpos_printer.proxy.hw("init")
escpos_printer.proxy.set(align="center", bold=True)
escpos_printer.proxy.block_text(data.name, columns=16)
escpos_printer.proxy.text("\n")
escpos_printer.proxy.set(align="left", bold=False)
escpos_printer.proxy.image(data.get_image())
escpos_printer.proxy.text("\n")
escpos_printer.proxy.block_text(data.description, columns=32)
escpos_printer.proxy.print_and_feed(4)
escpos_printer.final_print()
if __name__ == "__main__":
if not os.path.exists(CACHE_DIR):
os.makedirs(CACHE_DIR)
parser = argparse.ArgumentParser(
description='Load image and description of xkcd')
parser.add_argument('comic_number',
metavar="number",
type=str,
help="Number of comic to load",
default="", nargs="*")
parser.add_argument('-f', '--overwrite',
action='store_true',
help="Overwrite if already exists")
parser.add_argument('-p', '--print_if_new',
action='store_true',
help="Print only if new")
args = parser.parse_args()
(data, new_comic) = load("" if args.comic_number == ""
else args.comic_number[0], args.overwrite)
if (new_comic and args.print_if_new) or not args.print_if_new:
print_data(data)
else:
print("Not printing, because of argument print_if_new")
<file_sep>/scripts/prniotlet-wlan
#!/usr/bin/env python3
#
"""Print QR-Code for WLAN through python-escpos"""
from escpos import printer
import click
import asyncio
import prniotlet
def wlanQR_prn(prn, ssid, security):
prn.proxy.qr("WIFI:S:{0}:T:WPA:P:{1};;".format(ssid, security), size=12)
@click.command()
@click.option("--ssid", required=True)
@click.option("--security", required=True)
def print_data(ssid, security):
"""Print the specified data
:param ssid: SSID of the WLAN
:param security: Security of that WLAN
"""
escpos_printer = prniotlet.PrnIOTlet()
escpos_printer.proxy.hw("init")
escpos_printer.proxy.set(align="center", bold=True, width=2, height=2)
escpos_printer.proxy.block_text(ssid, columns=16)
escpos_printer.proxy.print_and_feed(1)
wlanQR_prn(escpos_printer, ssid, security)
escpos_printer.proxy.print_and_feed()
escpos_printer.proxy.set(align="center", bold=False, width=1, height=1)
escpos_printer.proxy.text("Key:\n")
escpos_printer.proxy.block_text(security, font='a', columns=16)
escpos_printer.proxy.print_and_feed(4)
escpos_printer.final_print()
if __name__ == "__main__":
print_data()
<file_sep>/scripts/prniotlet-advent
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 ch <<EMAIL>>
#
# Distributed under terms of the MIT license.
"""
Print party gag after keypress
Usage:
advent.py [<day>]
"""
from escpos import printer
from PIL import Image
import logging
from datetime import date
import pathlib
import click
import aiomas
import asyncio
import os
import pickle
PRINT_WIDTH = 384
DOCUMENT_ROOT = "/home/ch/Dokumente/advent"
PICKLE_FILE = os.path.join(DOCUMENT_ROOT, ".days.pckl")
TASTER = 4
START_DATE = date(2017, 12, 1)
END_DATE = date(2017, 12, 24)
ESCPOS_PRINTER = printer.Dummy()
logging.basicConfig(format='%(message)s', level=logging.INFO)
def load_daylog():
"""Loads pickled day data from file"""
returnval = {}
if os.path.isfile(PICKLE_FILE):
try:
with open(PICKLE_FILE, "rb") as pf:
returnval = pickle.load(pf)
except:
logging.warning("Could not load pickle file, starting empty!")
returnval = {}
return returnval
def save_daylog(daylog):
"""Save the daylog"""
with open(PICKLE_FILE, "wb") as pf:
pickle.dump(daylog, pf)
def daycount(daylog):
if date.today() in daylog:
return daylog[date.today()]
return 0
def inc_day(daylog):
"""Increase the Daycount by one.
If the day is not contained, it will be one"""
daylog[date.today()] = daycount(daylog) + 1
save_daylog(daylog)
def umlaut_to_ASCII(text):
"""Replace umlaut with ascii compliant chars
:param text: String to replace
:returns: text with replaced characters
"""
text = text.replace('ä', "ae")
text = text.replace('Ä', "Ae")
text = text.replace('ö', "oe")
text = text.replace('Ö', "Oe")
text = text.replace('ü', "ue")
text = text.replace('Ü', "Ue")
text = text.replace('ß', "ss")
return text
def print_advent_day(daylog):
"""Evaluate if print date is in date range"""
if date.today() < START_DATE:
logging.info("Too early!")
ESCPOS_PRINTER.hw("init")
ESCPOS_PRINTER.text("\nZu frueh gedrueckt!")
ESCPOS_PRINTER.text("\n\n\n\n")
elif date.today() > END_DATE:
logging.info("Too late!")
ESCPOS_PRINTER.hw("init")
ESCPOS_PRINTER.text("\nZu spaet gedrueckt!")
ESCPOS_PRINTER.text("\n\n\n\n")
elif daycount(daylog) > 0:
counter = daycount(daylog)
logging.info("Button pressed already: %d", counter)
ESCPOS_PRINTER.hw("init")
ESCPOS_PRINTER.text("\nTaste schon {0} mal gedrueckt!".format(counter))
ESCPOS_PRINTER.text("\n\n\n\n")
inc_day(daylog)
else:
print_day(date.today().day)
inc_day(daylog)
aiomas.run(_final_print())
def print_day(advent_day):
"""Print specified day
:param advent_day: Number of date to print
"""
logging.info("Starting with advent day %s", advent_day)
img = Image.open("{0}/{1}/{2}.png".format(
DOCUMENT_ROOT, date.today().year, advent_day
)
)
ESCPOS_PRINTER.image(img)
ESCPOS_PRINTER.text("\n")
filename = "{0}/{1}/{2}.txt".format(
DOCUMENT_ROOT, date.today().year, advent_day
)
if pathlib.Path(filename).exists():
text_file = open(filename, 'r')
logging.info("Reading text...")
lines = text_file.readlines()
for i in lines:
if i == "\n":
ESCPOS_PRINTER.text("\n")
else:
ESCPOS_PRINTER.block_text(
umlaut_to_ASCII(i), font='a', columns=32
)
ESCPOS_PRINTER.text("\n")
text_file.close()
logging.info("Printing text done.")
else:
logging.info("No text found!")
ESCPOS_PRINTER.text("\n\n\n\n")
logging.info("Printing done.")
async def _final_print():
rpc_con = await aiomas.rpc.open_connection(('raspberrypi', 5555), codec=aiomas.MsgPack)
try:
session = await rpc_con.remote.start_session()
await rpc_con.remote.raw_data(session, ESCPOS_PRINTER.output)
await rpc_con.remote.final_print(session)
del ESCPOS_PRINTER._output_list[:]
except Exception as e:
print("Error occurred!", e)
finally:
await rpc_con.remote.close_session(session)
await rpc_con.close()
@click.command()
@click.option("--day")
def main(day):
"""Main Function
:param args: Arguments found by docopt
"""
logging.info("Starting...")
if day:
print_day(day)
aiomas.run(_final_print())
else:
daylog = load_daylog()
import pigpio
pi_instance = pigpio.pi()
pi_instance.set_mode(TASTER, pigpio.INPUT)
logging.info("Going into loop...")
while True:
if pi_instance.wait_for_edge(TASTER):
logging.info("Taster was pressed!")
print_advent_day(daylog)
logging.debug("Left the loop!")
if __name__ == "__main__":
main()
<file_sep>/setup.py
#! /usr/bin/env python3
from setuptools import setup
setup(
name="prniotlet",
version="0.2.1",
author="<NAME>",
author_email="<EMAIL>",
license="MIT",
install_requires=['python-escpos', 'aiomas[mp]', 'click'],
packages=setuptools.find_packages(),
scripts=[
'scripts/prniotlet-server', 'scripts/prniotlet-xkcd',
'scripts/prniotlet-wlan', 'scripts/prniotlet-advent',
'scripts/prniotlet-text',
],
)
|
e88be956c99ace4f3ca2930e11e5ad5e32c01f14
|
[
"Markdown",
"Python",
"Shell"
] | 11 |
Shell
|
braveheuel/prniotlet
|
86eb56a1ab0841a84637e4b8f61ee4820c052855
|
c529789f148542c8e335448cd08b90dd51efdc02
|
refs/heads/master
|
<repo_name>PhilipYordanov/BookstoreService<file_sep>/BookstoreService/BookstoreService/Entities/Cart.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BookstoreService.Entities
{
public class Cart
{
public int CartID { get; set; }
public string UserID { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime LastModification { get; set; }
public bool IsPaid { get; set; }
public int? PaymentMethodID { get; set; }
public int? DeliveryOptionID { get; set; }
public virtual PaymentMethod PaymentMethod { get; set; }
public virtual DeliveryOption DeliveryOption { get; set; }
public virtual ICollection<CartBook> Books { get; set; } = new List<CartBook>();
}
}
<file_sep>/BookstoreService/BookstoreService/Services/IBooksService.cs
using System.Collections.Generic;
using BookstoreService.Entities;
using System.ServiceModel;
namespace BookstoreService.Services
{
[ServiceContract(Namespace = "http://unwe.bg")]
public interface IBooksService
{
[OperationContract]
IEnumerable<Book> GetAllBooks();
[OperationContract]
IEnumerable<Category> GetAllCategories();
[OperationContract(Name = "GetBooksByCategoryId")]
IEnumerable<Book> GetBooksByCategory(int categoryId);
[OperationContract]
IEnumerable<Book> GetBooksByCategory(Category category);
[OperationContract]
Book GetBook(int id);
[OperationContract]
Book GetBookByISBN(string isbn);
[OperationContract]
IEnumerable<ExternalBook> GetSimilarBooks(int id);
[OperationContract]
Book CreateBook(Book book);
[OperationContract]
Book UpdateBook(Book book);
[OperationContract]
void RemoveBook(int bookId);
}
}
<file_sep>/BookstoreService/BookstoreConsole/Program.cs
using BookstoreService.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BookstoreConsole
{
class Program
{
static void Main(string[] args)
{
var service = new BooksService();
var allBooks = service.GetAllBooks();
foreach (var b in allBooks)
{
Console.WriteLine($"Book: {b.Title} - Price: {b.Price} - Category: {b.Category.Name}");
}
var fantasyBooks = service.GetBooksByCategory(1);
Console.WriteLine();
Console.WriteLine("Fantasy Books: ");
foreach (var b in fantasyBooks)
{
Console.WriteLine($"Book: {b.Title} - Price: {b.Price}");
}
Console.Read();
}
}
}
<file_sep>/BookstoreService/BookstoreService/Entities/ExternalBook.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BookstoreService.Entities
{
public class ExternalBook
{
public string Title { get; set; }
public string Publisher { get; set; }
public string Link { get; set; }
public string ISBN { get; set; }
}
}
<file_sep>/BookstoreService/BookstoreWebForms/CartPay.aspx.cs
using BookstoreWebForms.CartService;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace BookstoreWebForms
{
public partial class CartPay : System.Web.UI.Page
{
private const string _ePayClientID = "D165763063";
private const string _secretEPayKey = "<KEY>";
private CartServiceClient cs = new CartServiceClient();
protected string _encoded;
protected string _checksum;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) //подготвяме заявка към ePay
{
if (!User.Identity.IsAuthenticated)
{
Response.Redirect("~/Account/Login.aspx");
Response.End();
return;
}
var cart = (CartService.Cart)Session["cart"];
if (cart == null)
{
cart = cs.CreateCart(User.Identity.GetUserId());
Session["cart"] = cart;
}
int cartId = ((CartService.Cart)Session["cart"]).CartID;
cart = cs.GetCart(cartId);
decimal sum = cart.Books.Sum(x => x.Book.Price * x.Quantity);
string request = $"MIN={_ePayClientID}\r\n"
+ $"INVOICE={1000 + cart.CartID}\r\n"
+ $"AMOUNT={sum.ToString("G")}\r\n"
+ "CURRENCY=BGN\r\n"
+ $"EXP_TIME={DateTime.Now.AddDays(2).ToString("dd.MM.yyyy")}\r\n"
+ "DESCR=Buying books";
_encoded = Convert.ToBase64String(Encoding.ASCII.GetBytes(request));
_checksum = HMACSHA1(_encoded, _secretEPayKey);
}
else //получаваме потвърждение от ePay
{
string encoded = Request.Form["ENCODED"];
string checksum = Request.Form["CHECKSUM"];
if (checksum != HMACSHA1(encoded, _secretEPayKey))
{
//невалиден отговор
}
else
{
//обработваме статуса на плащането
//обикновен стринг като например: "INVOICE=1230001:STATUS=PAID:PAY_TIME=YYYYMMDDhhmmss:STAN=[6 числа]:BCODE=[6 числа/букви]"
string decoded = Encoding.ASCII.GetString(Convert.FromBase64String(encoded));
string[] kvPairs = decoded.Split(':');
string invoice = "", status = "";
foreach (var pair in kvPairs)
{
string[] kv = pair.Split('=');
switch (kv[0])
{
case "INVOICE":
invoice = kv[1];
break;
case "STATUS":
status = kv[1];
break;
}
}
//изпращаме заявка към сървис-а със статуса на плащането...
//...
//ако всичко е наред, връщаме ОК, за да не получаваме повече известия за това плащане
Response.Write($"INVOICE={invoice}:STATUS=OK");
Response.End();
}
}
}
private string HMACSHA1(string text, string secretkey)
{
byte[] byteArray = Encoding.ASCII.GetBytes(text);
byte[] key = Encoding.ASCII.GetBytes(secretkey);
using (var h = new HMACSHA1(key))
{
var hashArray = h.ComputeHash(byteArray);
var result = new StringBuilder();
foreach (var b in hashArray)
{
result.Append(b.ToString("X2"));
}
return result.ToString();
}
}
}
}<file_sep>/BookstoreService/BookstoreDesktop/EditBook.cs
using BookstoreDesktop.BookstoreService;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BookstoreDesktop
{
public partial class EditBook : Form
{
private readonly BooksServiceClient _service = new BooksServiceClient();
private int _selectedBookID;
private Book _selectedBook;
private IList<Book> _allBooks;
public EditBook()
{
InitializeComponent();
}
public EditBook(int selectedBookID)
{
_selectedBookID = selectedBookID;
_allBooks = _service.GetAllBooks().ToList();
_selectedBook = _service.GetBook(_selectedBookID);
InitializeComponent();
}
private void EditBook_Load(object sender, EventArgs e)
{
var categories = _service.GetAllCategories();
categoryBindingSource.DataSource = categories;
bookBindingSource.DataSource = _allBooks;
bookBindingSource.Position = _allBooks.IndexOf(_selectedBook);
UpdateInfo();
}
private void bookBindingSource_PositionChanged(object sender, EventArgs e)
{
UpdateInfo();
}
private void UpdateInfo()
{
_selectedBook = _service.GetBook(((Book)bookBindingSource.Current).BookID);
categoryIDComboBox.SelectedValue = 0;
categoryIDComboBox.SelectedValue = _selectedBook.CategoryID;
if (_selectedBook.Cover != null)
{
coverPictureBox.Image = Image.FromStream(new MemoryStream(_selectedBook.Cover));
coverPictureBox.Refresh();
}
}
}
}
<file_sep>/BookstoreService/BookstoreService/Services/CartService.cs
using BookstoreService.Entities;
using System.Data.SqlClient;
using System.Configuration;
using Dapper;
using System;
using System.Linq;
using System.Collections.Generic;
namespace BookstoreService.Services
{
public class CartService : ICartService
{
private readonly SqlConnection db;
public CartService()
{
db = new SqlConnection(ConfigurationManager.ConnectionStrings["bookstore"].ConnectionString);
}
public bool AddToCart(int cartId, int bookId)
{
int affected = db.Execute("UPDATE CartBooks SET Quantity=Quantity+1 WHERE CartID=@cartid AND BookID=@bookid", new { cartid = cartId, bookid = bookId });
if (affected == 0)
{
return db.Execute("INSERT INTO CartBooks (CartID,BookID,Quantity) VALUES (@cartid,@bookid,@quantity)", new
{
cartid = cartId,
bookid = bookId,
quantity = 1
}) > 0;
}
else return true;
}
public Cart CreateCart(string userId)
{
int newCartId = db.ExecuteScalar<int>("INSERT INTO Carts (UserID) VALUES (@userid); SELECT CAST(SCOPE_IDENTITY() as int)", new { userid = userId });
return GetCart(newCartId);
}
public Cart GetCart(int cartId)
{
var cart = db.QuerySingle<Cart>("SELECT CartID,UserID,CreatedOn,LastModification,IsPaid,PaymentMethodID,DeliveryOptionID FROM Carts WHERE CartID=@cartid", new { cartid = cartId });
cart.PaymentMethod = db.QuerySingleOrDefault<PaymentMethod>("SELECT * FROM PaymentMethods WHERE PaymentMethodID=@id", new { id = cart.PaymentMethodID });
cart.DeliveryOption = db.QuerySingleOrDefault<DeliveryOption>("SELECT * FROM DeliveryOptions WHERE DeliveryOptionID=@id", new { id = cart.DeliveryOptionID });
cart.Books = db.Query<CartBook, Book, CartBook>("SELECT cb.CartID,cb.AddedOn,cb.Quantity,b.BookID,Title,Year,Price,ISBN,Description,CategoryID FROM CartBooks cb INNER JOIN Books b ON b.BookID=cb.BookID WHERE cb.CartID=@id",
(cb, b) => { cb.BookID = b.BookID; cb.Book = b; return cb; },
new { id = cart.CartID },
splitOn: "BookID")
.ToList();
return cart;
}
public bool Purchase(int cartId)
{
throw new NotImplementedException();
}
public bool RemoveFromCart(int cartId, int bookId)
{
return db.Execute("DELETE FROM CartBooks WHERE CartID=@cartid AND BookID=@bookid", new
{
cartid = cartId,
bookid = bookId
}) > 0;
}
public bool SetDeliveryOptions(int cartId, DeliveryOption options)
{
return db.Execute("UPDATE Carts SET DeliveryOptionID=@doid WHERE CartID=@cartid", new { cartid = cartId, doid = options.DeliveryOptionID }) > 0;
}
public bool SetPaymentMethod(int cartId, PaymentMethod method)
{
return db.Execute("UPDATE Carts SET PaymentMethodID=@pmid WHERE CartID=@cartid", new { cartid = cartId, pmid = method.PaymentMethodID }) > 0;
}
public IEnumerable<DeliveryOption> GetDeliveryOptions()
{
return db.Query<DeliveryOption>("SELECT * FROM DeliveryOptions ORDER BY 1");
}
public IEnumerable<PaymentMethod> GetPaymentMethods()
{
return db.Query<PaymentMethod>("SELECT * FROM PaymentMethods ORDER BY 1");
}
}
}
<file_sep>/BookstoreService/BookstoreDesktop/Books.cs
using BookstoreDesktop.BookstoreService;
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 BookstoreDesktop
{
public partial class Books : Form
{
private readonly BooksServiceClient _service = new BooksServiceClient();
public Books()
{
InitializeComponent();
}
private void Books_Load(object sender, EventArgs e)
{
var categories = _service.GetAllCategories();
categoryBindingSource.DataSource = categories;
var books = _service.GetBooksByCategoryId(Convert.ToInt32(listBox1.SelectedValue));
bookBindingSource.DataSource = books;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var books = _service.GetBooksByCategoryId(Convert.ToInt32(listBox1.SelectedValue));
bookBindingSource.DataSource = books;
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
var form = new EditBook(Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value));
form.MdiParent = this.MdiParent;
form.Show();
}
}
}<file_sep>/README.md
# BookstoreService
University assignment,to start up the project go to : BookstoreService\BookstoreServiceHost\bin\Debug and run BookstoreServiceHost.exe as administrartor,than run BookstoreService.sln
<file_sep>/BookstoreService/BookstoreServiceHost/Program.cs
using BookstoreService.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;
namespace BookstoreServiceHost
{
class Program
{
static void Main(string[] args)
{
var baseAddressBooks = new Uri("http://localhost:8123/");
var baseAddressCart = new Uri("http://localhost:8124/");
var selfHostBooks = new ServiceHost(typeof(BooksService), baseAddressBooks);
var selfHostCart = new ServiceHost(typeof(CartService), baseAddressCart);
try
{
selfHostBooks.AddServiceEndpoint(typeof(IBooksService), new WSHttpBinding(SecurityMode.None), "BooksService");
selfHostCart.AddServiceEndpoint(typeof(ICartService), new WSHttpBinding(SecurityMode.None), "CartService");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHostBooks.Description.Behaviors.Add(smb);
((ServiceDebugBehavior)selfHostBooks.Description.Behaviors[typeof(ServiceDebugBehavior)]).IncludeExceptionDetailInFaults = true;
selfHostCart.Description.Behaviors.Add(smb);
((ServiceDebugBehavior)selfHostCart.Description.Behaviors[typeof(ServiceDebugBehavior)]).IncludeExceptionDetailInFaults = true;
selfHostBooks.Open();
selfHostCart.Open();
Console.WriteLine("The service is ready.");
Console.ReadLine();
selfHostBooks.Close();
selfHostCart.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
selfHostBooks.Abort();
selfHostCart.Abort();
Console.Read();
}
}
}
}
<file_sep>/BookstoreService/BookstoreService/Entities/CartBook.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BookstoreService.Entities
{
public class CartBook
{
public int CartID { get; set; }
public int BookID { get; set; }
public int Quantity { get; set; }
public DateTime AddedOn { get; set; }
public virtual Book Book { get; set; }
}
}
<file_sep>/BookstoreService/BookstoreService/Services/ICartService.cs
using BookstoreService.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace BookstoreService.Services
{
[ServiceContract(Namespace = "http://unwe.bg")]
public interface ICartService
{
[OperationContract]
Cart CreateCart(string userId);
[OperationContract]
bool AddToCart(int cartId, int bookId);
[OperationContract]
Cart GetCart(int cartId);
[OperationContract]
bool RemoveFromCart(int cartId, int bookId);
[OperationContract]
bool SetPaymentMethod(int cartId, PaymentMethod method);
[OperationContract]
bool SetDeliveryOptions(int cartId, DeliveryOption options);
[OperationContract]
bool Purchase(int cartId);
[OperationContract]
IEnumerable<DeliveryOption> GetDeliveryOptions();
[OperationContract]
IEnumerable<PaymentMethod> GetPaymentMethods();
}
}
<file_sep>/BookstoreService/BookstoreWebForms/ViewBook.aspx.cs
using BookstoreWebForms.CartService;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace BookstoreWebForms
{
public partial class ViewBook : System.Web.UI.Page
{
private int _bookId;
protected void Page_Load(object sender, EventArgs e)
{
_bookId = Convert.ToInt32(this.Request.QueryString["id"]);
}
protected void BuyButton_Click(object sender, EventArgs e)
{
if (!User.Identity.IsAuthenticated)
{
Response.Redirect("~/Account/Login.aspx");
Response.End();
return;
}
string userId = User.Identity.GetUserId();
using (var cs = new CartServiceClient())
{
var cart = (CartService.Cart)Session["cart"];
if (cart == null)
{
cart = cs.CreateCart(userId);
Session["cart"] = cart;
}
bool success = cs.AddToCart(cart.CartID, _bookId);
if (success)
{
Response.Redirect("~/Cart.aspx");
}
}
}
}
}<file_sep>/BookstoreService/BookstoreService/Services/BooksService.cs
using BookstoreService.Entities;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Configuration;
using Newtonsoft.Json;
using System.Net;
namespace BookstoreService.Services
{
public class BooksService:IBooksService
{
private readonly SqlConnection db;
public BooksService()
{
db = new SqlConnection(ConfigurationManager.ConnectionStrings["bookstore"].ConnectionString);
}
public IEnumerable<Book> GetAllBooks()
{
return db.Query<Book>("SELECT BookID,Title,Year,Price,ISBN,Description,CategoryID FROM Books");
}
public IEnumerable<Book> GetBooksByCategory(int categoryId)
{
return db.Query<Book>("SELECT BookID,Title,Year,Price,ISBN,Description,CategoryID FROM Books WHERE CategoryID=@cid", new { cid = categoryId });
}
public IEnumerable<Book> GetBooksByCategory(Category category)
{
return GetBooksByCategory(category.CategoryID);
}
public Book GetBook(int id)
{
return db.QuerySingle<Book>("SELECT BookID,Title,Year,Price,Cover,ISBN,Description,CategoryID FROM Books WHERE BookID=@bookid", new { bookid = id });
}
public Book GetBookByISBN(string isbn)
{
return db.QuerySingle<Book>("SELECT BookID,Title,Year,Price,Cover,ISBN,Description,CategoryID FROM Books WHERE ISBN=@isbn", new { isbn = isbn });
}
public IEnumerable<Category> GetAllCategories()
{
return db.Query<Category>("SELECT * FROM Categories");
}
public Book CreateBook(Book book)
{
int newId = db.ExecuteScalar<int>(@"INSERT INTO Books (Title,Year,Price,Cover,ISBN,Description,CategoryID) VALUES (@title,@year,@price,@cover,@isbn,@description,@categoryid);
SELECT CAST(SCOPE_IDENTITY() as int)",
new
{
title = book.Title,
year = book.Year,
price = book.Price,
cover = book.Cover,
isbn = book.ISBN,
description = book.Description,
categoryid = book.CategoryID
}
);
return GetBook(newId);
}
public Book UpdateBook(Book book)
{
db.Execute(@"UPDATE Books SET Title=@title,Year=@year,Price=@price,Cover=@cover,ISBN=@isbn,Description=@description,CategoryID=@categoryid
WHERE BookID=@bookid",
new
{
bookid = book.BookID,
title = book.Title,
year = book.Year,
price = book.Price,
cover = book.Cover,
isbn = book.ISBN,
description = book.Description,
categoryid = book.CategoryID
}
);
return GetBook(book.BookID);
}
public void RemoveBook(int bookId)
{
db.Execute("DELETE FROM Books WHERE BookID=@bookid", new { bookid = bookId });
}
public IEnumerable<ExternalBook> GetSimilarBooks(int id)
{
string apiKey = ConfigurationManager.AppSettings["BooksKey"];
var book = GetBook(id);
using (var client = new WebClient())
{
string json = client.DownloadString(new Uri($"https://www.googleapis.com/books/v1/volumes?q={book.Title}&key={apiKey}"));
dynamic result = JsonConvert.DeserializeObject<dynamic>(json);
var similarBooks = new List<ExternalBook>();
foreach (var item in result.items)
{
similarBooks.Add(new ExternalBook()
{
Title = item.volumeInfo.title,
Publisher = item.volumeInfo.publisher,
Link = item.volumeInfo.previewLink,
ISBN = item.volumeInfo.industryIdentifiers[0].identifier
});
}
return similarBooks;
}
}
}
}
<file_sep>/BookstoreService/BookstoreWebForms/Cover.ashx.cs
using BookstoreWebForms.BookstoreService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BookstoreWebForms
{
/// <summary>
/// Summary description for Cover
/// </summary>
public class Cover : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var client = new BooksServiceClient();
var book = client.GetBook(Convert.ToInt32(context.Request.QueryString["id"]));
context.Response.OutputStream.Write(book.Cover, 0, book.Cover.Length);
context.Response.ContentType = "image/jpeg";
client.Close();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}<file_sep>/BookstoreService/BookstoreWebForms/Cart.aspx.cs
using BookstoreWebForms.CartService;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace BookstoreWebForms
{
public partial class Cart : System.Web.UI.Page
{
private CartServiceClient cs = new CartServiceClient();
protected void Page_Load(object sender, EventArgs e)
{
if (!User.Identity.IsAuthenticated)
{
Response.Redirect("~/Account/Login.aspx");
Response.End();
return;
}
string userId = User.Identity.GetUserId();
var cart = (CartService.Cart)Session["cart"];
if (cart == null)
{
cart = cs.CreateCart(userId);
Session["cart"] = cart;
}
cart = RefreshCart(cart.CartID);
}
private CartService.Cart RefreshCart(int cartId)
{
var cart = cs.GetCart(cartId);
gvCart.DataSource = cart.Books;
gvCart.DataBind();
lblSum.Text = cart.Books.Sum(x => x.Quantity * x.Book.Price).ToString("G");
return cart;
}
protected void gvCart_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int bookId = Convert.ToInt32(e.Keys["BookID"]);
int cartId = ((CartService.Cart)Session["cart"]).CartID;
bool success = cs.RemoveFromCart(cartId, bookId);
if (success)
{
RefreshCart(cartId);
}
else
{
lblErrorDeleting.Visible = true;
}
}
protected void btnPurchase_Click(object sender, EventArgs e)
{
int cartId = ((CartService.Cart)Session["cart"]).CartID;
cs.SetDeliveryOptions(cartId, new DeliveryOption() { DeliveryOptionID = Convert.ToInt32(listDeliveryOptions.SelectedValue) });
cs.SetPaymentMethod(cartId, new PaymentMethod() { PaymentMethodID = Convert.ToInt32(listPaymentMethods.SelectedValue) });
Response.Redirect("~/CartPay.aspx");
}
}
}
|
8da4250503323ab2acef827ea49f78624d5452b4
|
[
"Markdown",
"C#"
] | 16 |
C#
|
PhilipYordanov/BookstoreService
|
5b487b2cf189fc334c50e6212398bd126d5b98bf
|
cea3ad3661c7b0d1c8dd45e02b85b4574533f72f
|
refs/heads/master
|
<file_sep>import React from 'react';
import Layout from '../components/layout';
import SEO from '../components/seo';
import { HomeHeader, Banner, BannerButton } from '../utils';
import img from '../images/bcg/homeBcg.jpeg';
import QuickInfo from '../components/HomePageComponent/QuickInfo';
import Gallery from '../components/HomePageComponent/Gallery-1';
import Menu from '../components/HomePageComponent/Menu';
const IndexPage = () => (
<Layout>
<SEO
title="Home"
keywords={[
`gatsby`,
`application`,
`react`,
`accounting`,
`accountant`,
`bookkeeping`,
`taxation`,
`programming`,
]}
/>
<HomeHeader img={img}>
<Banner
title="eatery"
subtitle="142/191 Moo 7 Kathu, Kathu, Phuket 83120"
>
<BannerButton style={{ margin: '2rem auto' }}>menu</BannerButton>
</Banner>
</HomeHeader>
<QuickInfo />
<Gallery />
<Menu />
</Layout>
);
export default IndexPage;
<file_sep>[](https://app.netlify.com/sites/sharp-heisenberg-aada2f/deploys)
|
b50521ac28daf7c2407eaa8068014731b201b5eb
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
Means-Business/restaurant
|
75d695b3f3f6c09c9a81a3e5d165ff330eb80507
|
38a9790b5daefcbebcd98a7e52f1d8dedd86de09
|
refs/heads/master
|
<repo_name>b1b2b3b4b5b6/goc<file_sep>/tl/debt/rpc.go
package debt
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
"github.com/b1b2b3b4b5b6/goc/tl/cfgt"
"github.com/b1b2b3b4b5b6/goc/tl/errt"
"github.com/b1b2b3b4b5b6/goc/tl/jsont"
)
type response struct {
ErrorCode int
Message string `json:"Message,omitempty"`
Result map[string]interface{} `json:"Result,omitempty"`
}
type requestArg struct {
Func string
Params interface{}
}
func init() {
http.HandleFunc("/debug", debFunc)
http.HandleFunc("/echo", echoFunc)
cfg := cfgt.New("conf.json")
port, err := cfg.TakeInt("DebugPort")
errt.Errpanic(err)
go http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
fmt.Printf("[rpc.go]debug tool work on port[%d]\r\n", port)
}
var funcList = make(map[string]interface{})
func AddFunc(name string, foo interface{}) {
_, ok := funcList[name]
if ok {
panic(fmt.Sprintf("repeat debug func name[%s]", name))
}
funcList[name] = foo
fmt.Printf("[rpc.go]add debug func[%s]\r\n", name)
}
func echoFunc(w http.ResponseWriter, r *http.Request) {
res := response{ErrorCode: 0, Result: make(map[string]interface{})}
defer func() {
w.Header().Add("Content-Type", "application/json")
w.Write([]byte(jsont.Encode(&res)))
}()
err := r.ParseForm()
errt.Errpanic(err)
var m interface{}
err = json.NewDecoder(r.Body).Decode(&m)
fmt.Printf("echo[%+v]\r\n", m)
}
func debFunc(w http.ResponseWriter, r *http.Request) {
res := response{ErrorCode: 0, Result: make(map[string]interface{})}
defer func() {
w.Header().Add("Content-Type", "application/json")
w.Write([]byte(jsont.Encode(&res)))
}()
err := r.ParseForm()
errt.Errpanic(err)
var request requestArg
err = json.NewDecoder(r.Body).Decode(&request)
if err != nil {
res.ErrorCode = -1
res.Message = err.Error()
return
}
fmt.Printf("request:%+v", request)
foo, ok := funcList[request.Func]
if !ok {
res.ErrorCode = -1
res.Message = fmt.Sprintf("no func[%s]", request.Func)
return
}
f := reflect.ValueOf(foo)
paramsArray := request.Params.([]interface{})
if len(paramsArray) != f.Type().NumIn() {
panic(fmt.Sprintf("func[%s] params[%d] not match give[%d]", request.Func, f.Type().NumIn(), len(paramsArray)))
}
in := make([]reflect.Value, len(paramsArray))
for i, v := range paramsArray {
in[i] = reflect.ValueOf(jsont.TypeValue(f.Type().In(i), v))
}
tres := f.Call(in)
for k, v := range tres {
res.Result[fmt.Sprintf("Res_%d", k)] = v.Interface()
}
}
<file_sep>/pt/mom/mqtt/mqtt.go
package mqtt
import (
"github.com/b1b2b3b4b5b6/goc/logface"
"time"
pahoMqtt "github.com/eclipse/paho.mqtt.golang"
)
var log = logface.New(logface.InfoLevel)
type Cfg struct {
Topic string
IsSubscribe bool
Qos int
Broker string
Username string
Password string
ClientID string
AliveTime int
Timeout int
IsClean bool
Will string `json:"Will,omitempty"`
ConCb func() `json:"ConCb,omitempty"`
DisconCb func() `json:"DisconCb,omitempty"`
}
type Handle struct {
client pahoMqtt.Client
option *pahoMqtt.ClientOptions
token *pahoMqtt.Token
chRecv chan (string)
conf Cfg
}
func New(cfg Cfg) *Handle {
m := &Handle{chRecv: make(chan string, 10)}
m.conf = cfg
log.Debug("mqtt cfg:[%+v]", m.conf)
m.option = pahoMqtt.NewClientOptions()
m.option.SetAutoReconnect(true)
m.option.AddBroker(m.conf.Broker)
m.option.SetClientID(m.conf.ClientID)
m.option.SetPassword(m.option.Password)
m.option.SetUsername(m.option.Username)
m.option.SetCleanSession(m.conf.IsClean)
m.option.SetConnectTimeout(time.Second * time.Duration(m.conf.Timeout))
m.option.SetKeepAlive(time.Second * time.Duration(m.conf.AliveTime))
if len(m.conf.Will) > 0 {
m.option.SetWill(m.conf.Topic, m.conf.Will, 1, false)
}
m.option.SetOnConnectHandler(func(c pahoMqtt.Client) {
if cfg.ConCb != nil {
cfg.ConCb()
}
})
m.option.SetConnectionLostHandler(func(c pahoMqtt.Client, err error) {
if cfg.DisconCb != nil {
cfg.DisconCb()
}
})
m.client = pahoMqtt.NewClient(m.option)
log.Debug("mqtt client init success")
return m
}
func (p *Handle) Connect() error {
if token := p.client.Connect(); token.Wait() && token.Error() != nil {
log.Panic("mqtt connect fail")
}
var recvHandle = func(client pahoMqtt.Client, msg pahoMqtt.Message) {
log.Trace("mqtt recv payload [%s]", string(msg.Payload()))
p.chRecv <- string(msg.Payload())
}
if p.conf.IsSubscribe {
if token := p.client.Subscribe(p.conf.Topic, byte(p.conf.Qos), recvHandle); token.Wait() && token.Error() != nil {
log.Panic("mqtt subscribe fail")
}
}
log.Debug("mqtt connect success")
return nil
}
func (p *Handle) DisConnect() error {
if p.conf.IsSubscribe {
if token := p.client.Unsubscribe(p.conf.Topic); token.Wait() && token.Error() != nil {
log.Panic("mqtt unsubscribe fail")
}
}
p.client.Disconnect(250)
log.Debug("mqtt disconnect success")
return nil
}
func (p *Handle) Send(str string) error {
if token := p.client.Publish(p.conf.Topic, byte(p.conf.Qos), false, str); token.Wait() && token.Error() != nil {
return token.Error()
}
log.Debug("mqtt send success")
return nil
}
func (p *Handle) Recv() string {
return <-p.chRecv
}
<file_sep>/tl/errt/errtool.go
package errt
//Errpanic is
func Errpanic(err error) {
if err != nil {
panic(err.Error())
}
}
//Assert is
func Assert(val bool) {
if !val {
panic("assert fail")
}
}
func Ignore(err error) {
}
<file_sep>/tl/nett/net.go
package nett
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"github.com/b1b2b3b4b5b6/goc/tl/errt"
)
func GetLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Println(err)
panic("no network device")
}
for _, address := range addrs {
// 检查ip地址判断是否回环地址
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
panic("no lan ip")
return ""
}
func GetOutIP() string {
conn, err := net.Dial("udp", "8.8.8.8:80")
errt.Errpanic(err)
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP.String()
}
func PostJson(url string, jsonStr string) (string, error) {
req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(jsonStr)))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", errors.New(fmt.Sprintf("[%s]post json fail[%+v]", url, err))
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.New(fmt.Sprintf("[%s]body recv fail[%+v]", url, err))
}
return string(body), nil
}
<file_sep>/tl/cfgt/conf.go
package cfgt
import (
"fmt"
"io/ioutil"
"strings"
"github.com/b1b2b3b4b5b6/goc/tl/errt"
"github.com/b1b2b3b4b5b6/goc/tl/iot"
"github.com/b1b2b3b4b5b6/goc/tl/jsont"
)
type CfgData struct {
V map[string]interface{}
}
var confInterface []byte
func New(filePath string) *CfgData {
//reletive path
if strings.Index(filePath, "/") != 0 {
filePath = fmt.Sprintf("%s/%s", iot.GetCurrentDirectory(), filePath)
}
buf, err := ioutil.ReadFile(filePath)
errt.Errpanic(err)
cfg_data := &CfgData{}
jsont.Decode(string(buf), &cfg_data.V)
return cfg_data
}
func (p *CfgData) TakeInt(key string) (int, error) {
m, ok := p.V[key]
if !ok {
return 0, fmt.Errorf("can not find key[%s]", key)
}
switch v := m.(type) {
case int:
return v, nil
case float64:
return int(v), nil
default:
return 0, fmt.Errorf("key[%s] is not int", key)
}
}
func (p *CfgData) TakeString(key string) (string, error) {
m, ok := p.V[key]
if !ok {
return "", fmt.Errorf("can not find key[%s]", key)
}
switch v := m.(type) {
case string:
return v, nil
default:
return "", fmt.Errorf("key[%s] is not string", key)
}
}
func (p *CfgData) TakeFloat(key string) (float64, error) {
m, ok := p.V[key]
if !ok {
return 0, fmt.Errorf("can not find key[%s]", key)
}
switch v := m.(type) {
case float64:
return v, nil
default:
return 0, fmt.Errorf("key[%s] is not float", key)
}
}
func (p *CfgData) TakeBool(key string) (bool, error) {
m, ok := p.V[key]
if !ok {
return false, fmt.Errorf("can not find key[%s]", key)
}
switch v := m.(type) {
case bool:
return v, nil
default:
return false, fmt.Errorf("key[%s] is not bool", key)
}
}
func (p *CfgData) TakeCfg(key string) (*CfgData, error) {
m, ok := p.V[key]
if !ok {
return nil, fmt.Errorf("can not find key[%s]", key)
}
switch v := m.(type) {
case map[string]interface{}:
return &CfgData{V: v}, nil
default:
return nil, fmt.Errorf("key[%s] is not map", key)
}
}
func (p *CfgData) TakeJson(key string) (string, error) {
m, ok := p.V[key]
if !ok {
return "", fmt.Errorf("can not find key[%s]", key)
}
return jsont.Encode(m), nil
}
<file_sep>/tl/jsont/jsontool.go
package jsont
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/b1b2b3b4b5b6/goc/tl/errt"
"github.com/b1b2b3b4b5b6/goc/tl/dumpt"
)
func DecodeString(jsonStr string, key string) (string, error) {
var m interface{}
Decode(jsonStr, &m)
t := m.(map[string]interface{})
v, ok := t[key]
if !ok {
panic(fmt.Sprintf("can not find %s", key))
}
return v.(string), nil
}
func DecodeInt(jsonStr string, key string) (int, error) {
var m interface{}
Decode(jsonStr, &m)
t := m.(map[string]interface{})
v, ok := t[key]
if !ok {
panic(fmt.Sprintf("can not find %s", key))
}
return int(v.(float64)), nil
}
func Encode(arg interface{}) string {
json_byte, err := json.Marshal(arg)
errt.Errpanic(err)
return string(json_byte)
}
func EncodeIndent(arg interface{}) string {
json_byte, err := json.MarshalIndent(arg, "", "\t")
errt.Errpanic(err)
return string(json_byte)
}
func Decode(jsonStr string, arg interface{}) error {
strings.TrimRight(jsonStr, "\x00")
err := json.Unmarshal([]byte(jsonStr), arg)
errt.Errpanic(err)
return err
}
func TypeValue(typ reflect.Type, value interface{}) interface{} {
switch value.(type) {
case float64:
v := value.(float64)
t := reflect.New(typ)
switch t.Interface().(type) {
case *int:
return int(v)
case *int16:
return int16(v)
case *int32:
return int32(v)
case *int64:
return int64(v)
case *uint:
return uint(v)
case *uint16:
return uint16(v)
case *uint32:
return uint32(v)
case *uint64:
return uint64(v)
case *float32:
return float32(v)
case *float64:
return float64(v)
default:
panic(fmt.Sprintf("value[%+v] can not convert to typ[%+v] ", dumpt.Sdump(value), typ))
return nil
}
case string:
return value
case bool:
return value
default:
panic(fmt.Sprintf("json not no support [%s]", dumpt.Sdump(value)))
return nil
}
}
<file_sep>/tl/prot/process.go
package prot
type retryFunc func() bool
//RetryUntilTrue is
func RetryUntilTrue(f retryFunc, times int) bool {
for i := 0; i < times; i++ {
if f() == true {
return true
}
}
return false
}
//RetryUntilFalse is
func RetryUntilFalse(f retryFunc, times int) bool {
for i := 0; i < times; i++ {
if f() == false {
return false
}
}
return true
}
<file_sep>/tl/debt/format.md
### format
#### requst
```json
{
"Func":"foo",
"Params":{
"P1": "123",
"P2": 123,
}
}
```
#### result
```json
{
"StatusCode":1,
"Message": "no messsage",
"Result":{}
}
```
#### HttpMethod
Post<file_sep>/tl/nett/http.go
package nett
import (
"io/ioutil"
"net/http"
"strings"
)
func httpGet(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
func Http_Post(url string, body string) ([]byte, error) {
//创建请求
postReq, err := http.NewRequest("POST",
url, //post链接
strings.NewReader(body)) //post内容
if err != nil {
return nil, err
}
//增加header
postReq.Header.Set("Content-Type", "application/json; encoding=utf-8")
//执行请求
client := &http.Client{}
resp, err := client.Do(postReq)
if err != nil {
return nil, err
}
//读取响应
resBody, err := ioutil.ReadAll(resp.Body) //此处可增加输入过滤
if err != nil {
return nil, err
}
defer resp.Body.Close()
return resBody, nil
}
<file_sep>/tl/dumpt/dump.go
package dumpt
import (
"io"
"github.com/davecgh/go-spew/spew"
)
func Dump(args ...interface{}) {
spew.Dump(args)
}
func Sdump(args ...interface{}) string {
return spew.Sdump(args)
}
func Fdump(w io.Writer, args ...interface{}) {
spew.Fdump(w, args)
}
<file_sep>/tl/turnt/mac.go
package turnt
import (
"fmt"
)
//Mac2Str is
func Mac2Str(mac []byte) string {
return fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5])
}
//Str2mac is
func Str2mac(str string) []byte {
mac := make([]byte, 6)
fmt.Sscanf(str, "%02x:%02x:%02x:%02x:%02x:%02x", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5])
return mac
}
<file_sep>/logface/remote.go
package logface
import (
"fmt"
"github.com/b1b2b3b4b5b6/goc/tl/jsont"
"github.com/b1b2b3b4b5b6/goc/tl/errt"
"os"
"time"
"github.com/gomodule/redigo/redis"
"github.com/sirupsen/logrus"
)
type remoteWirte struct {
}
func (p remoteWirte) Write(data []byte) (n int, err error) {
chRemote <- string(data)
return os.Stdout.Write(data)
}
var rw remoteWirte
var chRemote = make(chan string, 1000)
func init() {
go remoteLoop()
}
func remoteLoop() {
json, err := cfg.TakeJson("LogRedisCfg")
if err != nil {
logrus.Warn("no cfg, remote log not init")
for {
<-chRemote
}
}
var remoteCfg struct {
Host string
}
err = jsont.Decode(json, &remoteCfg)
errt.Errpanic(err)
pool := redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) { return redis.Dial("tcp", remoteCfg.Host) },
}
for {
logStr := <-chRemote
rep, err := pool.Get().Do("LPUSH", "log", logStr)
if err != nil {
logrus.Warn(fmt.Sprintf("send remote log fail[%+v, %+v]", rep, err))
}
}
}
<file_sep>/logface/logface.go
//Package logface implements a simple library
package logface
import (
"fmt"
"github.com/b1b2b3b4b5b6/goc/tl/cfgt"
"os"
"runtime"
"strings"
"github.com/sirupsen/logrus"
)
//Level is
type Level uint32
// These are the different logging levels. You can set the logging level to log
// on your instance of logger, obtained with `logrus.New()`.
const (
// PanicLevel level, highest level of severity. Logs and then calls panic with the
// message passed to Debug, Info, ...
PanicLevel Level = iota
// FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
// logging level is set to Panic.
FatalLevel
// ErrorLevel level. Logs. Used for errors that should definitely be noted.
// Commonly used for hooks to send errors to an error tracking service.
ErrorLevel
// WarnLevel level. Non-critical entries that deserve eyes.
WarnLevel
// InfoLevel level. General operational entries about what's going on inside the
// application.
InfoLevel
// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
DebugLevel
// TraceLevel level. Designates finer-grained informational events than the Debug.
TraceLevel
)
//Logface is
type Logface struct {
logInner *logrus.Logger
level Level
}
var cfg = cfgt.New("conf.json")
//New is
func New(argLevel Level) *Logface {
logger := &Logface{logInner: logrus.New(), level: argLevel}
logger.logInner.Out = rw
logger.logInner.Level = turnLevel(argLevel)
logger.logInner.SetFormatter(&logrus.TextFormatter{
//DisableTimestamp: true,
})
return logger
}
func turnLevel(argLevel Level) logrus.Level {
switch argLevel {
case PanicLevel:
return logrus.PanicLevel
case FatalLevel:
return logrus.FatalLevel
case ErrorLevel:
return logrus.ErrorLevel
case WarnLevel:
return logrus.WarnLevel
case InfoLevel:
return logrus.InfoLevel
case DebugLevel:
return logrus.DebugLevel
case TraceLevel:
return logrus.TraceLevel
}
os.Exit(-1)
return logrus.TraceLevel
}
//Logkit is
func (p *Logface) Logkit(format string, args ...interface{}) {
_, file, line, _ := runtime.Caller(1)
offset := strings.LastIndex(file, "/")
file = file[offset+1:]
p.logInner.Trace(fmt.Sprintf("[%s][%d] ", file, line), fmt.Sprintf(format, args...))
}
//Trace is
func (p *Logface) Trace(format string, args ...interface{}) {
_, file, line, _ := runtime.Caller(1)
offset := strings.LastIndex(file, "/")
file = file[offset+1:]
p.logInner.Trace(fmt.Sprintf("[%s][%d] ", file, line), fmt.Sprintf(format, args...))
}
//Debug is
func (p *Logface) Debug(format string, args ...interface{}) {
_, file, line, _ := runtime.Caller(1)
offset := strings.LastIndex(file, "/")
file = file[offset+1:]
p.logInner.Debug(fmt.Sprintf("[%s.%d] ", file, line), fmt.Sprintf(format, args...))
}
//Info is
func (p *Logface) Info(format string, args ...interface{}) {
_, file, line, _ := runtime.Caller(1)
offset := strings.LastIndex(file, "/")
file = file[offset+1:]
p.logInner.Info(fmt.Sprintf("[%s][%d] ", file, line), fmt.Sprintf(format, args...))
}
//Print is
func (p *Logface) Print(format string, args ...interface{}) {
_, file, line, _ := runtime.Caller(1)
offset := strings.LastIndex(file, "/")
file = file[offset+1:]
p.logInner.Print(fmt.Sprintf("[%s][%d] ", file, line), fmt.Sprintf(format, args...))
}
//Warn is
func (p *Logface) Warn(format string, args ...interface{}) {
_, file, line, _ := runtime.Caller(1)
offset := strings.LastIndex(file, "/")
file = file[offset+1:]
p.logInner.Warn(fmt.Sprintf("[%s][%d] ", file, line), fmt.Sprintf(format, args...))
}
//Warning is
func (p *Logface) Warning(format string, args ...interface{}) {
_, file, line, _ := runtime.Caller(1)
offset := strings.LastIndex(file, "/")
file = file[offset+1:]
p.logInner.Warning(fmt.Sprintf("[%s][%d] ", file, line), fmt.Sprintf(format, args...))
}
//Error is
func (p *Logface) Error(format string, args ...interface{}) {
_, file, line, _ := runtime.Caller(1)
offset := strings.LastIndex(file, "/")
file = file[offset+1:]
p.logInner.Error(fmt.Sprintf("[%s][%d] ", file, line), fmt.Sprintf(format, args...))
}
//Fatal is
func (p *Logface) Fatal(format string, args ...interface{}) {
_, file, line, _ := runtime.Caller(1)
offset := strings.LastIndex(file, "/")
file = file[offset+1:]
p.logInner.Fatal(fmt.Sprintf("[%s][%d] ", file, line), fmt.Sprintf(format, args...))
}
//Panic is
func (p *Logface) Panic(format string, args ...interface{}) {
_, file, line, _ := runtime.Caller(1)
offset := strings.LastIndex(file, "/")
file = file[offset+1:]
p.logInner.Panic(fmt.Sprintf("[%s][%d] ", file, line), fmt.Sprintf(format, args...))
}
|
a379eba285fd322cd8f69e264b74f402340d4e1b
|
[
"Markdown",
"Go"
] | 13 |
Go
|
b1b2b3b4b5b6/goc
|
d06e94e77a4fcc3b65257758e5238a299baa6766
|
590deda5e77c096b88a8dc042237e20ebe90280a
|
refs/heads/master
|
<repo_name>Karpatsky/csgobot<file_sep>/app/Item.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
protected $fillable = ['name', 'phase', 'id', 'full_name'];
public function tasks(){
return $this->hasMany(Task::class);
}
public function patterns(){
return $this->hasMany(Pattern::class);
}
}
<file_sep>/app/Commands/SearchCommand.php
<?php
namespace App\Commands;
use App\Classes\NeedItem;
use App\Dealer;
use App\Item;
use App\Pattern;
use App\Site;
use App\Task;
use Carbon\Carbon;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Telegram\Bot\Actions;
use Telegram\Bot\Commands\Command;
use Telegram\Bot\Laravel\Facades\Telegram;
class SearchCommand extends Command
{
protected $name = "search";
protected $description = "Поиск предмета. Для поиска предмета введи /search номер сайта,название предмета. Пример поиска предмета без фазы: /search 1,★ Karambit | Doppler (Factory New).\r\nПример поиска предмета с фазой: /search номер сайта,название сайта,фаза. Так же четвертым параметром можно добавить верхнюю границу float";
public function handle($arguments)
{
set_time_limit(0);
$updades = Telegram::getWebhookUpdates();
$oMessage = $updades->getMessage();
$user = $oMessage->getFrom();
$message = '';
$dealer = Dealer::where('username', '=', $user->getUsername())->where('subscription', '=', 1)->first();
if ($dealer) {
$now = Carbon::now()->format('Y-m-d');
$end = $dealer->end_subscription;
if ($now >= $end) {
$dealer->subscription = 0;
$dealer->save();
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => 'Продлите подписку']);
} else {
$str_request = explode(',', $arguments);
$count_params = count($str_request);
if ($count_params == 2 || $count_params == 3 || $count_params == 4) {
$pattern_names = Pattern::groupBy('name')->pluck('name')->toArray();
$pattern_items = collect(DB::select('select distinct items.name from items, patterns where items.id = patterns.item_id'));
$site = trim(explode(',', $arguments)[0]);
$item = trim(explode(',', $arguments)[1]);
$phase = false;
$float = null;
$pattern = null;
if ($count_params == 3) {
if (is_numeric(trim($str_request[2]))) {
$float = trim($str_request[2]);
} else {
if (in_array(trim(last($str_request)), $pattern_names)) $pattern = trim(last($str_request));
else $phase = trim($str_request[2]);
}
} elseif ($count_params == 4) {
if (is_numeric(trim(last($str_request))) && trim(last($str_request)) > 0) {
$float = trim(last($str_request));
if (in_array(trim($str_request[2]), $pattern_names)) $pattern = trim($str_request[2]);
else $phase = trim($str_request[2]);
} else {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => 'Неверный float']);
}
}
if ($mSite = Site::find($site)) {
$mItem = !$phase ? Item::where('name', '=', "{$item}")->first() : Item::where([
['name', '=', "{$item}"],
['phase', '=', "{$phase}"]
])->first();
if ($mItem) {
if ($pattern && !count($pattern_items->where('name','=', $mItem->name))){
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => 'Поиск по паттерну для данного предмета невозможен']);
}
else {
$message = "Поиск {$item} на сайте {$mSite->url} начался";
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => $message]);
//Логика поиска
$obj = new NeedItem($mItem->name, $mSite->url, $oMessage->getChat()->getId(), $phase, $float, $pattern);
$curl = curl_init();
$url = $mSite->id == 8 ? $mSite->get_data . str_replace(' ', '', $obj->full_name) : $mSite->get_data;
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = null;
if ($mSite->id == 11) {
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Origin: https://ru.cs.deals",
"Referer: https://ru.cs.deals/",
"Connection: keep-alive",
"Content-Length: 0",
"Origin: https://ru.cs.deals",
"X-Requested-With: XMLHttpRequest",
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
"Referer: https://ru.cs.deals/",
"Accept: application/json, text/javascript, */*; q=0.01",
"Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4",
"Authority: ru.cs.deals",
"Method: POST",
"Path: /ajax/botsinventory",
"Scheme: https"
));
$curl_response = curl_exec($curl);
$curl_response = json_decode(utf8_decode($curl_response))->response;
}
elseif ($mSite->id == 12) {
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Origin: https://ru.tradeskinsfast.com",
"Referer: https://ru.tradeskinsfast.com/",
"Connection: keep-alive",
"Content-Length: 0",
"X-Requested-With: XMLHttpRequest",
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
"Accept: application/json, text/javascript, */*; q=0.01",
"Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4",
"Authority: ru.tradeskinsfast.com",
"Method: POST",
"Path: /ajax/botsinventory",
"Scheme: https"
));
$curl_response = curl_exec($curl);
$curl_response = json_decode(utf8_decode($curl_response))->response;
}
else {
$curl_response = json_decode(curl_exec($curl));
}
$response = false;
switch ($mSite->id) {
case 1:
$response = $this->check_raffletrades($obj, $curl_response);
break;
case 2:
$response = $this->check_raffletrades($obj, $curl_response);
break;
case 3:
$response = $this->check_raffletrades($obj, $curl_response);
break;
case 4:
$response = $this->check_cstradegg($obj, $curl_response);
break;
case 5:
$response = $this->check_skintrade($obj, $curl_response);
break;
case 7:
$response = $this->check_csmoney($obj, $curl_response);
break;
case 8:
$response = $this->check_csgosum($obj, $curl_response);
break;
case 9:
$response = $this->check_skinsjar($obj, $curl_response);
break;
case 10:
$response = $this->check_lootfarm($obj, $curl_response);
break;
case 11:
$response = $this->check_csdeals($obj, $curl_response);
break;
case 12:
$response = $this->check_csdeals($obj, $curl_response);
break;
}
curl_close($curl);
if (!$response) Task::create(['item_id' => $mItem->id, 'site_id' => $mSite->id,
'float' => $float, 'chat_id' => $oMessage->getChat()->getId(), 'pattern' => $pattern]);
//---------------------------
}
}
else {
$message = "Предмет {$item} не существует.";
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => $message]);
}
}
else {
$message = "Сайт {$site} не существует.";
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => $message]);
}
} else {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => 'Неправильный формат комманды']);
}
}
} else {
$message = 'Купи подписку у @ska4an';
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => $message]);
}
}
private function check_csmoney($obj, $curl_response)
{
$statuses = ['FN' => '(Factory New)', 'MW' => '(Minimal Wear)', 'FT' => '(Field-Tested)',
'BS' => '(Battle-Scarred)', 'WW' => '(Well-Worn)'];
$find = false;
if ($obj->float) {
foreach ($curl_response as $item) {
$item_name = '';
try {
$item_name = $item->m . " {$statuses[$item->e]}";
} catch (\Exception $exception) {
$item_name = $item->m;
}
if ($item_name == $obj->full_name && $item->f[0] <= $obj->float) {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$obj->phase}\r\n{$item->f[0]}"]);
$find = true;
break;
}
}
} else {
foreach ($curl_response as $item) {
$item_name = '';
try {
$item_name = $item->m . " {$statuses[$item->e]}";
} catch (\Exception $exception) {
$item_name = $item->m;
}
if ($item_name == $obj->full_name) {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$obj->phase}\r\n{$item->f[0]}"]);
$find = true;
break;
}
}
}
return $find;
}
private function check_raffletrades($obj, $curl_response)
{
$curl_response = $curl_response->response;
$find = false;
if ($obj->float) {
foreach ($curl_response as $item) {
if ($item->custom_market_name == $obj->full_name && $item->float <= $obj->float) {
$url = "https://metjm.net/shared/screenshots-v5.php?cmd=request_new_link&inspect_link={$item->inspect_link}";
$inspectUrl = explode('%20', $item->inspect_link)[1];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response);
$pattern = null;
$url_metjm = '';
if ($response->success) {
$pattern = $response->result->item_paintseed;
$url_metjm = "https://metjm.net/csgo/#{$inspectUrl}";
}
if ($obj->pattern){
if (Pattern::where('name', '=',$obj->pattern)
->where('value', '=', $pattern)->first()){
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$item->float}\r\n{$obj->pattern}\r\n{$url_metjm}"]);
$find = true;
break;
}
}
else {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$obj->phase}\r\n{$item->float}\r\npattern index = {$pattern}\r\n{$url_metjm}"]);
$find = true;
break;
}
}
}
}
else {
foreach ($curl_response as $item) {
if ($item->custom_market_name == $obj->full_name) {
$url = "https://metjm.net/shared/screenshots-v5.php?cmd=request_new_link&inspect_link={$item->inspect_link}";
$inspectUrl = explode('%20', $item->inspect_link)[1];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response);
$pattern = null;
$url_metjm = '';
if ($response->success) {
$pattern = $response->result->item_paintseed;
$url_metjm = "https://metjm.net/csgo/#{$inspectUrl}";
}
if ($obj->pattern){
if (Pattern::where('name', '=',$obj->pattern)
->where('value', '=', $pattern)->first()){
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$item->float}\r\n{$obj->pattern}\r\n{$url_metjm}"]);
$find = true;
break;
}
}
else {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$obj->phase}\r\n{$item->float}\r\npattern index = {$pattern}\r\n{$url_metjm}"]);
$find = true;
break;
}
}
}
}
return $find;
}
private function check_cstradegg($obj, $curl_response)
{
$curl_response = $curl_response->inventory;
$find = false;
foreach ($curl_response as $item) {
if ($obj->float) {
if ($item->market_hash_name == $obj->full_name && $item->wear <= $obj->float) {
$url = "https://metjm.net/shared/screenshots-v5.php?cmd=request_new_link&inspect_link={$item->inspect_link}";
$inspectUrl = explode('%20', $item->inspect_link)[1];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response);
$pattern = null;
$url_metjm = '';
if ($response->success) {
$pattern = $response->result->item_paintseed;
$url_metjm = "https://metjm.net/csgo/#{$inspectUrl}";
}
if ($obj->pattern){
if (Pattern::where('name', '=',$obj->pattern)
->where('value', '=', $pattern)->first()){
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$item->float}\r\n{$obj->pattern}\r\n{$url_metjm}"]);
$find = true;
break;
}
}
else {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$obj->phase}\r\n{$item->float}\r\npattern index = {$pattern}\r\n{$url_metjm}"]);
$find = true;
break;
}
}
} else {
if ($item->market_hash_name == $obj->full_name) {
$url = "https://metjm.net/shared/screenshots-v5.php?cmd=request_new_link&inspect_link={$item->inspect_link}";
$inspectUrl = explode('%20', $item->inspect_link)[1];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response);
$pattern = null;
$url_metjm = '';
if ($response->success) {
$pattern = $response->result->item_paintseed;
$url_metjm = "https://metjm.net/csgo/#{$inspectUrl}";
}
if ($obj->pattern){
if (Pattern::where('name', '=',$obj->pattern)
->where('value', '=', $pattern)->first()){
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$item->float}\r\n{$obj->pattern}\r\n{$url_metjm}"]);
$find = true;
break;
}
}
else {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$obj->phase}\r\n{$item->float}\r\npattern index = {$pattern}\r\n{$url_metjm}"]);
$find = true;
break;
}
}
}
}
return $find;
}
private function check_skintrade($obj, $curl_response)
{
$curl_response = array_merge($curl_response->cooler613, $curl_response->peter6364, $curl_response->para6350,
$curl_response->erikli74,
$curl_response->etipuf257, $curl_response->adobe1470, $curl_response->baron1578, $curl_response->katkat750);
$find = false;
if ($obj->float) {
foreach ($curl_response as $item) {
if ($item->m == $obj->full_name && $item->f <= $obj->float) {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$item->f}\r\n{$obj->phase}\r\nhttps://metjm.net/csgo/#{$item->i}"]);
$find = true;
break;
}
}
}
else {
foreach ($curl_response as $item) {
if ($item->m == $obj->full_name) {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$obj->phase}\r\nhttps://metjm.net/csgo/#{$item->i}"]);
$find = true;
break;
}
}
}
return $find;
}
private function check_csgosum($obj, $curl_response)
{
try {
$find = false;
$curl_response = $curl_response[0]->response;
foreach ($curl_response as $item) {
if ($item->name == $obj->full_name && $item->current > 0) {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$obj->phase}"]);
$find = true;
break;
}
}
return $find;
} catch (\Exception $exception) {
return false;
}
}
private function check_skinsjar($obj, $curl_response)
{
$curl_response = collect($curl_response->items);
$find_obj = null;
if ($obj->float) {
$find_obj = $curl_response->where('name', '=', $obj->full_name)->where('floatMax', '<=', $obj->float);
}
else {
$find_obj = $curl_response->where('name', '=', $obj->full_name);
}
if (count($find_obj)) {
if ($obj->pattern){
foreach ($find_obj as $fo){
$id = $fo->items[0]->id;
$inspectUrl = $fo->items[0]->inspectUrl;
$url = "https://metjm.net/shared/screenshots-v5.php?cmd=request_new_link&inspect_link=steam://rungame/730/{$id}/+csgo_econ_action_preview%25{$inspectUrl}";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response);
$pattern = null;
$url_metjm = '';
if ($response->success) {
$pattern = $response->result->item_paintseed;
$url_metjm = "https://metjm.net/csgo/#{$inspectUrl}";
}
if (Pattern::where('name', '=',$obj->pattern)
->where('value', '=', $pattern)->first())
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$fo->floatMax}\r\n{$pattern}\r\n{$url_metjm}"]);
return true;
}
} else {
$find_obj = $find_obj->first();
$id = $find_obj->items[0]->id;
$inspectUrl = $find_obj->items[0]->inspectUrl;
$url = "https://metjm.net/shared/screenshots-v5.php?cmd=request_new_link&inspect_link=steam://rungame/730/{$id}/+csgo_econ_action_preview%25{$inspectUrl}";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response);
$pattern = null;
$url_metjm = '';
if ($response->success) {
$pattern = $response->result->item_paintseed;
$url_metjm = "https://metjm.net/csgo/#{$inspectUrl}";
}
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$obj->phase}\r\n{$find_obj->floatMax}\r\npattern index = {$pattern}\r\n{$url_metjm}"]);
return true;
}
}
return false;
}
private function check_lootfarm($obj, $curl_response)
{
$find = false;
foreach ($curl_response as $item) {
if ($item->name == $obj->full_name) {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$obj->phase}"]);
$find = true;
}
}
return $find;
}
private function check_csdeals($obj, $curl_response)
{
$find = null;
foreach ($curl_response as $item) {
$item_name = $item->m;
if (is_numeric($item_name)) $item_name = $curl_response[$item_name]->m;
if ($obj->float) {
if ($item_name == $obj->full_name && $item->k < $obj->float) {
$obj->float = $item->k;
$find = $obj;
break;
}
} else {
if ($item_name == $obj->full_name) {
$find = $obj;
break;
}
}
}
if ($find) {
$this->replyWithChatAction(['action' => Actions::TYPING]);
$this->replyWithMessage(['text' => "{$obj->name}\r\n{$obj->url}\r\n{$obj->phase}\r\n{$obj->float}"]);
}
return $find;
}
}<file_sep>/app/Http/Controllers/TelegramController.php
<?php
namespace App\Http\Controllers;
use App\Item;
use App\Pattern;
use App\Site;
use App\Task;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Telegram\Bot\Laravel\Facades\Telegram;
class TelegramController extends Controller
{
public function handle()
{
set_time_limit(0);
Telegram::commandsHandler(true);
}
public function test(){
$pattern_names = DB::select('select distinct items.name from items, patterns where items.id = patterns.item_id');
dd(collect($pattern_names)->where('name', '=', '★ Bayonet | Autotronic (Battle-Scarred)ads'));
// $name = explode(" (", "★ Bayonet | Autotronic (Battle-Scarred)");
// dd($name);
// $csmoney = Site::find(2);
$curl = curl_init();
// curl_setopt($curl, CURLOPT_URL,"https://metjm.net/shared/screenshots-v5.php?cmd=request_new_link&inspect_link=steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198360517576A12592785808D4801592215145461771");
curl_setopt($curl, CURLOPT_URL,"https://cs.money/load_bots_inventory");
// curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($curl, CURLOPT_HTTPHEADER, array(
// "Origin: https://ru.tradeskinsfast.com",
// "Referer: https://ru.tradeskinsfast.com/",
// "Connection: keep-alive",
// "Content-Length: 0",
// "X-Requested-With: XMLHttpRequest",
// "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
// "Accept: application/json, text/javascript, */*; q=0.01",
// "Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4",
// "Authority: ru.tradeskinsfast.com",
// "Method: POST",
// "Path: /ajax/botsinventory",
// "Scheme: https"
// ));
// curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// curl_setopt( $curl, CURLOPT_HEADER, true );
// curl_setopt ($curl, CURLOPT_USERAGENT, "Mozilla/5.0");
$curl_response = curl_exec($curl);
// $curl_response = json_decode($curl_response);
$csmoney_items = collect(json_decode($curl_response));
$item = $csmoney_items->where('m', '=', 'M4A4 | Howl')->where('e', '=', 'MW')->first();
dd($item);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// dd($code);
if ($code == '503') {
sleep(4);
$curl_response = curl_exec($curl);
}
dd($curl_response);
}
}
<file_sep>/app/Classes/NeedItem.php
<?php
/**
* Created by PhpStorm.
* User: Egor
* Date: 30.10.2017
* Time: 21:48
*/
namespace App\Classes;
class NeedItem
{
public $name;
public $full_name;
public $url;
public $chat_id;
public $phase;
public $float;
public $pattern;
public function __construct($name, $url, $chat_id, $phase, $float, $pattern)
{
$this->name = $name;
$this->full_name = $name;
if ($phase) {
if (strpos($this->name, '(') !== false) {
$parts_name = explode('(', $this->name);
$this->full_name = $parts_name[0];
$this->full_name .= $phase . ' (';
$this->full_name .= $parts_name[1];
} else {
$this->full_name .= " {$this->phase}";
}
}
$this->url = $url;
$this->chat_id = $chat_id;
$this->phase = $phase;
$this->float = $float;
$this->pattern = $pattern;
}
}<file_sep>/app/Console/Commands/Lootfarm.php
<?php
namespace App\Console\Commands;
use App\Site;
use App\Task;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Telegram\Bot\Laravel\Facades\Telegram;
class Lootfarm extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'lootfarm:check';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
Log::info('lootfarm check');
$site = Site::find(10);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $site->get_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$items = json_decode(curl_exec($curl));
$items = collect($items);
Log::info(count($items));
$tasks = Task::with('item')->where('site_id', '=', 10)->get();
foreach ($tasks as $task){
$item = $items->where('name', '=', $task->item->full_name)->first();
if ($item){
Telegram::sendMessage([
'chat_id' => $task->chat_id,
'text' => "{$task->item->name}\r\n{$site->url}\r\n{$task->item->phase}"
]);
$task->delete();
}
}
Log::info('end check lootfarm');
}
}
<file_sep>/app/Console/Commands/CsMoney.php
<?php
namespace App\Console\Commands;
use App\Item;
use App\Site;
use App\Task;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Telegram\Bot\Laravel\Facades\Telegram;
class CsMoney extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'csmoney:check';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Checking csmoney items';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
Log::info('csmoney check');
$csmoney = Site::find(7);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $csmoney->get_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_exec = curl_exec($curl);
$csmoney_items = collect(json_decode($curl_exec));
Log::info(count($csmoney_items));
if (count($csmoney_items) > 0) {
$statuses = ['Factory New' => 'FN', 'Minimal Wear' => 'MW', 'Field-Tested' => 'FT',
'Battle-Scarred' => 'BS', 'Well-Worn' => 'WW'];
$tasks = Task::with('item')->where('site_id', '=', 7)->get();
foreach ($tasks as $task) {
$name_parts = explode(' (', $task->item->full_name);
$name = trim($name_parts[0]);
$status = count($name_parts) > 1 ? trim($statuses[str_replace(')', '', $name_parts[1])]) : null;
$item = null;
if ($task->float) {
if ($status) $item = $csmoney_items->where('m', '=', $name)->where('e', '=', $status)->where('f.0', '<=', $task->float)->first();
else $item = $csmoney_items->where('m', '=', $name)->where('f.0', '<=', $task->float)->first();
}
else {
if ($status) $item = $csmoney_items->where('m', '=', $name)->where('e', '=', $status)->first();
else $item = $csmoney_items->where('m', '=', $name)->first();
}
if ($item) {
Telegram::sendMessage([
'chat_id' => $task->chat_id,
'text' => "{$task->item->name}\r\n{$csmoney->url}\r\n{$task->item->phase}\r\n{$item->f[0]}"
]);
$task->delete();
}
}
}
else {
Log::info($curl_exec);
}
Log::info('end check csmoney');
}
}
<file_sep>/app/Console/Commands/Skinsjar.php
<?php
namespace App\Console\Commands;
use App\Site;
use App\Task;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Telegram\Bot\Laravel\Facades\Telegram;
class Skinsjar extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'skinsjar:check';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
Log::info('skinsjar check');
$site = Site::find(9);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $site->get_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$items = json_decode(curl_exec($curl));
try {
$items = collect($items->items);
Log::info(count($items));
$tasks = Task::with('item')->where('site_id', '=', 9)->get();
foreach ($tasks as $task) {
$item = null;
if ($task->float) {
$item = $items->where('name', '=', $task->item->full_name)
->where('floatMin', '<=', $task->float)->first();
} else {
$item = $items->where('name', '=', $task->item->full_name)->first();
}
if ($item) {
$id = $item->items[0]->id;
$inspectUrl = $item->items[0]->inspectUrl;
$url = "https://metjm.net/shared/screenshots-v5.php?cmd=request_new_link&inspect_link=steam://rungame/730/{$id}/+csgo_econ_action_preview%25{$inspectUrl}";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response);
$pattern = null;
$url_metjm = '';
if ($response->success){
$pattern = $response->result->item_paintseed;
$url_metjm = "https://metjm.net/csgo/#{$inspectUrl}";
}
Telegram::sendMessage([
'chat_id' => $task->chat_id,
'text' => "{$task->item->name}\r\n{$site->url}\r\n{$task->item->phase}\r\n{$item->floatMin}\r\npattern index = {$pattern}\r\n{$url_metjm}"
]);
$task->delete();
}
}
}catch (\Exception $exception){
Log::info('error');
}
Log::info('end check skinsjar');
}
}
|
9851f730801a81c71356650d296fe19c10e46fce
|
[
"PHP"
] | 7 |
PHP
|
Karpatsky/csgobot
|
1e2a209cc8a300d5bcb9fabf5e8b2e1beb594969
|
2916ed934cf46fb0a50326fda758412204ad7944
|
refs/heads/master
|
<file_sep># Maintainer: <NAME> <<EMAIL>>
pkgname=python-h5py-openmpi
pkgver=2.3.0
pkgrel=1
pkgdesc="General-purpose Python bindings for the HDF5 library using OpenMPI"
url="http://www.h5py.org"
arch=('i686' 'x86_64')
license=('BSD')
depends=('hdf5-openmpi' 'python-mpi4py' 'python-numpy')
makedepends=('cython')
conflicts=('python-h5py')
provides=('python-h5py')
source=(https://github.com/h5py/h5py/archive/"$pkgver".tar.gz)
md5sums=('2dca39fb2ff6e70824487201e1d1fb84')
sha1sums=('10540a8cd2de9b12e9c08da5a2c70ad22af948fe')
sha256sums=('a2c60ed924195714c3ac3e2816a9c47bf092b43d9e519ccb18faa71ec00d8680')
build() {
cd "$srcdir/h5py-$pkgver"
export CC=mpicc
python setup.py build --mpi
}
check() {
cd "$srcdir/h5py-$pkgver"
export CC=mpicc
python setup.py test --mpi
}
package() {
cd "$srcdir/h5py-$pkgver"
python setup.py install --mpi --prefix=/usr --root="$pkgdir/" --optimize=1
install -D -m644 licenses/license.txt "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
}
# vim:set ts=2 sw=2 et:
<file_sep># Maintainer: <NAME> <<EMAIL>>
pkgname=python2-fftw
_py_pkgname=pyFFTW # The pypi package name
pkgver=0.9.2
pkgrel=3
pkgdesc="A pythonic wrapper around FFTW"
arch=('i686' 'x86_64')
url="http://pypi.python.org/pypi/pyFFTW/"
license=('GPL3')
depends=('python2-numpy' 'fftw')
options=(!emptydirs)
source=(http://pypi.python.org/packages/source/p/$_py_pkgname/$_py_pkgname-$pkgver.tar.gz)
md5sums=('34fcbc68afb8ebe5f040a02a8d20d565')
sha1sums=('f8ef40d54b3e6a7322cb824f222f9f47130d2284')
sha256sums=('f6bbb6afa93085409ab24885a1a3cdb8909f095a142f4d49e346f2bd1b789074')
## Note that for v0.9.2, several tests fail, but for git master (as of 2014-01-13), all the tests pass, but it takes about 10 minutes to complete
#check() {
# cd "$srcdir/$_py_pkgname-$pkgver"
# python2 setup.py build_ext --inplace
# python2 setup.py test
#}
build() {
cd "$srcdir/$_py_pkgname-$pkgver"
python2 setup.py build
}
package() {
cd "$srcdir/$_py_pkgname-$pkgver"
python2 setup.py install --root="$pkgdir/" --optimize=1
}
# vim:set ts=2 sw=2 et:
<file_sep>========
CONTENTS
========
This contains my work for Arch linux.
``python2-fftw``: The pyFFTW library
``python2-bufr``: Python interface to BUFR reader
``libbufr-ecmwf``: BUFR library from ECMWF
``pyresample`` : Image resampling of geospatial data
``python2-memoryprofiler``: Line-by-line memory profiler
.. vim: syntax=rst
<file_sep># Maintainer: <NAME> <<EMAIL>>
pkgname=bspwm-lightdm
_github_pkgname=bspwm
pkgver=0.8.8
pkgrel=1
pkgdesc='Files for lightdm to work with bspwm'
arch=('any')
url='https://github.com/baskerville/bspwm/tree/master/contrib/lightdm'
license=('custom:BSD')
depends=('lightdm')
optdepends=()
source=("https://github.com/baskerville/${_github_pkgname}/archive/${pkgver}.tar.gz")
md5sums=('3f9fa85c48282605b54321e042eeaabf')
sha1sums=('df24471169c3b705754fe0dbeeec88165d218038')
sha256sums=('378c5e42e9058a22e519a8f727e7d078eb5945915adb6edb17e2471310e73790')
package() {
cd "$srcdir/${_github_pkgname}-${pkgver}/contrib/lightdm"
install -D -m755 bspwm-session "${pkgdir}/usr/bin/bspwm-session"
install -D -m644 bspwm.desktop "${pkgdir}/usr/share/xsessions/bspwm.desktop"
cd "$srcdir/${_github_pkgname}-${pkgver}"
install -D -m644 LICENSE "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
}
<file_sep># Maintainer: <NAME> <rich at dranek com>
# Contributor: <NAME> <<EMAIL>>
# Contributor: <NAME> <<EMAIL>>
pkgname=taskd
pkgver=1.0.0
pkgrel=4
pkgdesc="A lightweight, secure server providing multi-user, multi-client access to task data"
url='http://tasktools.org/projects/taskd.html'
license=('MIT')
arch=('i686' 'x86_64')
depends=('task' 'gnutls')
makedepends=('cmake')
backup=('etc/conf.d/taskd')
install=taskd.install
source=('http://taskwarrior.org/download/taskd-1.0.0.tar.gz'
'taskd.conf' 'taskd.service'
'0001-fix-pki-generate-path.patch')
md5sums=('1cead23539e36d5623cb3ca1225072c0'
'ab545ca3081efb251a76f48574c7a6e4'
'fea451584f175beae776dc9f92281a22'
'e4ef803c7b6682e5893ec442b205cea2')
prepare() {
patch -p0 < "0001-fix-pki-generate-path.patch"
}
build() {
cd "$srcdir/taskd-${pkgver}"
cmake . \
-DCMAKE_INSTALL_PREFIX=/usr \
-DCMAKE_BUILD_TYPE=Release
make
}
# Doesn't exist in 1.0.0 tarball but it does in git...
#check() {
# cd "$srcdir/taskd-${pkgver}/test"
# make
# ./run_all
#}
package() {
cd "$srcdir/taskd-${pkgver}"
make DESTDIR="${pkgdir}" install
install -Dm644 "${srcdir}"/taskd.conf \
"${pkgdir}"/etc/conf.d/taskd
install -Dm644 "${srcdir}"/taskd.service \
"${pkgdir}"/usr/lib/systemd/system/taskd.service
install -d "${pkgdir}"/var/lib/taskd
install -Dm644 LICENSE \
"${pkgdir}"/usr/share/licenses/${pkgname}/LICENSE
install -d "${pkgdir}"/usr/share/taskd/pki
install -D "${srcdir}"/taskd-${pkgver}/pki/generate{,.ca,.client,.crl,.server} \
"${pkgdir}"/usr/share/taskd/pki/
}
|
f69c798a42dca30eb50a37a68d61a61e450f37d0
|
[
"reStructuredText",
"Shell"
] | 5 |
Shell
|
richli/arch
|
92838dcb3b9929db295a971a2c06b2f98701b621
|
74bc4b6697bd5e60f218af365f1bb6a92347e382
|
refs/heads/main
|
<file_sep># Generated by Django 2.2.5 on 2021-02-04 18:52
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='MyUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('email', models.EmailField(max_length=80, unique=True, verbose_name='Email')),
('first_name', models.CharField(max_length=80, null=True, verbose_name='First Name')),
('last_name', models.CharField(max_length=80, null=True, verbose_name='Last Name')),
('phone_number', models.IntegerField(null=True, verbose_name='Phone Number')),
('country', models.CharField(max_length=255, null=True, verbose_name='Country')),
('date_joined', models.DateTimeField(auto_now_add=True, verbose_name='Date Joined')),
('last_login', models.DateTimeField(auto_now_add=True, verbose_name='Last Login')),
('active', models.BooleanField(default=True, verbose_name='Is Active')),
('admin', models.BooleanField(default=False, verbose_name='Is Admin')),
('staff', models.BooleanField(default=False, verbose_name='Is Staff')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Country_files',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('country_code', models.CharField(max_length=100)),
('country_name', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='Currency_files',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('currency_name', models.CharField(max_length=100)),
('currency_code', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='XpayAccount',
fields=[
('currency', models.CharField(max_length=100)),
('date_opened', models.DateTimeField(auto_now_add=True)),
('iban_no', models.CharField(max_length=100)),
('account_number', models.AutoField(primary_key=True, serialize=False)),
('account_number2', models.CharField(max_length=50)),
('account_status', models.CharField(default='open', max_length=10)),
('email', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='AccountTransaction',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('sender_iban_no', models.CharField(max_length=80)),
('sender_full_name', models.CharField(max_length=80)),
('receiver_iban_no', models.CharField(max_length=80)),
('xpay_iban_no', models.CharField(max_length=80)),
('date_of_transaction', models.DateTimeField(auto_now_add=True, null=True)),
('receiver_full_name', models.CharField(max_length=80)),
('receiver_bank_name', models.CharField(max_length=80)),
('sender_bank_name', models.CharField(max_length=80)),
('account_balance', models.IntegerField(default=0)),
('amount', models.IntegerField()),
('xpayaccount_email', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='xpay.XpayAccount')),
],
),
]
<file_sep>from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .forms import UserAdminCreationForm, UserAdminChangeForm, XpayAccountForm
from .models import MyUser, XpayAccount, Currency_files,Country_files
from django.contrib.auth import get_user_model
MyUser = get_user_model()
class UserAdmin(BaseUserAdmin):
form = UserAdminChangeForm
add_form = UserAdminCreationForm
list_display = ('email', 'first_name', 'last_name', 'phone_number',
'country', 'last_login', 'admin', 'active', 'date_joined', 'staff')
list_filter = ('admin',)
fieldsets = (
(None, {'fields': ('email', 'password', 'first_name')}),
('Personal info', {'fields': ()}),
('Permissions', {'fields': ('is_admin', 'is_staff','is_active')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', '<PASSWORD>', '<PASSWORD>', 'first_name', 'last_name', 'phone_number', 'country')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
admin.site.register(MyUser, UserAdmin)
admin.site.register(XpayAccount)
admin.site.register(Country_files)
admin.site.register(Currency_files)
admin.site.unregister(Group)
<file_sep># Payment-System-Xpay
Ödeme sistemleri alanında projem
<file_sep># Generated by Django 2.2.5 on 2021-02-06 09:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('xpay', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='accounttransaction',
old_name='xpayaccount_email',
new_name='xpayaccount',
),
]
<file_sep>
{% extends 'navbar_profile.html' %}
{% block content %}
<div id = "sidebar">
<ul>
<li>
<a href="{% url 'open_and_close_account_page' %}">+/- Add/Delete</a>
</li>
</ul>
<div class='side_bar_iban_no'>
<ul>
<li>
{% for email in open_iban_list %}
<a href="{% url 'detail' email.account_number %}"> {{ email.iban_no }}</a>
{% endfor %}
</li>
</ul>
</div>
</div>
<div class='ibanno'><p>{{iban_detail_page.iban_no}}</p></div>
<div class='dateopened'><p>{{iban_detail_page.date_opened}}</p></div>
<div class='account_balance'><p>{{ account_transaction_last.account_balance }}</p></div>
<div class="bank_name"><p>Xpay Bank</p></div>
<div class='receiver_iban_no_account_balance'>
<ul>
{% for email in account_transaction %}
<br>{{ email.account_balance }}
{% endfor %}
</ul>
</div>
<div class='receiver_iban_no_detail_date'>
<ul>
{% for email in account_transaction %}
<br>{{ email.date_of_transaction }}
{% endfor %}
</ul>
</div>
<div class='receiver_iban_no_detail_sender_bank'>
<ul>
{% for email in account_transaction %}
<br>{{ email.sender_bank_name }}
{% endfor %}
</ul>
</div>
<div class='receiver_iban_no_detail_receiver_bank'>
<ul>
{% for email in account_transaction %}
<br>{{ email.receiver_bank_name }}
{% endfor %}
</ul>
</div>
<div class='receiver_iban_no_detail_sender_full_name'>
<ul>
{% for email in account_transaction %}
<br>{{ email.sender_full_name }}
{% endfor %}
</ul>
</div>
<div class='receiver_iban_no_receiver_full_name'>
<ul>
{% for email in account_transaction %}
<br>{{ email.receiver_full_name }}
{% endfor %}
</ul>
</div>
<div class='receiver_iban_no_detail_amount'>
<ul>
{% for email in account_transaction %}
<br>{{ email.amount }}
{% endfor %}
</ul>
</div>
<div class='my_iban_no'>
<h3 class="menu1">My {{iban_detail_page.iban_no}} account infermation</h3>
<ul class='iban_list_title'>
<li>Account oppening date</li>
<li>Latest balance</li>
<li>İban number</li>
<li>Bank name</li>
</ul>
</div>
<div class='my_iban_no2'>
<h3 class="menu2">My {{iban_detail_page.iban_no}} account history</h3>
<ul class='iban_list_title2'>
<li>Total</li>
<li>İncoming / Outgoing money</li>
<li>Sender name</li>
<li>Receiver name</li>
<li>Bank name</li>
<li>History</li>
</ul>
</div>
{% endblock %}<file_sep>from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.contrib.auth import authenticate
from xpay.models import XpayAccount, Currency_files, Country_files, AccountTransaction
import re
from django.db.models import Sum
from django.contrib.auth.forms import UserChangeForm
from django.db.models import F
MyUser = get_user_model()
class UserAdminCreationForm(forms.ModelForm):
password = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(
label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = MyUser
fields = ('email',)
def clean_password2(self):
password = self.cleaned_data.get("password")
password2 = self.cleaned_data.get("password2")
if password and password2 and password != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
user = super(UserAdminCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password"])
if commit:
user.save()
return user
class UserAdminChangeForm(forms.ModelForm):
password = ReadOnly<PASSWORD>Field()
class Meta:
model = MyUser
fields = ('email', 'password', 'active', 'admin')
def clean_password(self):
return self.initial["password"]
class SignUpForm(forms.ModelForm):
password = forms.CharField(min_length=8, widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)
k=Country_files.objects.all().values_list('country_code', flat=True)
v=Country_files.objects.all().values_list('country_name', flat=True)
country_choices =list(zip(k,v))
country = forms.ChoiceField(choices=country_choices, widget=forms.Select())
class Meta:
model = MyUser
fields = ('email', 'first_name', 'last_name',
'phone_number', 'country')
def clean_password2(self):
password = self.cleaned_data.get("password")
password2 = self.cleaned_data.get("password2")
if password != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
user = super(SignUpForm, self).save(commit=False)
user.set_password(self.cleaned_data["password"])
user.is_active = False
if commit:
user.save()
return user
class LoginForm(forms.Form):
email = forms.EmailField(label='Email:')
password = forms.CharField(label="Password:", widget=forms.PasswordInput)
class META:
model = MyUser
fields = ('email', 'password')
class EditProfileForm(UserChangeForm):
k=Country_files.objects.all().values_list('country_code', flat=True)
v=Country_files.objects.all().values_list('country_name', flat=True)
country_choices =list(zip(k,v))
country = forms.ChoiceField(choices=country_choices, widget=forms.Select())
class Meta:
model = MyUser
fields = ('email', 'first_name', 'last_name','phone_number','country')
class XpayAccountForm(forms.ModelForm):
k=Currency_files.objects.all().values_list('currency_code', flat=True)
v=Currency_files.objects.all().values_list('currency_name', flat=True)
currency_choices =list(zip(k,v))
currency = forms.ChoiceField(choices=currency_choices, widget=forms.Select())
class Meta:
model=XpayAccount
fields=('currency',)
class CurrentAccountForm(forms.ModelForm):
current_accounts = forms.ModelChoiceField(queryset=None, to_field_name='iban_no')
class Meta:
model=XpayAccount
fields=('current_accounts',)
def __init__(self, email, *args, **kwargs):
super(CurrentAccountForm, self).__init__(*args,**kwargs)
self.fields['current_accounts'].queryset = XpayAccount.objects.filter(email=email, account_status='open').values_list('iban_no', flat=True).distinct().order_by('account_number2')
class MoneyDepositingForm(forms.ModelForm):
receiver_iban_no = forms.ModelChoiceField(queryset=None, to_field_name='iban_no')
amount=forms.IntegerField(min_value=0)
class Meta:
model=AccountTransaction
fields=('receiver_iban_no','sender_full_name','sender_iban_no','sender_bank_name','amount',)
def __init__(self, email,*args, **kwargs):
super(MoneyDepositingForm, self).__init__(*args,**kwargs)
self.fields['receiver_iban_no'].queryset = XpayAccount.objects.filter(email=email, account_status='open').values_list('iban_no', flat=True).distinct().order_by('account_number2')
class SendMoneyForm(forms.ModelForm):
sender_iban_no = forms.ModelChoiceField(queryset=None, to_field_name='iban_no')
amount=forms.IntegerField(min_value=0)
class Meta:
model=AccountTransaction
fields=('sender_iban_no','receiver_iban_no','receiver_full_name','receiver_bank_name','amount',)
def __init__(self, email,*args, **kwargs):
super(SendMoneyForm, self).__init__(*args,**kwargs)
self.fields['sender_iban_no'].queryset = XpayAccount.objects.filter(email=email, account_status='open').values_list('iban_no', flat=True).distinct().order_by('account_number2')
def clean(self):
cleaned_data = super().clean()
amount=cleaned_data.get("amount")
sender_iban_no=cleaned_data.get("sender_iban_no")
account_balance_total=AccountTransaction.objects.filter(xpay_iban_no=sender_iban_no).aggregate(sum=Sum('amount'))['sum'] or 0
if account_balance_total < amount:
raise forms.ValidationError('Insufficient account balance !')
else:
pass
<file_sep>from django.apps import AppConfig
class XpayConfig(AppConfig):
name = 'xpay'
<file_sep>from django.conf import settings
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager, PermissionsMixin
)
from django.utils import timezone
import numpy as np
import pandas as pd
import uuid
from django.dispatch import receiver
from django.db.models.signals import post_save, pre_save
from django.db.models import Sum
from django.db.models import F
MyUser = settings.AUTH_USER_MODEL
class UserManager(BaseUserManager):
def create_user(self, email, password=<PASSWORD>, first_name=None, last_name=None, phone_number=None, country=None, is_active=True, is_staff=False, is_admin=False):
if not email:
raise ValueError('Users must have an email address')
if not password:
raise ValueError('Users must have a password')
user_obj = self.model(
email=self.normalize_email(email),
first_name=first_name,
last_name=last_name,
phone_number=phone_number,
country=country,
)
user_obj.active = is_active
user_obj.staff = is_staff
user_obj.admin = is_admin
user_obj.set_password(<PASSWORD>)
user_obj.save(using=self._db)
return user_obj
def create_staff_user(self, email, password=None):
user_obj = self.create_user(
email,
password=<PASSWORD>,
is_staff=True
)
return user_obj
def create_superuser(self, email, password=<PASSWORD>):
user_obj = self.create_user(
email,
password=<PASSWORD>,
is_staff=True,
is_admin=True,
)
return user_obj
class MyUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(null=False, blank=False,unique=True, max_length=80, verbose_name='Email')
first_name = models.CharField(null=True, blank=False, max_length=80, verbose_name='First Name')
last_name = models.CharField(null=True, blank=False, max_length=80, verbose_name='Last Name')
phone_number = models.IntegerField(blank=False, null=True, verbose_name='Phone Number')
country = models.CharField(max_length=255, blank=False, null=True, verbose_name='Country')
date_joined = models.DateTimeField(verbose_name='Date Joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='Last Login', auto_now_add=True)
active = models.BooleanField(default=True, verbose_name='Is Active')
admin = models.BooleanField(default=False, verbose_name='Is Admin')
staff = models.BooleanField(default=False, verbose_name='Is Staff')
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.email
def get_short_name(self):
if self.first_name:
return self.first_name
return self.email
def get_full_name(self):
if self.first_name and self.last_name:
return f"{self.first_name} {self.last_name}"
return self.email
@property
def is_active(self):
return self.active
@property
def is_staff(self):
return self.staff
@property
def is_superuser(self):
return self.admin
class Currency_files(models.Model):
currency_name=models.CharField(max_length=100)
currency_code=models.CharField(max_length=100)
df_currency_file=pd.read_csv("C:\\Users\\ekrem\\anaconda3\envs\\djangoenv\\pandas cvs dosyaları\\currenciees.csv", encoding = "ISO-8859-1", header=0, skip_blank_lines=True)
df_currency_file = df_currency_file.sort_values('Currency_name')
df_currency_file=df_currency_file.set_index("Currency_name")
idx = ['Turkish lira','European euro','United States Dollar'] + [i for i in df_currency_file.index if i not in ['Turkish lira','European euro','United States Dollar']]
df_currency_file = df_currency_file.reindex(idx)
df_currency_file.reset_index(drop=False,inplace=True)
crrncy = []
for i in range(len(df_currency_file)):
crrncy=Currency_files.objects.get_or_create( #csv dosya okuma
currency_name=df_currency_file.iloc[i][0],
currency_code=df_currency_file.iloc[i][1],
)
class Country_files(models.Model):
country_code=models.CharField(max_length=100)
country_name=models.CharField(max_length=100)
df_iso_country=pd.read_csv("C:\\Users\\ekrem\\anaconda3\envs\\djangoenv\\pandas cvs dosyaları\\iso_2digit_alpha_country_codes.csv", encoding = "ISO-8859-1", header=0, skip_blank_lines=True)
df_iso_country = df_iso_country.sort_values('Country_name')
cntry = []
for i in range(len(df_iso_country)):
cntry=Country_files.objects.get_or_create(
country_code=df_iso_country.iloc[i][0],
country_name=df_iso_country.iloc[i][1],
)
class XpayAccount(models.Model):
email = models.ForeignKey(MyUser,on_delete=models.CASCADE)
currency = models.CharField(max_length=100)
date_opened = models.DateTimeField(auto_now_add=True)
iban_no=models.CharField(max_length=100)
account_number=models.AutoField(primary_key=True)
account_number2=models.CharField(max_length=50)
account_status=models.CharField(max_length=10, default='open')
def save(self,*args, **kwargs):
self.iban_no =self.email.country + self.currency + self.account_number2
super(XpayAccount, self).save(*args, **kwargs)
@receiver(post_save, sender=XpayAccount)
def account_number_digit(sender,created, instance, **kwargs):
if created:
instance.account_number2 = "%016d" % instance.pk
instance.save()
class AccountTransaction(models.Model):
xpayaccount = models.ForeignKey(XpayAccount , on_delete=models.CASCADE)
sender_iban_no=models.CharField(max_length=80)
sender_full_name=models.CharField(max_length=80)
receiver_iban_no=models.CharField(max_length=80)
xpay_iban_no=models.CharField(max_length=80)
date_of_transaction = models.DateTimeField(auto_now_add=True,null=True, blank=True)
receiver_full_name=models.CharField(max_length=80)
receiver_bank_name=models.CharField(max_length=80)
sender_bank_name=models.CharField(max_length=80)
account_balance=models.IntegerField(default=0)
amount=models.IntegerField()
def save(self,*args, **kwargs):
account_balance_last = AccountTransaction.objects.filter(xpay_iban_no=self.xpay_iban_no).aggregate(sum=Sum('amount'))['sum'] or 0
if (account_balance_last < -self.amount) and (self.xpay_iban_no==self.sender_iban_no):
return account_balance_last
else:
self.account_balance = self.amount + account_balance_last
super(AccountTransaction, self).save(*args, **kwargs)
<file_sep>from django.urls import path
from . import views
from django.conf.urls import url
urlpatterns = [
path('', views.home_page, name='home_page'),
path('login_page/', views.login_page, name='login_page'),
path('signup_page/', views.signup_page, name='signup_page'),
path('profile_page/', views.profile_page, name='profile_page'),
path('my_xpay_account_page/', views.my_xpay_account_page, name='my_xpay_account_page'),
path('open_and_close_account_page/', views.open_and_close_account_page, name='open_and_close_account_page'),
path('money_depositing_page/', views.money_depositing_page, name='money_depositing_page'),
path('money_depositing_confirmation_page/', views.money_depositing_confirmation_page, name='money_depositing_confirmation_page'),
path('send_money_page/', views.send_money_page, name='send_money_page'),
path('send_money_confirmation_page/', views.send_money_confirmation_page, name='send_money_confirmation_page'),
path('my_xpay_account_page/<int:account_number>', views.detail, name='detail'),
path('user_profile_page', views.user_profile_page, name='user_profile_page'),
]<file_sep>import datetime
from django.contrib import messages
from django.contrib.auth import (authenticate, get_user_model, login,)
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.shortcuts import (get_list_or_404,
get_object_or_404,
redirect,
render)
from django.utils import timezone
from django.views import generic
from .forms import (CurrentAccountForm,
LoginForm,
MoneyDepositingForm,
SendMoneyForm,
SignUpForm,
XpayAccountForm,
EditProfileForm)
from .models import AccountTransaction, Country_files, XpayAccount
from django.contrib.auth.decorators import login_required
MyUser = get_user_model()
def signup_page(request):
form = SignUpForm(request.POST or None)
if form.is_valid():
data = form.cleaned_data
email = data.get('email')
password = <PASSWORD>('<PASSWORD>')
first_name = data.get('first_name')
last_name = data.get('last_name')
phone_number = data.get('phone_number')
country = data.get('country')
new_user = MyUser.objects.create_user(
email, password, first_name, last_name, phone_number, country)
new_user.save()
login(request, new_user)
messages.info(request, "Registration Successful")
return redirect('login_page')
context = {
"form": form
}
return render(request, "xpay/signup.html", context)
def login_page(request):
form = LoginForm(request.POST or None)
context = {
'form': form
}
if form.is_valid():
data = form.cleaned_data
email = data.get('email')
password = data.get('<PASSWORD>')
user = authenticate(request, email=email, password=password)
if user is not None:
login(request, user)
return redirect('profile_page')
else:
messages.warning(request, 'Email address or password is incorrect!')
return render(request, "xpay/login.html", context)
def home_page(request):
return render(request,'xpay/homepage.html')
def profile_page(request):
return render(request,'xpay/profile.html')
def my_xpay_account_page(request):
ibanNo=XpayAccount.objects.filter(email=request.user, account_status='open')
context={
'ibanNo':ibanNo,
}
return render(request,'xpay/my_account.html',context)
def detail(request, account_number):
iban_detail_page=get_object_or_404(XpayAccount, pk=account_number)
open_iban_list=XpayAccount.objects.filter(email_id=request.user, account_status='open')
account_transaction=AccountTransaction.objects.filter(xpay_iban_no=iban_detail_page.iban_no)
account_transaction_last=AccountTransaction.objects.filter(xpay_iban_no=iban_detail_page.iban_no).last()
context={
'open_iban_list' : open_iban_list,
'iban_detail_page' : iban_detail_page,
'account_transaction':account_transaction,
'account_transaction_last':account_transaction_last,
}
return render (request,'xpay/detail.html', context)
def user_profile_page(request):
if request.method == 'POST'and "update" in request.POST:
editform = EditProfileForm(request.POST, instance=request.user)
if editform.is_valid():
editform.save(commit=True)
return redirect("user_profile")
else:
return redirect("user_profile")
if request.method == 'POST'and "passform" in request.POST:
passform = PasswordChangeForm(user=request.user,data=request.POST)
if passform.is_valid():
passform.save()
update_session_auth_hash(request, passform.user)
messages.success(request, 'Your password was successfully updated!')
return redirect('user_profile')
else:
messages.error(request, 'Please correct the error below.')
return redirect('user_profile')
else:
editform=EditProfileForm(instance=request.user)
passform = PasswordChangeForm(request.user)
return render(request, 'xpay/user_profile.html',{"editform":editform, "passform":passform})
def open_and_close_account_page(request):
if request.method == "POST" and 'form1' in request.POST:
form1 = XpayAccountForm(request.POST)
if form1.is_valid():
post = form1.save(commit=False)
post.email = request.user
post.save()
if request.method == "POST" and 'form2' in request.POST:
form2= CurrentAccountForm(request.user, request.POST)
if form2.is_valid():
form2.iban_no = request.user
form2.iban_no = form2.cleaned_data['current_accounts']
account_status_query=XpayAccount.objects.filter(email=request.user, iban_no=form2.iban_no).update(account_status='close')
return redirect( 'open_and_close_account_page')
else:
form1 = XpayAccountForm()
form2 = CurrentAccountForm(request.user)
return render(request, 'xpay/open_and_close_account.html', {'form1': form1, 'form2':form2})
def money_depositing_page(request):
if request.method == "POST":
form = MoneyDepositingForm(request.user, request.POST)
if form.is_valid():
print('a')
return render(request,'xpay/money_depositing_confirmation.html',{'form': form})
print('b')
else:
form = MoneyDepositingForm(request.user)
return render(request, 'xpay/money_depositing.html', {'form': form})
def money_depositing_confirmation_page(request):
if request.method == "POST":
form = MoneyDepositingForm(request.user, request.POST)
if form.is_valid():
form = form.save(commit=False)
form.xpayaccount=XpayAccount.objects.get(account_number=request.user.id)
form.xpay_iban_no=form.receiver_iban_no
form.receiver_full_name=request.user.get_full_name()
form.save()
return redirect('money_depositing_page')
else:
form = MoneyDepositingForm(request.user)
return render(request, 'xpay/money_depositing.html', {'form': form})
def send_money_page(request):
if request.method == "POST":
form = SendMoneyForm(request.user, request.POST or None)
if form.is_valid():
return render(request,'xpay/send_money_confirmation.html',{'form': form})
else:
form = SendMoneyForm(request.user)
return render(request, 'xpay/send_money.html', {'form': form})
def send_money_confirmation_page(request):
if request.method == "POST":
form = SendMoneyForm(request.user, request.POST or None)
if form.is_valid():
form = form.save(commit=False)
form.xpayaccount=XpayAccount.objects.get(account_number=request.user.id)
form.sender_full_name=request.user.get_full_name()
form.xpay_iban_no=form.sender_iban_no
form.amount=form.amount*-1
form.save()
return redirect('send_money_page')
else:
form = SendMoneyForm(request.user)
return render(request, 'xpay/send_money.html', {'form': form})
|
2f170fd5fa18afac806fa3aece88c3456fc6bdbb
|
[
"Markdown",
"Python",
"HTML"
] | 10 |
Python
|
cetinodabasi/Payment-System-Xpay
|
7171c468aa43212e2aa5a12ab16e0fb9870a4277
|
a77c0e692fde26d68198d0a50bdafa2303d658d9
|
refs/heads/master
|
<repo_name>onXoot/OperationSystemCourseDesign<file_sep>/cal.h
#ifndef CAL_H
#define CAL_H
double exec(char *b);
int create(char a[],int n);
int deal(char a[],int n1);
int match_kuohao(char c[]);
double readnumber(char f[],int *i);
int priority(char op);
int is_operation(char op);
void postfix(char e[],char f[]);
double evalpost(char f[]);
#endif
<file_sep>/makefile
CXX = clang++
CPPFLAGS = -std=c++11
LDFLAGS = -pthread
server: cal.o stack.o server.o
$(CXX) -o $@ $^ $(LDFLAGS)
server.o: server.cpp
$(CXX) -c $^ $(CPPFLAGS)
cal.o : cal.c
$(CXX) -c $^ $(CPPFLAGS)
stack.o: stack.c
$(CXX) -c $^ $(CPPFLAGS)
client :client.o
$(CXX) -o client client.o -pthread
client.o: client.cpp
$(CXX) -c client.cpp -std=c++11
.PHONY : clean
clean:
-rm cal.o stack.o server.o client.o client server
<file_sep>/README.md
# OperationSystemCourseDesign
you are surpose to open 2 terminal to run this,<br>
one: <br>
make server<br>
./server<br>
and the other:<br>
make client<br>
./client<br>
<file_sep>/stack.h
#ifndef STACK_H
#define STACK_H
#define MAXSIZE 100
typedef char datatype;
typedef struct{
datatype a[MAXSIZE];
int top;
}sequence_stack;
void init(sequence_stack *st);
int empty(sequence_stack st);
datatype read(sequence_stack st);
void push(sequence_stack *st,datatype x);
void pop(sequence_stack *st);
#endif
<file_sep>/cal.c
#include "stack.h"
#include "cal.h"
#include <stdio.h>
#include <string.h>
double exec(char *b){
char f[100];
deal(b,strlen(b));
match_kuohao(b);
postfix(b,f);
return evalpost(f);
}
/*******************************************************/
/* 函数功能: 对输入的字符串中的负号进行处理! */
/*******************************************************/
int deal(char a[],int n1)
{
int i=0,k,k1;
while(i<=n1){
if(a[0]=='-'){ //当多项式中第一个字符就为负号时!
for(k=n1;k>=0;k--)
a[k+2]=a[k]; //将所有字符的元素后移2个单位!
n1=n1+2;
a[0]='('; //第一个位置插入'(';
a[1]='0'; //第二个位置插入'0';
k=4;
while(1){
if(((a[k]>='0')&&(a[k]<='9'))||(a[k]=='.')) k++;
else break;
}
for(k1=n1;k1>=k;k1--)
a[k1+1]=a[k1];
n1++;
a[k]=')'; //插入相应的')';
}
if((a[i]=='(')&&(a[i+1]=='-')){ //当负号在其他位置的情况:相应的只需在负号前插入一个'0'即可;
for(k=n1;k>i;k--)
a[k+1]=a[k];
a[i+1]='0';
n1++;
}
else i++;
}
a[n1+1]='\0';
k=n1+1;
return k; //字符串的实际长度发生变化,故将其返回!
}
/******************************************************/
/* 函数功能:判断表达式括号是否匹配 */
/* 函数参数:char类型数组c */
/* 函数返回值:int类型。返回1为匹配,返回0为不匹配 */
/******************************************************/
int match_kuohao(char c[])
{
int i=0;
sequence_stack s;
init(&s);
while(c[i]!='=')
{
switch(c[i])
{
case '{':
case '[':
case '(':push(&s,c[i]);break;
case '}':if(!empty(s)&&read(s)=='{' )
{pop(&s);break;}
else return 0;
case ']':if(!empty(s)&&read(s)=='[' )
{pop(&s);break;}
else return 0;
case ')':if(!empty(s)&&read(s)=='(' )
{pop(&s);break;}
else return 0;
}
i++;
}
return (empty(s));/*栈为空则匹配,否则不匹配*/
}
/****************************************************/
/* 函数功能:将数字字符串转变成相应的数 */
/* 函数参数:char类型数组f,指向int类型变量的指针i */
/* 函数返回值:double类型。返回数字字符串对应的数 */
/****************************************************/
double readnumber(char f[],int *i)
{ double x=0.0;
int k=0;
while(f[*i]>='0'&&f[*i]<='9') /*处理整数部分*/
{ x=x*10+(f[*i]-'0');
(*i)++;
}
if (f[*i]=='.') /*处理小数部分*/
{ (*i)++;
while (f[*i]>='0' && f[*i]<='9')
{x=x*10+(f[*i]-'0');
(*i)++;
k++;
}
}
while (k!=0)
{ x=x/10.0;
k=k-1;
}
return(x);
}
/**************************************************/
/* 函数功能:求运算符的优先级 */
/* 函数参数:char类型变量op */
/* 函数返回值:int类型。返回各中运算符的优先级。 */
/**************************************************/
int priority(char op)
{
switch(op)
{
case '=':return -1;
case '(':return 0;
case '+':
case '-':return 1;
case '*':
case '/':return 2;
default: return -1;
}
}
/*******************************************************/
/* 函数功能:判断一个字符是否为运算符 */
/* 函数参数:char类型变量op */
/* 函数返回值:int类型。返回1表示op运算符,否则不是。*/
/********************************************************/
int is_operation(char op)
{
switch(op)
{ case '+':
case '-':
case '*':
case '/':return 1;
default:return 0;
}
}
/**************************************************************/
/* 函数功能:将一个中缀表达式e转换为与它等价的后缀表达式f */
/* 函数参数:char类型数组变量e和f */
/* 函数返回值:空 */
/****************************************************** ********/
void postfix(char e[],char f[])
{ int i=0,j=0;
char opst[100];
int top,t;
top=0;
opst[top]='=';top++;
while(e[i]!='=')
{
if ((e[i]>='0'&&e[i]<='9')||e[i]=='.')
f[j++]=e[i]; /*遇到数字和小数点直接写入后缀表达式*/
else if (e[i]=='(') /*遇到左括号进入操作符栈*/
{ opst[top]=e[i];top++;}
else if (e[i]==')')
/*遇到右括号将其对应的左括号后的操作符全部写入后缀表达式*/
{
t=top-1;
while (opst[t]!='(') {f[j++]=opst[--top];t=top-1;}
top--; /*'('出栈*/
}
else if (is_operation(e[i])) /* '+ ,-, *, /' */
{
f[j++]=' '; /*用空格分开两个操作数*/
while (priority(opst[top-1])>=priority(e[i]))
f[j++]=opst[--top];
opst[top]=e[i];top++; /*当前元素进栈*/
}
i++; /*处理下一个元素*/
}
while (top) f[j++]=opst[--top];
}
/****************************************************/
/* 函数功能:求一个后缀表达式的值 */
/* 函数参数:char类型数组f */
/* 函数返回值:double类型。返回后缀表达式的值 */
/* 文件名:evalpost.c,函数名:evalpost() */
/****************************************************/
double evalpost(char f[])
{ double obst[100]; /*操作数栈*/
int top=0;
int i=0;
double x1,x2;
while (f[i]!='=')
{ if (f[i]>='0' && f[i]<='9')
{ obst[top]=readnumber(f,&i);top++;}
else if (f[i]==' ') i++;
else if (f[i]=='+')
{ x2=obst[--top];
x1=obst[--top];
obst[top]=x1+x2;top++;
i++;
}
else if (f[i]=='-')
{
x2=obst[--top];
x1=obst[--top];
obst[top]=x1-x2;top++;
i++;
}
else if (f[i]=='*')
{ x2=obst[--top];
x1=obst[--top];
obst[top]=x1*x2;top++;
i++;
}
else if (f[i]=='/')
{ x2=obst[--top];
x1=obst[--top];
obst[top]=x1/x2;top++;
i++;
}
}
return obst[0];
}
|
c1f560380de660cfe39e827f0eae21cc8dae7483
|
[
"Markdown",
"C",
"Makefile"
] | 5 |
C
|
onXoot/OperationSystemCourseDesign
|
84547b1060b4a49a8a5c69807d0d808e44d0be93
|
ce69872595e3bde097da98e4a1f9277e6ff37e90
|
refs/heads/master
|
<repo_name>panzhichao01/java-71<file_sep>/src/main/java/课后作业/_10月15日02/第三题/money.java
package 课后作业._10月15日02.第三题;
/**
* 描述:
*
* @author Administrator
* @create 2020-10-15 23:09
*/
public class money {
public static void main(String[] args) {
double[][] moneys={{22,66,44},{77,33,88},{25,45,65},{11,66,99}};
for (int i = 0; i < moneys.length; i++) {
double sum=0;
for (int j = 0; j < moneys[i].length; j++) {
sum+=moneys[i][j];
}
System.out.println("第"+(i+1)+"季度销售额:"+sum+"(万元)");
}
}
}
<file_sep>/src/main/java/数组/Test12.java
package 数组;
import java.util.Scanner;
/**
* 描述:
* 杨辉等腰三角
*
* @author Administrator
* @create 2020-10-19 0:05
*/
public class Test12 {
public static void main(String[] args) {
/* Scanner sc = new Scanner(System.in);
System.out.print("请输入杨辉三角的行数:");
int n = sc.nextInt();
*/
int[][] arrays = new int[10][];
for (int i = 0; i < arrays.length; i++) {
arrays[i] = new int[i + 1];
//左边打印空格,打印等腰三角形
for(int k = 0; k<= arrays.length-i; k++ ){
System.out.print(" ");
}
for (int j = 0; j < arrays[i].length; j++) {
if (i == 0 || j == 0 || i == j) {
arrays[i][j] = 1;
} else {
arrays[i][j] = arrays[i - 1][j] + arrays[i - 1][j - 1];
}
System.out.print(arrays[i][j] + " ");
}
System.out.println();
}
int [][] arr=new int[10][];
for (int i = 0; i < arr.length; i++) {
arr[i]=new int[i+1];
for (int k = 0; k <=arr.length-i; k++) {
System.out.print(" ");
}
for (int j = 0; j < arr[i].length; j++) {
if (i==0 || j==0 || j==i){
arr[i][j]=1;
}else {
arr[i][j]=arr[i-1][j-1]+arr[i-1][j];
}
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}<file_sep>/src/main/java/课后作业/_10月13日/第一题/sort.java
package 课后作业._10月13日.第一题;
import java.util.Arrays;
import java.util.Scanner;
/**
* 描述:
* 字符排序
*
* @author Administrator
* @create 2020-10-13 17:57
*/
public class sort {
public static void main(String[] args) {
char[] chars = {'a','c','u','b','e','p','f','z'};
Arrays.sort(chars,0,8);
System.out.println(Arrays.toString(chars));
System.out.println("请输入需要查找的特殊字符:");
Scanner input=new Scanner(System.in);
char ch=input.next().charAt(0);
for (int i = 0; i <chars.length; i++) {
if (ch==chars[i]){
System.out.println("特殊字符"+ch+"的下标是:"+i);
}
}
}
}<file_sep>/src/main/java/数组/Test03.java
package 数组;
import java.util.Arrays;
public class Test03 {
public static void main(String[] args) {
int[] arr={7,1,5,2};
int i=0;
int j=arr.length-1;
int temp;
/*while (i<j){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
System.out.println(Arrays.toString(arr));*/
for (int k = 0; k <arr.length-1; k++,j--) {
temp=arr[k];
arr[k]=arr[j];
arr[j]=temp;
}
System.out.println(Arrays.toString(arr));
}
}
<file_sep>/src/main/java/数组/Test11.java
package 数组;
/**
* 描述:
* 杨辉等腰三角形
*
* @author Administrator
* @create 2020-10-16 10:45
*/
public class Test11 {
public static void main(String[] args) {
int [][] arr=new int[10][10];
for (int i = 0; i <arr.length ; i++) {
arr[i][0]=1; //控制第一列的数等于1
}
for (int i = 1; i < arr.length; i++) {
for (int j = 1; j < arr.length; j++) {
arr[i][j]=arr[i-1][j-1]+arr[i-1][j]; //赋值
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = arr.length-i; j >0; j--) { //空格的控制
System.out.print(" ");
}
for (int k = 0; k < arr.length; k++) { //打印出数组的数字
if (arr[i][k] !=0){ //把没赋值的零清除掉
System.out.print(arr[i][k]+" ");
}
}
System.out.println();
}
}
}<file_sep>/src/main/java/课后作业/_10月12日/第二题/max.java
package 课后作业._10月12日.第二题;
public class max {
public static void main(String[] args) {
int[] nums = {8, 7, 3, 9, 5, 4, 1};
int max=nums[0];
int min=nums[0];
int index1=0;
int index2=0;
for (int i = 0; i <nums.length ; i++) {
if (nums[i]>max){
max=nums[i];
index1=i;
}else if(nums[i]<min){
min=nums[i];
index2=i;
}
}
System.out.println("数组中最大的值是:"+max+",其下标是:"+index1);
System.out.println("数组中最小的值是:"+min+",其下标是:"+index2);
}
}
<file_sep>/src/main/java/课后作业/_10月16日/第五题/array.java
package 课后作业._10月16日.第五题;
import java.util.Scanner;
/**
* 描述:
* 数组颠倒
*
* @author Administrator
* @create 2020-10-16 15:06
*/
public class array {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入数组的行和列:");
int n = input.nextInt();
int k = input.nextInt();
int[][] nums1 = new int[n][k];
int[][] nums2 = new int[k][n];
System.out.println("请输入数组的元素:");
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums1[i].length; j++) {
nums1[i][j] = input.nextInt();
}
System.out.println();
}
System.out.println("依次打印输入的二维数组:");
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums1[i].length; j++) {
System.out.print(nums1[i][j] + "\t");
}
System.out.println();
}
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums1[i].length; j++) {
nums2[j][i] = nums1[i][j];
}
}
System.out.println("依次输出行列颠倒的二维数组:");
for (int i = 0; i < nums2.length; i++) {
for (int j = 0; j < nums2[i].length; j++) {
System.out.print(nums2[i][j] + "\t");
}
System.out.println();
}
}
}<file_sep>/src/main/java/数组/Test01.java
package 数组;
import java.util.Scanner;
public class Test01 {
public static void main(String[] args) {
int [] list={99,85,82,63,60};
int[] lists=new int[6];
lists[0]=99;
lists[1]=85;
lists[2]=82;
lists[3]=63;
lists[4]=60;
Scanner input=new Scanner(System.in);
System.out.println("请输入您要插入的学生成绩:");
int num =input.nextInt();
int index=lists.length-1;
for (int i = 0; i <lists.length ; i++) {
if(num>lists[i]){
index=i;
break;
}
}
for (int i =lists.length-1; i>index; i--) {
lists[i]=lists[i-1];
}
lists[index]=num;
for (int i : lists) {
System.out.print(i+"\t");
}
}
}
<file_sep>/src/main/java/数组/Test09.java
package 数组;
/**
* 描述:
* 二分查找算法测试
*
* @author Administrator
* @create 2020-10-16 0:20
*/
public class Test09 {
public static void main(String[] args) {
int[] nums={0,1,2,3,4,5,6,7,8,9};
int num=5;
int startIndex=0;
int endIndex=nums.length-1;
int midIndex=0;
boolean judge=false;
do {
midIndex=(startIndex+endIndex)/2;
if (num==nums[midIndex]){
System.out.println("找到");
judge=true;
break;
}else if (nums[midIndex]>num){
endIndex=midIndex;
}else {
startIndex=midIndex;
}
}while (startIndex <= endIndex);
if (!judge){
System.out.println("找不到");
}
}
}<file_sep>/src/main/java/数组/Test07.java
package 数组;
/**
* 描述:
* 二分查找法
*
* @author Administrator
* @create 2020-10-15 14:49
*/
public class Test07 {
public static void main(String[] args) {
int [] arr={0,1,2,3,4,5,6,7,8,9};
int searchNum=5;
int startIndex=0;
int endIndex=arr.length-1;
int midIndex=-1;
boolean flag=false;
do {
midIndex=(startIndex+endIndex)/2;
if (arr[midIndex]==searchNum){
System.out.println("恭喜您,找到这个数,其下标为:"+midIndex);
flag=true;
break;
}else if (arr[midIndex]>searchNum){
endIndex=midIndex;
}else{
startIndex=midIndex+1;
}
}while(startIndex <= endIndex);
if (!flag){
System.out.println("很抱歉,没有找到您要找的数字!");
}
}
}
|
686c8c45c74f5c70b94b2b723b36c9d79f727d30
|
[
"Java"
] | 10 |
Java
|
panzhichao01/java-71
|
e1328b3d12400de85949c4292bc425b31b21f43a
|
a392b309170623b92d9cfd794f0548964c413664
|
refs/heads/main
|
<repo_name>Levon-98/graph<file_sep>/Graph.py
from typing import Union
class Edge:
def __init__(self, vertex_1: int, vertex_2: int, weight: int = 0):
self.edge = tuple(sorted([vertex_1, vertex_2]))
self.weight = weight
def __str__(self):
return str(self.__dict__)
def __repr__(self):
return str(self.__dict__)
class Nodes:
def __init__(self, vertex: int):
self.vertex = vertex
def __str__(self):
return str(self.__dict__)
def __repr__(self):
return f"Nodes({self.vertex})"
class Graph:
def __init__(self, *nodes: Union[Nodes, Edge]):
self.nodes = nodes
self.Edge_dict = {}
self.Vertex_dict = {}
for i in nodes:
if isinstance(i, Edge):
self.Edge_dict[f"{i.edge}"] = i.weight
elif isinstance(i, Nodes):
self.Vertex_dict[i.vertex] = i
else:
raise TypeError(f"excepted type Node or Edge {type(i)} found")
self.Neighbours_dict = self.__neighbours_dict_1()
def __str__(self):
return str(self.__dict__)
def __contains__(self, item: object):
if not isinstance(item, Graph):
raise TypeError("item is not Graph")
if set(item.Vertex_dict).issubset(set(self.Vertex_dict)) and set(
item.Edge_dict
).issubset(set(self.Edge_dict)):
return True
return False
def __neighbours_dict_1(self):
neighbor_dict = {vertex: [] for vertex in self.Vertex_dict}
for edge in self.Edge_dict:
edge = eval(edge)
if edge[0] in neighbor_dict:
neighbor_dict[edge[0]].append(edge[1])
if edge[1] in neighbor_dict:
neighbor_dict[edge[1]].append(edge[0])
return neighbor_dict
def add_vortex(self, i: int):
i_node = Nodes(i)
self.Vertex_dict[i_node.vertex] = i_node
self.Neighbours_dict = self.__neighbours_dict_1()
def add_edge(self, vertex_1: int, vertex_2: int, weight: int = 0):
new_edge = Edge(vertex_1, vertex_2, weight)
self.Edge_dict[f"{new_edge.edge}"] = new_edge.weight
self.Neighbours_dict = self.__neighbours_dict_1()
def delete_vertex(self, node: Nodes):
del self.Vertex_dict[node.vertex]
for i in self.nodes:
if isinstance(i, Edge):
if node.vertex in i.edge:
del self.Edge_dict[f"{i.edge}"]
if isinstance(i, Nodes):
if i.vertex != node.vertex:
self.Vertex_dict[i.vertex] = i
self.Neighbours_dict = self.__neighbours_dict_1()
if __name__ == "__main__":
pass
edge = Edge(1, 2)
edge_1 = Edge(1, 3, 1)
k = Edge(2, 1)
node = Nodes(1)
node_1 = Nodes(2)
node_3 = Nodes(3)
node_4 = Nodes(4)
graph = Graph(edge, edge_1, node, node_1, node_3, node_4, k)
graph_1 = Graph(edge, edge_1, node, node_1, node_4)
print(graph_1 in graph)
print(graph.Edge_dict)
print(graph.Vertex_dict)
print(graph.Neighbours_dict)
graph.delete_vertex(node_3)
print(graph.Edge_dict)
graph.add_vortex(5)
graph.add_edge(2, 8, 14)
|
14cd8dd47da091d30eeed568ae144aa5acd236bb
|
[
"Python"
] | 1 |
Python
|
Levon-98/graph
|
41f4a3369fa1b0d3d81caaa60a0533a173c9239d
|
f69a943833080cdeb0de1a8dab0c875982d0e86f
|
refs/heads/master
|
<repo_name>Ragab2010/Atmega-implementation-drivers-and-Interfacing-Modules<file_sep>/TIMERINPUTCAPTURE/inputcapture.c
/*
* inputcapture.c
*
* Created on: ٢٨/٠٦/٢٠١٧
* Author: RAGAB
*/
#include <avr/io.h>
#include "avr/delay.h"
#include <stdlib.h>
#include "lcdlib.h"
void timer1_inputcapture_init(){
DDRD &=~(1<<PD6);
TCCR1A =(1<<WGM12)|(1<<WGM13);
TCCR1B =(1<<CS10);
}
unsigned short inputCapture(){
while(!(TIFR & (1<<ICF1)));
TIFR |= (1<<ICF1);
return ICR1;
}
int main(){
LCD_init();
timer1_inputcapture_init();
unsigned short T ,P , B;
while(1){
T=inputCapture();
B=inputCapture();
P=T-B;
LCD_goToRowCol(1,1);
LCD_intToString(P);
}
return 0;
}
<file_sep>/TEST_SPI_SLAVE/slave.c
/*
* slave.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
#include "avr/io.h"
#define ACK 0X05
#define START 0X0F
#define STOP 'T'
void SPI_initMaster(){
DDRB |=(1<<PB4)|(1<<PB5)|(1<<PB7);
DDRB &=~(1<<PB6);
SPCR =(1<<SPE)|(1<<MSTR)| (1<<SPR1) |(1<<SPR0);
}
void SPI_initSlave(){
DDRB &=~((1<<PB4)|(1<<PB5)|(1<<PB7));
DDRB |=(1<<PB6);
SPCR =(1<<SPE);
}
unsigned char spi_tranceiver (unsigned char data)
{
SPDR=data;
while(!(SPSR)&(1<<SPIF));
while(!(PINB & (1<<PB4)));
return SPDR;
}
void SPI_sendByte(unsigned char byte){
SPDR = byte;
while(!(SPSR & (1<<SPIF)));
}
unsigned char SPI_recieveByte(){
while(!(SPSR & (1<<SPIF)));
return SPDR;
}
int main(){
SPI_initSlave();
DDRC =0xff;
PORTC =0X00;
unsigned char data=0x00;
while(1){
data =spi_tranceiver(ACK);
PORTC = data;
}
return 0;
}
<file_sep>/function_take_from_one_to_ten/main.c
/*
* main.c
*
* Created on: ٠٧/٠٨/٢٠١٧
* Author: RAGAB
*/
#include <avr/io.h>
void timer1_dutycycle_old(float num ){
num /=10;
unsigned short num_on= (num * 10000);
//OCR1A=9777;
OCR1AH=0X27;
OCR1AL=0X0F;
//OCR1BH=(num_on>>8);
//OCR1BL=(num_on);
OCR1B =num_on;
TCNT1 =0x00;
}
void timer1_dutycycle_init(){
DDRD |=(1<<PD5);
TCCR1A =(1<<COM1A0 | 1<<WGM12 | 1<<FOC1A);
TCCR1B =(1<<CS10);
}
void timer1_dutycycle(float num){
num /=10;
unsigned short num_on= (unsigned short)(num * 10000);
}
int main(){
timer1_dutycycle_init();
float num=1;
num /=10;
unsigned short num_on= 1000;//(unsigned short)(num * 10000);
unsigned short compar_register_val[2]={num_on , 9999-num_on};
unsigned char index=0;
TCNT1 =0x00;
while(1){
while(!(TIFR &(1<<OCF1A)));
while(TIFR &(1<<OCF1A)){
OCR1A = compar_register_val[index++];
TIFR |=(1<<OCF1A);
if(index >2)
index=0;
}
}
// while(1){
// while(flage ==1 ){
// if(TIFR &(1<<OCF1B)){
// PORTB ^=(1<<PB0);
// TIFR |=(1<<OCF1B);
// flage=0;
// }
// }
// while(flage ==0){
// if(TIFR &(1<<OCF1A)){
// PORTB &=~(1<<PB0);
// TIFR ^=(1<<OCF1A);
// TCNT1 =0x00;
// flage =1;
// }
// }
// }
return 0;
}
<file_sep>/TEST_F/main.c
/*
* main.c
*
* Created on: ٠٧/٠٨/٢٠١٧
* Author: RAGAB
*/
#include <stdio.h>
#include <stdlib.h>
#define SMALL 3
#define LARG 5
void swap(int arr1[],int arr2[],int size1,int size2)
{
int max= size1 > size2 ? size1:size2;
//printf("%d\n",size1);
int i;
int *temp;
temp=(int*)malloc(max*sizeof(int));
for(i = 0; i < max; i++) {
temp[i] = arr1[i];
arr1[i] = arr2[i];
arr2[i] = temp[i];
}
}
int main(){
int i,a1[SMALL]={1,2,3};
int a2[LARG]={7,8,9,10,11};
swap(a1 , a2 , SMALL, LARG);
for(i =0 ; i<SMALL;i++ )
printf("%d\t" , a1[i]);
printf("\n");
for(i =0 ; i<LARG;i++ )
printf("%d\t" , a2[i]);
return 0;
}
<file_sep>/I2C_TX/TX.c
/*
* TX.c
*
* Created on: ??�/??�/????
* Author: RAGAB
*/
#include "avr/io.h"
#include "util/delay.h"
/*in Master Mode*/
void I2C_init(){
//Frequncy eqaul 100KHz
TWBR = 0X20;
TWSR = 0X00;
//TWPS1 TWPS0 = 00 -- no Prescaler
TWCR = (1<<TWEN); //Enable the TWI module
}
void I2C_initSlave(unsigned char slaveAddr){
TWCR = (1<<TWEN); //Enable the TWI module FRIST IN SLAVE MODE
TWAR = slaveAddr;
TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);//ENABLE , CLAER FLAG , SEND ACK
//WE CAN REMOVE ACK
}
void I2C_listen(){
while(!(TWCR & (1<<TWINT))); //IS LISIN TO CALL FROM MASTER TO ACK
}
void I2C_start(){
TWCR = (1<<TWEN) | (1<<TWINT)| (1<<TWSTA);
//Enable the TWI module
// make flag be zero
//Transmit START bit on SDA bus
while(!(TWCR & (1<<TWINT))); //(start bit is send successfully)
}
void I2C_stop(){
TWCR = (1<<TWEN)|(1<<TWINT)|(1<<TWSTO);
//Enable the TWI module
// make flag be zero
//Transmit START bit on SDA bus
}
void I2C_write(unsigned char byte){
TWDR = byte; // assign byte to DATA REGISTER
TWCR = (1<<TWINT)|(1<<TWEN);
// make flag be zero
//Enable the TWI module
while(!(TWCR & (1<<TWINT)));//(data is send successfully)
}
unsigned char I2C_read(unsigned char isLast){
if(isLast == 0){//for more one byte
TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
// make flag be zero
//Enable the TWI module
//Transmit ACK bit on SDA bus
}else{//for one byte
TWCR = (1<<TWINT)|(1<<TWEN);
// make flag be zero
//Enable the TWI module
}
while(!(TWCR & (1<<TWINT))); //(data received successfully)
return TWDR ; // return byte from the DATA REGISTER
}
//int main(){
///*this master send 0x0F to slave and show it in PORTA*/
// _delay_ms(1000);
// I2C_init();
// I2C_start();
// I2C_write(0b11000000);
// I2C_write(0x0F);
// I2C_stop();
// while(1);
//
// return 0;
//}
int main(){
//this master recive Byte and show it in PORTA
DDRA = 0xFF;
PORTA = 0X00;
_delay_ms(1000);
I2C_init();
I2C_start();
I2C_write(0b11000001);
PORTA =I2C_read(1);
I2C_stop();
while(1);
return 0;
}
<file_sep>/SPI_TX/TX.c
/*
* TX.c
*
* Created on: ??�/??�/????
* Author: RAGAB
*/
#include <avr/io.h>
#include <util/delay.h>
void SPI_initMaster(){
/*THER SS AUTO WITH SPI*/
/*you have to make ss as ouput and then
* if you dont use it .. it will auto with spi module
* or you can make it low after translate and
* before make it high*/
DDRB |=(1<<PB5)|(1<<PB7)|(1<<PB4);
DDRB &=~(1<<PB6);
SPCR |= (1<<SPE)|(1<<MSTR);
PORTB |=(1<<PB4); //if you use ss manuale
}
void SPI_initSlave(){
DDRB &=~((1<<PB4)|(1<<PB5)|(1<<PB7));
DDRB |=(1<<PB6);
SPCR |=(1<<SPE);
}
void SPI_sendByte(unsigned char byte){
PORTB &=~(1<<PB4);//before translate make it low
SPDR = byte;
while(!(SPSR & (1<<SPIF)));
PORTB |=(1<<PB4);//after translate make it high
}
unsigned char SPI_reciveByte(){
while(!(SPSR & (1<<SPIF)));
return SPDR;
}
int main(){
SPI_initMaster();
_delay_ms(50);
SPI_sendByte(0x03);
SPI_sendByte(0xff);
while(1){
}
return 0;
}
<file_sep>/test_lcd/Debug/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../AVR_FUNCTIONS.c \
../LCD_code.c \
../LCD_main.c
OBJS += \
./AVR_FUNCTIONS.o \
./LCD_code.o \
./LCD_main.o
C_DEPS += \
./AVR_FUNCTIONS.d \
./LCD_code.d \
./LCD_main.d
# Each subdirectory must supply rules for building sources it contributes
%.o: ../%.c
@echo 'Building file: $<'
@echo 'Invoking: AVR Compiler'
avr-gcc -Wall -g2 -gstabs -O0 -fpack-struct -fshort-enums -ffunction-sections -fdata-sections -std=gnu99 -funsigned-char -funsigned-bitfields -mmcu=atmega16 -DF_CPU=8000000UL -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -c -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/test_lcd/util.h
#ifndef UTIL_H_INCLUDED
#define UTIL_H_INCLUDED
//=============
//Port Functions
//=============
#define set_reg(reg) reg=0xFF // set all the bits of the port to 1s
#define toggle(reg) ~(reg) // reverse (toggle) all the bits of the port
//=============
//Bit Functions
//=============
// get the value of a specific bit
#define get_bit(reg,bit_position) ((reg&(1<<bit_position))>>bit_position)
#define set_bit(reg,bit) (reg)|(1<<bit) // set a specific bit to 1
#define clr_bit(reg,bit) reg&(~(1<<bit)) // clear a specific bit (i.e set to to 0)
#define toggle_bit(reg,bit) reg^=(1<<bit) // reverse (toggle) a specific bit
// set a specific bit to specific value
#define assign_bit(reg,bit,value) ((value==1)?(reg|=(1<<bit)):(reg&=~(1<<bit)))
// assign a port a hex value
#define assign_port(reg,Hex_Value) reg=(reg|0xFF)&(Hex_Value)
//=============
//Nibble Functions
//=============
#define get_lonibble(reg) reg&(0x0F) // get the low nibble
#define get_hinibble(reg) (reg&(0xF0))>>4 // get the hi nibble
#define clr_lonibble(reg) reg&(0xF0) // Clear (reset) low nibble
#define clr_hinibble(reg) (reg&(0x0F)) // Clear (reset) hi nibble
// Toggle low nibble
#define toggle_lonibble(reg) (~(reg&(0x0F)))&(reg|(0x0F))
// Toggle hi nibble
#define toggle_hinibble(reg) (~(reg&(0xF0)))&(reg|(0xF0))
//assign a specific value to low nibble
#define assign_lonibble(reg,value) (reg&(0xF0))|(value)
//assign a specific value to hi nibble
#define assign_hinibble(reg,value) (reg&(0x0F))|(value<<4)
//Reverse low and hi nibbles
#define reverse_nibbles(reg) ((get_lownibble(reg))<<4)|(get_hinibble(reg))
#endif // UTIL_H_INCLUDED
<file_sep>/README.md
# atmega16_32_interface_implementation
all implementation drives for atmega32/16
<file_sep>/TEST_SPI_MASTER/master.c
/*
* master.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
#include "avr/io.h"
#include "util/delay.h"
#define ACK 0X05
#define START 0X0F
#define STOP 'T'
void SPI_initMaster(){
DDRB |=(1<<PB4)|(1<<PB5)|(1<<PB7);
DDRB &=~(1<<PB6);
SPCR =(1<<SPE)|(1<<MSTR)| (1<<SPR1) |(1<<SPR0);
PORTB |=(1<<PB4);
}
void SPI_initSlave(){
DDRB &=~((1<<PB4)|(1<<PB5)|(1<<PB7));
DDRB |=(1<<PB6);
SPCR =(1<<SPE);
}
unsigned char spi_tranceiver (unsigned char data)
{
SPDR=data;
PORTB &=~(1<<PB4);
while(!(SPSR & (1<<SPIF)));
data = SPDR;
PORTB |=(1<<PB4);
return data;
}
void SPI_sendByte(unsigned char byte){
SPDR = byte;
PORTB &=~(1<<PB4);
while(!(SPSR & (1<<SPIF)));
PORTB |=(1<<PB4);
}
unsigned char SPI_recieveByte(){
while(!(SPSR & (1<<SPIF)));
return SPDR;
}
int main(){
SPI_initMaster();
DDRC =0xff;
PORTC =0X00;
unsigned char data;
unsigned char flag;
_delay_ms(100);
data = spi_tranceiver(START);
while(1){
if(PIND & (1<<PD0)){
_delay_ms(20);
if((PIND & (1<<PD0))&&flag == 0){
flag=1;
spi_tranceiver(0X01);
}
}
else if(PIND & (1<<PD1)){
_delay_ms(20);
if((PIND & (1<<PD1))&&flag == 0){
flag=1;
spi_tranceiver(0X02);
}
}
else{
flag =0;
}
}
return 0;
}
<file_sep>/UART_TX/TX.c
/*
* TX.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
/*
//this uart by polling Send 'A'
#include <avr/io.h>
#include <util/delay.h>
void UART_init(){
UCSRA |=(1<<U2X);
UCSRB |=(1<<TXEN);
UCSRC |=(1<<URSEL)|(1<<USBS)|(1<<UCSZ1)|(1<<UCSZ0);
UBRRL =103;
}
void UART_sendByte(char byte){
while(!(UCSRA &(1<<UDRE)));
UDR = byte;
}
char UART_reciveByte(){
while(!(UCSRA &(1<<RXC)));
return UDR;
}
int main(){
UART_init();
_delay_ms(50);
UART_sendByte('A');
while(1){
}
return 0;
}
*/
//this uart by interrupt Send 'A'
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
ISR(USART_UDRE_vect ){
UDR = 'A';
}
void UART_init(){
UCSRA |=(1<<U2X);
UCSRB |=(1<<TXEN)|(1<<UDRIE);
UCSRC |=(1<<URSEL)|(1<<USBS)|(1<<UCSZ1)|(1<<UCSZ0);
UBRRL =103;
sei();
}
void UART_sendByte(char byte){
while(!(UCSRA &(1<<UDRE)));
UDR = byte;
}
char UART_reciveByte(){
while(!(UCSRA &(1<<RXC)));
return UDR;
}
int main(){
UART_init();
_delay_ms(50);
while(1){
}
return 0;
}
<file_sep>/REVSION_FOR_EXAM0/test1.c
/*
* test1.c
*
* Created on: ٠٧/٠٨/٢٠١٧
* Author: RAGAB
*/
#include <avr/io.h>
void timer0_init_pwm(){
DDRB = 1<<PB3 ;
TCCR0 = 1<<COM00 | 1<<CS00;
OCR0 = 63;
}
int main(){
timer0_init_pwm();
while(1);
return 0;
}
<file_sep>/ADC/lcdlib.h
/*
* lcdlib.h
*
* Created on: ٢٤/٠٤/٢٠١٧
* Author: RAGAB
*/
#ifndef LCDLIB_H_
#define LCDLIB_H_
#include "avr/io.h"
#include "avr/delay.h"
#include <stdlib.h>
#define RS PD0
#define RW PD1
#define E PD2
#define LCD_CTRL_PORT PORTD
#define LCD_CTRL_PORT_DIR DDRD
#define LCD_DATA_PORT PORTC
#define LCD_DATA_PORT_DIR DDRC
void LCD_init();
void LCD_command(unsigned char command);
void LCD_Data(unsigned char data);
void LCD_displayString(unsigned char *str );
void LCD_displayCharacter(unsigned char Byte );
void LCD_intToString(int data);
void LCD_clearScreen(void);
void LCD_displayStringRowCol(unsigned char row , unsigned char col , unsigned char *str );
void LCD_init(){
LCD_CTRL_PORT_DIR |=(1<<RS) |(1<<RW) |(1<<E);
LCD_DATA_PORT_DIR = 0XFF;
LCD_command(0x38);
LCD_command(0x0C);
LCD_command(0x01);
}
void storeShape(unsigned char row , unsigned char col ){
unsigned char i,shape[8]= {0,0,10,31,31,14,4,0};
LCD_command(0x40);//set adress pointer to point on adress 00000 in CGRAM
for( i=0 ; i < 8 ; i++ ){
LCD_Data(shape[i]);
}
LCD_goToRowCol(row , col);
LCD_Data(0x00); // show the address this of CGRAM
}
void LCD_command(unsigned char command){
LCD_CTRL_PORT &=~((1<<RS)|(1<<RW));
_delay_ms(1);
LCD_CTRL_PORT |=(1<<E);
_delay_ms(1);
LCD_DATA_PORT = command;
_delay_ms(1);
LCD_CTRL_PORT &=~(1<<E);
_delay_ms(1);
}
void LCD_Data(unsigned char data){
LCD_CTRL_PORT |=(1<<RS);
LCD_CTRL_PORT &=~(1<<RW);
_delay_ms(1);
LCD_CTRL_PORT |=(1<<E);
_delay_ms(1);
LCD_DATA_PORT = data;
_delay_ms(1);
LCD_CTRL_PORT &=~(1<<E);
_delay_ms(1);
}
void LCD_goToRowCol(unsigned char row ,unsigned char col ){
unsigned char fristCharAddr[]={0x80 , 0XC0, 0X94 ,0XD4};
LCD_command(fristCharAddr[row-1] + col-1);
_delay_ms(1);
}
void LCD_displayCharacter(unsigned char Byte ){
LCD_Data(Byte);
}
void LCD_displayString(unsigned char *str ){
do{
LCD_Data(*str++);
}while(*str);
}
void LCD_displayStringRowCol(unsigned char row , unsigned char col , unsigned char *str ){
LCD_goToRowCol(row , col);
LCD_displayString(str);
}
void LCD_clearScreen(void){
LCD_command(0x01); //clear display
}
void LCD_intToString(int data){
unsigned char buff[16]; /* String to hold the ascii result */
// itoa(data,buff,10); /* 10 for decimal */
sprintf(buff ,"%d",data);
LCD_displayString(buff);
}
#endif /* LCDLIB_H_ */
<file_sep>/test_lcd/AVR_FUNCTIONS.c
#include "AVR_FUNCTIONS.h"
//#include "util.h"
/*=========================*/
/* Configure the whole */
/* port to be output */
/* or input */
/*=========================*/
void Port_Direction_All(u8 base,u8 state)
{
if(state==OUTPUT)
(*(volatile u8*)(base+1))=0xff;
else
(*(volatile u8*)(base+1))=0x00;
}
/*=========================*/
/* Configure the port */
/* direction to a specific */
/* value */
/*=========================*/
void Port_Direction(u8 base,u8 value)
{
(*(volatile u8*)(base+1))=value;
}
/*=========================*/
/* Configure a single pin */
/* in the port to be */
/* input or output */
/*=========================*/
void Pin_Direction(u8 base,u8 pin,u8 state)
{
if(state==OUTPUT)
(*(volatile u8*)(base+1))|= (1<<pin);
else
(*(volatile u8*)(base+1))&=~(1<<pin);
}
/*=========================*/
/* Makes the physical */
/* pin electrically */
/* (grounded) (i.e 0) */
/*=========================*/
void Pin_Reset(u8 base,u8 pin)
{
(*(volatile u8*)(base+2))&=~(1<<pin);
}
/*=========================*/
/* Makes the physical */
/* pin 1 electrically */
/* (connected to Vdd) */
/*=========================*/
void Pin_Set(u8 base,u8 pin)
{
(*(volatile u8*)(base+2))|= (1<<pin);
}
/*=========================*/
/* Assign the required */
/* value to the */
/* physical port */
/*=========================*/
void Port_Write(u8 base ,u8 value)
{
(*(volatile u8*)(base+2))=value;
}
/*=========================*/
/* Read the port value */
/*=========================*/
u8 Port_Read(u8 base)
{
return(*(volatile u8*)base);
}
/*=========================*/
/* Assign 0 or 1 */
/* (electrically) */
/* to a specific pin */
/*=========================*/
void Pin_Write(u8 base,u8 pin,u8 value)
{
if(value==1)
(*(volatile u8*)(base+2))|= 1<<pin;
else
(*(volatile u8*)(base+2))&=~(1<<pin);
}
/*=========================*/
/* Read pin value */
/*(whole expression is */
/* used to evaluate value) */
/*=========================*/
u8 Pin_Read(u8 base,u8 pin)
{
if((*(volatile u8*)(base))&&(1<<pin))
return 1;
else
return 0;
}
<file_sep>/test_lcd/typedefs.h
#ifndef TYPEDEFS_H_INCLUDED
#define TYPEDEFS_H_INCLUDED
typedef signed char s8; // signed char = 1 byte = 8 bits
typedef unsigned char u8; // unsigned char = 1 byte = 8 bits
typedef int s32; // signed integer = 4 bytes = 32 bits
typedef unsigned int u32; //unsigned int = 4 bytes = 32 bits
typedef long long s64; // long long int= 8 bytes = 64 bits
typedef unsigned long long u64; // Unsgiend long long int 8 bytes = 64 bits
typedef float f32; // Floating point number = 4 bytes = 32 bits
typedef double d64; // Double-precision number 8 bytes = 64 bits
#endif // TYPEDEFS_H_INCLUDED
<file_sep>/TIMER1/timer.c
/*
* timer.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
#include "avr/io.h"
void TIMER1_init_overFlow(){
DDRD |=(1<<PD4) |(1<<PD5);
OCR1A =100;
OCR1B =100;
TCCR1A |=(1<<COM1A0)|(1<<COM1B0);
TCCR1B |=(1<<CS10)|(1<<WGM12);
}
int main(){
TIMER1_init_overFlow();
while(1);
return 0;
}
<file_sep>/test_lcd/LCD_main.c
/*
* LCD_main.c
*
* Created on: Oct 10, 2017
* Author: admin
*/
#include "LCD_code.h"
int main(){
LCD_Init();
LCD_Print("ali");
while(1);
}
<file_sep>/test_lcd/AVR_INTERFACE.h
#ifndef AVR_INTERFACE_H_INCLUDED
#define AVR_INTERFACE_H_INCLUDED
/*=========================*/
/* Port base value */
/*=========================*/
#define A 0x39
#define B 0x36
#define C 0x33
#define D 0x30
/*=========================*/
/* Digital I/O Directions */
/* states */
/*=========================*/
#define OUTPUT 1
#define INPUT 0
#endif // AVR_INTERFACE_H_INCLUDED
<file_sep>/Timer0/timer.c
/*
* timer.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
#include <avr/io.h>
void Timer0_delay(){
volatile unsigned int i=0;
TCCR0 =(1<<FOC0) | (1<<CS00);
TCNT0 = 0;
while(i < 62500){
while((TIFR &(1<<TOV0))){
TIFR |=(1<<TOV0);
i++;
}
}
}
int main(){
DDRB |=(1<<PC0);
PORTB &=~(1<<PC0);
while(1){
PORTB ^=(1<<PC0);
Timer0_delay();
}
}
<file_sep>/MASTER/debug.c
/*
* debug.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
<file_sep>/VALUE_PWM_PROBLEM/VALUE.c
/*
* VALUE.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
#include "avr/io.h"
#include "avr/interrupt.h"
/*
CRYSTAL = 1MHZ
Prescaller = 8
Normal mode timer0
and it take 0.002Sec to overflow
*/
/*-------NUMBER OF OVERFLOW FOR EVERY PWM----------*/
#define PA0_ON 50
#define PA0_OFF 50
#define PA1_ON 7
#define PA1_OFF 3
#define PA2_ON 4
#define PA2_OFF 1
#define PA2_OFF_PROB 5
/*-----------------*/
volatile char N_OVERFLOW_PA0=0;
volatile char N_OVERFLOW_PA1=0;
volatile char N_OVERFLOW_PA2=0;
volatile char ON_FRIST_RA1=0;
volatile char ON_FRIST_RA2=0;
ISR(TIMER0_OVF_vect){
TIFR |=(1<<TOV0);//clear overflow flage
++N_OVERFLOW_PA0;
++N_OVERFLOW_PA1;
++N_OVERFLOW_PA2;
//
// if(N_OVERFLOW_PA0 == PA0_ON ){ //ON -OFF ARE EQUAL 50 OVERFLOW
// N_OVERFLOW_PA0=0;
// PORTA ^=(1<<PA0);
// }
// /*
// here we found problem . that number of overflow of OFF less than ONN
// .so the condition of OFF always executes frist
// solve:
// 1-make Flage
// 2-sum the time of ONN with OFF
// ----------
// use method 1
// */
// if((N_OVERFLOW_PA1 == PA1_ON) && ON_FRIST ==0 ){
// N_OVERFLOW_PA1=0;
// ON_FRIST =1;
// PORTA ^=(1<<PA1);
// }else if((N_OVERFLOW_PA1 == PA1_OFF) && ON_FRIST ==1){
// N_OVERFLOW_PA1=0;
// ON_FRIST =0;
// PORTA ^=(1<<PA1);
// }
// /*
// same problem
// --------
// but here will use method 2
// */
//
// if(N_OVERFLOW_PA2 == PA2_ON){
// //N_OVERFLOW_PA2=0; //will make OFF make N_OVERFLOW_PA2 =0 after finishing cycle
// PORTA ^=(1<<PA2);
// }else if(N_OVERFLOW_PA2 == PA2_OFF_PROB){
// N_OVERFLOW_PA2=0;
// PORTA ^=(1<<PA2);
// }
//
}
void timer0_init_interrupt(){
TCCR0 |=(1<<FOC0) |(1<<CS01) ;
TIMSK |=(1<<TOIE0);
sei();
}
int main(){
DDRA |=(1<<PA0)|(1<<PA1)|(1<<PA2);//MAKE PA0 PA1 PA2 AS output
PORTA |=(1<<PA0)|(1<<PA1)|(1<<PA2);//MAKE VOLT ON PA0 PA1 PA2 ZERO VOLT
timer0_init_interrupt();
while(1){
if(N_OVERFLOW_PA0 == PA0_ON ){ //ON -OFF ARE EQUAL 50 OVERFLOW
N_OVERFLOW_PA0=0;
PORTA ^=(1<<PA0);
}
/*
here we found problem . that number of overflow of OFF less than ONN
.so the condition of OFF always executes frist
solve:
1-make Flage
2-sum the time of ONN with OFF
----------
use method 1
*/
if((N_OVERFLOW_PA1 == PA1_ON) && ON_FRIST_RA1 ==0 ){
N_OVERFLOW_PA1=0;
ON_FRIST_RA1 =1;
PORTA ^=(1<<PA1);
}else if((N_OVERFLOW_PA1 == PA1_OFF) && ON_FRIST_RA1 ==1){
N_OVERFLOW_PA1=0;
ON_FRIST_RA1 =0;
PORTA ^=(1<<PA1);
}
/*
same problem
--------
but here will use method 1
*/
if((N_OVERFLOW_PA2 == PA2_ON) && ON_FRIST_RA2 == 0){
N_OVERFLOW_PA2=0;
ON_FRIST_RA2 = 1;
PORTA ^=(1<<PA2);
}else if((N_OVERFLOW_PA2 == PA2_OFF) && ON_FRIST_RA2 == 1){
N_OVERFLOW_PA2=0;
ON_FRIST_RA2 = 0;
PORTA ^=(1<<PA2);
}
}
return 0;
}
<file_sep>/SPI_RX/RX.c
/*
* RX.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
#include <avr/io.h>
#include <util/delay.h>
void SPI_initMaster(){
/*THER SS AUTO WITH SPI*/
DDRB |=(1<<PB5)|(1<<PB7)|(1<<PB4);
DDRB &=~(1<<PB6);
SPCR |= (1<<SPE)|(1<<MSTR);
/*THER SS NOT AUTO WITH SPI*/
// DDRB |=(1<<PB5)|(1<<PB7)|(1<<PB4);
// DDRB &=~(1<<PB6);
// SPCR |= (1<<SPE);
// PORTB |=(1<<PB4);
}
void SPI_initSlave(){
DDRB &=~((1<<PB4)|(1<<PB5)|(1<<PB7));
DDRB |=(1<<PB6);
SPCR |=(1<<SPE);
}
void SPI_sendByte(unsigned char byte){
SPDR = byte;
while(!(SPSR & (1<<SPIF)));
}
unsigned char SPI_reciveByte(){
while(!(SPSR & (1<<SPIF)));
return SPDR;
}
int main(){
SPI_initSlave();
DDRA =0xff;
PORTA = 0X00;
_delay_ms(10);
unsigned char x;
while(1){
x = SPI_reciveByte();
PORTA = x;
}
return 0;
}
<file_sep>/test_lcd/LCD_user.h
/*
* LCD_user.h
*
* Created on: Oct 10, 2017
* Author: admin
*/
#ifndef LCD_USER_H_
#define LCD_USER_H_
#include "AVR_INTERFACE.h"
#define data A
#define cmd B
#define rs 0 /*pin 0 */
#define e 1 /*pin 1*/
#define mode 8
#endif /* LCD_USER_H_ */
<file_sep>/UASRT/main.c
/*
* main.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
#include "avr/io.h"
#include "util/delay.h"
void UART_init(){
UCSRA |= (1<<U2X);
UCSRB |=(1<<TXEN);
UCSRC |=(1<<URSEL) |(1<<UCSZ0) | (1<<UCSZ1);
UBRRL =103;
}
void UART_sendByte( char data){
while(!(UCSRA & (1<<UDRE)));
UDR = data;
}
int main(){
UART_init();
char *m="welcome";
while(1)
{
_delay_ms(4000);
while(*m){
UART_sendByte(*m++);
_delay_ms(50);
}
break;
}
}
<file_sep>/test_lcd/LCD_code.h
/*
* LCD_code.h
*
* Created on: Oct 10, 2017
* Author: admin
*/
#ifndef LCD_CODE_H_
#define LCD_CODE_H_
#include "AVR_FUNCTIONS.h"
#include "util/delay.h"
#include "typedefs.h"
#include "LCD_user.h"
void LCD_Init();
void LCD_Command(u8 command);
void LCD_Print(u8* str);
#endif /* LCD_CODE_H_ */
<file_sep>/UART_RX/RX.c
/*
* RX.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
/*
* RX.C
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
/*
//this uart with polling recive 'a'
#include <avr/io.h>
#include <util/delay.h>
void UART_init(){
UCSRA |=(1<<U2X);
UCSRB |=(1<<RXEN);
UCSRC |=(1<<URSEL)|(1<<USBS)|(1<<UCSZ1)|(1<<UCSZ0);
UBRRL =103;
}
void UART_sendByte(char byte){
while(!(UCSRA &(1<<UDRE)));
UDR = byte;
}
char UART_reciveByte(){
while(!(UCSRA &(1<<RXC)));
return UDR;
}
int main(){
UART_init();
DDRB |=(1<<PB0);
PORTB &=~(1<<PB0);
_delay_ms(50);
char buff;
while(1){
buff =UART_reciveByte();
if(buff == 'A'){
PORTB |=(1<<PB0);
}
}
return 0;
}
*/
//uart by interrupt for recive 'A'
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
volatile char buff;
ISR(USART_RXC_vect){
buff =UDR;
if(buff == 'A'){
PORTB |=(1<<PB0);
}
}
void UART_init(){
UCSRA |=(1<<U2X);
UCSRB |=(1<<RXEN) |(1<<RXCIE);
UCSRC |=(1<<URSEL)|(1<<USBS)|(1<<UCSZ1)|(1<<UCSZ0);
UBRRL =103;
sei();
}
void UART_sendByte(char byte){
while(!(UCSRA &(1<<UDRE)));
UDR = byte;
}
char UART_reciveByte(){
while(!(UCSRA &(1<<RXC)));
return UDR;
}
int main(){
UART_init();
DDRB |=(1<<PB0);
PORTB &=~(1<<PB0);
_delay_ms(50);
while(1){
}
return 0;
}
<file_sep>/TIMER_INPUT_CAPTURE/capture.c
/*
* capture.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
//
//#include "avr/io.h"
//
///*
//Assuming that clock pulses are fed into pin ICP1, write a program to read the TCNTI
//value on every rising edge. Place the result on PORTA and PORTB.
//
//*/
//void timer1_init(){
// DDRD |=(1<<PD6);
// TCCR1A =0X00;
// TCCR1B =(1<<ICES1)|(1<<CS10);
//
//
//
//}
//
//
//int main(){
//
// DDRA =0XFF;
// DDRB=0XFF;
// timer1_init();
//
// while(1){
//
// while(!(TIFR &(1<<ICF1)));
// TIFR |=(1<<ICF1);
// PORTA =ICR1L;
// PORTB =ICR1H;
//
// }
//
//
// return 0;
//}
/*-------------------------------------------------------*/
//
//#include "avr/io.h"
///*
//Assuming that clock pulses are fed into pin PORTD.6, write a program to measure the
//period of the pulses. Place the binary result on PORTA and PORTB.
//
//*/
//
//
//void timer1_init(){
// DDRD |=(1<<PD6);
// TCCR1A =0X00;
// TCCR1B =(1<<ICES1)|(1<<CS10);
//
//
//
//}
//
//
//int main(){
//
// DDRA =0XFF;
// DDRB=0XFF;
// timer1_init();
// unsigned int t;
// while(1){
//
// while(!(TIFR &(1<<ICF1)));
// TIFR |=(1<<ICF1);
// t=ICR1;
// while(!(TIFR &(1<<ICF1)));
// TIFR |=(1<<ICF1);
// t=ICR1-t;
// PORTA = t;
// PORTB = t>>8;
//
// }
//
//
// return 0;
//}
/*------------------------------------------------------*/
/*
Assume that a 60-Hz frequency pulse is connected to lepl (pin PD6). Write a program
to measure its pulse width. Use the prescaler value that gives the result ina single byte.
Display the result on PORTB. Assume XTAL = 8 MHz.
*/
#include "avr/io.h"
void timer1_init_rising(){
TCCR1A =0X00;
TCCR1B =(1<<ICES1)|(1<<CS10);
}
void timer1_init_falling(){
TCCR1A =0X00;
TCCR1B =(1<<CS10);
}
int main(){
DDRD |=(1<<PD6); // the ICP1 PIN FOR INPUT CAPTURE
DDRA =0XFF;
DDRB=0XFF;
unsigned int t;
//calculate the rising of pulse
timer1_init_rising();
while(!(TIFR &(1<<ICF1)));
TIFR |=(1<<ICF1);
t=ICR1;
//calculate the falling of pulse
timer1_init_falling();
while(!(TIFR &(1<<ICF1)));
TIFR |=(1<<ICF1);
PORTA=ICR1-t;
while(1);
return 0;
}
<file_sep>/I2C_RX/RX.c
/*
* RX.c
*
* Created on: ??�/??�/????
* Author: RAGAB
*/
#include "avr/io.h"
/*slave mode*/
void I2C_init(){
//Frequncy eqaul 125KHz
TWBR = 0X47;
TWSR = 0X00;
//TWPS1 TWPS0 = 00 -- no Prescaler
TWCR = (1<<TWEN); //Enable the TWI module
}
void I2C_initSlave(unsigned char slaveAddr){
TWCR = (1<<TWEN); //Enable the TWI module FRIST IN SLAVE MODE
TWAR = slaveAddr;
TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);//ENABLE , CLAER FLAG , SEND ACK
//WE CAN REMOVE ACK
}
void I2C_listen(){
while(!(TWCR & (1<<TWINT))); //IS LISIN TO CALL FROM MASTER TO ACK
}
void I2C_start(){
TWCR = (1<<TWEN) | (1<<TWINT)| (1<<TWSTA);
//Enable the TWI module
// make flag be zero
//Transmit START bit on SDA bus
while(!(TWCR & (1<<TWINT))); //(start bit is send successfully)
}
void I2C_stop(){
TWCR = (1<<TWEN)|(1<<TWINT)|(1<<TWSTO);
//Enable the TWI module
// make flag be zero
//Transmit START bit on SDA bus
}
void I2C_write(unsigned char byte){
TWDR = byte; // assign byte to DATA REGISTER
TWCR = (1<<TWINT)|(1<<TWEN);
// make flag be zero
//Enable the TWI module
while(!(TWCR & (1<<TWINT)));//(data is send successfully)
}
unsigned char I2C_read(unsigned char isLast){
if(isLast == 0){//for more one byte
TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
// make flag be zero
//Enable the TWI module
//Transmit ACK bit on SDA bus
}else{//for one byte
TWCR = (1<<TWINT)|(1<<TWEN);
// make flag be zero
//Enable the TWI module
}
while(!(TWCR & (1<<TWINT))); //(data received successfully)
return TWDR ; // return byte from the DATA REGISTER
}
//int main(){
///*this slave receive byte and show it in PORTA*/
// DDRA =0XFF;
// PORTA=0X00;
// I2C_initSlave(0b11000000);
// I2C_listen();
// PORTA = I2C_read(1);
//
// while(1);
//
// return 0;
//}
//
int main(){
/*this slave send 0x0f to master*/
I2C_initSlave(0b11000000);
I2C_listen();
I2C_write(0x0F);
while(1);
return 0;
}
<file_sep>/Imp_interrupt/main.c
/*
* main.c
*
* Created on: ١٢/١٠/٢٠١٧
* Author: RAGAB
*/
#include "avr/io.h"
#include "avr/interrupt.h"
int main(){
return 0;
}
<file_sep>/LCD_CHARACTER/main.c
/*
* main.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
#include "avr/io.h"
#include "util/delay.h"
#include "KEYPAD.h"
#include <stdio.h>
#define LCD_DDR_DATA DDRC
#define LCD_PORT_DATA PORTC
#define LCD_DDR_CTRL DDRD
#define LCD_PORT_CTRL PORTD
#define RS PD0
#define RW PD1
#define E PD2
void LCD_sendCommand(unsigned char comm){
LCD_PORT_CTRL &=~((1<<RS)|(1<<RW));
_delay_ms(1);
LCD_PORT_CTRL |=(1<<E);
_delay_ms(1);
LCD_PORT_DATA =comm;
_delay_ms(1);
LCD_PORT_CTRL &=~(1<<E);
_delay_ms(1);
}
void LCD_sendData(unsigned char Character){
LCD_PORT_CTRL |=(1<<RS);
LCD_PORT_CTRL &=~(1<<RW);
_delay_ms(1);
LCD_PORT_CTRL |=(1<<E);
_delay_ms(1);
LCD_PORT_DATA =Character;
_delay_ms(1);
LCD_PORT_CTRL &=~(1<<E);
_delay_ms(1);
}
void LCD_displayCharacter(unsigned char ch){
LCD_sendData(ch);
}
void LCD_goToRowCol(unsigned char row ,unsigned char col ){
unsigned char fristCharAddr[]={0x80 , 0XC0, 0X94 ,0XD4};
LCD_sendCommand(fristCharAddr[row -1] + (col -1));
_delay_ms(1);
}
void LCD_displayString(const unsigned char *ptr){
unsigned char i=0;
do{
LCD_displayCharacter(ptr[i++]);
}while(ptr[i]);
}
void LCD_displayStringRowCol(unsigned char row , unsigned char col , unsigned char *str ){
LCD_goToRowCol(row , col);
LCD_displayString(str);
}
void LCD_clearScreen(void){
LCD_sendCommand(0x01); //clear display
}
void LCD_intToString(int data){
unsigned char buff[16]; /* String to hold the ascii result */
// itoa(data,buff,10); /* 10 for decimal */
sprintf(buff, "%s" , data);
LCD_displayString(buff);
}
void LCD_init(){
LCD_DDR_CTRL |=(1<<RS) | (1<<RW) | (1<<E);
LCD_DDR_DATA = 0XFF;
LCD_sendCommand(0x38);
LCD_sendCommand(0x0C);
}
int main(){
LCD_init();
//unsigned char pt[30] ="welcome in egypt";
//LCD_displayString(pt);
unsigned char key=0;
while(1){
key =KEYPAD_pressed();
LCD_displayCharacter(key);
}
return 0;
}
//#include "avr/io.h"
//#include "avr/delay.h"
//#include <stdlib.h>
//#include <stdio.h>
//
//
//#define RS PD0
//#define RW PD1
//#define E PD2
//#define LCD_CTRL_PORT PORTD
//#define LCD_CTRL_PORT_DIR DDRD
//#define LCD_DATA_PORT PORTC
//#define LCD_DATA_PORT_DIR DDRC
//
//void LCD_init();
//void LCD_command(unsigned char command);
//void LCD_Data(unsigned char data);
//void LCD_displayString(unsigned char *str );
//void LCD_displayCharacter(unsigned char Byte );
//void LCD_goToRowCol(unsigned char row ,unsigned char col );
//void LCD_intToString(int data);
//void LCD_clearScreen(void);
//void LCD_displayStringRowCol(unsigned char row , unsigned char col , unsigned char *str );
//
//
//
//int main(){
// LCD_init();
// LCD_goToRowCol(1,1);
//
// //unsigned char *a="welcome I'm Ragab";
// //LCD_displayString(a);
// LCD_intToString(15);
//
// while(1)
// {
// }
//
//}
//void LCD_init(){
// LCD_CTRL_PORT_DIR |=(1<<RS) |(1<<RW) |(1<<E);
// LCD_DATA_PORT_DIR = 0XFF;
// LCD_command(0x38);
// LCD_command(0x0C);
//
//
//
//
//}
//void LCD_command(unsigned char command){
// LCD_CTRL_PORT &=~((1<<RS)|(1<<RW));
// _delay_ms(1);
// LCD_CTRL_PORT |=(1<<E);
// _delay_ms(1);
// LCD_DATA_PORT = command;
// _delay_ms(1);
// LCD_CTRL_PORT &=~(1<<E);
// _delay_ms(1);
//}
//void LCD_Data(unsigned char data){
// LCD_CTRL_PORT |=(1<<RS);
// LCD_CTRL_PORT &=~(1<<RW);
// _delay_ms(1);
// LCD_CTRL_PORT |=(1<<E);
// _delay_ms(1);
// LCD_DATA_PORT = data;
// _delay_ms(1);
// LCD_CTRL_PORT &=~(1<<E);
// _delay_ms(1);
//}
//void LCD_goToRowCol(unsigned char row ,unsigned char col ){
// unsigned char fristCharAddr[]={0x80 , 0XC0, 0X94 ,0XD4};
// LCD_command(fristCharAddr[row-1] + col-1);
// _delay_ms(1);
//
//}
//void LCD_displayCharacter(unsigned char Byte ){
// LCD_Data(Byte);
//}
//
//void LCD_displayString(unsigned char *str ){
// do{
// LCD_Data(*str++);
// }while(*str);
//}
//void LCD_displayStringRowCol(unsigned char row , unsigned char col , unsigned char *str ){
// LCD_goToRowCol(row , col);
// LCD_displayString(str);
//}
//void LCD_clearScreen(void){
// LCD_command(0x01); //clear display
//}
//void LCD_intToString(int data){
// unsigned char buff[16]; /* String to hold the ascii result */
// itoa(data,buff,10); /* 10 for decimal */
// //sprintf((char *)buff , "%c" , data);
// LCD_displayString(buff);
//}
<file_sep>/test_lcd/LCD_code.c
#include "LCD_code.h"
void LCD_Command(u8 command){
Pin_Reset(cmd,rs); //Reset RS for command write
if(mode==8) // 8-bit mode
Port_Write(data,command);
else // 4-bit mode
{ // Move the MSB first
Port_Write(data,assign_hinibble(data,get_hinibble(command)));
Pin_Set(cmd,e);
_delay_us(1);
Pin_Reset(cmd,e); // E from High to Low to latch command
_delay_us(100);
// Move the LSB
Port_Write(data,assign_hinibble(data,get_lonibble(command)));
}
Pin_Set(cmd,e);
_delay_us(1);
Pin_Reset(cmd,e);
_delay_us(100);
}
void LCD_Out(u8 yourdata){
Pin_Set(cmd,rs); // Enable RS for data transfer
if(mode==8) // send command on the data pins at once
Port_Write(data,yourdata);
else
{
Port_Write(data,assign_hinibble(data,get_hinibble(yourdata)));
Pin_Set(cmd,e);
_delay_us(1);
Pin_Reset(cmd,e);
_delay_us(100);
Port_Write(data,assign_hinibble(data,get_lonibble(yourdata)));
}
Pin_Set(cmd,e);
_delay_us(1);
Pin_Reset(cmd,e);
_delay_us(100);
}
void LCD_Init()
{
Port_Direction(data,0xff);
Port_Direction(cmd,0xff);
Port_Write(data,0);
Pin_Reset(cmd,e); // Reset E pin
_delay_ms(2); // wait for 20 ms
if(mode==8)
{
_delay_ms(2);
LCD_Command(0x38);
}
else
{
LCD_Command(0x33); //init command
LCD_Command(0x32); //init command
LCD_Command(0x28); //init command
}
LCD_Command(0x0e); //init command
LCD_Command(0x01); //init command
_delay_ms(2);
LCD_Command(0x06); //init command
}
void LCD_Print(u8* str)
{
u8 i;
for(i=0;str[i]!='\0';++i)
{
LCD_Out(str[i]);
}
}
<file_sep>/SPI_BLUE_MASTER/MASTER.c
///*
// * MASTER.c
// *
// * Created on: ??�/??�/????
// * Author: RAGAB
// */
//
//
//#include <avr/io.h>
//#include <util/delay.h>
//#define ACK 0X05
//
//#define START 'S'
//#define STOP 'T'
//
//#define MOTOR1_FORWOARD 'A'
//#define MOTOR1_REVERSE 'B'
//
//void SPI_initMaster(){
// DDRB |=(1<<PB4)|(1<<PB5)|(1<<PB7);
// DDRB &=~(1<<PB6);
// SPCR =(1<<SPE)|(1<<MSTR)| (1<<SPR1) |(1<<SPR0);
// PORTB |=(1<<PB4);
//}
//
//void SPI_initSalve()
//{
// DDRB &=~((1<<PB4)|(1<<PB5)|(1<<PB7));
// DDRB |=(1<<PB6);
// SPCR |=(1<<SPE);
//}
//unsigned char spi_tranceiver (unsigned char data)
//{
// PORTB &=~(1<<PB4);
// SPDR=data;
// while(!(SPSR & (1<<SPIF)));
// data = SPDR;
// PORTB |=(1<<PB4);
// return data;
//
//}
//
//int main(void)
//{
// SPI_initMaster();
// DDRC = 0x00; //Initialize PORTA as INPUT
//
// unsigned char data;
// unsigned char q=0;
//
// /* Replace with your application code */
//
//
// data = spi_tranceiver(START); //send start recive data
//
//
//
//
// while (1)
// {
//
// if ((PINC &(1<<PC0)))
// {
// if(q==0){
// spi_tranceiver(MOTOR1_FORWOARD);
// q=1;
// }else{
// spi_tranceiver(MOTOR1_REVERSE);
// q=0;
// }
// while((PINC &(1<<PC0)));
// }
//
//
//
// }
//}
#define F_CPU 4000000
#include <avr/io.h>
#include <util/delay.h>
#define ACK 0X05
#define START 'S'
#define STOP 'T'
#define MOTOR1_FORWOARD 'A'
#define MOTOR1_REVERSE 'B'
void SPI_initMaster(){
DDRB |=(1<<PB4)|(1<<PB5)|(1<<PB7);
DDRB &=~(1<<PB6);
SPCR |=(1<<SPE)|(1<<MSTR);
}
void SPI_initSalve(){
DDRB &=~((1<<PB4)|(1<<PB5)|(1<<PB7));
DDRB |=(1<<PB6);
SPCR |=(1<<SPE);
}
unsigned char spi_tranceiver (unsigned char data)
{
SPDR=data;
while(!(SPSR & (1<<SPIF)));
return data;
}
int main(void)
{
SPI_initMaster();
DDRC = 0x00; //Initialize PORTA as INPUT
//unsigned char data;
unsigned char q=0;
/* Replace with your application code */
spi_tranceiver(START); //send start recive data
while (1)
{
if ((PINC &(1<<PC0)))
{
if(q==0){
spi_tranceiver(MOTOR1_FORWOARD);
q=1;
}
else{
spi_tranceiver(MOTOR1_REVERSE);
q=0;
}
while((PINC &(1<<PC0)));
}
}
}
<file_sep>/TEST_SIZE/main.c
/*
* main.c
*
* Created on: ٣١/٠٣/٢٠١٧
* Author: RAGAB
*/
#include "avr/io.h"
unsigned int nn;
int main() {
DDRB = 0XFF;
unsigned int n;
unsigned int a=256;
unsigned int b=257;
unsigned int c=a + b;
unsigned char ss=nn*255;
PORTB = c;
while(1){
}
return 0;
}
<file_sep>/PWM_TIMER/PWM.c
/*
* PWM.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
#include "avr/io.h"
void TIMER0_init_pwm(unsigned char duty_cycle){
/* using non-inverted mode, Write a program that generates a
wave with frequency of 31,250 Hz and duty cycle of75%.-
31.250HZ = (8*10^6)/(N * 256) then N=1 no prescaller
*/
DDRB |=(1<<PB3);
OCR0 = duty_cycle;
TCCR0 =(1<<WGM01) |(1<<WGM00)|(1<<COM01)|(1<<CS00);
}
void TIMER0_init_pwm_phaseCorrect(unsigned char duty_cycle){
/* using non-inverted.mode, Write api:o~ ~t geeerates a
wave with frequency of 15.,686Hz and
duty cycle Of 75% then N=1 no prescaller
*/
DDRB |=(1<<PB3);
OCR0 = duty_cycle;
TCCR0 =(1<<WGM00) |(1<<COM01)|(1<<COM00)|(1<<CS00); //|(1<<WGM01)
}
int main(){
TIMER0_init_pwm(0); // 75% equal to ((75*256)-1)/100 =191
//TIMER0_init_pwm_phaseCorrect(0);//75% equal to 191
while(1);
return 0;
}
<file_sep>/Timer_test_mazidi/timer.c
/*
* timer.c
*
* Created on: ٢٢/٠٦/٢٠١٧
* Author: RAGAB
*/
#include <avr/io.h>
#define NUMBER_OF_OVERFLOW 2
volatile unsigned int dutycycle = 0;
void timer0_init(){
TCCR0 =(1<<FOC0)|(1<<CS01)|(1<<COM00);
OCR0 =128;
}
void timer1_pwn(unsigned short dutycycle){
DDRD |=(1<<PD5);
OCR1A = dutycycle;
TCCR1A = (1<<COM1A1) |(1<<WGM10)|(1<<WGM11) |(1<<WGM12);
TCCR1B = (1<<CS10);
}
int main(){
DDRD =0XFF;
DDRC =0X00;
PORTD =0X00;
while(1){
while(!(PINC &(1<<PC0)))
{
PORTD++;
while(!(PINC &(1<<PC0)));
}
}
return 0;
}
<file_sep>/USRT_TX/TX.c
/*
* TX.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
#include <avr/io.h>
#include <util/delay.h>
/*
* syn mode - 1MHZ -boudrate=9600bps
*/
void UART_init(){
//UCSRA |=(1<<U2X); //we use syn mode
UCSRB |=(1<<TXEN);
UCSRC |=(1<<UMSEL)|(1<<UCSZ1)|(1<<UCSZ0);
UBRRH |=(1<<URSEL);
UBRRL =52;
DDRB |=(1<<PB0);
}
void UART_sendByte(char byte){
while(!(UCSRA &(1<<UDRE)));
UDR = byte;
}
char UART_reciveByte(){
while(!(UCSRA &(1<<RXC)));
return UDR;
}
int main(){
UART_init();
_delay_ms(50);
UART_sendByte('A');
while(1){
}
return 0;
}
<file_sep>/LCD_CHARACTER_TEST_SHAPE/main.c
/*
* main.c
*
* Created on: ٢٤/٠٤/٢٠١٧
* Author: RAGAB
*/
#include "lcdlib.h"
void LCD_build(unsigned char location, unsigned char *ptr){
unsigned char i;
if(location<8){
LCD_command(0x40+(location*8));
for(i=0;i<8;i++)
LCD_Data(ptr[ i ]);
}
}
int main(){
LCD_init();
// const char *a="welcome I'm Ragab";
// LCD_displayString(a);
storeShape(1,2);
// LCD_build(1,shape);
while(1);
return 0;
}
<file_sep>/TIMER0_DELAY_500MSEC/main.c
/*
* main.c
*
* Created on: ٢٢/٠٤/٢٠١٧
* Author: RAGAB
*/
#include <avr/io.h>
void TIMER0_DELAY(){
//TCNT0=192;
OCR0 =255;
TCCR0 = (1<<FOC0)|(1<<CS00)|(1<<CS02)|(1<<COM00);
while(TIFR &(1<<TIFR)){
TIFR |=(1<<TIFR);
}
}
int main(){
DDRB |=(1<<PB3);
PORTB =0x00;
TIMER0_DELAY();
for(;;){
PORTB ^=(1<<PB0);
}
return 0;
}
<file_sep>/test_for_facebook/main.c
#define F_CPU 4000000
#include <avr/io.h>
#include <util/delay.h>
#define ACK 5
#define START 'S'
#define MOTOR1_FORWOARD 'A'
#define MOTOR1_REVERSE 'B'
void SPI_initMaster()
{
DDRB |=(1<<PB4)|(1<<PB5)|(1<<PB7);
DDRB &=~(1<<PB6);
SPCR |=(1<<SPE)|(1<<MSTR)|(1<<SPR0)|(1<<SPR1);
}
void SPI_initSalve()
{
DDRB &=~((1<<PB4)|(1<<PB5)|(1<<PB7));
DDRB |=(1<<PB6);
SPCR |=(1<<SPE);
}
uint8_t spi_tranceiver (uint8_t data)
{
SPDR=data;
while(!(SPSR)&(1<<SPIF));
return SPDR;
}
int main(void)
{
SPI_initSalve();
DDRC = 0x00; //Initialize PORTA as INPUT
PORTC = 0xFF;
unsigned char data;
/* Replace with your application code */
while (1)
{ do{
data = spi_tranceiver(ACK); //send ack recive data
}
while(data != START);
if (PINC==0)
{
spi_tranceiver('A');
_delay_ms(1000);
}
if (PINC==1)
{
spi_tranceiver('B');
_delay_ms(1000);
}
}
}
<file_sep>/ADC/adc.c
/*
* adc.c
*
* Created on: ٢٧/٠٦/٢٠١٧
* Author: RAGAB
*/
#include <avr/io.h>
#include "util/delay.h"
#include "lcdlib.h"
#define VREF 5
void ADC_init(){
/*Internal 2.56V Voltage Reference with external capacitor at AREF pin*/
ADMUX |=(1<<REFS0) ;
/* ADC Enable*/
ADCSRA |=(1<<ADEN)|(1<<ADPS1)|(1<<ADPS2);
}
unsigned short ADC_read(unsigned char ch){
ch &=0x07;
DDRA &=~(1<<ch);
ADMUX |= ch ;
ADCSRA |=(1<<ADSC);
while(!(ADCSRA & (1<<ADIF)) );
ADCSRA |=(1<<ADIF);
return ADC;
}
void PWM_init_phaseCorrect(){
DDRB |=(1<<PB3);
OCR0 =0;
TCCR0 =(1<<WGM00)|(1<<COM01)|(1<<CS00);
}
void PWM_init_fastPwm(){
DDRB |=(1<<PB3);
OCR0 =0;
TCCR0 =(1<<WGM00)|(1<<WGM01)|(1<<COM01)|(1<<CS00);
}
void adc_to_pwmbyPhaseCorrect(float inputVolt ){
float duty= (inputVolt/VREF)*100;
unsigned char ocr = ((duty*255)/100);
OCR0 =ocr;
LCD_goToRowCol(1,11);
LCD_intToString(ocr);
}
void adc_to_pwmbyFastPwm(float inputVolt){
float duty= (inputVolt/VREF)*100;
unsigned char ocr;
if(duty==0){
ocr =0;
}else{
ocr = ((duty*256)/100)-1;
}
OCR0 =ocr;
LCD_goToRowCol(1,11);
LCD_intToString(ocr);
}
int main(){
LCD_init();
ADC_init();
//PWM_init_fastPwm();
PWM_init_phaseCorrect();
DDRB = 0XFF;
PORTB=0X00;
float rest;
float vo;
while(1){
LCD_goToRowCol(1,1);
rest =ADC_read(0);
vo =(rest * 5)/1024;
LCD_intToString(vo*100);
/*output the volt by pwm*/
//adc_to_pwmbyFastPwm(vo);
adc_to_pwmbyPhaseCorrect(vo);
}
return 0;
}
<file_sep>/SPI_BLUE_SLAVE/SALAVE.c
/*
* SALAVE.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
#include <avr/io.h>
#include <util/delay.h>
#define ACK 0X05
#define START 'S'
#define STOP 'T'
#define MOTOR1_FORWOARD 'A'
#define MOTOR1_REVERSE 'B'
void SPI_initMaster()
{
DDRB |=(1<<PB4)|(1<<PB5)|(1<<PB7);
DDRB &=~(1<<PB6);
SPCR |=(1<<SPE)|(1<<MSTR)|(1<<SPR0)|(1<<SPR1);
}
void SPI_initSalve()
{
DDRB &=~((1<<PB4)|(1<<PB5)|(1<<PB7));
DDRB |=(1<<PB6);
SPCR |=(1<<SPE);
}
unsigned char SPI_reciveByte( )
{
//SPDR=data;
while(!(SPSR)&(1<<SPIF));
return SPDR;
}
int main(void)
{
SPI_initSalve();
DDRC=0xFF;
DDRD=0xFF;
PORTC = 0X00;
PORTD = 0X00;
unsigned char data;
unsigned char flag=0;
_delay_ms(1000);
/* Replace with your application code */
while(1){
data =SPI_reciveByte();
if(data == START){
PORTD =0x0f;
}
if (data == MOTOR1_FORWOARD && flag==0 )
{
flag=1;
PORTC =(1<<PC0);
_delay_ms(3000);
PORTC =0x00;
}
if(data == MOTOR1_REVERSE&& flag==1 )
{
flag=0;
PORTC =(1<<PC1);
_delay_ms(3000);
PORTC =0x00;
}
}
}
<file_sep>/TIMER_MODE/Timer.c
/*
* Timer.c
*
* Created on: ??þ/??þ/????
* Author: RAGAB
*/
#include "avr/io.h"
void timer0_init(){
DDRB |=(1<<PB3);
TCCR0 =(1<<FOC0)|(1<<COM00)|(1<<CS01)|(1<<WGM01);
}
int main(){
DDRB |=(1<<PB2);
timer0_init();
char i=0;
while(1){
if(TIFR & (1<<TOV0)){
PORTB ^=(1<<PB2);
TIFR |=(1<<TOV0);
}
if((TIFR & (1<<OCF0)) && i == 0){
TIFR |=(1<<OCF0);
OCR0 = 100;
i=1;
}
else if((TIFR & (1<<OCF0)) && i == 1){
TIFR |=(1<<OCF0);
OCR0 = 250;
i=0;
}
}
return 0;
}
<file_sep>/test_lcd/AVR_FUNCTIONS.h
/*=========================*/
/* Functions definitions */
/*=========================*/
#ifndef LCD_FUNCTION_H_
#define LCD_FUNCTION_H_
#include "typedefs.h"
#include "AVR_INTERFACE.h"
#include "util.h"
void Port_Direction_All(u8 base,u8 state); // Configure the whole port direction as input or output
void Port_Direction(u8 base,u8 value); // configure the whole port direction to be a specific value
void Pin_Direction(u8 base,u8 pin,u8 state); // configure a single pin in the port to be output or input
void Pin_Reset(u8 base,u8 pin); //makes the physical pin 0 electrically (grounded)
void Pin_Set(u8 base,u8 pin); //makes the physical pin 1 electrically (connected to vdd)
void Port_Write(u8 base ,u8 value); //assign the required value to the physical port
u8 Port_Read(u8 base); // assign the value of the whole port to a value and return it
void Pin_Write(u8 base,u8 pin,u8 value); // assign 0 or 1 (electrically) to a specific pin
u8 Pin_Read(u8 base,u8 pin); // note that we use && to get a false or true result from the whole expression
#endif
|
512c6884ab252ac0ce65267496ca738c7d35a165
|
[
"Markdown",
"C",
"Makefile"
] | 43 |
C
|
Ragab2010/Atmega-implementation-drivers-and-Interfacing-Modules
|
b721b83938c4ec30a8a5b5f77371fe8394cc8c0c
|
b6597ee3cd7c0a279e055d7ee52556d3f4821127
|
refs/heads/master
|
<repo_name>fangtoby/breadwallet-actinium-ios<file_sep>/actiniumwallet/src/Wallet/WalletCoordinator.swift
//
// WalletCoordinator.swift
// actiniumwallet
//
// Created by <NAME> on 2017-01-07.
// Copyright © 2018 Actiniumwallet Team. All rights reserved.
//
import Foundation
import UIKit
//Coordinates the sync state of all wallet managers to
//display the activity indicator and control backtround tasks
class WalletCoordinator : Subscriber, Trackable {
private var backgroundTaskId: UIBackgroundTaskIdentifier?
private var reachability = ReachabilityMonitor()
private var walletManagers: [String: WalletManager]
init(walletManagers: [String: WalletManager]) {
self.walletManagers = walletManagers
addSubscriptions()
}
private func addSubscriptions() {
reachability.didChange = { [weak self] isReachable in
self?.reachabilityDidChange(isReachable: isReachable)
}
//Listen for sync state changes in all wallets
Store.subscribe(self, selector: {
for (key, val) in $0.wallets {
if val.syncState != $1.wallets[key]!.syncState {
return true
}
}
return false
}, callback: { [weak self] state in
self?.syncStateDidChange(state: state)
})
Store.state.currencies.forEach { currency in
Store.subscribe(self, name: .retrySync(currency), callback: { _ in
DispatchQueue.walletQueue.async {
self.walletManagers[currency.code]?.peerManager?.connect()
}
})
Store.subscribe(self, name: .rescan(currency), callback: { _ in
Store.perform(action: WalletChange(currency).setRecommendScan(false))
Store.perform(action: WalletChange(currency).setIsRescanning(true))
DispatchQueue.walletQueue.async {
self.walletManagers[currency.code]?.peerManager?.rescan()
}
})
}
}
private func syncStateDidChange(state: State) {
let allWalletsFinishedSyncing = state.wallets.values.filter { $0.syncState == .success}.count == state.wallets.values.count
if allWalletsFinishedSyncing {
endActivity()
endBackgroundTask()
} else {
startActivity()
startBackgroundTask()
}
}
private func endBackgroundTask() {
if let taskId = backgroundTaskId {
UIApplication.shared.endBackgroundTask(taskId)
backgroundTaskId = nil
}
}
private func startBackgroundTask() {
guard backgroundTaskId == nil else { return }
backgroundTaskId = UIApplication.shared.beginBackgroundTask(expirationHandler: {
DispatchQueue.walletQueue.async {
self.walletManagers.values.forEach {
$0.peerManager?.disconnect()
}
}
})
}
private func reachabilityDidChange(isReachable: Bool) {
if !isReachable {
DispatchQueue.walletQueue.async {
self.walletManagers.values.forEach {
$0.peerManager?.disconnect()
}
DispatchQueue.main.async {
Store.state.currencies.forEach {
Store.perform(action: WalletChange($0).setSyncingState(.connecting))
}
}
}
}
}
private func startActivity() {
UIApplication.shared.isIdleTimerDisabled = true
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
private func endActivity() {
UIApplication.shared.isIdleTimerDisabled = false
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
<file_sep>/actiniumwallet/src/ViewModels/TxListViewModel.swift
//
// TxListViewModel.swift
// actiniumwallet
//
// Created by <NAME> on 2018-01-13.
// Copyright © 2018 breadwallet LLC. All rights reserved.
//
import UIKit
/// View model of a transaction in list view
struct TxListViewModel: TxViewModel {
// MARK: - Properties
let tx: Transaction
var shortDescription: String {
let isComplete = tx.status == .complete
if let comment = comment, comment.count > 0, isComplete {
return comment
} else {
var format: String
switch tx.direction {
case .sent, .moved:
format = isComplete ? S.Transaction.sentTo : S.Transaction.sendingTo
case .received:
format = isComplete ? S.Transaction.receivedVia : S.Transaction.receivingVia
}
let address = tx.toAddress
return String(format: format, address)
}
}
func amount(rate: Rate) -> NSAttributedString {
guard let tx = tx as? RvnTransaction else { return NSAttributedString(string: "") }
let text = DisplayAmount(amount: Satoshis(rawValue: tx.amount),
selectedRate: nil,
minimumFractionDigits: nil,
currency: tx.currency,
negative: (tx.direction == .sent)).description
let color: UIColor = (tx.direction == .received) ? .receivedGreen : .sentRed
return NSMutableAttributedString(string: text,
attributes: [.foregroundColor: color])
}
}
<file_sep>/Modules/core/README.md
New wallet creation:
If the native secure keystore is verified as being available, and it does not contain a master public key, then present the user with the option to create a new wallet.
Using a native source of entropy suitable for cryptographic use, obtain 128bits of random data.
Use BRBIP39Encode() to encode this 128bits of data as a 12 word recovery phrase.
Store the resulting recovery phrase in the native secure keystore.
Store any appropriate wallet authentication information in the secure keystore as well, such as a user selected passcode.
Use BIP39DeriveKey() to derive a master private key from the recovery phrase, feed this to BIP32MasterPubKey() to get the master pubkey, and store the master pubkey in the secure keystore.
Store the timestamp when the wallet was created in the secure keystore.
The creation time and master pubkey should be available to the wallet app without user authentication, so that it can be used for background network syncing, and/or syncing immediately on app launch prior to the user being authenticated. It's desirable to use the keystore so that it will be removed in any situation where the keystore data goes missing, such as a backup/restore to a different device that fails to migrate keystore data.
Existing wallet startup:
Retrieve the master pubkey and wallet creation time from the native secure keystore.
Create an array of BRTransaction structs from all transactions in the local data store.
Create a BRWallet struct with BRWalletNew(), using the master pubkey and transaction array.
Use BRWalletSetCallbacks() to setup callback functions to be notified of balance changes, and to add/update/remove transactions from the local data store.
Create arrays of BRPeer and BRMerkleBlock structs from peers and blocks in the local data store.
Create a BRPeerManager struct with BRPeerManagerNew() using the wallet struct, creation time, and arrays of peers and merkleblocks.
Use BRPeerManagerSetCallbacks() to setup callback functions to be notified of network syncing start/success/failure, of changes to transaction status (when a new block arrives), to store peers and blocks in the local data store, and a callback function for the peer manager to check the current status of the network connection.
Call BRPeerManagerConnect() to initiate connection and syncing with the bitcoin network.
Call BRPeerManagerSyncProgress() to monitor syncing progress.
Transaction creation and broadcast:
Call BRWalletCreateTransaction() with a payment address and amount.
Call BRWalletFeeForTx() to get the amount of the bitcoin network fee, and BRWalletAmountSentByTx()(no longer exists - simple search in the modules)_ for the final total, and present this information to the user along with anything else such as the payment address that the user needs to decide to authorize the transaction or not.
If the user chooses to authorize the transaction and successfully authenticates with passcode or fingerprint, retrieve the 12 word recovery phrase from the native secure keystore, and use BIP39DeriveKey() to derive a master private key (wallet seed) from the recovery phrase.
Call BRWalletSignTransaction() with the transaction and master private key (seed) to sign the transaction.
Call BRPeerManagerPublishTx() to broadcast the signed transaction to the bitcoin network.
Call BRPeerManagerRelayCount() with the transaction hash to monitor network propagation.<file_sep>/actiniumwallet/src/ViewModels/RvnTransaction.swift
//
// BtcTransaction.swift
// actiniumwallet
//
// Created by <NAME> on 2018-01-12.
// Copyright © 2018 breadwallet LLC. All rights reserved.
//
import Foundation
import BRCore
/// Wrapper for BTC transaction model + metadata
struct RvnTransaction: Transaction {
// MARK: Transaction Properties
let currency: CurrencyDef
let hash: String
let status: TransactionStatus
let direction: TransactionDirection
let toAddress: String
let timestamp: TimeInterval
let blockHeight: UInt64
let confirmations: UInt64
let isValid: Bool
var hasKvStore: Bool {
return kvStore != nil
}
// MARK: BTC-specific properties
var rawTransaction: BRTransaction? {
return tx.pointee
}
var metaData: TxMetaData? {
return metaDataContainer?.metaData
}
let amount: UInt64
let fee: UInt64
let startingBalance: UInt64
let endingBalance: UInt64
// MARK: Private
private let tx: BRTxRef
private let metaDataContainer: MetaDataContainer?
private let kvStore: BRReplicatedKVStore?
// MARK: - Init
init?(_ tx: BRTxRef, walletManager: WalletManager, kvStore: BRReplicatedKVStore?, rate: Rate?) {
guard let wallet = walletManager.wallet,
let peerManager = walletManager.peerManager else { return nil }
self.currency = walletManager.currency
self.tx = tx
self.kvStore = kvStore
let amountReceived = wallet.amountReceivedFromTx(tx)
let amountSent = wallet.amountSentByTx(tx)
let fee = wallet.feeForTx(tx) ?? 0
self.fee = fee
// addresses from outputs
let myAddress = tx.outputs.filter({ output in
wallet.containsAddress(output.swiftAddress)
}).first?.swiftAddress ?? ""
let otherAddress = tx.outputs.filter({ output in
!wallet.containsAddress(output.swiftAddress)
}).first?.swiftAddress ?? ""
// direction
var direction: TransactionDirection
if amountSent > 0 && (amountReceived + fee) == amountSent {
direction = .moved
} else if amountSent > 0 {
direction = .sent
} else {
direction = .received
}
self.direction = direction
let endingBalance: UInt64 = wallet.balanceAfterTx(tx)
var startingBalance: UInt64
var address: String
switch direction {
case .received:
address = myAddress
amount = amountReceived
startingBalance = endingBalance.subtractingReportingOverflow(amount).0.subtractingReportingOverflow(fee).0
case .sent:
address = otherAddress
amount = amountSent - amountReceived - fee
startingBalance = endingBalance.addingReportingOverflow(amount).0.addingReportingOverflow(fee).0
case .moved:
address = myAddress
amount = amountSent
startingBalance = endingBalance.addingReportingOverflow(self.fee).0
}
self.startingBalance = startingBalance
self.endingBalance = endingBalance
toAddress = address
hash = tx.pointee.txHash.description
timestamp = TimeInterval(tx.pointee.timestamp)
isValid = wallet.transactionIsValid(tx)
blockHeight = (tx.pointee.blockHeight == UInt32.max) ? UInt64.max : UInt64(tx.pointee.blockHeight)
let lastBlockHeight = UInt64(peerManager.lastBlockHeight)
confirmations = blockHeight > lastBlockHeight
? 0
: (lastBlockHeight - blockHeight) + 1
if isValid {
switch confirmations {
case 0:
status = .pending
case 1..<6:
status = .confirmed
default:
status = .complete
}
} else {
status = .invalid
}
if let kvStore = kvStore {
metaDataContainer = MetaDataContainer(key: tx.pointee.txHash.txKey, kvStore: kvStore)
if let rate = rate,
confirmations < 6 && direction == .received {
metaDataContainer!.createMetaData(tx: tx, rate: rate)
}
} else {
metaDataContainer = nil
}
}
// MARK: -
func saveComment(comment: String, rate: Rate) {
guard let metaDataContainer = metaDataContainer else { return }
metaDataContainer.save(comment: comment, tx: tx, rate: rate)
}
}
/// Encapsulates the transaction metadata in the KV store
class MetaDataContainer {
var metaData: TxMetaData? {
get {
guard metaDataCache == nil else { return metaDataCache }
guard let data = TxMetaData(txKey: key, store: kvStore) else { return nil }
metaDataCache = data
return metaDataCache
}
}
private var key: String
private var kvStore: BRReplicatedKVStore
private var metaDataCache: TxMetaData?
init(key: String, kvStore: BRReplicatedKVStore) {
self.key = key
self.kvStore = kvStore
}
/// Creates and stores new metadata in KV store if it does not exist
func createMetaData(tx: BRTxRef, rate: Rate, comment: String? = nil) {
guard metaData == nil else { return }
let newData = TxMetaData(transaction: tx.pointee,
exchangeRate: rate.rate,
exchangeRateCurrency: rate.code,
feeRate: 0.0,
deviceId: UserDefaults.standard.deviceID)
if let comment = comment {
newData.comment = comment
}
do {
let _ = try kvStore.set(newData)
} catch let error {
print("could not update metadata: \(error)")
}
}
func save(comment: String, tx: BRTxRef, rate: Rate) {
if let metaData = metaData {
metaData.comment = comment
do {
let _ = try kvStore.set(metaData)
} catch let error {
print("could not update metadata: \(error)")
}
} else {
createMetaData(tx: tx, rate: rate, comment: comment)
}
}
}
<file_sep>/actiniumwallet/src/Views/SyncingIndicator.swift
//
// SyncingIndicator.swift
// actiniumwallet
//
// Created by <NAME> on 2018-02-16.
// Copyright © 2018 breadwallet LLC. All rights reserved.
//
import UIKit
/// Small syncing progress indicator
class SyncingIndicator: UIView {
enum Style {
case home
case account
}
// MARK: Vars
private let style: Style
private let label = UILabel(font: .customBold(size: 12.0), color: .transparentWhiteText)
private let progressBar = ProgressBar()
var progress: CGFloat = 0.0 {
didSet {
progressBar.setProgress(ratio: progress)
}
}
var text: String = S.SyncingView.syncing {
didSet {
label.text = text
progressBar.pulse()
}
}
// MARK: Init
init(style: Style) {
self.style = style
super.init(frame: .zero)
setup()
}
private func setup() {
addSubview(progressBar)
addSubview(label)
setupConstraints()
label.font = (style == .home) ? .customBold(size: 12.0) : .customBody(size: 14.0)
label.textAlignment = .right
label.text = text
}
private func setupConstraints() {
label.constrain([
label.leadingAnchor.constraint(equalTo: leadingAnchor),
label.topAnchor.constraint(equalTo: topAnchor),
label.bottomAnchor.constraint(equalTo: bottomAnchor)
])
progressBar.constrain([
progressBar.trailingAnchor.constraint(equalTo: trailingAnchor),
progressBar.leadingAnchor.constraint(equalTo: label.trailingAnchor, constant: C.padding[1]),
progressBar.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 1.0),
progressBar.heightAnchor.constraint(equalToConstant: 4.0),
progressBar.widthAnchor.constraint(equalToConstant: 34.0)
])
}
func pulse() {
progressBar.pulse()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private class ProgressBar: UIView {
private let progress: UIView
private var progressWidth: NSLayoutConstraint!
init(backgroundColor: UIColor = UIColor.white.withAlphaComponent(0.5),
foregroundColor: UIColor = .white) {
progress = UIView(color: foregroundColor)
super.init(frame: .zero)
self.backgroundColor = backgroundColor
setup()
}
private func setup() {
addSubview(progress)
progressWidth = progress.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.0)
progress.constrain([
progress.leadingAnchor.constraint(equalTo: leadingAnchor),
progress.topAnchor.constraint(equalTo: topAnchor),
progress.bottomAnchor.constraint(equalTo: bottomAnchor),
progressWidth
])
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = frame.height / 2.0
layer.masksToBounds = true
progress.layer.cornerRadius = layer.cornerRadius
progress.layer.masksToBounds = true
}
/// Set progress ratio (0.0 to 1.0)
func setProgress(ratio: CGFloat) {
let ratio = max(0.0, min(ratio, 1.0))
progressWidth.isActive = false
progressWidth = progress.widthAnchor.constraint(equalTo: widthAnchor, multiplier: ratio)
progressWidth.isActive = true
UIView.animate(withDuration: 0.2) {
self.progress.setNeedsLayout()
}
}
/// pulse animation
func pulse() {
self.progress.layer.removeAllAnimations()
self.progress.backgroundColor = .white
UIView.animate(withDuration: 1.0,
delay: 0.5,
options: [.repeat, .autoreverse],
animations: {
self.progress.backgroundColor = UIColor.white.withAlphaComponent(0.3)
}, completion: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
<file_sep>/Modules/core/BIP44Sequence.h
//
// Created by ROSHii on 7/25/18.
//
#ifndef BRBIP44Sequence_h
#define BRBIP44Sequence_h
#include "BRKey.h"
#include "BRInt.h"
#include <stddef.h>
#include <inttypes.h>
#include <stdarg.h>
#include "BRBIP32Sequence.h"
#ifdef __cplusplus
extern "C" {
#endif
#define BIP32_HARD 0x80000000
#define BIP44_PURPOSE 44
#define BIP44_RVN_COINTYPE 175
#define BIP44_DEFAULT_ACCOUNT 0
#define BIP44_CHANGE 0
#define SEQUENCE_GAP_LIMIT_EXTERNAL 1
#define SEQUENCE_GAP_LIMIT_INTERNAL 1
BRMasterPubKey BIP44MasterPubKey(const void *seed, size_t seedLen, uint32_t account, uint32_t coinType);
// writes the public key for path N(m/0H/chain/index) to pubKey
// returns number of bytes written, or pubKeyLen needed if pubKey is NULL
size_t BIP44PubKey(uint8_t *pubKey, size_t pubKeyLen, BRMasterPubKey mpk, uint32_t chain, uint32_t index);
// sets the private key for path m/44H/chain/index to each element in keys
void BIP44PrivKeyList(BRKey keys[], size_t keysCount, const void *seed, size_t seedLen, uint32_t coinType,
// uint32_t account, uint32_t chain,
const uint32_t indexes[]);
void BIP44AddrKey(BRKey *key, const void *seed, size_t seedLen);
#ifdef __cplusplus
}
#endif
#endif // BRBIP44Sequence_h
<file_sep>/actiniumwallet/src/ViewControllers/HomeScreenViewController.swift
//
// HomeScreenViewController.swift
// actiniumwallet
//
// Created by <NAME> on 2017-11-27.
// Copyright © 2018 Actiniumwallet Team. All rights reserved.
//
import UIKit
class HomeScreenViewController : UIViewController, Subscriber, Trackable {
var primaryWalletManager: WalletManager? {
didSet {
setInitialData()
setupSubscriptions()
currencyList.reload()
attemptShowPrompt()
}
}
private let currencyList = AssetListTableView()
private let subHeaderView = UIView()
private var logo: UIImageView = {
let image = UIImageView(image: #imageLiteral(resourceName: "newLogo"))
image.contentMode = .scaleAspectFit
return image
}()
private let total = UILabel(font: .customBold(size: 30.0), color: .darkGray)
private let totalHeader = UILabel(font: .customMedium(size: 18.0), color: .mediumGray)
private let prompt = UIView()
private var promptHiddenConstraint: NSLayoutConstraint!
var didSelectCurrency : ((CurrencyDef) -> Void)?
var didTapSecurity: (() -> Void)?
var didTapSupport: (() -> Void)?
var didTapSettings: (() -> Void)?
// MARK: -
init(primaryWalletManager: WalletManager?) {
self.primaryWalletManager = primaryWalletManager
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
currencyList.didSelectCurrency = didSelectCurrency
currencyList.didTapSecurity = didTapSecurity
currencyList.didTapSupport = didTapSupport
currencyList.didTapSettings = didTapSettings
addSubviews()
addConstraints()
setInitialData()
setupSubscriptions()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
DispatchQueue.main.asyncAfter(deadline: .now() + promptDelay) { [weak self] in
self?.attemptShowPrompt()
}
}
// MARK: Setup
private func addSubviews() {
view.addSubview(subHeaderView)
subHeaderView.addSubview(logo)
subHeaderView.addSubview(totalHeader)
subHeaderView.addSubview(total)
view.addSubview(prompt)
}
private func addConstraints() {
let height: CGFloat = 136.0
if #available(iOS 11.0, *) {
subHeaderView.constrain([
subHeaderView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
subHeaderView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0.0),
subHeaderView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
subHeaderView.heightAnchor.constraint(equalToConstant: height) ])
} else {
subHeaderView.constrain([
subHeaderView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
subHeaderView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 0.0),
subHeaderView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
subHeaderView.heightAnchor.constraint(equalToConstant: height) ])
}
let yConstraint = NSLayoutConstraint(item: logo, attribute: .centerY, relatedBy: .equal, toItem: subHeaderView, attribute: .centerY, multiplier: 0.5, constant: 0.0)
logo.constrain([
logo.constraint(.centerX, toView: subHeaderView, constant: nil),
logo.trailingAnchor.constraint(equalTo: subHeaderView.trailingAnchor, constant: -C.padding[2]),
logo.leadingAnchor.constraint(equalTo: subHeaderView.leadingAnchor, constant: C.padding[2]),
yConstraint])
totalHeader.constrain([
totalHeader.trailingAnchor.constraint(equalTo: total.trailingAnchor),
totalHeader.bottomAnchor.constraint(equalTo: total.topAnchor, constant: 0.0),
totalHeader.topAnchor.constraint(equalTo: logo.bottomAnchor, constant: C.padding[2])
])
total.constrain([
total.trailingAnchor.constraint(equalTo: subHeaderView.trailingAnchor, constant: -C.padding[2]),
total.topAnchor.constraint(equalTo: totalHeader.bottomAnchor)])
promptHiddenConstraint = prompt.heightAnchor.constraint(equalToConstant: 0.0)
prompt.constrain([
prompt.leadingAnchor.constraint(equalTo: view.leadingAnchor),
prompt.trailingAnchor.constraint(equalTo: view.trailingAnchor),
prompt.topAnchor.constraint(equalTo: subHeaderView.bottomAnchor),
promptHiddenConstraint
])
addChildViewController(currencyList, layout: {
currencyList.view.constrain([
currencyList.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
currencyList.view.topAnchor.constraint(equalTo: prompt.bottomAnchor),
currencyList.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
currencyList.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)])
})
}
private func setInitialData() {
view.backgroundColor = .whiteBackground
subHeaderView.backgroundColor = .whiteBackground
subHeaderView.clipsToBounds = false
navigationItem.titleView = UIView()
navigationController?.navigationBar.isTranslucent = true
navigationController?.navigationBar.shadowImage = #imageLiteral(resourceName: "TransparentPixel")
navigationController?.navigationBar.setBackgroundImage(#imageLiteral(resourceName: "TransparentPixel"), for: .default)
totalHeader.text = S.HomeScreen.totalAssets
totalHeader.textAlignment = .left
total.textAlignment = .left
total.text = "0"
title = ""
updateTotalAssets()
}
private func updateTotalAssets() {
let fiatTotal = Store.state.currencies.map {
let balance = Store.state[$0].balance ?? 0
let rate = Store.state[$0].currentRate?.rate ?? 0
return Double(balance)/$0.baseUnit * rate * 0.001
}.reduce(0.0, +)
let format = NumberFormatter()
format.isLenient = true
format.numberStyle = .currency
format.generatesDecimalNumbers = true
format.negativeFormat = format.positiveFormat.replacingCharacters(in: format.positiveFormat.range(of: "#")!, with: "-#")
format.currencySymbol = Store.state[Currencies.rvn].currentRate?.currencySymbol ?? ""
self.total.text = format.string(from: NSNumber(value: fiatTotal))
}
private func setupSubscriptions() {
Store.unsubscribe(self)
Store.subscribe(self, selector: {
var result = false
let oldState = $0
let newState = $1
$0.currencies.forEach { currency in
if oldState[currency].balance != newState[currency].balance {
result = true
}
if oldState[currency].currentRate?.rate != newState[currency].currentRate?.rate {
result = true
}
}
return result
},
callback: { _ in
self.updateTotalAssets()
})
// prompts
Store.subscribe(self, name: .didUpgradePin, callback: { _ in
if self.currentPrompt?.type == .upgradePin {
self.currentPrompt = nil
}
})
Store.subscribe(self, name: .didEnableShareData, callback: { _ in
if self.currentPrompt?.type == .shareData {
self.currentPrompt = nil
}
})
Store.subscribe(self, name: .didWritePaperKey, callback: { _ in
if self.currentPrompt?.type == .paperKey {
self.currentPrompt = nil
}
})
}
// MARK: - Prompt
private let promptDelay: TimeInterval = 0.6
private var currentPrompt: Prompt? {
didSet {
if currentPrompt != oldValue {
var afterFadeOut: TimeInterval = 0.0
if let oldPrompt = oldValue {
afterFadeOut = 0.15
UIView.animate(withDuration: 0.2, animations: {
oldValue?.alpha = 0.0
}, completion: { _ in
oldPrompt.removeFromSuperview()
})
}
if let newPrompt = currentPrompt {
newPrompt.alpha = 0.0
prompt.addSubview(newPrompt)
newPrompt.constrain(toSuperviewEdges: .zero)
prompt.layoutIfNeeded()
promptHiddenConstraint.isActive = false
// fade-in after fade-out and layout
UIView.animate(withDuration: 0.2, delay: afterFadeOut + 0.15, options: .curveEaseInOut, animations: {
newPrompt.alpha = 1.0
})
} else {
promptHiddenConstraint.isActive = true
}
// layout after fade-out
UIView.animate(withDuration: 0.2, delay: afterFadeOut, options: .curveEaseInOut, animations: {
self.view.layoutIfNeeded()
})
}
}
}
private func attemptShowPrompt() {
guard let walletManager = primaryWalletManager else {
currentPrompt = nil
return
}
if let type = PromptType.nextPrompt(walletManager: walletManager) {
self.saveEvent("prompt.\(type.name).displayed")
currentPrompt = Prompt(type: type)
currentPrompt!.dismissButton.tap = { [unowned self] in
self.saveEvent("prompt.\(type.name).dismissed")
self.currentPrompt = nil
}
currentPrompt!.continueButton.tap = { [unowned self] in
if let trigger = type.trigger(currency: Currencies.rvn) {
Store.trigger(name: trigger)
}
self.saveEvent("prompt.\(type.name).trigger")
self.currentPrompt = nil
}
if type == .biometrics {
UserDefaults.hasPromptedBiometrics = true
}
if type == .shareData {
UserDefaults.hasPromptedShareData = true
}
} else {
currentPrompt = nil
}
}
// MARK: -
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
<file_sep>/Modules/core/BIP44Sequence.c
//
// Created by ROSHii on 7/25/18.
//
#include "BIP44Sequence.h"
#include "BRBIP32Sequence.h"
#include "BRCrypto.h"
#include "BRBase58.h"
#include "BRInt.h"
#include <string.h>
#include <assert.h>
#include <stdarg.h>
#define BIP32_SEED_KEY "Bitcoin seed"
#define BIP32_XPRV "\x04\x88\xAD\xE4"
#define BIP32_XPUB "\x04\x88\xB2\x1E"
static void _CKDpriv(UInt256 *k, UInt256 *c, uint32_t i) {
uint8_t buf[sizeof(BRECPoint) + sizeof(i)];
UInt512 I;
if (i & BIP32_HARD) {
buf[0] = 0;
UInt256Set(&buf[1], *k);
} else
BRSecp256k1PointGen((BRECPoint *)buf, k);
UInt32SetBE(&buf[sizeof(BRECPoint)], i);
BRHMAC(&I, BRSHA512, sizeof(UInt512), c, sizeof(*c), buf, sizeof(buf)); // I = HMAC-SHA512(c, k|P(k) || i)
BRSecp256k1ModAdd(k, (UInt256 *)&I); // k = IL + k (mod n)
*c = *(UInt256 *)&I.u8[sizeof(UInt256)]; // c = IR
var_clean(&I);
mem_clean(buf, sizeof(buf));
}
static void _CKDpub(BRECPoint *K, UInt256 *c, uint32_t i) {
uint8_t buf[sizeof(*K) + sizeof(i)];
UInt512 I;
if ((i & BIP32_HARD) != BIP32_HARD) { // can't derive private child key from public parent key
*(BRECPoint *)buf = *K;
UInt32SetBE(&buf[sizeof(*K)], i);
BRHMAC(&I, BRSHA512, sizeof(UInt512), c, sizeof(*c), buf, sizeof(buf)); // I = HMAC-SHA512(c, P(K) || i)
*c = *(UInt256 *)&I.u8[sizeof(UInt256)]; // c = IR
BRSecp256k1PointAdd(K, (UInt256 *)&I); // K = P(IL) + K
var_clean(&I);
mem_clean(buf, sizeof(buf));
}
}
// returns the master public key for the default BIP32 wallet layout - derivation path N(m/44'/coinType'/account')
BRMasterPubKey BIP44MasterPubKey(const void *seed, size_t seedLen, uint32_t account, uint32_t coinType) {
BRMasterPubKey mpk = BR_MASTER_PUBKEY_NONE;
UInt512 I;
UInt256 secret, chain;
BRKey key;
assert(seed != NULL || seedLen == 0);
if (seed || seedLen == 0) {
BRHMAC(&I, BRSHA512, sizeof(UInt512), BIP32_SEED_KEY, strlen(BIP32_SEED_KEY), seed, seedLen);
secret = *(UInt256 *)&I;
chain = *(UInt256 *)&I.u8[sizeof(UInt256)];
var_clean(&I);
_CKDpriv(&secret, &chain, BIP44_PURPOSE | BIP32_HARD); // path m/44H
_CKDpriv(&secret, &chain, coinType | BIP32_HARD); // path m/44H/coinType'
_CKDpriv(&secret, &chain, account | BIP32_HARD); // path m/44H/coinType'/account'
BRKeySetSecret(&key, &secret, 1);
mpk.fingerPrint = BRKeyHash160(&key).u32[0];
mpk.chainCode = chain;
BRKeySetSecret(&key, &secret, 1);
var_clean(&secret, &chain);
BRKeyPubKey(&key, &mpk.pubKey, sizeof(mpk.pubKey)); // path N(m/0H)
BRKeyClean(&key);
}
return mpk;
}
// writes the public key for path N(m/44H/coinType'/account') to pubKey
// returns number of bytes written, or pubKeyLen needed if pubKey is NULL
size_t BIP44PubKey(uint8_t *pubKey, size_t pubKeyLen, BRMasterPubKey mpk, uint32_t chain, uint32_t index ) {
UInt256 chainCode = mpk.chainCode;
assert(memcmp(&mpk, &BR_MASTER_PUBKEY_NONE, sizeof(mpk)) != 0);
if (pubKey && sizeof(BRECPoint) <= pubKeyLen) {
*(BRECPoint *)pubKey = *(BRECPoint *)mpk.pubKey;
_CKDpub((BRECPoint *)pubKey, &chainCode, chain); // path N(m/44'/account'/chain)
_CKDpub((BRECPoint *)pubKey, &chainCode, index); // index'th key in chain
var_clean(&chainCode);
}
return (! pubKey || sizeof(BRECPoint) <= pubKeyLen) ? sizeof(BRECPoint) : 0;
}
// sets the private key for path m/0H/chain/index to each element in keys
void BIP44PrivKeyList(BRKey keys[], size_t keysCount, const void *seed, size_t seedLen, uint32_t coinType,
//uint32_t account, uint32_t chain,
const uint32_t indexes[]) {
UInt512 I;
UInt256 secret, chainCode, s, c;
assert(keys != NULL || keysCount == 0);
assert(seed != NULL || seedLen == 0);
assert(indexes != NULL || keysCount == 0);
if (keys && keysCount > 0 && (seed || seedLen == 0) && indexes) {
BRHMAC(&I, BRSHA512, sizeof(UInt512), BIP32_SEED_KEY, strlen(BIP32_SEED_KEY), seed, seedLen);
secret = *(UInt256 *)&I;
chainCode = *(UInt256 *)&I.u8[sizeof(UInt256)];
var_clean(&I);
// _CKDpriv(&secret, &chainCode, 0 | BIP32_HARD); // path m/0H
// _CKDpriv(&secret, &chainCode, chain); // path m/0H/chain
_CKDpriv(&secret, &chainCode, BIP44_PURPOSE | BIP32_HARD); // path m/44H
_CKDpriv(&secret, &chainCode, BIP44_RVN_COINTYPE | BIP32_HARD); // path m/44H/coinType'
_CKDpriv(&secret, &chainCode, BIP44_CHANGE | BIP32_HARD); // path m/44H/coinType'/account'
for (size_t i = 0; i < keysCount; i++) {
s = secret;
c = chainCode;
_CKDpriv(&s, &c, BIP44_CHANGE); // path m/44'/coinType'/account'/chain
_CKDpriv(&s, &c, indexes[i]); // path m/44'/coinType'/account'/chain/index
BRKeySetSecret(&keys[i], &s, 1);
}
var_clean(&secret, &chainCode, &c, &s);
}
}
// initial key used for address derivation,- path m/44'/0'/0'
void BIP44AddrKey(BRKey *key, const void *seed, size_t seedLen) {
BRBIP32PrivKeyPath(key, seed, seedLen, 5, BIP44_PURPOSE | BIP32_HARD, BIP44_RVN_COINTYPE | BIP32_HARD,
BIP44_DEFAULT_ACCOUNT | BIP32_HARD);
}
<file_sep>/actiniumwallet/src/Constants/Constants.swift
//
// Constants.swift
// actiniumwallet
//
// Created by <NAME> on 2016-10-24.
// Copyright © 2018 Actiniumwallet Team. All rights reserved.
//
import UIKit
let π: CGFloat = .pi
struct Padding {
subscript(multiplier: Int) -> CGFloat {
get {
return CGFloat(multiplier) * 8.0
}
}
}
struct C {
static let padding = Padding()
struct Sizes {
static let buttonHeight: CGFloat = 48.0
static let headerHeight: CGFloat = 48.0
static let largeHeaderHeight: CGFloat = 220.0
static let logoAspectRatio: CGFloat = 125.0/417.0
static let roundedCornerRadius: CGFloat = 6.0
}
static var defaultTintColor: UIColor = {
return UIView().tintColor
}()
static let animationDuration: TimeInterval = 0.3
static let secondsInDay: TimeInterval = 86400
static let maxMoney: UInt64 = 21000000000*100000000
static let satoshis: UInt64 = 100000000
// TODO Ravenize
static let walletQueue = "com.breadwallet.walletqueue"
static let rvnCurrencyCode = "ACM"
static let null = "(null)"
static let maxMemoLength = 250
static let feedbackEmail = "<EMAIL>"
static let iosEmail = "<EMAIL>"
static let reviewLink = "https://itunes.apple.com/us/app/rvn-wallet/id1371751946?action=write-review"
static var standardPort: Int {
return E.isTestnet ? 18767 : 8767
}
static let feeCacheTimeout: TimeInterval = C.secondsInDay*3
static let bCashForkBlockHeight: UInt32 = E.isTestnet ? 1155876 : 478559
static let bCashForkTimeStamp: TimeInterval = E.isTestnet ? (1501597117 - NSTimeIntervalSince1970) : (1501568580 - NSTimeIntervalSince1970)
static let txUnconfirmedHeight = Int32.max
static var logFilePath: URL {
let cachesDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
return URL(fileURLWithPath: cachesDirectory).appendingPathComponent("log.txt")
}
}
<file_sep>/actiniumwallet/src/ViewControllers/AssetListTableView.swift
//
// AssetListTableView.swift
// actiniumwallet
//
// Created by <NAME> on 2017-12-04.
// Copyright © 2018 Actiniumwallet Team. All rights reserved.
//
import UIKit
class AssetListTableView: UITableViewController, Subscriber {
var didSelectCurrency: ((CurrencyDef) -> Void)?
var didTapSecurity: (() -> Void)?
var didTapSupport: (() -> Void)?
var didTapSettings: (() -> Void)?
// MARK: - Init
init() {
super.init(style: .grouped)
}
override func viewDidLoad() {
tableView.backgroundColor = .whiteBackground
tableView.register(HomeScreenCell.self, forCellReuseIdentifier: HomeScreenCell.cellIdentifier)
tableView.register(MenuCell.self, forCellReuseIdentifier: MenuCell.cellIdentifier)
tableView.separatorStyle = .none
tableView.reloadData()
Store.subscribe(self, selector: {
var result = false
let oldState = $0
let newState = $1
$0.currencies.forEach { currency in
if oldState[currency].balance != newState[currency].balance
|| oldState[currency].currentRate?.rate != newState[currency].currentRate?.rate
|| oldState[currency].maxDigits != newState[currency].maxDigits {
result = true
}
}
return result
}, callback: { _ in
self.tableView.reloadData()
})
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.visibleCells.forEach {
if let cell = $0 as? HomeScreenCell {
cell.refreshAnimations()
}
}
}
func reload() {
tableView.reloadData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Data Source
enum Section: Int {
case assets
case menu
}
enum Menu: Int {
case settings
case security
case support
var content: (String, UIImage) {
switch self {
case .settings:
return (S.MenuButton.settings, #imageLiteral(resourceName: "Settings"))
case .security:
return (S.MenuButton.security, #imageLiteral(resourceName: "Shield"))
case .support:
return (S.MenuButton.support, #imageLiteral(resourceName: "Faq"))
}
}
static let allItems: [Menu] = [.settings, .security, .support]
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let section = Section(rawValue: section) else { return 0 }
switch section {
case .assets:
return Store.state.wallets.count
case .menu:
return Menu.allItems.count
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let section = Section(rawValue: indexPath.section) else { return 0 }
switch section {
case .assets:
return 85.0
case .menu:
return 53.0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let section = Section(rawValue: indexPath.section) else { return UITableViewCell() }
switch section {
case .assets:
let currency = Store.state.currencies[indexPath.row]
let viewModel = AssetListViewModel(currency: currency)
let cell = tableView.dequeueReusableCell(withIdentifier: HomeScreenCell.cellIdentifier, for: indexPath) as! HomeScreenCell
cell.set(viewModel: viewModel)
return cell
case .menu:
let cell = tableView.dequeueReusableCell(withIdentifier: MenuCell.cellIdentifier, for: indexPath) as! MenuCell
guard let item = Menu(rawValue: indexPath.row) else { return cell }
let content = item.content
cell.set(title: content.0, icon: content.1)
return cell
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let section = Section(rawValue: section) else { return nil }
switch section {
case .assets:
return S.HomeScreen.portfolio
case .menu:
return S.HomeScreen.admin
}
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let header = view as? UITableViewHeaderFooterView,
let label = header.textLabel else { return }
label.text = label.text?.capitalized
label.textColor = .mediumGray
label.font = .customBody(size: 12.0)
header.tintColor = tableView.backgroundColor
}
// MARK: - Delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let section = Section(rawValue: indexPath.section) else { return }
switch section {
case .assets:
didSelectCurrency?(Store.state.currencies[indexPath.row])
case .menu:
guard let item = Menu(rawValue: indexPath.row) else { return }
switch item {
case .settings:
didTapSettings?()
case .security:
didTapSecurity?()
case .support:
didTapSupport?()
}
}
}
}
<file_sep>/actiniumwallet/src/Extensions/UIColor+BRWAdditions.swift
//
// UIColor+BRWAdditions.swift
// actiniumwallet
//
// Created by <NAME> on 2016-10-21.
// Copyright © 2018 Actiniumwallet Team. All rights reserved.
//
import UIKit
extension UIColor {
// MARK: Buttons
static var primaryButton: UIColor {
return UIColor(red:46/255.0, green:62/255.0, blue:128/255.0, alpha:1.0)
}
static var primaryText: UIColor {
return .white
}
static var tertiaryButton: UIColor {
return UIColor(red: 241.0/255.0, green: 103.0/255.0, blue: 38.0/255.0, alpha: 1.0)
}
static var secondaryButton: UIColor {
return UIColor(red: 86.0/255.0, green: 103.0/255.0, blue: 165.0/255.0, alpha: 1.0)
}
static var secondaryBorder: UIColor {
return UIColor(red: 241.0/255.0, green: 103.0/255.0, blue: 38.0/255.0, alpha: 1.0)
}
static var tertiaryBorder: UIColor {
return UIColor(red: 241.0/255.0, green: 103.0/255.0, blue: 38.0/255.0, alpha: 1.0)
}
static var darkText: UIColor {
return UIColor(red: 35.0/255.0, green: 37.0/255.0, blue: 38.0/255.0, alpha: 1.0)
}
static var darkLine: UIColor {
return UIColor(red: 36.0/255.0, green: 35.0/255.0, blue: 38.0/255.0, alpha: 1.0)
}
static var secondaryShadow: UIColor {
return UIColor(red: 213.0/255.0, green: 218.0/255.0, blue: 224.0/255.0, alpha: 1.0)
}
// MARK: Gradient
static var gradientStart: UIColor {
return UIColor(red:0/255.0, green:10/255.0, blue:69/255.0, alpha:1.0)
}
static var gradientEnd: UIColor {
return UIColor(red:46/255.0, green:62/255.0, blue:128/255.0, alpha:1.0)
}
static var offWhite: UIColor {
return UIColor(white: 247.0/255.0, alpha: 1.0)
}
static var borderGray: UIColor {
return UIColor(white: 221.0/255.0, alpha: 1.0)
}
static var separatorGray: UIColor {
return UIColor(white: 221.0/255.0, alpha: 1.0)
}
static var grayText: UIColor {
return UIColor(white: 136.0/255.0, alpha: 1.0)
}
static var grayTextTint: UIColor {
return UIColor(red: 163.0/255.0, green: 168.0/255.0, blue: 173.0/255.0, alpha: 1.0)
}
static var secondaryGrayText: UIColor {
return UIColor(red: 101.0/255.0, green: 105.0/255.0, blue: 110.0/255.0, alpha: 1.0)
}
static var grayBackgroundTint: UIColor {
return UIColor(red: 250.0/255.0, green: 251.0/255.0, blue: 252.0/255.0, alpha: 1.0)
}
static var cameraGuidePositive: UIColor {
return UIColor(red: 72.0/255.0, green: 240.0/255.0, blue: 184.0/255.0, alpha: 1.0)
}
static var cameraGuideNegative: UIColor {
return UIColor(red: 240.0/255.0, green: 74.0/255.0, blue: 93.0/255.0, alpha: 1.0)
}
static var purple: UIColor {
return UIColor(red: 74.0/255.0, green: 29.0/255.0, blue: 92.0/255.0, alpha: 1.0)
}
static var darkPurple: UIColor {
return UIColor(red: 127.0/255.0, green: 83.0/255.0, blue: 230.0/255.0, alpha: 1.0)
}
static var pink: UIColor {
return UIColor(red: 252.0/255.0, green: 83.0/255.0, blue: 148.0/255.0, alpha: 1.0)
}
static var blue: UIColor {
return UIColor(red: 46.0/255.0, green: 62.0/255.0, blue: 128.0/255.0, alpha: 1.0)
}
static var webBlue: UIColor {
return UIColor(red: 40.0/255.0, green: 54.0/255.0, blue: 116.0/255.0, alpha: 1.0)
}
static var whiteTint: UIColor {
return UIColor(red: 245.0/255.0, green: 247.0/255.0, blue: 250.0/255.0, alpha: 1.0)
}
static var transparentWhite: UIColor {
return UIColor(white: 1.0, alpha: 0.3)
}
static var transparentWhiteText: UIColor {
return UIColor(white: 1.0, alpha: 0.7)
}
static var disabledWhiteText: UIColor {
return UIColor(white: 1.0, alpha: 0.5)
}
static var transparentBlack: UIColor {
return UIColor(white: 0.0, alpha: 0.3)
}
static var blueGradientStart: UIColor {
return UIColor(red: 99.0/255.0, green: 188.0/255.0, blue: 255.0/255.0, alpha: 1.0)
}
static var blueGradientEnd: UIColor {
return UIColor(red: 56.0/255.0, green: 141.0/255.0, blue: 252.0/255.0, alpha: 1.0)
}
static var orangeGradientStart: UIColor {
return UIColor(red: 241.0/255.0, green: 91.0/255.0, blue: 35.0/255.0, alpha: 1.0)
}
static var orangeGradientEnd: UIColor {
return UIColor(red: 246.0/255.0, green: 135.0/255.0, blue: 47.0/255.0, alpha: 1.0)
}
static var txListGreen: UIColor {
return UIColor(red: 23.0/255.0, green: 175.0/255.0, blue: 99.0/255.0, alpha: 1.0)
}
static var blueButtonText: UIColor {
return UIColor(red: 127.0/255.0, green: 181.0/255.0, blue: 255.0/255.0, alpha: 1.0)
}
static var darkGray: UIColor {
return UIColor(red: 84.0/255.0, green: 104.0/255.0, blue: 117.0/255.0, alpha: 1.0)
}
static var lightGray: UIColor {
return UIColor(red: 179.0/255.0, green: 192.0/255.0, blue: 200.0/255.0, alpha: 1.0)
}
static var mediumGray: UIColor {
return UIColor(red: 120.0/255.0, green: 143.0/255.0, blue: 158.0/255.0, alpha: 1.0)
}
static var receivedGreen: UIColor {
return UIColor(red: 23.0/255.0, green: 175.0/255.0, blue: 99.0/255.0, alpha: 1.0)
}
static var sentRed: UIColor {
return UIColor(red: 208.0/255.0, green: 10.0/255.0, blue: 10.0/255.0, alpha:1.0)
}
static var statusIndicatorActive: UIColor {
return UIColor(red: 75.0/255.0, green: 119.0/255.0, blue: 243.0/255.0, alpha: 1.0)
}
static var grayBackground: UIColor {
return UIColor(red: 224.0/255.0, green: 229.0/255.0, blue: 232.0/255.0, alpha: 1.0)
}
static var whiteBackground: UIColor {
return UIColor(red: 249.0/255.0, green: 251.0/255.0, blue: 254.0/255.0, alpha: 1.0)
}
static var separator: UIColor {
return UIColor(red: 236.0/255.0, green: 236.0/255.0, blue: 236.0/255.0, alpha: 1.0)
}
}
|
2005b06dbf03c178e6f9ec9ff790f494ad233b2c
|
[
"Swift",
"C",
"Markdown"
] | 11 |
Swift
|
fangtoby/breadwallet-actinium-ios
|
a2424aef53ac930d7a776ff7ac87a203ff9ebe05
|
ca09d518c809c693f85405202697973f3a2910a8
|
refs/heads/master
|
<file_sep>package mainApplication;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.print.attribute.standard.PresentationDirection;
public class TestMain {
public static void main(String[] args) {
Customer c1= new Customer("anil", 3000.05f , "M", "pune");
Customer c2= new Customer("akash", 4000.05f , "M", "mumbai");
Customer c3= new Customer("anita", 6000.05f , "F", "pune");
Customer c4= new Customer("rajiv", 8000.05f , "M", "pune");
Customer c5= new Customer("kavita", 10000.05f , "F", "banglor");
List< Customer> customerList= new ArrayList<Customer>();
customerList.add(c1);
customerList.add(c2);
customerList.add(c3);
customerList.add(c4);
customerList.add(c5);
System.out.println("customer List");
System.out.println(customerList.toString());
//here we pass customer as argument in lamada expression
//in body we check the condition and return boolean value
//filter all the employee whose salary is grater then 5000
//we cannot return any other then boolean value because method
//of predicate functional interface always return boolean value
Predicate<Customer> filterConditionForSalary= (Customer c) -> c.getCustSalary().floatValue()>=5000;
List<Customer> custsalaryGraterThen5000= customerList.stream().filter(filterConditionForSalary).collect(Collectors.toList());
List<Customer> custsalaryGraterThen50000= customerList.stream().filter(x -> x.getCustSalary().floatValue()>=5000).collect(Collectors.toList());
System.out.println("\n customer whose salary grater then 5000");
System.out.println(custsalaryGraterThen5000.toString());
//filter those customer living in pune
Predicate<Customer> filterConditionForCity= (Customer c) -> c.getCity().equalsIgnoreCase("PUNE");
List<Customer> custlivingInPune= customerList.stream().filter(filterConditionForCity).collect(Collectors.toList());
System.out.println("\n customer those living in pune");
System.out.println(custlivingInPune.toString());
//filter those customer who are living in pune and salary grater then 5000
//here we use AND because both the condition should strictly compulsory satisfied
// both the condition are true then and then only the AND opreation return true.
Predicate<Customer> filterConditionForCityAndSalary=filterConditionForSalary.and(filterConditionForCity);
List<Customer> custlivingInPuneAndsalaryGraterThen5000= customerList.stream().filter(filterConditionForCityAndSalary).collect(Collectors.toList());
System.out.println("\n customer those living in pune AND salary grater then 5000");
System.out.println(custlivingInPuneAndsalaryGraterThen5000.toString());
//similarly like AND there is OR condition
//filter those customer who are living in pune or salary grater then 5000
//here filter those record if either of condition is satisfied
Predicate<Customer> filterConditionForCityOrSalary=filterConditionForSalary.or(filterConditionForCity);
List<Customer> custlivingInPuneOrsalaryGraterThen5000= customerList.stream().filter(filterConditionForCityOrSalary).collect(Collectors.toList());
System.out.println("\n customer those living in pune or salary grater then 5000");
System.out.println(custlivingInPuneOrsalaryGraterThen5000.toString());
//this also provide NEGATION condition
//filter those customer living in pune
Predicate<Customer> customerNotLivingInPune= (Customer c) -> c.getCity().equalsIgnoreCase("PUNE");
customerNotLivingInPune=customerNotLivingInPune.negate();
List<Customer> customerNotLivingInPuneList= customerList.stream().filter(customerNotLivingInPune).collect(Collectors.toList());
System.out.println("\n customer those not living in pune");
System.out.println(customerNotLivingInPuneList.toString());
//------------------------------------------------------------------------------------
Predicate<String> string= x -> x.equals("sunil");
System.out.println(string.test("anil"));
//--------------------------------------------------------------------------------------------
UserFunctionI username = new UserFunctionI() {
@Override
public String extractFirstNmae(String fullName) {
String[] names = fullName.split("-");
return names[0];
}
};
String firstnmae = username.extractFirstNmae("anil-kumar");
System.out.println(firstnmae);
//----------------------------------------------------------------------------------------
UserFunctionI usernam = fullName -> {
String[] names = fullName.split("-");
return names[0];
};
String user = usernam.extractFirstNmae("sunil-kumar");
System.out.println(user);
//--------------------------------------------------------------
String[] namesArray = new String[] { "anil-kumar", "sunil/kumar", "anil-singh" };
List<String> names = Arrays.asList(namesArray);
List<String> rsult = names.stream().filter(x -> {
if (x.contains("-")) {
return true;
}
return false;
}).collect(Collectors.toList());
System.out.println(rsult);
}
String[] namesArray = new String[] { "anil-kumar", "sunil-kumar", "pankaj-singh" };
ArrayList<String> names = new ArrayList<String>();
public String checkUserName(Predicate<String> name) {
return null;
}
}
<file_sep>package mainApplication;
import java.util.function.Predicate;
public interface PredicateDemo {
boolean findUser(String string);
}
<file_sep>package mainApplication;
public class Customer {
private String custNmae;
private Float custSalary;
private String gender;
private String city;
public Customer(String custNmae, Float custSalary, String gender, String city) {
super();
this.custNmae = custNmae;
this.custSalary = custSalary;
this.gender = gender;
this.city = city;
}
public String getCustNmae() {
return custNmae;
}
public void setCustNmae(String custNmae) {
this.custNmae = custNmae;
}
public Float getCustSalary() {
return custSalary;
}
public void setCustSalary(Float custSalary) {
this.custSalary = custSalary;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "[custNmae=" + custNmae + ", custSalary=" + custSalary + ", gender=" + gender + ", city=" + city
+ "]";
}
}
<file_sep>package mainApplication.mapMethod;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import mainApplication.Employee;
public class EntrySetDemo {
public static void main(String[] args) {
//employee
Employee e1 = new Employee(1, "anil", 5000.0f, "M", "PUNE");
Employee e2 = new Employee(4, "sunil", 8000.0f, "F", "PUNE");
// creatre map for employes
Map<Integer, Employee> mapOfEmployee = new HashMap<Integer, Employee>();
System.out.println("empty map is created");
System.out.println(mapOfEmployee);
System.out.println("\n add new entry in the map");
System.out.println("entry :- "+ e1);
System.out.println("entry :- "+ e2);
mapOfEmployee.put(e1.getEmpId(), e1);
mapOfEmployee.put(e2.getEmpId(), e2);
Set<Entry<Integer, Employee>>entryset=mapOfEmployee.entrySet();
System.out.println(entryset);
System.out.println("iterating entry ");
System.out.println("-----------------------------------BEFORE java 8----------------------------------------------------------");
System.out.println("iterating through iterator method ");
Iterator<Entry<Integer,Employee>> iterator=entryset.iterator();
while(iterator.hasNext()) {
Entry<Integer,Employee> entry=iterator.next();
System.out.println("KEY :- "+entry.getKey() + " VALUE :- "+ entry.getValue());
}
System.out.println("-------------------------------------java 8----------------------------------------------------------");
System.out.println("iterating through forEach loop");
for(Entry<Integer, Employee> entry2 : entryset) {
System.out.println("KEY :- "+entry2.getKey() + " VALUE :- "+ entry2.getValue());
}
System.out.println("\niterating through forEach default method");
entryset.forEach(entry -> {
System.out.println("KEY :- "+entry.getKey() + " VALUE :- "+ entry.getValue());
});
}
/*
empty map is created
{}
add new entry in the map
entry :- [empId=1, empNmae=anil, empSalary=5000.0, empgender=M, empcity=PUNE]
entry :- [empId=4, empNmae=sunil, empSalary=8000.0, empgender=F, empcity=PUNE]
[1=[empId=1, empNmae=anil, empSalary=5000.0, empgender=M, empcity=PUNE], 4=[empId=4, empNmae=sunil, empSalary=8000.0, empgender=F, empcity=PUNE]]
iterating entry
-----------------------------------BEFORE java 8----------------------------------------------------------
iterating through iterator method
KEY :- 1 VALUE :- [empId=1, empNmae=anil, empSalary=5000.0, empgender=M, empcity=PUNE]
KEY :- 4 VALUE :- [empId=4, empNmae=sunil, empSalary=8000.0, empgender=F, empcity=PUNE]
-------------------------------------java 8----------------------------------------------------------
iterating through forEach loop
KEY :- 1 VALUE :- [empId=1, empNmae=anil, empSalary=5000.0, empgender=M, empcity=PUNE]
KEY :- 4 VALUE :- [empId=4, empNmae=sunil, empSalary=8000.0, empgender=F, empcity=PUNE]
iterating through forEach default method
KEY :- 1 VALUE :- [empId=1, empNmae=anil, empSalary=5000.0, empgender=M, empcity=PUNE]
KEY :- 4 VALUE :- [empId=4, empNmae=sunil, empSalary=8000.0, empgender=F, empcity=PUNE]
*/
}
<file_sep>package mainApplication.mapMethod;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import mainApplication.Employee;
public class ValuesDemo {
public static void main(String[] args) {
Employee e1 = new Employee(1, "anil", 5000.0f, "M", "PUNE");
Employee e2 = new Employee(4, "sunil", 8000.0f, "M", "PUNE");
Employee e3 = new Employee(5, "anita", 7000.0f, "F", "MUMBAI");
// creatre map of employee
Map<Integer, Employee> mapOfEmployee = new HashMap<Integer, Employee>();
mapOfEmployee.put(e1.getEmpId(), e1);
mapOfEmployee.put(e2.getEmpId(), e2);
mapOfEmployee.put(e2.getEmpId(), e3);
System.out.println(mapOfEmployee);
System.out.println("\nGIVEN 1 :-map of employee is provided and map is not empty, ");
System.out.println("REQUIREMENT 1 :- only wants the list of values");
Collection<Employee> values =mapOfEmployee.values();
System.out.println("list of value :-");
System.out.println(values);
System.out.println("\n GIVEN 2:-if map is empty ");
System.out.println("REQUIREMENT 1 :- only wants the list of values");
mapOfEmployee = new HashMap<Integer, Employee>();
Collection<Employee> valuesforEmptyMap = mapOfEmployee.values();
System.out.println("list of value :-");
System.out.println(valuesforEmptyMap);
//{1=[empId=1, empNmae=anil, empSalary=5000.0, empgender=M, empcity=PUNE], 4=[empId=5, empNmae=anita, empSalary=7000.0, empgender=F, empcity=MUMBAI]}
//GIVEN 1 :-map of employee is provided and map is not empty,
//REQUIREMENT 1 :- only wants the list of values
//list of value :-
//[[empId=1, empNmae=anil, empSalary=5000.0, empgender=M, empcity=PUNE], [empId=5, empNmae=anita, empSalary=7000.0, empgender=F, empcity=MUMBAI]]
//GIVEN 2:-if map is empty
//REQUIREMENT 1 :- only wants the list of values
//list of value :-
//[]
}
}
<file_sep>package mainApplication.mapMethod;
import java.util.HashMap;
import java.util.Map;
import mainApplication.Employee;
public class computeDemo {
public static void main(String[] args) {
Employee e1 = new Employee(1, "anil", 5000.0f, "M", "PUNE");
Employee e2 = new Employee(4, "sunil", 8000.0f, "F", "PUNE");
// creatre map of employee
Map<Integer, Employee> mapOfEmployee = new HashMap<Integer, Employee>();
mapOfEmployee.put(e1.getEmpId(), e1);
mapOfEmployee.put(e2.getEmpId(), e2);
System.out.println(mapOfEmployee);
mapOfEmployee.compute(4, (key, val) -> {
Float newSalary = val.getEmpSalary().floatValue() + 9999.9f;
val.setEmpSalary(newSalary);
return val;
});
System.out.println("\n CASE 1:- employe id 4 is present and its salary is incremented by 9999.9");
System.out.println(mapOfEmployee);
// {1=[empId=1, empNmae=anil, empSalary=5000.0, empgender=M, empcity=PUNE],
// 4=[empId=4, empNmae=sunil, empSalary=8000.0, empgender=F, empcity=PUNE]}
// {1=[empId=1, empNmae=anil, empSalary=5000.0, empgender=M, empcity=PUNE],
// 4=[empId=4, empNmae=sunil, empSalary=17999.9, empgender=F, empcity=PUNE]}
// CASE 2:- if key not found then it throw null pointer exception
try {
mapOfEmployee.compute(3, (key, val) -> {
Float newSalary = val.getEmpSalary().floatValue() + 9999.9f;
val.setEmpSalary(newSalary);
return val;
});
System.out.println(mapOfEmployee);
} catch (Exception e) {
System.out.println("\n CASE 2:- employe id 3 is not present that why it throw NullpointerException");
e.printStackTrace();
/*
* Exception in thread "main" java.lang.NullPointerException at
* mainApplication.mapMethod.computeDemo.lambda$1(computeDemo.java:37) at
* java.util.HashMap.compute(Unknown Source) at
* mainApplication.mapMethod.computeDemo.main(computeDemo.java:36)
*/
}
// CASE 3:- if key is null it throw null pointer exception
try {
mapOfEmployee.compute(null, (key, val) -> {
Float newSalary = val.getEmpSalary().floatValue() + 9999.9f;
val.setEmpSalary(newSalary);
return val;
});
} catch (Exception e) {
System.out.println("\n CASE 3:- employe id passing null as argument that why it throw NullpointerException");
e.printStackTrace();
/*
* Exception in thread "main" java.lang.NullPointerException at
* mainApplication.mapMethod.computeDemo.lambda$1(computeDemo.java:37) at
* java.util.HashMap.compute(Unknown Source) at
* mainApplication.mapMethod.computeDemo.main(computeDemo.java:36)
*/
}
// CASE 4:- return value is null for key which is present in the map ,it will
// remove that key value pair from table
mapOfEmployee.compute(4, (key, val) -> {
Float newSalary = val.getEmpSalary().floatValue() + 9999.9f;
val.setEmpSalary(newSalary);
return null;
});
System.out.println("\n CASE 4:- employe id 4 is present but in return we send null that why it delete key value pair from map");
System.out.println(mapOfEmployee);
}
}
<file_sep>package mainApplication.mapMethod;
import java.util.HashMap;
import java.util.Map;
import mainApplication.Employee;
public class ContainsKeyDemo {
public static void main(String[] args) {
Employee e1 = new Employee(1, "anil", 5000.0f, "M", "PUNE");
Employee e2 = new Employee(4, "sunil", 8000.0f, "F", "PUNE");
// creatre map of employee
Map<Integer, Employee> mapOfEmployee = new HashMap<Integer, Employee>();
mapOfEmployee.put(e1.getEmpId(), e1);
mapOfEmployee.put(e2.getEmpId(), e2);
mapOfEmployee.put(5, null);
mapOfEmployee.put(null, null);
System.out.println(mapOfEmployee);
System.out.println("\n CASE:- 1 \n given:- key is present and it is associated with a value \n check if specifid key is present in the map or not return true if present");
System.out.println("KEY :- "+ e2.getEmpId());
System.out.println(mapOfEmployee.containsKey(e2.getEmpId()));
System.out.println("\n CASE:- 2 \n given :- key is present and it is accociated with null value, \n check if specifid key is present in the map or not return true if present");
System.out.println("KEY :- "+ "5");
System.out.println(mapOfEmployee.containsKey(5));
System.out.println("\n CASE:- 2 \n given :- key is not present \n check if specifid key is present in the map or not return true if present");
System.out.println("KEY :- "+ "9");
System.out.println(mapOfEmployee.containsKey(9));
System.out.println("\n CASE:- 2 \n given :- null as key is present \n check if specifid key is present in the map or not return true if present");
System.out.println("KEY :- "+ "null");
System.out.println(mapOfEmployee.containsKey(null));
}
}
|
11b92aa40a10f1804d8f52aad82a18262d201af7
|
[
"Java"
] | 7 |
Java
|
nilesh44/MapDemo
|
a7e413652501854d442e5227b0d684eda4f6d20d
|
593a2bbb75cb6fc3a07506065abbaf2fd6e11e30
|
refs/heads/master
|
<file_sep># Obstacles to Studying Alternative Splicing Using scRNA-seq
The purpose of this repository is to document the bioinformatics experiments in the preprint/publication with this name. The the main figures in this publication can be reproduced by cloning this repository and executing
```
./wrapper.sh
```
You will need a working installation of Julia, version 1.1.1. You will also need to install the Julia packages used in this code base.
This code base is released under the MIT license.
<file_sep>#!/bin/bash
input="scnorm_file_list.txt"
while IFS= read -r line
do
output=`echo $line | awk -F\/ '{print $NF}' | awk -F_ '{print $1"_"$2".png"}'`
$HOME/julia-1.1.1/bin/julia src/run_iPredict.jl --mode global --countsMatrix $line --GeneIsoformRelationships ../iPredict_data/gencode_human_gene_isoform_relationships.txt --NumSimulations 10 --output $output
mv $output ../Obstacles_figs/fig2/$output
mv "log_"$output ../Obstacles_figs/fig2/"log_"$output
mv expression_distribution.png ../Obstacles_figs/fig2/$output"_mean_expression.png"
mv pDropout_distribution.png ../Obstacles_figs/fig2/$output"_pdropout.png"
done < "$input"
<file_sep>#This script will remake the figures from the publication
#Note that the order of the figures changed several times during drafting
#so don't pay too much attention to the names of the output pngs.
tar -xvzf data.tar.gz
mkdir figures/figure1
mkdir figures/figure1_data
mkdir figures/figure2
mkdir figures/figure2_data
mkdir figures/figure3
mkdir figures/figure3_data
mkdir figures/figure4
mkdir figures/figure4_data
mkdir figures/figure5
mkdir figures/figure5_data
mkdir figures/figure6
mkdir figures/figure6_data
julia figure1_julia_script.jl
julia figure2_julia_script.jl
julia figure3_julia_script.jl
julia figure4_julia_script.jl
julia figure5_julia_script.jl
julia figure6_julia_script.jl
julia iPredict.jl/src/pDropouts.jl
<file_sep>#!/bin/bash
$HOME/julia-1.1.1/bin/julia iPredict.jl/src/pDropouts.jl
|
a3f85939bc17ed5ff1c3de2d1ae7389c9232405b
|
[
"Markdown",
"Shell"
] | 4 |
Markdown
|
jenni-westoby/Obstacles
|
d7e850fd64acb16f6ed872186989352a33e996c8
|
157ad85420a27a87755845f4f67f30886f1d2514
|
refs/heads/master
|
<repo_name>itMovieKing/vueproject<file_sep>/reacttest/app/test1/login.js
import React,{Component} from "react";
export default class Login extends Component{
constructor(props){
super(props);
this.state={
text:","
}
}
change=(e)=>{
console.log(e.target.value);
this.setState({
text:e.target.value
})
}
submit=(e)=>{
e.preventDefault();
console.log(this.state.text);
return this.state.text;
}
render(){
return (
<form>
<input onChange={this.change}/>
<button onClick={this.submit}>登录</button>
</form>
)
}
}
<file_sep>/reacttest/webpack.config.js
var path=require("path");
module.exports={
entry:"./app/test1/test.js",
output:{
path:path.resolve(__dirname,"./"),
filename:"test.js"
},
mode : "development",
module:{
rules:[
{
test:/\.js$/,
exclude:/node-modules/,
loader:"babel-loader",
query:{
presets:[
'es2015','stage-0','react'
]}
},
{
test:/\.css$/,
exclude:/node-modules/,
loader:'style-loader!css-loader'
},
{
test:/\.jsx$/,
exclude:/node-modules/,
loader:"babel-loader",
query:{
presets:['es2015','stage-0','react']
}
},
{
test:/\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader:"url-loader?limit=8129&name=img/[name].[hash:8].[ext]"
}
]
}
},
plugin={
$:"jquery",
jQuery:"jquery",
"window.jQuery":"jquery"
}
<file_sep>/myvue/vueproject/src/vuex/store.js
import Vuex from 'vuex'
import Vue from 'vue'
import $http from 'axios'
Vue.use(Vuex)
// var arr=$http.get('/static/index.js').then(res=>{
// // console.log(res.data)
// return res
// })
// console.log(arr)
var arr
$http({
method:'get',
url:'/static/index.js'
}).then(res=>{
arr=res.data
})
const store=new Vuex.Store({
state:{
name:'lily',
age:50,
obj:arr
},
mutations:{
showName(state,name){
state.name=name
}
}
})
export default store
|
7c24d749ef7dcaf0ffd1e008db269485a77a2953
|
[
"JavaScript"
] | 3 |
JavaScript
|
itMovieKing/vueproject
|
bca3ce01c90f7d00c59b744ba6959f16d4793104
|
e25d0cc61e6ad9c5d3628ecd3d147ab4f447fcb6
|
refs/heads/master
|
<repo_name>fany/MinD-Mail-Spamfilter<file_sep>/bin/spam-triage
#!/bin/bash -e
readonly prefix=/var/qmail/quarantine/
for mail in "$prefix/pending/"*; do
tmpmbox=$(mktemp)
spam-quarantine2mbox "$mail" >"$tmpmbox"
mutt -f "$tmpmbox"
rm "$tmpmbox"
while :; do
echo -n '(H)am oder (S)pam? '
read decision
case "$decision" in
H|h)
mv "$mail" "$prefix/ham/"
break
;;
S|s)
sender=$(sed -n '/^SENDER=/s/^SENDER=//p' "$mail" | tr [:upper:] [:lower:] | head -1)
spamdir="$prefix/spam/$sender"
if ! test -d "$spamdir"; then
mkdir -m 1700 "$spamdir"
chown vpopmail: "$spamdir"
fi
mv "$mail" "$spamdir/"
break
;;
esac
done
done
<file_sep>/bin/strip_quarantined_mail
#!/bin/bash
# Gibt den Mail-Quelltext aus einer Quarantäne-Datei aus.
exec sed '0,/^----$/d' "$@"
|
d9dd2835797513504681c6cbb84ca02dc8c09993
|
[
"Shell"
] | 2 |
Shell
|
fany/MinD-Mail-Spamfilter
|
9f5ebf7de485d58ca9721a7d71b53e56cd405231
|
268e9ccac99b089a3ffb154abd539261514326d8
|
refs/heads/master
|
<repo_name>marcelomaiajuvencio/AssinaturaDigital-DSA<file_sep>/README.md
# AssinaturaDigital-DSA
Hello World de assinatura digital com DSA.<br>
Mostra como gerar chaves privada, pública e a assinatura usando DSA.<br>
Mostra como converter as chaves privada e pública em bytes. Essa conversão é necessária para gravar as chaves, por exemplo, em um banco de dados.<br>
Mostra como recuperar as chaves privada e pública a partir dos bytes lidos, por exemplo, de um banco de dados.
Fontes: <br>
https://www.devmedia.com.br/como-criar-uma-assinatura-digital-em-java/31287<br>
https://tassioauad.com/2015/04/13/java-como-armazenar-as-chaves-de-uma-criptografia-assimetrica/
<file_sep>/src/RemetenteAssiDig.java
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RemetenteAssiDig {
private PublicKey pubKey;
private PublicKey publicKey;
private byte[] publicKeyBytes;
public PublicKey getPubKey() {
return pubKey;
}
public PublicKey getPubKey2() {
return publicKey;
}
public void setPubKey(PublicKey pubKey) {
this.pubKey = pubKey;
}
public PublicKey getPubKeyByte() {
return pubKey;
}
public byte[] geraAssinatura(String mensagem) throws NoSuchAlgorithmException,
InvalidKeyException, SignatureException, InvalidKeySpecException {
Signature sig = Signature.getInstance("DSA");
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
// Geração das chaves púlicas e privadas
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
SecureRandom secRan = new SecureRandom();
kpg.initialize(512, secRan);
KeyPair keyP = kpg.generateKeyPair();
// Gera chave pública
this.pubKey = keyP.getPublic();
// Converte chave pública em bytes (para gravar na base, por exemplo)
this.publicKeyBytes = this.pubKey.getEncoded();
// Recupera chave pública (da base, por exemplo)
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
this.publicKey = keyFactory.generatePublic(publicKeySpec);
// Gera chave privada
PrivateKey priKey = keyP.getPrivate();
// Converte chave privada em bytes (para gravar na base, por exemplo)
byte[] privateKeyBytes = priKey.getEncoded();
// Recupera chave privada (da base, por exemplo)
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
//Inicializando Obj Signature com a Chave Privada
//sig.initSign(priKey);
sig.initSign(privateKey);
//Gerar assinatura
sig.update(mensagem.getBytes());
byte[] assinatura = sig.sign();
return assinatura;
}
}
|
3d5833656c8aa645cb94a14f0a8a580268f37d8b
|
[
"Markdown",
"Java"
] | 2 |
Markdown
|
marcelomaiajuvencio/AssinaturaDigital-DSA
|
8482b845f140f293e72a7b663932ddc70e5cd445
|
691296735d9a6b64b0d9988859163a4bcebf1251
|
refs/heads/master
|
<repo_name>ari165/notgoodcalculator<file_sep>/README.md
# notgoodcalculator
a calculator that supports (/ * - +) up to 100
<file_sep>/generator.py
version = "1.0"
max_num = 100 # change this number to change the max number (a friendly note: DONT GO HIGHER THAN 500 the generator
# can handle it but you will need very powerful hardware to open the calculator file even with notepad
# and 500 is 82.1MB already and 1000 is 327.57MB and 2000 is 1.35GB and you will need 8gb of ram to open 1000)
# pre work
file = open('calculator.py', "w+")
file.write(f"print('jk calculator \\n"
f"the max number for both is {max_num}')\n"
f"print('version: {version}') \n"
"num1 = int(input('num1: '))\n"
"opr = input('operation[- + * /]: ')\n"
"num2 = int(input('num2: '))\n")
max_num += 1
# +
for i in range(max_num):
for j in range(max_num):
file.write(f"if num1 == {i} and opr == '+' and num2 == {j}:\n"
f" print('{i} + {j} = {i + j}')\n")
# -
for i in range(max_num):
for j in range(max_num):
file.write(f"if num1 == {i} and opr == '-'and num2 == {j}:\n"
f" print('{i} - {j} = {i - j}')\n")
# *
for i in range(max_num):
for j in range(max_num):
file.write(f"if num1 == {i} and opr == '*' and num2 == {j}:\n"
f" print('{i} * {j} = {i * j}')\n")
# /
for i in range(max_num):
for j in range(max_num):
if j == 0:
file.write(f"if num1 == {i} and opr == '/' and num2 == {j}:\n"
f" print('cant divide by zero')\n")
else:
file.write(f"if num1 == {i} and opr == '/' and num2 == {j}:\n"
f" print('{i} / {j} = {i / j}')\n")
|
f87591ed671713e39a3fd9f5191825d7036ccd32
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
ari165/notgoodcalculator
|
1c2d73bbbd8ec36672228a55781c33dd09e5a1ac
|
7a2021e0d40a7ae45837ad9b63b46741b41de4f9
|
refs/heads/main
|
<repo_name>logicalsingular/BankCardParse<file_sep>/BankCardParse.py
def parser(text):
for n in range(len(text)-15):
if text[n:n+16].isdigit():
return text[n:n+16]
elif text[n:n+4].isdigit() and text[n+5:n+5+4].isdigit() and text[n+10:n+10+4].isdigit() and text[n+15:n+15+4].isdigit():
if len(text[n:n+4])==4 and len(text[n+5:n+5+4])==4 and len(text[n+10:n+10+4])==4 and len(text[n+15:n+15+4])==4:
spaceless_text = text[n:n+19].replace(" ","")
if len(spaceless_text)==16:
return spaceless_text
return False<file_sep>/tests.py
from BankCardParse import parser
text_1 = "1134 1234 1234 1234"
text_2 = "Alex 12/12 1234123412341234"
text_3 = "Alex 12/12 12341234123412349"
text_4 = "Alex 01/21 1334 1234 1234 1234"
text_5 = "Alex 01/21 1434 1234 56785678"
print(parser(text_1))
print(parser(text_2))
print(parser(text_3))
print(parser(text_4))
print(parser(text_5))
|
33aa4bdde28fcc489e21c6e67d1e8d986e7e6ffb
|
[
"Python"
] | 2 |
Python
|
logicalsingular/BankCardParse
|
312f2a8a80dd5b91030230fe222b703de05b5b24
|
89cb2d6681d5e7e636498f990b26946062503d52
|
refs/heads/main
|
<file_sep># csvchrome
Dump all open chrome tabs to a CSV on OSX
<file_sep>import subprocess
import datetime
import csv
get_template = """osascript -e 'set text item delimiters to linefeed' -e 'tell app "google chrome" to {} of tabs of window {} as text'"""
def getUrls(windowId : int) -> str:
return get_template.format("url", windowId)
def getTitles(windowId : int) -> str:
return get_template.format("title", windowId)
def getWindow(windowId : int) -> [(str,str)]:
getproc = lambda s : subprocess.run(s, shell=True, check=True, stdout=subprocess.PIPE)
urlp = getproc(getUrls(windowId))
titlep = getproc(getTitles(windowId))
urls = urlp.stdout.decode("utf-8").splitlines()
titles = titlep.stdout.decode("utf-8").splitlines()
titles_urls = zip(titles,urls)
return list(map(lambda tu: [windowId] + list(tu), titles_urls))
def getAllWindows(maxWindow : int) -> [(str,str)]:
"""maxWindow is 1-indexed"""
allWindows = []
for widx in range(1, maxWindow + 1):
ws = getWindow(widx)
allWindows.extend(ws)
return allWindows
def windows2csv(fn, windows):
with open(fn, 'w',) as fh:
writer = csv.writer(fh, quoting=csv.QUOTE_MINIMAL)
writer.writerows(windows)
def countWindows() -> int:
chromeWindows = """osascript -e 'tell app "google chrome" to count of windows as text'"""
countp = subprocess.run(chromeWindows, shell=True, check=True, stdout=subprocess.PIPE)
counts = countp.stdout.decode("utf-8").strip()
return int(counts)
def savetabs():
num_windows = countWindows() #1-indexed
windows = getAllWindows(num_windows)
fn = "alltabs_{}.csv".format(datetime.datetime.now().date())
windows2csv(fn, windows)
if __name__ == "__main__":
savetabs()
|
89525caaa16473629086624ff3566ff1c112c684
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
mmaz/csvchrome
|
188033b201f277ac766b6144d47ada628551d14c
|
5c397ec8fd4d23c054058b86d341328cb59d081c
|
refs/heads/master
|
<repo_name>cpflores/sample_ajax<file_sep>/app/models/post.rb
class Post < ActiveRecord::Base
belongs_to :user
rails_admin do
configure :user do
label 'Owner of this post: '
end
end
end
|
749de53ef2e2b1f9acd70fc1af5762a48fd8af0c
|
[
"Ruby"
] | 1 |
Ruby
|
cpflores/sample_ajax
|
cb3ced8a304002d25643e5da3e45a21bb14431a6
|
b6945a93e17f4b59a9616667e2764f3ce6d2aa71
|
refs/heads/master
|
<file_sep>import base64
for record in records:
input_stream = record.value['fileRef'].getInputStream()
newRecord = sdcFunctions.createRecord(record.sourceId)
bytes = []
while (True):
cur_byte_in_int = input_stream.read()
if (cur_byte_in_int == -1):
break
bytes.append(cur_byte_in_int)
file_value = ''.join(map(chr, bytes))
file_value_base64 = base64.b64encode(file_value)
log.info(file_value)
log.info(file_value_base64)
filename = record.value['fileInfo']['filename']
full_file_path_list = record.value['fileInfo']['file'].split("/")
encoded_incident = full_file_path_list[len(full_file_path_list) - 2]
(incident_key, project_key) = base64.decodestring(encoded_incident).split(",")
sizeOfOriginalFile = record.value['fileInfo']['size']
log.info(filename)
newRecord.value = {'text' : file_value_base64 }
newRecord.attributes['filename'] = filename
newRecord.attributes['incidentKey'] = incident_key
newRecord.attributes['projectKey'] = project_key
output.write(newRecord)
input_stream.close()
<file_sep>import pytest
from sortedcollections import SortedList,SortedDict, SortedSet
A = 2
B = 5
Pr = [0.6,0.6, 0.6, 0.6,0.6]
G = []
PrG = []
Strats = []
def gen_all_group():
'''
generates G
:return:
'''
for i in range(0, A+1):
G.append(i)
print(G)
def gen_pr():
'''
generates PrG
:return:
'''
for g in G:
p = 1.0
for i in range(0,g):
p = p * Pr[i]
if (g < A):
#if g >= A means that all A's are correct
p = p* (1 - Pr[g])
PrG.append(p)
print(PrG)
def gen_all_strats():
for i in range(0, A+1):
Strats.append(i)
print(Strats)
def eval_all_strats():
min_steps = 100*B
for s in Strats:
steps = 0
for g in G:
steps += eval(s, g, PrG[g])
min_steps = min(min_steps, steps)
min_steps = min(min_steps, B+2)
print(min_steps)
def eval(s,g,pr):
nbs = s
err_loc = g
steps = 0
if (err_loc < A - nbs):
steps = 2 * nbs + B - A + 1 + B + 1
else:
steps = 2 * nbs + B - A + 1
return steps*pr
def test_all():
gen_all_group()
gen_pr()
gen_all_strats()
eval_all_strats()
def test_till_strats():
gen_all_group()
gen_pr()
gen_all_strats()
def test_eval():
eval(1, 0, 0.6)
sorted(l, k)
<file_sep>from functools import reduce
'''
'''
nodes = [0,1,2,3,4,5]
edges =[(0,1,16), (0,2,13), (1,3,12), (1,2, 4), (2,3,9), (2,4,14), (3,4,7), (3,5,20),(4,5,4)]
list_edges = []
aug_edges = []
flow = 0
def create_augmented_edgges(edges):
global aug_edges
for e in edges:
e1 = (e[0],e[1],e[2],0,0)
aug_edges.append(e1)
def create_edge_map():
for v in nodes:
list_edges.append([])
for i,e in zip(range(0,len(edges)),edges):
v1 = e[0]
v2 = e[1]
list_edges[v1].append(i)
list_edges[v2].append(i)
create_augmented_edgges(edges)
create_edge_map()
print(aug_edges)
print(list_edges)
def cal_flow():
global flow
while do_dfs(0,5) == 1:
flow += 1
print(flow)
def do_dfs(src = 0, dest= 5, visited = set()):
nbrs_edges = list_edges[src] #[[0, 1], [0, 2, 3], [1, 3, 4, 5], [2, 4, 6, 7], [5, 6, 8], [7, 8]]
appl_nbrs_edges = applicable_nbrs_edges(src, nbrs_edges) #[0,1,2]
acc = set()
for appl_nbrs_edge in appl_nbrs_edges:
acc.add(edges[appl_nbrs_edge][0])
acc.add(edges[appl_nbrs_edge][1])
acc.remove(src)
set_of_nbr_vertices = acc
set_of_nbr_vertices = set_of_nbr_vertices.difference(visited)
if dest in set_of_nbr_vertices:
return update_edges_passing_thru_node(appl_nbrs_edges, src, dest)
if len(set_of_nbr_vertices) == 0:
return 0
visited.add(src)
for i in set_of_nbr_vertices:
t = do_dfs(i, dest, visited.copy())
if (t == 1):
return update_edges_passing_thru_node(appl_nbrs_edges, src, i)
return 0
def update_edges_passing_thru_node(appl_nbrs_edges, src, dest):
global aug_edges
for edge in appl_nbrs_edges:
if edges[edge][0] == dest and edges[edge][1] == src:
aug_edges[edge] = (aug_edges[edge][0],aug_edges[edge][1], aug_edges[edge][2], aug_edges[edge][3], aug_edges[edge][4] + 1)
return 1
if edges[edge][0] == src and edges[edge][1] == dest:
aug_edges[edge] = (aug_edges[edge][0],aug_edges[edge][1], aug_edges[edge][2], aug_edges[edge][3] + 1, aug_edges[edge][4])
return 1
def applicable_nbrs_edges(src, edges): # (0, [0, 1])
global aug_edges
applicable_edges = []
for e in edges:
aug_edge = aug_edges[e] #(0, 1, 16, 0, 0),
if src == aug_edge[0]:
if aug_edge[3] < aug_edge[4] + aug_edge[2]:
applicable_edges.append(e)
else:
if src == aug_edge[1]:
if aug_edge[4] < aug_edge[3] + aug_edge[2]:
applicable_edges.append(e)
return applicable_edges
cal_flow()
<file_sep>"""
Author: <NAME>
Licensed To: Peritus.ai
"""
# python -m SimpleHTTPPutServer 8080
import SimpleHTTPServer
import BaseHTTPServer
import random
import datetime
class SputHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_WORK(self):
print(self.headers)
#length = int(self.headers["Content-Length"])
length = 100
path = self.translate_path(self.path) + "/rand_drop_" + str(random.randint(1, 100000))
with open(path, "wb") as dst:
dst.write(self.rfile.read(length))
def do_PUT(self):
return self.do_WORK();
def do_POST(self):
return self.do_WORK();
def do_POST(self):
return self.do_WORK();
def test(self):
f = open("/tmp",'r')
if __name__ == '__main__':
SimpleHTTPServer.test(HandlerClass=SputHTTPRequestHandler)
<file_sep>"""
Author: <NAME>
Licensed To: Peritus.ai
"""
import json
import sys
from kafka import KafkaProducer
print(sys.version)
producer = KafkaProducer(bootstrap_servers='kafka.int.peritus.ai:9092')
with open("/Users/nishchaysinha/cisco/UserStory-All-Fields-rally_200.json") as file:
rally_data = json.load(file)
for dict_line in rally_data:
line_str = json.dumps(dict_line)
print(line_str)
producer.send('cisco_topic', line_str.encode('utf-8'))
#with open("/Users/nishchaysinha/cisco/UserStory-All-Fields-rally_200.json") as file:
producer.close()
<file_sep>from sortedcollections import SortedList,SortedDict,SortedListWithKey,SortedSet
from queue import Queue
graph = {}
graph["v1"] = ["v2","v3"]
graph["v2"] = ["v3","v4"]
graph["v3"] = ["v4","v5"]
graph["v4"] = []
graph["v5"] = []
graph["v6"] = ["v7"]
graph["v7"] = []
'''
a parent should come before its child
a loop causes impposibility cycle. cycle_check_set should be maintained.
if a node is already visted we should not visit that again
'''
res = list()
visited = set()
graph_nodes = Queue()
for node in graph.keys():
graph_nodes.put(node)
cycle = False
def topo_sort():
while not graph_nodes.empty():
el = graph_nodes.get()
if not el in visited:
res.append(Queue())
do_dfs(el, set())
print(res)
def do_dfs(el, cycle_set):
if el in cycle_set:
cycle = True
return
cycle_set.add(el)
visited.add(el)
nbrs = graph[el]
for nbr in nbrs:
if not nbr in visited:
do_dfs(nbr, cycle_set)
res[len(res) - 1].put(el)
return
topo_sort()
<file_sep>from sortedcollections import SortedList, SortedDict
import pytest
car_speeds = [4,2,1,1]
car_pos = [0, 29, 35, 44]
state = 0
attempts = 0
def create_sorted_dist_lane(lane): #lane = list of car nos
res = []
for i in lane:
res.append((i, car_pos[i], car_speeds[i]))
return SortedList(res, key=lambda x: x[1])
lane_l = create_sorted_dist_lane([0,1,2,3])
lane_r = create_sorted_dist_lane([])
lanes = [lane_l, lane_r]
def find_min_coll_len(lane):
m = 1e6
for i in range(0, len(lane)):
if i < len(lane) - 1:
dist = lane[i + 1][1] - lane[i][1]
if (lane[i][2] > lane[i + 1][2]):
t = dist/(lane[i][2] - lane[i + 1][2])
m = min(m,t)
return m
def update_state():
global state, attempts
attempts += 1
print(str(state) + " attempts:" + str(attempts))
t = 1e6
critical_lane = 0
for (i,lane) in zip(range(0,len(car_speeds)),lanes):
t1 = find_min_coll_len(lane)
if (t > t1):
t = t1
critical_lane = i
state += t
for (i, lane) in zip(range(0, len(car_speeds)), lanes):
lanes[i] = eval_locs(lane, t)
car_tuple = remove_critical_car(lanes[critical_lane])
col_happened = add_critical_car(lanes[critical_lane + 1 %2], car_tuple)
if (col_happened):
return state
else:
if all_sorted():
return "Possible"
else:
update_state()
def eval_locs(lane, delta_t):
n = SortedList(key=lambda x:x[1])
for l in lane:
ll = (l[0], l[1] + l[2]*delta_t, l[2])
n.add(ll)
return n
def remove_critical_car(lane):
for i,l in zip(range(0, len(lane) - 1), lane):
if round(l[1],2) == round(lane[i + 1][1],2):
lane.remove(l)
return l
def add_critical_car(lane, crit_car):
if (crit_car is not None):
lane.add(crit_car)
for i,l in zip(range(0, len(lane)), lane):
if (i != len(lane) - 1):
if l[1] <= lane[i + 1][1] and l[1] > lane[i+1][1] -5 :
return True
return False
def all_sorted():
global lanes
for lane in lanes:
last_speed = 0
for x in lane:
if (last_speed > x[2]):
print (str(last_speed) + " cur_speed:" + str(x[2]))
return False
last_speed = x[2]
return True
if __name__ == '__main__':
update_state()
def test_each():
find_min_coll_len(lane_l)
p = eval_locs(lane_l, 6)
c = remove_critical_car(p)
add_critical_car(p, (1,40,2))
add_critical_car(p, (1,41,2))
assert False ==all_sorted()
<file_sep>from queue import Queue
graph = dict()
graph["v1"] = [("v2",2), ("v3", 4)]
graph["v2"] = [("v3",3), ("v4", 7)]
graph["v3"] = [("v4",2), ("v5", 1)]
graph["v4"] = []
graph["v5"] = []
cost_map = {}
p_que = Queue()
visited = set()
def dijstra(src, dest):
cost_map[src] = 0
p_que.put(src)
visited = set()
dijstra_real()
print(str(cost_map.get(dest)))
def dijstra_real():
if p_que.empty():
return
el = p_que.get()
if el in visited:
return dijstra_real()
nbrs_tuples = graph[el]
cur_cost = cost_map[el]
for nbrs_tuple in nbrs_tuples:
nbr_cost = cost_map.get(nbrs_tuple[0])
if (nbr_cost is not None):
if (nbr_cost > cur_cost + nbrs_tuple[1]):
cost_map[nbrs_tuple[0]] = cur_cost + nbrs_tuple[1]
else:
cost_map[nbrs_tuple[0]] = cur_cost + nbrs_tuple[1]
if not (nbrs_tuple[0] in visited):
p_que.put(nbrs_tuple[0])
visited.add(el)
return dijstra_real()
dijstra("v1","v4")<file_sep>"""
Author: <NAME>
"""
Cas
<file_sep>"""
Author: <NAME>
"""
import sortedcontainers
from math import ceil
def gen_all_offsets():
global offsets
for i in range(0, R+1):
for j in range(0, G*R+1):
offset = i*G + j;
if (offset <= R*G):
offsets.add(offset)
def create_rewards(N):
global rewards
p = float(sum(N)/float(len(N)))
last = p
rewards[0] = p
for i in range(1, R + 1):
acc = 0.0
for j in range(0, len(N)):
if (N[j] < p):
acc += last/len(N)
else:
acc += N[j]/float(len(N))
rewards[i] = acc
last = rewards[i]
def create_a_map_offset_p():
mp = sortedcontainers.SortedDict()
global offsets
for i in offsets:
mp[i] = 0
return mp
def compare_two_map_not_converged(mp1: sortedcontainers.SortedDict, mp2: sortedcontainers.SortedDict):
for i in mp1.keys():
if ((abs(mp1[i] - mp2[i])/(mp1[i] + 1e-8)) > 1e-6):
return True
return False
def copy_map (mp1, mp2):
for i in mp1.keys():
mp2[i]=mp1[i]
def play(cur_prob, repeats, total):
return (cur_prob * total + rewards[repeats])/(total + 1)
def play_more(mp2, last_total):
mp3 = create_a_map_offset_p()
for i in mp2.keys():
remaining_tokens = i
cur_prob = mp2[i]
reroll = 0
next_prob = play(cur_prob, reroll, last_total)
index = remaining_tokens + 1
if (index > R*G): index = R*G
if (mp3[index] < next_prob):
mp3[index] = next_prob
while (remaining_tokens >= G):
remaining_tokens -= G;
reroll += 1
next_prob = play(cur_prob, reroll, last_total)
index = remaining_tokens + 1
if (index > R*G): index = R*G
if (mp3[index] < next_prob):
mp3[index] = next_prob
mp2 = mp3
return mp2
if __name__ == '__main__':
N = [1,0,0.5]
R = 1
G = 1
offsets = sortedcontainers.SortedSet();
rewards = sortedcontainers.SortedDict();
gen_all_offsets();
mp1 = create_a_map_offset_p()
mp2 = create_a_map_offset_p()
copy_map(mp1,mp2)
create_rewards(N)
total = 0
while True:
mp2 = play_more(mp2, total)
total += 1
if compare_two_map_not_converged(mp1, mp2) == True:
copy_map(mp2,mp1)
continue
else:
break;
print(max(mp1.values()))
<file_sep>import sortedcontainers
mem = sortedcontainers.SortedDict()
min_value_found = 0;
def solve(n: int, A :int, B: int, r: int):#returns days
global min_value_found, breakOut
#generate all m*A + n*B
res = max_for_days(n, A, B, r) - n
if (res < 0):
j=solve(n, A, B, r + A)
k=solve(n, A, B, r + B)
return min(j,k)
else:
if (min_value_found > r):
min_value_found = r
breakOut = True
solve2(n,A,B)
return r
def solve2(n,A,B):
index = mem.bisect_left(min_value_found)
if (index > 1):
low = mem.keys()[index-1]
high = min_value_found
print(linear_search(low, high))
else:
print(index)
def linear_search(low, hi):
i = low + 1
while(True):
if (max_for_days(n,A, B, i) > n):
print(i)
raise Exception
else: i += 1
def max_for_days(n: int, A, B, cur_days: int) -> int: #returns max for cur_days
global mem
if (min_value_found != 0 and cur_days > min_value_found):
return mem[min_value_found]
if (mem.get(cur_days) is None):
if (cur_days < A): return mem[A]
if (cur_days < B): return mem[A]
mem[cur_days] = max_for_days(n, A, B, cur_days - A) + max_for_days(n, A, B, cur_days -B)
return mem[cur_days]
if __name__ == '__main__':
n= 574503743127099
A= 55
B= 66
mem[B] = 3
mem[A] = 2
min_value_found = n *B;
breakOut = False
print(solve(n, A, B, 0))
solve(n, A, B, 0)
<file_sep>"""
Author: <NAME>
"""
def find_all_substrings(s: str):
res = []
for i in range(0, len(s)):
res.extend(find_all_substrings_with_start(s, i))
return res
def find_all_substrings_with_start(s: str, start):
res = []
start
rem = len(s) - start
for i in range(1, rem + 1):
res.append(s[start: start + i])
return res
def closest_match(f: float, closest_yet_f: float, potential: str, eval_cand: str):
cur_prop = len([s for s in eval_cand if s == '1'])/float(len(eval_cand))
if (abs(f -cur_prop) < abs(f - closest_yet_f)):
return (cur_prop, eval_cand)
else:
return (closest_yet_f, potential)
def solve(s: str, f: float):
all_substr = find_all_substrings(s)
all_substr_set = set(all_substr)
potential = s
closest_yet = f + 1000
potential_acc = set()
for sub in all_substr_set:
(closest_yet_new, potential_new) = closest_match(f, closest_yet, potential, sub)
if (closest_yet_new != closest_yet):
potential_acc = set()
potential_acc.add(potential_new)
potential = potential_new
closest_yet = closest_yet_new
print(s.index(potential), potential, closest_yet)
if __name__ == "__main__":
s = "001001010111"
f = 0.66667
solve(s, f)
<file_sep># nsinha-misc2
<file_sep>**Problem of food = 1**
1. Order the spells(S) according to lowest output. Lowest output comes first.
2. What is two things have lowest output. If one has higher input then that comes
1. if earlier:
(5,2) (3,2) leads to +2 -2 +2 = 2
2. If later:
(3,2) (5,2) leads to +2 -2 +2 = 2
it does not matter.
3. So a clean algo is order by o/p and that's it.
**Problem of food =2**
0. Treat the 2 food as group and reduce the problem to 1.
1. Solve it as like 1.
2. But when coming to case like:
S1(3,2|2,2) , S2(4,2|2,2)
1. S1 vs S2:
<file_sep>
nos = [1,2 ,3]
subsets = []
def gen_subs():
for i in range(0,len(nos) + 1):
subsets.extend(choose(i, nos))
for i in subsets:
print(i)
def choose(how_many, all_nos): # -> []
if (how_many == 0):
return [[]]
new_subsets = []
for i in range(0,len(all_nos)):
choose_one = all_nos[i]
new_all_nos = all_nos[i+1:len(all_nos)]
for subset in choose(how_many -1, new_all_nos):
subset.append(choose_one)
new_subsets.append(subset)
return new_subsets
def gen_all_combs(how_many):
a = choose(how_many, nos)
for i in a:
print(i)
def gen_all_perms(all_nos):
res = []
for i in range(0,min(1, len(all_nos))):
choose_one = all_nos[i]
remains = all_nos.copy()
remains.remove(choose_one)
remains_perms = gen_all_perms(remains)
for r in remains_perms:
for j in range(0, len(r) + 1):
m = r.copy()
m.insert(j, choose_one)
res.append(m)
if len(res) != 0:
return res
else:
return [[]]
print(len(gen_all_perms([1,2,3,4,5])))
<file_sep>"""
Author: <NAME>
"""
import queue
nodes = [0, 1, 2, 3]
connections = [(0, 1, 4),(0,2,3), (1,3, 3), (1,2,2), (2,3,3)]
class Edge(object):
def __init__(self):
self.nodes_ids = [0,1]
self.weight = 1
class Node(object):
def __init__(self):
self.edges_ids = []
self.node_id = 0;
class FlowEdge(object):
def __init__(self, cap, id):
self.id = id
self.capacity = cap
self.ab = 0
self.ba = 0
class MaxFlowMinCut(object):
def __init__(self, nodes: list[Node], connections: list[(int,int,int)], src_node_id: int, dest_node_id: int):
self.nodes_dict = {} #type: Dict[Node]
self.edges_dict = {}
self.nodes_to_edge = {}
self.flow_edges_dict = {}
self.src_node_id = src_node_id
self.dest_node_id = dest_node_id
for i in nodes:
node = Node()
self.nodes_dict[i] = node
node.node_id = i
edge_num = 0
for (n1,n2,w) in connections:
node_n1 = self.nodes_dict(n1) # type: Node
node_n2 = self.nodes_dict(n2)
node_n1.edges_ids.append(edge_num)
node_n2.edges_ids.append(edge_num)
edge = Edge()
edge.nodes_ids = [node_n1.node_id, node_n2].sort()
self.edges_dict[edge_num] = edge
edge_num = edge_num + 1;
edge.weight = w
self.nodes_to_edge[tuple(edge.nodes_ids)] = edge_num
self.form_augmented_graph();
def form_augmented_graph(self):
for edge_num in self.edges_dict:
flow_edge = FlowEdge(self.edges_dict[edge_num].weight, edge_num)
self.flow_edges_dict[edge_num] = flow_edge
def solve_flow(self):
max_flow = 0
while (True):
flow = self.find_a_path_to_dest_start()
if (flow > 0):
max_flow += flow
else:
break
print("max_flow is {}", max_flow)
def find_a_path_to_dest_start(self):
self.visited = set()
self.bfs_queue = queue.deque()
self.bfs_queue.append((self.src_node_id, []))
self.result_bfs = []
if (self.do_bfs_till_dest_node() == -1):
return -1
else:
flow = evaluate_flow()
subtract_flow(flow)
return flow
def do_bfs_till_dest_node(self):
if len(self.bfs_queue) == 0:
return -1
(next_node_id, present_path) = self.bfs_queue.remove()
if (next_node_id == self.dest_node_id):
self.result_bfs = present_path.append(next_node_id)
return 0
nbrs = self.find_not_full_unvisited_nbrs(next_node_id)
[self.bfs_queue.append(nbr) for nbr in nbrs]
return self.do_bfs_till_dest_node()
def find_not_full_unvisited_nbrs(self, cur_node_id):
cur_node = self.nodes_dict[cur_node_id] #type: Node
results = []
for i in cur_node.edges_ids:
edge = self.edges_dict[i]
flow_edge = self.flow_edges_dict[i] #type: FlowEdge
other_node_id = set(edge.nodes_ids).difference(set(cur_node_id)).pop()
if (self.visited.isdisjoint(set(other_node_id))):
if (cur_node_id > other_node_id):
if (flow_edge.ba < (flow_edge.capacity+ flow_edge.ab)):
results.append(other_node_id)
else:
if (flow_edge.ab < (flow_edge.capacity + flow_edge.ba)):
results.append(other_node_id)
else:
pass
return results
def evaluate_flow(self):
last_node_id = None
min_flow = 1e6
for cur_node_id in self.result_bfs:
flow = 1e6
if (last_node_id is not None):
if (last_node_id < cur_node_id):
edge_num = self.nodes_to_edge((last_node_id, cur_node_id))
flow_edge = self.flow_edges_dict[edge_num]
flow = flow_edge.capacity + flow_edge.ba - flow_edge.ab
else:
edge_num = self.nodes_to_edge((cur_node_id, last_node_id))
flow_edge = self.flow_edges_dict[edge_num]
flow = flow_edge.capacity + flow_edge.ba - flow_edge.ab
if (min_flow > flow):
min_flow = flow
else:
pass
return min_flow
def subtract_flow(self, flow):
last_node_id = None
for cur_node_id in self.result_bfs:
if (last_node_id is not None):
if (last_node_id < cur_node_id):
edge_num = self.nodes_to_edge((last_node_id, cur_node_id))
flow_edge = self.flow_edges_dict[edge_num]
flow_edge.ab += flow
else:
edge_num = self.nodes_to_edge((ur_node_id, last_node_id))
flow_edge = self.flow_edges_dict[edge_num]
flow_edge.ba += flow
if (min_flow > flow):
min_flow = flow
else:
pass
return
<file_sep>import functools
from collections import deque
levels = [(0,5), (0,1), (1,1), (4,7), (5,6)]
def comp_levels(l, m):
if (l[1]> m[1]):
return 1
else:
if (l[1] < m[1]):
return -1
else:
if (l[0] > m[0]):
return 1
else:
if (l[0] < m[1]):
return -1
return 0
sorted_levels = sorted(levels,key= functools.cmp_to_key(comp_levels),reverse=True)
attempts = 0
deq = deque(sorted_levels)
stars = 0
while len(deq) > 0:
cur_el = deq.pop()
attempts +=1
if cur_el[1] <= stars:
stars += 1
if (cur_el[0] >= 0):
stars += 1
continue
else:
if cur_el[0] >= 0 and cur_el[0] <= stars:
cur_el = (-1,cur_el[1])
stars += 1
deq.append(cur_el)
else:
attempts = -1
print("impossoble")
break;
if (attempts > 0):
print(attempts)
|
8888f3ed4bfc513dcc41a377e3cf491d3758dabc
|
[
"Markdown",
"Python"
] | 17 |
Python
|
nsinha-git/nsinha-misc2
|
ac96bfeeb3e0d47e4eea736afce3e284f141948f
|
68143af2055fa779d956897bc4f43e9306f1a6d4
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerRoomLoader : MonoBehaviour
{
public Animator transition;
public int sceneToLoad;
void OnTriggerEnter2D(Collider2D other) {
if(other.CompareTag("Player") && !other.isTrigger) {
LoadRoom();
}
}
public void LoadRoom() {
StartCoroutine(LoadScene(sceneToLoad));
}
IEnumerator LoadScene(int levelindex) {
// Play loading animation
transition.SetTrigger("Start");
// Wait animation to finish
yield return new WaitForSeconds(1f);
// Load scene
SceneManager.LoadScene(levelindex);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Sign : MonoBehaviour
{
public GameObject dialogBox;
public Text dialogText;
public string dialogTextString;
private string currentText = "";
public bool playerInRange;
public float timeDelay = 0.05f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space) && playerInRange) {
if (dialogBox.activeInHierarchy) {
dialogBox.SetActive(false);
} else {
dialogBox.SetActive(true);
StartCoroutine(ShowText());
}
}
}
void OnTriggerEnter2D(Collider2D collision) {
if(collision.CompareTag("Player")) {
playerInRange = true;
}
}
void OnTriggerExit2D(Collider2D collision) {
if(collision.CompareTag("Player")) {
playerInRange = false;
dialogBox.SetActive(false);
}
}
IEnumerator ShowText() {
for (int i = 0; i <= dialogTextString.Length; i++) {
currentText = dialogTextString.Substring(0,i);
dialogText.text = currentText;
yield return new WaitForSeconds(timeDelay);
}
}
}
|
394cd7d3012777f7d39cee21997f6fbb7a2c3215
|
[
"C#"
] | 2 |
C#
|
mwinailan/AdvenTure
|
ab18661ae6027f82a5128dfda4b2ccdb19252129
|
a45f90038b280cd84dbf7a5adb75fb1466f5ef82
|
refs/heads/master
|
<file_sep>package com.lateral.service;
public interface IEmailService {
void sendEmail(String from, String to, String message) throws Exception;
}
|
8ab051dcb158c66ba7ba0a3eb1d52ab2995154f9
|
[
"Java"
] | 1 |
Java
|
milorad-kukic/TestingDemo
|
961805394ce253a3922edc63f1ede87278f54b27
|
e9dc2423c7a8dd8c7a33f2a01779ec6c0c162b93
|
refs/heads/master
|
<repo_name>eduardosantonascimento/AppTeste<file_sep>/src/apiGit.js
(function(){
const url = 'https://www.github.com./users';
})();<file_sep>/App.js
import React, {Component} from 'react';
import { Button, StyleSheet, Text, View,Image,FlatList, TextInput } from 'react-native';
import api from './src/apiGit';
class App extends Component{
render(){
var img = 'https://scontent.fsdu8-2.fna.fbcdn.net/v/t1.0-1/57349685_2391572707589789_2176599257069387776_n.jpg?_nc_cat=109&ccb=1-3&_nc_sid=dbb9e7&_nc_ohc=K1jx9ymputMAX8SLVG5&_nc_ht=scontent.fsdu8-2.fna&oh=8bd1f01f4547e64041be4f74b3683bff&oe=607DF765'
var img2= 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBw0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ8NDQ0NFREWFhURFRYYHCgsGSYlGxUfIjEtJikrLi8uFx81ODMtOCgtLzcBCgoKDQ0OFRAQFS0dFh0tLSsrLS0tLS0rLy0rLSstLTctLy0rLTUrMi8rLS0yLS0rLS0uLS0tKy0rKzAtLS0tLf/AABEIALcBEwMBIgACEQEDEQH/xAAaAAEAAwEBAQAAAAAAAAAAAAACAAEDBQYE/8QAPxAAAgEDAgMFBgIHBgcAAAAAAAECAwQRBRIGEzEhIkFRYRQycYGRobHBBxUzNULh8FJyc3Sy0RYjJDRikqL/xAAZAQADAQEBAAAAAAAAAAAAAAABAgMABAX/xAApEQEBAAIBAwIFBAMAAAAAAAAAAQIREgMhQRMxIl<KEY>
return(
<View
style={styles.container}
>
<Image
style={styles.img}
source={{uri:img2}}
/>
<Text
style={styles.text}>
Estamos buscando desenvolvedores competentes para nosso time de desenvolvimento, faça uma busca no
Github para achar um novo integrante para nossa equipe.
</Text>
<Text
style={styles.text}
>
Digite o nome do programador que está procurando:
</Text>
<TextInput
style={styles.input}
>
</TextInput>
<FlatList>
</FlatList>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex:1,
margin:10,
backgroundColor:'#ea80fc'
},
input: {
height:45,
borderWidth:2,
borderColor: '#223',
margin:10,
fontSize: 20,
padding:10
},
img:{
width: 300,
height:150,
alignItems:'center',
justifyContent: 'center',
marginLeft:30
},
text:{
fontSize:20,
margin:5
}
});
export default App;
|
e0ef35f2b692746e94d106621b43838e6f9d4677
|
[
"JavaScript"
] | 2 |
JavaScript
|
eduardosantonascimento/AppTeste
|
7937b1161204513bfdff4ff74a78b969e3a09b01
|
b0799fc8d862fde13ac70526fdc08dde657784c5
|
refs/heads/master
|
<file_sep>'use strict';
exports.main = async (event, context) => {
//event为客户端上传的参数
const bodyObj = JSON.parse(event.body)
const parent = bodyObj.parent
const pathArray = parent.split('/')
console.log('query file in parent:', pathArray)
const pathStack = []
let parentId = null
for (const folder of pathArray) {
const whereClause = {
name: folder,
parent: parentId
}
const resp = await uniCloud.database().collection('opendb-netdisk-files').where(whereClause).orderBy("isFolder", "desc").orderBy("createOn","desc").get()
const folderInfo = resp.data
if (folderInfo.length > 0) {
parentId = folderInfo[0]._id
pathStack.push({
name: folder,
id: parentId,
isFolder: folderInfo[0].isFolder
})
} else {
console.error('path not exist when query folder:', folder)
return {
code: '-1',
message: '路径不存在'
}
}
}
const lastPath = pathStack.slice(-1).pop()
let files = []
if (lastPath.isFolder) {
const whereClause = {
parent: lastPath.id
}
const resp = await uniCloud.database().collection('opendb-netdisk-files').where(whereClause).orderBy("isFolder", "desc").orderBy("createOn","desc").get()
files = resp.data
}
//返回数据给客户端
return {
code: 0,
data: {
paths: pathStack,
files: files
}
}
};
|
8d07808a6620fa3e26faaf7a3b2cf5847fdffa91
|
[
"JavaScript"
] | 1 |
JavaScript
|
ncist-fe/cloud-admin
|
2b52fecd33efaf86b14092c143c2e02b9dc345ba
|
7672ab47af85bca928ec7634bf9142573cd65829
|
refs/heads/master
|
<repo_name>kimamula/ts-babel<file_sep>/ts/module_loaders.ts
// Dynamic loading – ‘System’ is default loader
System.import("lib/math").then(function(m: {sum: (a: number, b: number) => number, pi: number}) {
alert("2π = " + m.sum(m.pi, m.pi));
});
// Create execution sandboxes – new Loaders
var loader = new Loader({
global: fixup(window) // replace ‘console.log’
});
loader.eval("console.log(\"hello world!\");");
// Directly manipulate module cache
System.get("jquery");
System.set("jquery", Module({$: window['$']})); // WARNING: not yet finalized
<file_sep>/ts/proxies.ts
// Proxying a normal object
interface TargetObject {
world: string
}
var targetObject: TargetObject = {'world': null};
var objectHandler = {
get: function (receiver: TargetObject, name: string) {
return `Hello, ${name}!`;
}
};
var objectProxy = new Proxy(targetObject, objectHandler);
objectProxy.world === "Hello, world!";
// This raises a compilation error! Great!
// objectProxy.foo === "Hello, world!";
// Proxying a function object
var targetFunction = (name: string) => { return `I am ${name}`; };
var functionHandler = {
apply: function (receiver: Function, ...args: any[]) {
return "I am the proxy";
}
};
var functionProxy = new Proxy(targetFunction, functionHandler);
functionProxy() === "I am the proxy";
// This does not raise a compilation error...
functionProxy(0) === "I am the proxy";
// This rases "Cannot find name 'Proxy'"
// (<Proxy<(name: string) => string>>new Proxy(targetFunction, functionHandler))(0);
<file_sep>/ts/module_import.ts
// app.js
import exp, {pi, e} from "./module_export";
alert(exp(pi) + exp(e));
<file_sep>/ts/classes.ts
export class MySuperClass {
constructor(private id: number, private name: string) {
}
createHello(): string {
return 'Hello ' + this.name + ', your id is ' + this.id;
}
}
export class MyClass extends MySuperClass {
private hello: string;
constructor(id: number, name: string) {
super(id, name);
this.hello = super.createHello();
}
static getInstance(): MySuperClass {
return new MyClass(0, 'Mathew');
}
}
<file_sep>/ts/generators.ts
var generatorFibonacci = {
[Symbol.iterator]: function*() {
var pre = 0, cur = 1;
for (;;) {
var temp = pre;
pre = cur;
cur += temp;
yield cur;
}
}
}
for (var n of generatorFibonacci) {
// truncate the sequence at 1000
if (n > 1000)
break;
console.log(n);
}
<file_sep>/ts/module_export.ts
export * from "lib/math";
export var e = 2.71828182846;
export default function(x: number) {
return Math.exp(x);
}
<file_sep>/ts/iterators_for_of.ts
let fibonacci = {
[Symbol.iterator]() {
let pre = 0, cur = 1;
return {
next() {
[pre, cur] = [cur, pre + cur];
return { done: false, value: cur }
}
}
}
}
for (var n of fibonacci) {
// truncate the sequence at 1000
if (n > 1000)
break;
console.log(n);
}
<file_sep>/ts/subclassable_built_ins.ts
// User code of Array subclass
class MyArray<T> extends Array<T> {
constructor(...args: T[]) { super(...args); }
}
var arr = new MyArray();
arr[1] = 12;
arr.length == 2
class MyDate extends Date {
constructor() {
super();
}
}
class MyElement extends Element {
}
<file_sep>/ts/default_rest_spread.ts
function fDefault(x: number, y = 12) {
// y is 12 if not passed (or passed as undefined)
return x + y;
}
fDefault(3) === 15;
function fRest(x: number, ...y: any[]) {
// y is an Array
return x * y.length;
}
fRest(3, "hello", true) === 6
function fSpread(x: number, y: number, z: number) {
return x + y + z;
}
// Pass each elem of array as argument
fSpread(...[1, 2, 3]) === 6;
(<any>fSpread)(...[1, 2, 3]) === 6; // This can be compiled
<file_sep>/ts/reflect_api.ts
var O = {a: 1};
Object.defineProperty(O, 'b', {value: 2});
O[Symbol('c')] = 3;
Reflect.ownKeys(O); // ['a', 'b', Symbol(c)]
function C(a: number, b: number){
this.c = a + b;
}
var instance = Reflect.construct(C, [20, 22]);
instance.c; // 42
<file_sep>/ts/arrows.ts
var evens = [0, 2, 4, 6, 8];
var fives: number[];
// Expression bodies
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i);
// Statement bodies
nums.forEach(v => {
if (v % 5 === 0)
fives.push(v);
});
// Lexical this
var bob: {
_name: string,
_friends: string[],
printFriends: () => void
} = {
_name: "Bob",
_friends: [],
printFriends() {
this._friends.forEach((f: string) =>
console.log(this._name + " knows " + f));
}
}
<file_sep>/tsconfig.json
{
"version": "1.5.0-beta",
"compilerOptions": {
"declaration": false,
"noImplicitAny": true,
"removeComments": true,
"noLib": false,
"preserveConstEnums": true,
"suppressImplicitAnyIndexErrors": true,
"outDir": "tsc-babel-intermediate"
},
"filesGlob": [
"./ts/**/*.ts"
],
"files": [
"./ts/arrows.ts",
"./ts/binary_and_octal_literals.ts",
"./ts/classes.ts",
"./ts/default_rest_spread.ts",
"./ts/destructuring.ts",
"./ts/generators.ts",
"./ts/iterators_for_of.ts",
"./ts/let_const.ts",
"./ts/lib/math.ts",
"./ts/map_set_weakmap_weakset.ts",
"./ts/math_number_string_object_apis.ts",
"./ts/module_export.ts",
"./ts/module_import.ts",
"./ts/module_loaders.ts",
"./ts/object_literals.ts",
"./ts/promises.ts",
"./ts/proxies.ts",
"./ts/reflect_api.ts",
"./ts/subclassable_built_ins.ts",
"./ts/symbols.ts",
"./ts/tail_calls.ts",
"./ts/template_strings.ts",
"./ts/unicode.ts"
]
}
<file_sep>/ts/template_strings.ts
// Multiline strings
`In ES5 this is
not legal.`
// Interpolate variable bindings
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
<file_sep>/ts/destructuring.ts
// list matching
var [a, , b] = [1,2,3];
class ASTNode {
constructor(public op: string, public lhs: ASTNode, public rhs: ASTNode) {}
}
function getASTNode() {
return new ASTNode('op', null, null);
}
// object matching
var { op: o, lhs: { op: lo }, rhs: r }
= getASTNode();
// object matching shorthand
// binds `op`, `lhs` and `rhs` in scope
var {op, lhs, rhs} = getASTNode();
// Can be used in parameter position
function g({name: x}: {name: string}) {
console.log(x);
}
g({name: 'Taro'});
// Fail-soft destructuring
var num: number;
var [num]: number[] = [];
// num === undefined;
// Fail-soft destructuring with defaults
var [num = 1]: number[] = [];
// num === 1;
<file_sep>/ts/tail_calls.ts
function factorial(n: number, acc = 1): number {
"use strict";
if (n <= 1) return acc;
return factorial(n - 1, n * acc);
}
// Stack overflow in most implementations today,
// but safe on arbitrary inputs in ES2015
factorial(100000)
<file_sep>/ts/object_literals.ts
import {MyClass} from 'classes';
var handler = (resultCode: number) => {return resultCode * 10};
var obj = {
// __proto__
__proto__: new MyClass(10, 'Luke'),
// Shorthand for ‘handler: handler’
handler,
// Methods
toString() {
// Super calls
return "d " + super.toString();
},
// Computed (dynamic) property names
["prop_" + (() => 42)()]: 42
};
console.log(obj.handler(1));
<file_sep>/ts/map_set_weakmap_weakset.ts
// Sets
var s = <Set<string>>new Set();
s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") === true;
// Maps
var m = <Map<any, number>>new Map();
m.set("hello", 42);
m.set(s, 34);
m.get(s) == 34;
// Weak Maps
var wm = <WeakMap<Set<string>, any>>new WeakMap();
wm.set(s, { extra: 42 });
wm['size'] === undefined;
// Weak Sets
var ws = <WeakSet<{data: number}>>new WeakSet();
ws.add({ data: 42 });
// Because the added object has no other references, it will not be held in the set
<file_sep>/README.md
ts-babel
============
TypeScript codes written in ECMAScript 2015 (ES6) for examining "tsc --target es6 && babel"
##Usage
```shell
npm install
npm run tsc-babel # For examining "tsc --target es6 && babel". You can see the result at tsc-babel directory.
npm run tsc-only # For examining "tsc --target es5". You can see the result at tsc-only directory.
```
Currently, both `npm run tsc-babel` and `npm run tsc-only` fail at tsc.
You can change the TypeScript version used by editing package.json (The specified commit is the newest in the master branch on 18th of July, 2015).
<file_sep>/ts/lib/math.ts
// lib/math.js
export function sum(x: number, y: number) {
return x + y;
}
export var pi = 3.141593;
<file_sep>/ts/math_number_string_object_apis.ts
Number.EPSILON
Number.isInteger(Infinity) // false
Number.isFinite(Infinity) // true
Number.isNaN(NaN) // true
Math.acosh(3) // 1.762747174039086
Math.hypot(3, 4) // 5
Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
"abcde".startsWith("xy") // false
"abcde".includes("cd") // true
"abcde".endsWith("de") // true
"abcde".normalize()
"abc".repeat(3) // "abcabcabc"
Array.from(document.querySelectorAll("*")) // Returns a real Array
Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
var numberArray = [1, 2, 3];
numberArray.fill(7, 1) // [1,7,7]
numberArray.findIndex((x: number) => x === 2) // 1
["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
["a", "b", "c"].keys() // iterator 0, 1, 2
["a", "b", "c"].values() // iterator "a", "b", "c"
class Point {
constructor(private x: number, private y: number) {}
}
Object.assign(Point, { origin: new Point(0,0) })
<file_sep>/ts/unicode.ts
// same as ES5.1
"𠮷".length == 2
// new RegExp behaviour, opt-in ‘u’
"𠮷".match(/./u)[0].length == 2
// new form
"\u{20BB7}" == "𠮷";
"𠮷" == "\uD842\uDFB7"
// new String ops
"𠮷".codePointAt(0) == 0x20BB7
// for-of iterates code points
for(var ch of "𠮷") {
console.log(ch);
}
<file_sep>/ts/symbols.ts
module MyModule {
// module scoped symbol
var key = Symbol("key");
export class MyClass {
constructor(privateData: string) {
this[key] = privateData;
}
doStuff() {
this[key];
}
}
}
var c = new MyModule.MyClass("hello");
c["key"] === undefined
<file_sep>/ts/let_const.ts
function f() {
{
let x: string;
{
// okay, block scoped name
const x = "sneaky";
// error, const
// x = "foo";
}
// error, already declared in block
// let x = "inner";
}
}
<file_sep>/ts/promises.ts
function timeout(duration = 0) {
return new Promise((resolve: () => void, reject: () => void) => {
setTimeout(resolve, duration);
})
}
var promise = timeout(1000).then(() => {
return timeout(2000);
}).then((): {} => {
throw new Error("hmm");
}).catch((err: any) => {
return Promise.all([timeout(100), timeout(200)]);
})
|
0607d635f5b8cc48436329665d4bd3acd10674dc
|
[
"Markdown",
"TypeScript",
"JSON with Comments"
] | 24 |
TypeScript
|
kimamula/ts-babel
|
89f8ec23e1480b1c7364e60f96ff4b9819e3949d
|
39ec32e66ce681c0fe249139e61a2f0596e2470d
|
refs/heads/master
|
<repo_name>edelperi/aggBreakPBE<file_sep>/showPBEfeatures.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from aggBreakPBE import *
import numpy as np
import matplotlib.pyplot as plt
#-Plot with LaTeX
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
#------------------------------Display Kernels---------------------------------#
v_list = np.arange(1,121)
D_F = 2.2
R_p = 1.16e-6
R_list = radiusOfGyration(v_list, D_F, R_p)
G = 1.0
#Brownian collision kernel:
T = 310.0
mu = 1.25e-3
D_list = EinsteinStokes(R_list, T, mu)
k_b = Brownian_kernel(R_list, D_list)
plt.pcolor(k_b)
plt.colorbar()
plt.xlabel('v_j')
plt.ylabel('v_i')
plt.show()
#Shear collision kernel:
k_s = shear_kernel(R_list, G)
plt.pcolor(k_s)
plt.colorbar()
plt.xlabel('v_j')
plt.ylabel('v_i')
plt.show()
#Breakup kernel:
b = 2.
Gstar = 1000.0
c = 1.
k_b_c1 = breakup_kernel(R_list, G, Gstar, b, c)
c = 2.
k_b_c2 = breakup_kernel(R_list, G, Gstar, b, c)
c = 3.
k_b_c3 = breakup_kernel(R_list, G, Gstar, b, c)
plt.subplot(3,1,1)
plt.plot(v_list, k_b_c1, label='c = 1')
plt.legend(loc=2)
plt.xlabel('v_j')
plt.ylabel('k_b')
plt.subplot(3,1,2)
plt.plot(v_list, k_b_c2, label='c = 2')
plt.legend(loc=2)
plt.xlabel('v_j')
plt.ylabel('k_b')
plt.subplot(3,1,3)
plt.plot(v_list, k_b_c3, label='c = 3')
plt.legend(loc=2)
plt.xlabel('v_j')
plt.ylabel('k_b')
plt.show()
#---------------------Display Fragment Mass Distributions----------------------#
def showMatrix(fragDist, v_list):
n_bin = fragDist.shape[0]
fig = plt.figure(1, figsize=(5, 5))
plt.clf()
ax = fig.add_subplot(111)
ax.set_aspect(1)
ax.matshow(fragDist,cmap=plt.cm.binary)
for i in xrange(n_bin):
for j in xrange(n_bin):
if fragDist[i,j] >= 1.5:
color = "white"
else:
color = "black"
ax.annotate("{:.2f}".format(fragDist[i][j]),
xy=(j,i),
horizontalalignment="center",
verticalalignment="center",
color=color,
fontsize=10)
plt.xticks(range(n_bin), [str(int(i)) for i in v_list])
plt.yticks(range(n_bin), [str(int(i)) for i in v_list])
plt.xlabel("v_j")
plt.ylabel("v_i")
n_bin = 10
v_list = np.linspace(1, n_bin, n_bin)
#Binary splitting:
showMatrix(binaryFrag(n_bin), v_list)
plt.show()
#Normal splitting:
showMatrix(normalFrag(n_bin = 10, lambd = 4.), v_list)
plt.show()
#Uniform splitting:
showMatrix(uniformFrag(n_bin = 10), v_list)
plt.show()
#Erosion:
showMatrix(erosionFrag(n_bin = 10), v_list)
plt.show()
#-----------------------Display Interpolation Function-------------------------#
def showMatrix(fragDist, v_list):
n_bin = fragDist.shape[0]
fig = plt.figure(1, figsize=(5, 5))
plt.clf()
ax = fig.add_subplot(111)
ax.set_aspect(1)
ax.matshow(fragDist,cmap=plt.cm.binary)
for i in xrange(n_bin):
for j in xrange(n_bin):
if fragDist[i,j] >= 0.75:
color = "white"
else:
color = "black"
ax.annotate("{:.2f}".format(fragDist[i][j]),
xy=(j,i),
horizontalalignment="center",
verticalalignment="center",
color=color,
fontsize=10)
plt.xticks(range(n_bin), [str(int(i)) for i in v_list])
plt.yticks(range(n_bin), [str(int(i)) for i in v_list])
plt.xlabel("v_j")
plt.ylabel("v_i")
plt.title("\chi_{ij}(v_i, v_j, v_k = 256)")
n_bin = 10
v_list = np.logspace(0., n_bin - 1, n_bin, base=2.0)
chi = interpolate(v_list)
showMatrix(chi[:, :, 8],v_list)
plt.show()
<file_sep>/aggBreakPBE.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Sun 18 5 18:01:01 2014
@author: rudolf
_list = vector array
_ts = time series
_list_ts = time series of vector array
_pddf = pandas.DataFrame()
_pds = pandas.Series()
"""
import numpy as np
import scipy.integrate as si
from scipy import stats
import pandas as pd
import time
#==============================================================================#
class aggBreak(object):
def __init__(self, dictionary):
readDict(self, dictionary)
setCMD(self)
setPBE(self)
self.isSolved = False
self.isDataProcessed = False
def solve(self):
if self.isSolved:
print "PBE has already been solved!"
else:
print "Solving..."
tic = time.time()
if self.isGridUniform:
self.C_list_ts = si.odeint(PBE_uniformGrid,
self.C0,
self.t,
args=(self,),
printmessg=1,
rtol=1e-10,
atol=1e-10)
else:
self.C_list_ts = si.odeint(PBE_nonuniformGrid,
self.C0,
self.t,
args=(self,),
printmessg=1,
rtol=1e-10,
atol=1e-10)
toc = time.time()
runTime = toc - tic
print "\tRun time = {0:3g} s\n".format(runTime)
self.isSolved = True
#check the quality of the simulation by testing mass conservation
M1_ts = moment(self.C_list_ts, self.v_list, 1)
conservation_tests = monomer_conservation(M1_ts)
print "Initial and final total monomers in the box are {0:.2g} \
and {1:.2g}, respectively.".format(
conservation_tests[0], conservation_tests[1])
print "Mass is conserved up to {0:.2f} %".format(
conservation_tests[2]*100.)
print ""
#check whether simulation hits the grid ceiling, whose results are unphysical.
PPD_list_ts = PPD(self.C_list_ts, self.v_list)
print "Relative platelet population in the last bin (grid ceiling)\
is {0:.3f} %".format(PPD_list_ts[-1,self.n_bin -1]*100.)
print ""
def processData(self):
if self.isSolved:
print "Processing time series...\n"
self.t_dimLess_s = self.t / self.t_s
self.t_dimLess_d = self.t / self.t_d
self.t_dimLess_b = self.t / self.t_b
self.G_ts = self.G * np.ones_like(self.t)
self.tau_ts = self.mu * self.G_ts
self.freeMono_ts = free_monomers(self.C_list_ts)
self.M0_ts = moment(self.C_list_ts, self.v_list, 0)
self.M1_ts = moment(self.C_list_ts, self.v_list, 1)
self.M2_ts = moment(self.C_list_ts, self.v_list, 2)
self.PPD_list_ts = PPD(self.C_list_ts, self.v_list)
self.monoC_list_ts = monomer_distribution(self.C_list_ts, self.v_list)
self.R_mean_ts = meanR(self.C_list_ts, self.v_list, self.R_list)
self.R_rms_ts = rmsR(self.C_list_ts, self.v_list, self.R_list)
self.v_mean_ts = meanV(self.C_list_ts, self.v_list)
self.PA_ts = PA(self.C_list_ts)
self.dCdt_list_ts = np.empty_like(self.C_list_ts)
if self.isGridUniform:
for i, (Ci, ti) in enumerate(zip(self.C_list_ts, self.t)):
self.dCdt_list_ts[i] = PBE_uniformGrid(Ci, ti, self)
else:
for i, (Ci, ti) in enumerate(zip(self.C_list_ts, self.t)):
self.dCdt_list_ts[i] = PBE_nonuniformGrid(Ci, ti, self)
self.isDataProcessed = True
print "Done!"
else:
print "Cannot process data before solving the PBE!\n"
def printSetup(self):
print "+System setup:"
if self.isGridUniform:
print "- Grid: UNIFORM"
else:
print "|- Grid: GEOMETRIC"
print "| |- n_bin = {0:d}, v_max = {1:d}".format(self.n_bin, self.v_max)
print "| |- C_p = {0:2g} count/m3, R_p = {1:3g} m".format(self.C_p,
self.R_p)
print "|"
print "|- G = {0:2g} s-1".format(self.G)
print "|"
if self.isAggregationOn:
print "|- Aggregation: ON"
print '| |- BROWNIAN: {0}, SORENSENIAN: {1}, SHEAR: {2}'.format(
self.isBrownAggOn,
self.isSorensenAggOn,
self.isShearAggOn)
else:
print "Aggregation: OFF!!!"
print "| |- t_s = {0:2g} s, t_d = {1:2g} s, Pe = {2:2g}".format(self.t_s,
self.t_d,
self.Pe)
print "| |- eta = {0:2g}, t_a = {1:2g} s".format(self.eta, self.t_a)
print "|"
if self.isBreakupOn:
print "|- Breakup: ON"
else:
print "|- Breakup: OFF"
print "| |- G* = {0:2g} s-1, a = {1:2g}, b = {2:2g}, c = {3:2g}".format(
self.Gstar,
self.a,
self.b,
self.c)
print "| |- t_b = {0:2g} s".format(self.t_b)
print "|"
print "|- theta = {0:2g}, K_ab = {1:2g}".format(self.theta, self.K_ab)
print ""
def saveOutput(self):
if self.isSolved:
if not self.isDataProcessed:
aggBreak.processData(self)
filePrefix = self.saveFolder \
+ self.jobName + '-' \
+ self.jobDate + '-' \
+ self.jobTime + '-'
#Input data:
input_pds = pd.Series({'jobName':self.jobName,
'jobDate':self.jobDate,
'jobTime':self.jobTime,
'isGridUniform':self.isGridUniform,
'v_max':self.v_max,
'n_bin':self.n_bin,
'tmin':self.t[0],
'tmax':self.t[-1],
'tstep':self.t[1] - self.t[0],
'D_F':self.D_F,
'R_p':self.R_p,
'V_p':self.V_p,
'C_p':self.C_p,
'eta':self.eta,
'G':self.G,
'isBrownAggOn':self.isBrownAggOn,
'isShearAggOn':self.isShearAggOn,
'isSorensenAggOn':self.isSorensenAggOn,
'isAggregationOn':self.isAggregationOn,
'T':self.T,
'mu':self.mu,
't_d':self.t_d,
't_s':self.t_s,
'Pe':self.Pe,
't_a':self.t_a,
'isBreakupOn':self.isBreakupOn,
'a':self.a, 'b':self.b, 'c':self.c,
'Gstar':self.Gstar,
'lambd':self.lambd,
't_b':self.t_b,
'theta':self.theta,
'K_ab':self.K_ab})
inputFileName = filePrefix + 'inputParameters.csv'
print "Saving input in " + inputFileName
input_pds.to_csv(inputFileName)
# v_list and R_list as a table:
vR_list_pddf = pd.DataFrame()
vR_list_pddf['v'] = self.v_list.astype(int)
vR_list_pddf['R'] = self.R_list
vR_listFileName = filePrefix + 'vR_lists.csv'
print "Saving cluster sizes in " + vR_listFileName
vR_list_pddf.to_csv(vR_listFileName)
#Fragment mass distribution:
fragDist_pddf = pd.DataFrame(self.fragDistr)
fragFileName = filePrefix + 'fragDist.csv'
print "Saving fragment distribution in " + fragFileName
fragDist_pddf.to_csv(fragFileName)
#Output time series (ts):
C_nameList = []
for i in xrange(self.v_list.shape[0]):
C_nameList.append('C_v[{0:d}]'.format(i))
output_pddf_ts = pd.DataFrame(self.C_list_ts,columns=C_nameList)
output_pddf_ts['t'] = self.t
output_pddf_ts['t_dimLess_s'] = self.t_dimLess_s
output_pddf_ts['t_dimLess_d'] = self.t_dimLess_d
output_pddf_ts['t_dimLess_b'] = self.t_dimLess_b
output_pddf_ts['G'] = self.G_ts
output_pddf_ts['tau'] = self.tau_ts
output_pddf_ts['freeMono'] = self.freeMono_ts
output_pddf_ts['M_0'] = self.M0_ts
output_pddf_ts['M_1'] = self.M1_ts
output_pddf_ts['M_2'] = self.M2_ts
output_pddf_ts['R_mean'] = self.R_mean_ts
output_pddf_ts['R_rms'] = self.R_rms_ts
output_pddf_ts['v_mean'] = self.v_mean_ts
output_pddf_ts['PA'] = self.PA_ts
for i in xrange(self.v_list.shape[0]):
output_pddf_ts['PPD_v[{0:d}]'.format(i)] = self.PPD_list_ts[:,i]
for i in xrange(self.v_list.shape[0]):
output_pddf_ts['dCdt_v[{0:d}]'.format(i)] = self.dCdt_list_ts[:,i]
outputFileName = filePrefix + 'output_timeSeries.csv'
print "Saving output time series in " + outputFileName
output_pddf_ts.to_csv(outputFileName)
def reset(self):
print "Clearing simulation results\n"
del self.C_list_ts
print "Clearing processed data\n"
del self.t_dimLess_s
del self.t_dimLess_d
del self.t_dimLess_b
del self.G_ts
del self.tau_ts
del self.freeMono_ts
del self.M0_ts
del self.M1_ts
del self.M2_ts
del self.PPD_list_ts
del self.monoC_list_ts
del self.R_mean_ts
del self.R_rms_ts
del self.v_mean_ts
del self.PA_ts
del self.dCdt_list_ts
print "Reseting the system with new data\n"
setCMD(self)
setPBE(self)
aggBreak.printSetup(self)
self.isSolved = False
self.isDataProcessed = False
#---------------------system initialization functions--------------------------#
def readDict(self, dictionary):
self.saveFolder = dictionary['saveFolder']
self.jobName = dictionary['jobName']
self.jobDate = dictionary['jobDate']
self.jobTime = dictionary['jobTime']
self.C_p = dictionary['C_p']
self.R_p = dictionary['R_p']
self.D_F = dictionary['D_F']
self.v_max = dictionary['v_max']
self.isGridUniform = dictionary['isGridUniform']
self.t = dictionary['t']
self.G = dictionary['G']
self.eta = dictionary['eta']
self.aggPhysics = dictionary['aggPhysics']
self.T = dictionary['T']
self.mu = dictionary['mu']
self.isBreakupOn = dictionary['isBreakupOn']
self.fragModel = dictionary['fragModel']
self.lambd = dictionary['lambd']
self.a = dictionary['a']
self.b = dictionary['b']
self.c = dictionary['c']
self.Gstar = dictionary['Gstar']
def setCMD(self):
self.n_bin = 0 #number of bins i = [0, 1, 2, ..., n]
self.chi = [] #interpolation operator
self.R_list = [] #cluster radius of gyration
self.v_list = [] #number of monomers in each cluster
if self.isGridUniform:
#list of number of monomers in the cluster
self.v_list = np.linspace(1.,
self.v_max,
self.v_max)
self.n_bin = int(len(self.v_list))
else:
#geometric grid
self.n_bin = int(np.floor(np.log2(self.v_max)) + 1)
self.v_list = np.logspace(0.,
self.n_bin - 1,
self.n_bin,
base=2.0)
self.chi = interpolate(self.v_list)
self.v_max = int(self.v_list[-1]) #v_max label gets truncated
self.R_list = radiusOfGyration(self.v_list, self.D_F, self.R_p)
self.V_p = 4./3.*np.pi * self.R_p**3 #monomer volume
def setPBE(self):
self.D_list = [] # diffusivity of each cluster
self.k_c = np.zeros([self.n_bin, self.n_bin]) # Smoluchowski collision kernel
self.k_d = np.zeros([self.n_bin, self.n_bin]) # Diffusion collision kernel
self.k_s = np.zeros([self.n_bin, self.n_bin]) # Shear collision kernel
self.k_b = np.zeros(self.n_bin) # Breakup kernel
self.t_a = 1e30
self.t_d = 1e30
self.t_s = 1e30
self.t_b = 1e30
self.isAggregationOn = False
self.isShearAggOn = False
self.isSorensenAggOn = False
self.isBrownAggOn = False
#checks the given aggregation physics and sums the collision kernels into k_c
if 'Brownian' in self.aggPhysics or 'Sorensenian' in self.aggPhysics:
self.isBrownAggOn = True
self.isAggregationOn = True
self.D_list = EinsteinStokes(self.R_list, self.T, self.mu)
if 'Sorensenian' in self.aggPhysics:
self.isSorensenAggOn = True
self.k_d = Sorensenian_kernel(self.R_list, self.D_list, self.G)
self.t_d = 1.0 / ( (1.0 + 1.05*self.G) \
* 4.0*np.pi \
* 2.0 * self.D_list[0] \
* 2.0 * self.R_p * self.C_p)
else:
self.k_d = Brownian_kernel(self.R_list, self.D_list)
self.t_d = 1.0 / ( 4.0*np.pi \
* (2.0 * self.D_list[0]) \
* (2.0 * self.R_p) \
* self.C_p)
if 'shear'in self.aggPhysics:
self.isAggregationOn = True
self.isShearAggOn = True
self.k_s = shear_kernel(self.R_list, self.G)
self.t_s = 1.0 / ( 4./3. * self.eta * self.G \
* (2.0 * self.R_p)**3. \
* self.C_p)
self.k_c = self.k_s + self.k_d
self.Pe = self.t_d / self.t_s
self.t_a = 1.0 / (self.eta * (1.0 / self.t_s + 1.0 / self.t_d))
# else:
# print "No valid aggregation physics was given! Aggregation is OFF!" \
# + " Try: 'shear', 'Brownian', or 'Sorensenian'."
if self.isBreakupOn:
self.k_b = breakup_kernel(self.R_list, self.G, self.Gstar, self.b, self.c)
if self.fragModel is 'binary':
if self.isGridUniform:
self.fragDistr = binaryFrag(self.n_bin)
else:
self.fragDistr = nonunifBinaryFrag(self.n_bin)
# elif self.fragModel is 'normalFrag':
# if self.isGridUniform:
# self.fragDistr = normalFrag()
# else:
# self.fragDistr = nonunifNormalFrag()
# elif self.fragModel is 'uniform':
# if self.isGridUniform:
# self.fragDistr = uniformFrag()
# else:
# self.fragDistr = nonunifUniformFrag()
# elif self.fragModel is 'erosion':
# if self.isGridUniform:
# self.fragDistr = erosionFrag()
# else:
# self.fragDistr = nonunifErosionFrag()
self.t_b = 1.0 / ((self.G / self.Gstar)**self.b)
else:
print "No valid fragmentation model was given! Turning breakup OFF!"
self.isBreakupOn = False
self.fragDistr = np.zeros((self.n_bin, self.n_bin))
else:
self.k_b = breakup_kernel(self.R_list, 0.0, 1.0, 1.0, 1.0)
self.fragDistr = np.zeros((self.n_bin, self.n_bin))
self.theta = self.t_a / self.t_b
self.K_ab = 1./self.theta
#generate initial condition (no aggregates, just monomers)
self.C0 = np.zeros(self.n_bin)
self.C0[0] = self.C_p
#-----------------------------other functions----------------------------------#
def EinsteinStokes(R, T, mu):
"""Diffusivity constant using Einsteins-Stokes equation."""
k_B = 1.386488e-23 # (J K-1) Boltzmann constant
return (k_B * T) / (6.0 * np.pi * mu * R)
def radiusOfGyration(v, D_F, R_p):
"""Radius of gyration of a fractal aggregate ball."""
return v**(1.0 / D_F) * R_p
def interpolate(v_list):
"""Interpolation function of Kumar & Ramkrishna (1997), also presented by \
Garrick, Lehtinen & Zachariah (2006)."""
n_bin = int(len(v_list))
chi = np.zeros((n_bin, n_bin, n_bin))
# Vsum_ij = (v_i + v_j) is a matrix
Vsum = v_list[:,np.newaxis] + v_list[np.newaxis,:]
for k in xrange(1, n_bin): # no aggregation to the last bin
if k < n_bin -1:
chi[:,:,k] = np.where((Vsum <= v_list[k+1]) & (Vsum >= v_list[k]),
(v_list[k+1] - Vsum) / (v_list[k+1] - v_list[k]),
chi[:,:,k] )
chi[:,:,k] = np.where((Vsum <= v_list[k]) & (Vsum >= v_list[k-1]),
(Vsum - v_list[k-1]) / (v_list[k] - v_list[k-1]),
chi[:,:,k])
return chi
#----------------------------kernel functions----------------------------------#
def Brownian_kernel(R_list, D_list):
k_d = 4.0 * np.pi \
* (R_list[:,np.newaxis] + R_list[np.newaxis,:]) \
* (D_list[:,np.newaxis] + D_list[np.newaxis,:])
return removeIndexN(k_d)
def Sorensenian_kernel(R_list, D_list, G):
return (1.0 + 1.05 * G) * Brownian_kernel(R_list, D_list)
def shear_kernel(R_list, G):
k_s = 4.0 / 3.0 * G * (R_list[:,np.newaxis] + R_list[np.newaxis,:])**3.0
return removeIndexN(k_s)
def breakup_kernel(R_list, G, Gstar, b, c):
kern_mat = (G / Gstar)**b * (R_list[:] / R_list[0])**c
kern_mat[0] = 0.0 # monomer doesn't break
return kern_mat
def removeIndexN(k):
"""Remove i = n from Smoluchowski collision kernel. The aggregation with the\
largest aggregate causes mass loss."""
n_bin = k.shape[0]
for i in xrange(n_bin):
k[i, n_bin-1] = 0.0
k[n_bin-1, i] = 0.0
return k
#-----------------------fragment mass distributions----------------------------#
def erosionFrag(n_bin):
massDistr = np.zeros((n_bin, n_bin))
for j in xrange(n_bin):
p = np.zeros(n_bin)
for i in xrange(np.int((j+1)/2)):
p[0] = 1.0
for i in xrange(n_bin):
massDistr[i][j] = p[i] + p[j-i-1]
return massDistr
#def nonunifErosionFrag(n_bin):
# massDistr = np.zeros((n_bin, n_bin))
# for j in xrange(n_bin):
# p = np.zeros(n_bin)
# for i in xrange(np.int((j+1)/2)):
# p[0] = 1.0
# for i in xrange(n_bin):
# massDistr[i][j] =
# return massDistr
def binaryFrag(n_bin):
massDistr = np.zeros((n_bin, n_bin))
for j in xrange(n_bin):
p = np.zeros(n_bin)
for i in xrange(np.int((j+1)/2)):
p[np.int((j)/2)] = 1.0
for i in xrange(n_bin):
massDistr[i][j] = p[i] + p[j-i-1]
return massDistr
def nonunifBinaryFrag(n_bin):
massDistr = np.zeros((n_bin, n_bin))
for j in xrange(1, n_bin):
for i in xrange(0, n_bin):
if i == j - 1:
massDistr[i,j] = 2.0
return massDistr
def normalFrag(n_bin, lambd = 1):
massDistr = np.empty((n_bin,n_bin))
for j in xrange(n_bin):
p = np.zeros(n_bin)
std = (j+1)/2 / float(lambd)
mean = (j+1)/2
N = stats.norm(loc=mean, scale=std)
for i in xrange(np.int((j+1)/2)):
p[i] = N.cdf(i+1) - N.cdf(i)
# to regulate the distribution to the probability p[i<0] = 1 and sum(p[i>0]) = 1
sump = p.sum()
if sump != 0:
par = 1.0 / sump
else:
par = 2.0
for i in xrange(n_bin):
massDistr[i][j] = par * (p[i] + p[j-i-1])
return massDistr
def nonunifNormalFrag(n_bin, lambd):
massDistr = np.zeros((n_bin, n_bin))
nIntP = 500 #number of integration points
for j in xrange(1, n_bin):
p = np.zeros(n_bin)
std = (v_list[j] / 2) / float(lambd)
mean = v_list[j] / 2
N = stats.norm(loc=mean, scale=std)
for i in xrange(j+1):
if i > 0: #don't do this if i == 0
#chi is the interpolation vector
chi = np.linspace(0.,
1.,
nIntP)
ps = 2*N.pdf(np.linspace(v_list[i-1],
v_list[i],
nIntP))
x = np.linspace(v_list[i-1], v_list[i], nIntP)
#Simpson integration of vector chi * ps
p[i] += si.simps(chi * ps, x)
if i < n_bin-1: #don't do this is i == n_bin
chi = np.linspace(1.,
0.,
nIntP)
ps = 2*N.pdf(np.linspace(v_list[i],
v_list[i+1],
nIntP))
x = np.linspace(v_list[i], v_list[i+1], nIntP)
p[i] += si.simps(chi * ps, x)
# to regulate the distribution to the probability p[i<0] = and sum(p[i>0]) = 1
sump = p.sum()
if sump != 0:
par = 2.0 / sump
for i in xrange(n_bin):
massDistr[i][j] = par * p[i]
return massDistr
def uniformFrag(n_bin):
massDistr = np.empty((n_bin, n_bin))
for j in xrange(n_bin):
p = np.zeros(n_bin)
for i in xrange(np.int((j+1)/2)):
p[i] = 1.0 / np.floor((j+1)/2)
for i in xrange(n_bin):
massDistr[i][j] = p[i] + p[j-i-1]
return massDistr
#def unifDistr(v_j, intPoints): #used in nonunifUniformFrag()
# p = 2.0 / v_j
# ps = p * np.ones_like(intPoints)
# for i in xrange(np.shape(intPoints)[0]):
# if intPoints[i] > v_j:
# ps[i] = 0
# return ps
#def nonunifUniformFrag():
# massDistr = np.zeros((n_bin, n_bin))
# nIntP = 500 #number of integration points
# for j in xrange(1, n_bin):
# p = np.zeros(n_bin)
# unif = 2.0 / v_list[j]
# for i in xrange(j+1):
# if i > 0: #don't do this if i == 0
# #chi is the interpolation vector
# chi = np.linspace(0.,
# 1.,
# nIntP)
## ps = unif * np.ones(nIntP)
# x = np.linspace(v_list[i-1], v_list[i], nIntP)
# ps = unifDistr(v_list[j], x)
# #Simpson integration of vector chi * ps
# p[i] += si.simps(chi * ps, x)
# if i < n_bin-1: #don't do this is i == n_bin
# chi = np.linspace(1.,
# 0.,
# nIntP)
## ps = unif * np.ones(nIntP)
# x = np.linspace(v_list[i], v_list[i+1], nIntP)
# ps = unifDistr(v_list[j], x)
# p[i] += si.simps(chi * ps, x)
# if v_list[i] == v_list[j]/2:
# p[i] += unif
#
## sump = p.sum()
## if sump != 0:
## par = 2.0 / sump
# par = 1
# for i in xrange(n_bin):
# massDistr[i][j] = par * p[i]
# return massDistr
#---------------------------------PBE's----------------------------------------#
def PBE_uniformGrid(y, t, self):
aggregation = np.zeros(self.n_bin)
breakup = np.zeros(self.n_bin)
# Smoluchowski (1917)
if self.isAggregationOn:
creation = np.zeros(self.n_bin)
destruction = np.zeros(self.n_bin)
destruction = -np.dot(np.transpose(self.k_c), y) * y
kyn = self.k_c * y[:,np.newaxis] * y[np.newaxis,:]
for i in xrange(self.n_bin):
creation[i] = np.sum(kyn[np.arange(i), i - np.arange(i) - 1])
creation = 0.5 * creation
aggregation = self.eta * (creation + destruction)
# Pandya & Spielman (1982)
if self.isBreakupOn:
creation = np.zeros(self.n_bin)
destruction = np.zeros(self.n_bin)
destruction = -self.k_b * y
creation = np.dot(self.fragDistr, self.k_b * y)
breakup = creation + destruction
return aggregation + breakup
def PBE_nonuniformGrid(y, t, self):
aggregation = np.zeros(self.n_bin)
breakup = np.zeros(self.n_bin)
# aggregation PBE by Smoluchowski (1917)
creation = np.zeros(self.n_bin)
destruction = np.zeros(self.n_bin)
if self.isAggregationOn:
for i in xrange(self.n_bin):
creation[i] = np.dot(np.dot(self.k_c * self.chi[:, :, i], y), y)
creation = 0.5 * creation
destruction = -np.dot(self.k_c, y) * y
aggregation = self.eta * (creation + destruction)
# breakup PBE by Pandya & Spielman (1982)
if self.isBreakupOn:
creation = np.zeros(self.n_bin)
destruction = np.zeros(self.n_bin)
destruction = -self.k_b * y
creation = np.dot(self.fragDistr, self.k_b * y)
breakup = creation + destruction
return aggregation + breakup
#--------------------------Data process functions------------------------------#
def moment(C_list_ts, v_list, order):
"""Integral moment of the CMD."""
out = np.sum(C_list_ts * v_list**order, axis=1)
return out
def monomer_conservation(M1_ts):
"""Evalluates mass concervation.
Returns [initial monomer, final monomer, final / initial ratio]."""
ini_monomerC = M1_ts[0]
fin_monomerC = M1_ts[-1]
conservation = fin_monomerC / ini_monomerC
results = np.array([ini_monomerC, fin_monomerC, conservation])
return results
def free_monomers(C_list_ts):
"""Concentration of free platelets."""
return C_list_ts[:,0]
def meanV(C_list_ts, v_list):
"""Mean number of platelets per aggregate."""
M0_ts = moment(C_list_ts, v_list, 0)
M1_ts = moment(C_list_ts, v_list, 1)
return M1_ts / M0_ts
def meanR(C_list_ts, v_list, R_list):
"""Mean radius of gyration."""
numerator = np.sum(C_list_ts * R_list, axis=1)
denominator = moment(C_list_ts, v_list, 0)
return numerator / denominator
def rmsR(C_list_ts, v_list, R_list):
"""Root-mean-square radius of gyration"""
numerator = np.sum(C_list_ts * (R_list * v_list)**2, axis=1)
denominator = moment(C_list_ts, v_list, 2)
return np.sqrt(numerator / denominator)
def monomer_distribution(C_list_ts, v_list):
"""Calculates the distribution of monomers in cluster."""
out = C_list_ts * v_list
return out
def PA(C_list_ts):
"""Fraction of aggregated platelets."""
N_t = free_monomers(C_list_ts)
return (1 - N_t/N_t[0])
def PPD(C_list_ts, v_list):
"""Platelet population distribution"""
n_bin = v_list.shape[0]
M1_ts = moment(C_list_ts, v_list, 1)
return C_list_ts * v_list / np.repeat(M1_ts[:,np.newaxis], n_bin, axis=1)
#def fitting_stat(x, y):
# slope, intercept, r, prob2, see = stats.linregress(x, y)
# if len(x) > 2:
# see=see*np.sqrt(len(x)/(len(x)-2.))
# mx = x.mean()
# sx2 = ((x-mx)**2).sum()
# sd_intercept = see * np.sqrt(1./len(x) + mx*mx/sx2)
# sd_slope = see * np.sqrt(1./sx2)
# results=np.zeros(5)
# results[0]=slope
# results[1]=intercept
# results[2]=r
# if len(x) > 2:
# results[3]=sd_slope
# results[4]=sd_intercept
# return results
<file_sep>/README.md
Aggregation-Breakup Equation
============================
The Python code **aggBreakPBE.py** is used to simulate the aggregation and breakup of colloid particles using the Smoluchowski coagulation equation for aggregation and the empirical breakup model of Pandya and Spielman. This code was originally designed for simulating the aggregation of blood platelets, but it can be generalized for any kind of colloid particle without much trouble. Be aware that the code may contain bugs. Please don't hesitate in contacting me if you find any bug.
Aggregation rate is related with the statistical average collision of particles. The collision can occur by Brownian motion, shear flow (gradient of velocity), or by an enhanced diffusion effect caused by the tumbling and rolling of red blood cells under motion. The Sorensen enhanced diffusivity model is used for that.
The class **aggBreak** possesses methods for setting the system up, solving it, processing the data, and saving the simulation case in cvs files for further analysis.
References
==========
1. <NAME>, <NAME>. Versuch einer mathematischen Theorie der Koagulationskinetik kolloider Lösungen. Zeitschrift fuer Phys. Chemie 92, 129–168 (1917).
2. <NAME>. & <NAME>. Floc breakage in agitated suspensions: Effect of agitation rate. Chem. Eng. Sci. 38, 1983–1992 (1983).
3. <NAME>. & <NAME>. On the solution of population balance equations by discretization—I. A fixed pivot technique. Chem. Eng. Sci. 51, 1311–1332 (1996).
4. <NAME>., <NAME>. & <NAME>. Nanoparticle coagulation via a Navier–Stokes/nodal methodology: Evolution of the particle field. J. Aerosol Sci. 37, 555–576 (2006).
5. <NAME>. & <NAME>. Analysis of the aggregation-fragmentation population balance equation with application to coagulation. J. Colloid Interface Sci. 316, 428–41 (2007).
<file_sep>/main.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from aggBreakPBE import *
import numpy as np
import matplotlib.pyplot as plt
#-Plot with LaTeX
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
#---------------------------Simulation Inputs----------------------------------#
abProps = {} # input dictionary of aggregation-breakup properties
# CMD parameters:
abProps['C_p'] = 6e13#3.0e14 # (m-3) absolute monomer concentration
R_p = 1.16e-6 # (m) radius of each monomer
abProps['R_p'] = R_p
abProps['V_p'] = 4./3.*np.pi * R_p**3. # (m3) volume of each monomer
abProps['D_F'] = 2.2 # fractal dimension of aggregates
abProps['v_max'] = 2.**20. #maximum number of monomers in an aggregate
#-Specify the bin structure you want to use: isGridUniform ?
# True ---> v = [1, 2, 3, ..., vmax]
# False ---> v = [1, 2, 4, 8, ..., 2**i <= v_max]
#abProps['isGridUniform'] = True
abProps['isGridUniform'] = False
# PBE parameters:
tmin, tmax, tstep = (0., 2.*60., .1)
abProps['t'] = np.arange(tmin, tmax, tstep) #time vector
abProps['G'] = 250. #shear rate >= 0 (s-1)
# Aggregation parameters:
abProps['eta'] = 0.30 #aggregation efficiency
abProps['aggPhysics'] = [
'shear',
#'Brownian',
#'Sorensenian',
]
abProps['T'] = 310. # (K) blood temperature
abProps['mu'] = 1.3e-3 # (Pa s) plasma viscosity
# Breakup Parameters:
abProps['isBreakupOn'] = True
#abProps['isBreakupOn'] = False
abProps['fragModel'] = 'binary' #aggregate splits in half parts
#abProps['fragModel'] = 'normal' #splits in parts that follow a normal PDF
#abProps['fragModel'] = 'uniform' #splits in parts with the same probability
#abProps['fragModel'] = 'erosion' #aggregate always loses 1 single monomer
# regulates the standard deviation of the normal splitting mass distribution
abProps['lambd'] = 1000
a = 1.8e17
b = 2.0
c = 4.0
Gstar = (a*R_p**c)**(-1./b)
#Gstar = 1000.
abProps['a'] = a
abProps['b'] = b
abProps['c'] = c
abProps['Gstar'] = Gstar
abProps['saveFolder'] = "./outputs/"
abProps['jobName'] = "selfSimilar-Kab=1e-1"
abProps['jobDate'] = str(time.localtime().tm_year) + '-' \
+ str(time.localtime().tm_mon) + '-' \
+ str(time.localtime().tm_mday)
abProps['jobTime'] = str(time.localtime().tm_hour) + ':' \
+ str(time.localtime().tm_min) + ':' \
+ str(time.localtime().tm_sec)
#--------------------------------Run case--------------------------------------#
K_ab = []
PAmax = []
v_mean = []
G = np.linspace(10., 5000., 400)
for Gi in G:
print "G = {0:3g}".format(Gi)
abProps['G'] = Gi
tmin, tmax, tstep = (0., 5.*60., .005)
abProps['t'] = 250./Gi*np.arange(tmin, tmax, tstep) #time vector
ab = aggBreak(abProps)
#ab.printSetup()
ab.solve()
ab.processData()
K_ab.append(ab.K_ab)
PAmax.append(ab.PA_ts[-1])
v_mean.append(ab.v_mean_ts[-1])
del ab
output = pd.DataFrame()
output["K_ab"] = K_ab
output["PAmax"] = PAmax
output["v_mean"] = v_mean
output.to_csv(abProps['saveFolder']+"Kab_PAmax_vMean_c=4"+abProps['jobDate']+abProps['jobTime']+".csv")
plt.plot(K_ab, PAmax, color='black')
plt.plot(K_ab, v_mean, color='black')
plt.ylabel('Fraction of Aggregated Platelets, PA (\%)')
plt.xlabel('$K_{ab}$')
plt.show()
#ab = aggBreak(abProps)
#ab.printSetup()
#ab.solve()
#ab.processData()
##ab.saveOutput()
#------------------------------plot results------------------------------------#
#plt.plot(ab.t, 100. * ab.PA_ts, color='black')
#plt.ylabel('Fraction of Aggregated Platelets, PA (\%)')
#plt.xlabel('Time, t (s)')
#plt.show()
#plt.plot(ab.t, ab.v_mean_ts)
#plt.ylabel('Mean Number of Platelets per Aggregate, \\textlangle v \\textrangle')
#plt.xlabel('Time, t (s)')
#plt.show()
#for i in xrange(ab.n_bin):
# plt.plot(ab.t, 100.*ab.PPD_list_ts[:,i], label='v = ' +str(ab.v_list.astype(int)[i]))
#plt.ylabel('Platelet Population Distribution, \\tilde{C} (\%)')
#plt.xlabel('Time, t (s)')
#plt.legend()
#plt.show()
#plt.loglog(ab.v_list/ab.v_mean_ts[-1], ab.PPD_list_ts[-1], "ko-")
#plt.xlabel('Normalized Number of Platelets per Aggregate, v / \\textlangle v \\textrangle')
#plt.ylabel('Platelet Population Distribution, \\tilde{C} (\%)')
#plt.ylim(ymin=1e-16)
#plt.xlim(1e-3, 1e3)
#plt.grid()
##plt.savefig('./self-similarDistribution.pdf', format='pdf')
#plt.show()
#plt.plot(ab.v_list, 100.*ab.PPD_list_ts[-1], 'ko-')
#plt.axis([1,6,0, 80])
#plt.xlabel('Number of Platelets in Cluster')
#plt.ylabel('Platelet Population Distribution, \\tilde{C} (\%)')
##plt.savefig('PPD.pdf', format='pdf')
#plt.show()
<file_sep>/example.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from aggBreakPBE import *
import numpy as np
import matplotlib.pyplot as plt
import time
#-Plot with LaTeX
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
#---------------------------Simulation Inputs----------------------------------#
abProps = {} # input dictionary of aggregation-breakup properties
abProps['saveFolder'] = "./output/"
abProps['jobName'] = "test"
abProps['jobDate'] = str(time.localtime().tm_year) + '-' \
+ str(time.localtime().tm_mon) + '-' \
+ str(time.localtime().tm_mday)
abProps['jobTime'] = str(time.localtime().tm_hour) + ':' \
+ str(time.localtime().tm_min) + ':' \
+ str(time.localtime().tm_sec)
# CMD parameters:
abProps['C_p'] = 3.0e14 # (m-3) absolute monomer concentration
R_p = 1.16e-6 # (m) radius of each monomer
abProps['R_p'] = R_p
abProps['D_F'] = 2.2 # fractal dimension of aggregates
abProps['v_max'] = 2e3 #maximum number of monomers in an aggregate
#-Specify the bin structure you want to use: isGridUniform ?
# True ---> v = [1, 2, 3, ..., vmax]
# False ---> v = [1, 2, 4, 8, ..., 2**i <= v_max]
#abProps['isGridUniform'] = True
abProps['isGridUniform'] = False
# PBE parameters:
tmin, tmax, tstep = (0., 60., 0.01)
abProps['t'] = np.arange(tmin, tmax, tstep) #time vector
abProps['G'] = 1000. #shear rate >= 0 (s-1)
# Aggregation parameters:
abProps['eta'] = 0.30 #aggregation efficiency
abProps['aggPhysics'] = [
'shear',
#'Brownian',
#'Sorensenian',
]
abProps['T'] = 310. # (K) blood temperature
abProps['mu'] = 1.25e-3 # (Pa s) plasma viscosity
# Breakup Parameters:
abProps['isBreakupOn'] = True
#abProps['isBreakupOn'] = False
abProps['fragModel'] = 'binary' #aggregate splits in half parts
#abProps['fragModel'] = 'normal' #splits in parts that follow a normal PDF
#abProps['fragModel'] = 'uniform' #splits in parts with the same probability
#abProps['fragModel'] = 'erosion' #aggregate always loses 1 single monomer
# regulates the standard deviation of the normal splitting mass distribution
abProps['lambd'] = 1000
a = 1e11
b = 2.0
c = 3.0
Gstar = (a*R_p**c)**(-1./b)
#Gstar = 1000.
abProps['a'] = a
abProps['b'] = b
abProps['c'] = c
abProps['Gstar'] = Gstar
#---------------------Case 1: using above dictionary---------------------------#
ab1 = aggBreak(abProps)
ab1.printSetup()
ab1.solve()
ab1.processData()
#ab1.saveOutput()
plt.plot(ab1.t, 100. * ab1.PA_ts, color='black')
plt.ylabel('Fraction of Aggregated Platelets, PA (\%)')
plt.xlabel('Time, t (s)')
plt.show()
plt.plot(ab1.t, ab1.v_mean_ts)
plt.ylabel('Mean Number of Platelets per Aggregate, \\textlangle v \\textrangle')
plt.xlabel('Time, t (s)')
plt.show()
for i in xrange(ab1.n_bin):
plt.plot(ab1.t, 100.*ab1.PPD_list_ts[:,i], label='v = ' +str(ab1.v_list.astype(int)[i]))
plt.ylabel('Platelet Population Distribution, \\tilde{C} (\%)')
plt.xlabel('Time, t (s)')
plt.legend()
plt.show()
plt.loglog(ab1.v_list/ab1.v_mean_ts[-1], ab1.PPD_list_ts[-1], "ko-")
plt.xlabel('Normalized Number of Platelets per Aggregate, v / \\textlangle v \\textrangle')
plt.ylabel('Platelet Population Distribution, \\tilde{C} (\%)')
plt.ylim(ymin=1e-6)
plt.xlim(1e-3, 1e3)
plt.grid()
plt.show()
plt.plot(ab1.v_list, 100.*ab1.PPD_list_ts[-1], 'ko-')
plt.axis([1, 64, 0, 80])
plt.xlabel('Number of Platelets in Cluster')
plt.ylabel('Platelet Population Distribution, \\tilde{C} (\%)')
plt.show()
#-----------------Case 2: same theta, different conditions---------------------#
abProps2 = abProps.copy()
abProps2['G'] = 500.
a = 2e11
abProps2['Gstar'] = (a*R_p**c)**(-1./b)
ab2 = aggBreak(abProps2)
ab2.printSetup()
ab2.solve()
ab2.processData()
#ab2.saveOutput()
lbl1 = "G = {0:3.0f}, G* = {1:3.0f}, $\\theta$ = {2:.3g}".format(ab1.G,
ab1.Gstar,
ab1.theta)
lbl2 = "G = {0:3.0f}, G* = {1:3.0f}, $\\theta$ = {2:.3g}".format(ab2.G,
ab2.Gstar,
ab2.theta)
plt.plot(ab1.t, 100. * ab1.PA_ts, color='blue', label=lbl1)
plt.plot(ab2.t, 100. * ab2.PA_ts, color='red', label=lbl2)
plt.legend(loc=4)
plt.ylabel('Fraction of Aggregated Platelets, PA (\%)')
plt.xlabel('Time, t (s)')
plt.show()
plt.plot(ab1.t, ab1.v_mean_ts, color='blue', label=lbl1)
plt.plot(ab2.t, ab2.v_mean_ts, color='red', label=lbl2)
plt.legend(loc=4)
plt.ylabel('Mean Number of Platelets per Aggregate, \\textlangle v \\textrangle')
plt.xlabel('Time, t (s)')
plt.show()
del abProps2
del ab2
del lbl2
#----------------Case 3: same conditions of case 1 + Diffusion-----------------#
abProps3B = abProps.copy()
abProps3B['aggPhysics']= ['Brownian',
'shear',
]
ab3B = aggBreak(abProps3B)
ab3B.printSetup()
ab3B.solve()
ab3B.processData()
abProps3S = abProps.copy()
abProps3S['aggPhysics']= ['Sorensenian',
'shear',
]
ab3S = aggBreak(abProps3S)
ab3S.printSetup()
ab3S.solve()
ab3S.processData()
lbl1 = "Shear alone, G = {0:3.0f}, Pe = {1:1.3g}".format(ab1.G, ab1.Pe)
lbl3B = "Shear + Brownian, G = {0:3.0f}, Pe = {1:1.3g}".format(ab3B.G, ab3B.Pe)
lbl3S = "Shear + Sorensenian, G = {0:3.0f}, Pe = {1:1.3g}".format(ab3S.G,
ab3S.Pe)
plt.plot(ab1.t, 100. * ab1.PA_ts, color='blue', label=lbl1)
plt.plot(ab3B.t, 100. * ab3B.PA_ts, color='red', label=lbl3B)
plt.plot(ab3S.t, 100. * ab3S.PA_ts, color='green', label=lbl3S)
plt.legend(loc=4)
plt.ylabel('Fraction of Aggregated Platelets, PA (\%)')
plt.xlabel('Time, t (s)')
plt.show()
plt.plot(ab1.t, ab1.v_mean_ts, color='blue', label=lbl1)
plt.plot(ab3B.t, ab3B.v_mean_ts, color='red', label=lbl3B)
plt.plot(ab3S.t, ab3S.v_mean_ts, color='green', label=lbl3S)
plt.legend(loc=4)
plt.ylabel('Mean Number of Platelets per Aggregate, \\textlangle v \\textrangle')
plt.xlabel('Time, t (s)')
plt.show()
del abProps3B
del ab3B
del lbl3B
#----------Case 4: same theta comparing effect of Sorensenian collision--------#
abProps4S = abProps3S.copy()
abProps4S['G']= 100.
a = 1005640024739.8469
abProps4S['Gstar'] = (a*R_p**c)**(-1./b)
ab4S = aggBreak(abProps4S)
ab4S.printSetup()
ab4S.solve()
ab4S.processData()
abProps4lt1 = abProps3S.copy()
abProps4lt1['G']= 500.
a = 2.001e10
abProps4lt1['Gstar'] = (a*R_p**c)**(-1./b)
ab4lt1 = aggBreak(abProps4lt1)
ab4lt1.printSetup()
ab4lt1.solve()
ab4lt1.processData()
abProps4lt2 = abProps3S.copy()
abProps4lt2['G']= 1000.
a = 1e10
abProps4lt2['Gstar'] = (a*R_p**c)**(-1./b)
ab4lt2 = aggBreak(abProps4lt2)
ab4lt2.printSetup()
ab4lt2.solve()
ab4lt2.processData()
time.sleep(1)
lbl3S = "G = {0:3.0f}, G* = {2:3.0f}, Pe = {1:1.3g}, $\\theta$ = {3:.3g}".format(ab3S.G, ab3S.Pe, ab3S.Gstar, ab3S.theta)
lbl4S = "G = {0:3.0f}, G* = {2:3.0f}, Pe = {1:1.3g}, $\\theta$ = {3:.3g}".format(ab4S.G, ab4S.Pe, ab4S.Gstar, ab4S.theta)
lbl4lt1 = "G = {0:3.0f}, G* = {2:3.0f}, Pe = {1:1.3g}, $\\theta$ = {3:.3g}".format(ab4lt1.G, ab4lt1.Pe, ab4lt1.Gstar, ab4lt1.theta)
lbl4lt2 = "G = {0:3.0f}, G* = {2:3.0f}, Pe = {1:1.3g}, $\\theta$ = {3:.3g}".format(ab4lt2.G, ab4lt2.Pe, ab4lt2.Gstar, ab4lt2.theta)
plt.plot(ab3S.t, 100. * ab3S.PA_ts, color='blue', label=lbl3S)
plt.plot(ab4S.t, 100. * ab4S.PA_ts, color='red', label=lbl4S)
plt.plot(ab4lt1.t, 100. * ab4lt1.PA_ts, color='green', label=lbl4lt1)
plt.plot(ab4lt2.t, 100. * ab4lt2.PA_ts, color='magenta', label=lbl4lt2)
plt.legend(loc=4)
plt.ylabel('Fraction of Aggregated Platelets, PA (\%)')
plt.xlabel('Time, t (s)')
plt.show()
plt.plot(ab3S.t, ab3S.v_mean_ts, color='blue', label=lbl3S)
plt.plot(ab4S.t, ab4S.v_mean_ts, color='red', label=lbl4S)
plt.plot(ab4lt1.t, ab4lt1.v_mean_ts, color='green', label=lbl4lt1)
plt.plot(ab4lt2.t, ab4lt2.v_mean_ts, color='magenta', label=lbl4lt2)
plt.legend(loc=5)
plt.ylabel('Mean Number of Platelets per Aggregate, \\textlangle v \\textrangle')
plt.xlabel('Time, t (s)')
plt.show()
plt.loglog(ab3S.v_list/ab3S.v_mean_ts[-1], ab3S.PPD_list_ts[-1],
"bs-", label=lbl3S)
plt.loglog(ab4S.v_list/ab4S.v_mean_ts[-1], ab4S.PPD_list_ts[-1],
"ro--", label=lbl4S)
plt.loglog(ab4lt1.v_list/ab4lt1.v_mean_ts[-1], ab4lt1.PPD_list_ts[-1],
"gs-", label=lbl4lt1)
plt.loglog(ab4lt2.v_list/ab4lt2.v_mean_ts[-1], ab4lt2.PPD_list_ts[-1],
"mo--", label=lbl4lt2)
plt.xlabel('Normalized Number of Platelets per Aggregate, v / \\textlangle v \\textrangle')
plt.legend(loc=3)
plt.ylabel('Platelet Population Distribution, \\tilde{C} (\%)')
plt.ylim(ymin=1e-6)
plt.xlim(1e-3, 1e3)
plt.grid()
plt.show()
plt.plot(ab3S.v_list, 100.*ab3S.PPD_list_ts[-1], "bs-", label=lbl3S)
plt.plot(ab4S.v_list, 100.*ab4S.PPD_list_ts[-1], "ro--", label=lbl4S)
plt.plot(ab4lt1.v_list, 100.*ab4lt1.PPD_list_ts[-1], "gs-", label=lbl4lt1)
plt.plot(ab4lt2.v_list, 100.*ab4lt2.PPD_list_ts[-1], "mo--", label=lbl4lt2)
plt.axis([1, 64, 0, 80])
plt.legend(loc=1)
plt.xlabel('Number of Platelets in Cluster')
plt.ylabel('Platelet Population Distribution, \\tilde{C} (\%)')
plt.show()
del abProps3S, abProps4lt1, abProps4lt2
del ab3S, ab4S, ab4lt1, ab4lt2
|
25073805495af31415e861443e532a9fa28ab64a
|
[
"Markdown",
"Python"
] | 5 |
Python
|
edelperi/aggBreakPBE
|
a0666a3db954a9954d0856458afe161fb9967c15
|
93c3c8fc58600874ed3a7d6d289b91d29e961a8e
|
refs/heads/master
|
<repo_name>niagr/mission-plan<file_sep>/backend/missioncontrol/api.py
import jwt
import requests
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.middleware.csrf import rotate_token
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.response import Response as DRFResponse
from rest_framework.views import APIView
from .models import Task, Board, User
class APIResponse(DRFResponse):
"""All API responses must use this class instead of Response"""
def __init__(self, *, data=None, user_msg=None, cookies=None, **kwargs):
data = data or {}
if user_msg:
data['userMsg'] = user_msg
super().__init__(data=data, **kwargs)
cookies = cookies or []
for cookie in cookies:
self.set_cookie(**cookie)
@api_view(['GET'])
def health_check(request):
return APIResponse(status=200)
@api_view(['POST'])
@authentication_classes([])
@permission_classes([])
def github_login(request):
"""
Get's a user's Github email, creates a new user or retrieves the existing user,
and creates a JWT for the user. It also creates a new CSRF token and sets the cookie for it.
The JWT is set as an httponly cookie.
Accepts the Github OAuth authorization code and the state token we sent it.
"""
code = request.POST.get('code')
state = request.POST.get('state')
if not (code and state):
return APIResponse(status=400, user_msg="The 'code' and 'state' params are required.")
# Fetch the OAuth access token
resp = requests.post('https://github.com/login/oauth/access_token',
data={'client_id': settings.GITHUB_OAUTH_CLIENT_ID,
'client_secret': settings.GITHUB_OAUTH_CLIENT_SECRET,
'code': code,
'state': state},
headers={'Accept': 'application/json'})
data = resp.json()
access_token = data.get('access_token')
# Use access token to fetch user email
resp = requests.get(f'https://api.github.com/user/emails?access_token={access_token}')
data = resp.json()
email = data[0].get('email')
# Get or create user with corresponding email
user = User.objects.filter(username=email, email=email).first()
if not user:
user = User.objects.create_user(username=email, email=email)
# create JWT
token = jwt.encode({'id': user.id, 'email': user.email}, settings.SECRET_KEY)
# We create a new CSRF token (which is set in a cookie automatically by CSRFViewMiddleware).
rotate_token(request)
# Set JWT as an httponly cookie
return APIResponse(status=200, cookies=[{'key': 'authToken', 'value': token.decode(), 'httponly': True}])
class TaskListAPIView(APIView):
@staticmethod
def get(request, board_id):
"""
Get list of tasks
:return APIResponse 200 Array of task objects
"""
tasks = Board.get_tasks(board_id)
return APIResponse(status=200, data={'tasks': [t.to_json() for t in tasks]})
@staticmethod
def post(request, board_id):
"""
Create new task
:return: APIResponse:
200 The new task object
400 Wrong params
"""
name = request.POST.get('name')
desc = request.POST.get('desc')
if not all([name, desc]):
return APIResponse(status=400, user_msg="'name' and 'desc' params are required.")
try:
new_task = Task.create_task(board_id, name, desc)
except ObjectDoesNotExist:
return APIResponse(status=404, user_msg=f'Board with ID {board_id} not found')
return APIResponse(status=201, data={'task': new_task.to_json()}, user_msg='Task created.')
class TaskAPIView(APIView):
@staticmethod
def get(request, board_id, task_id):
"""
Gets the task with the specified ID
:param task_id: ID of the task to retrieve
:return: APIResponse:
200 The task object
404 If the task with specified ID does not exist
"""
try:
task = Task.objects.get(id=task_id)
return APIResponse(status=200, data={'task': task.to_json()})
except ObjectDoesNotExist:
return APIResponse(status=404, user_msg='Task not found')
@staticmethod
def put(request, board_id, task_id):
"""
Modify a task.
POST params: name, desc, status
:param task_id: ID of the task to modify
:return: APIResponse:
200 The updated task
400 Wrong params
404 If the task with specified ID does not exist
"""
name = request.data.get('name')
desc = request.data.get('desc')
status = request.data.get('status')
if status and not Task.is_status_valid(status):
return APIResponse(status=400, user_msg=f"'{status}' is not a valid status")
try:
task = Task.update_task_by_id(task_id, name=name, desc=desc, status=status)
except ObjectDoesNotExist:
return APIResponse(status=404, user_msg='Task not found')
return APIResponse(status=200, data={'task': task.to_json()}, user_msg='Task updated.')
class BoardListAPIView(APIView):
@staticmethod
def post(request):
name = request.POST.get('name')
if not name:
return APIResponse(status=400, user_msg="The 'name' param is required")
name = name.lower()
if not Board.is_name_valid(name):
return APIResponse(status=400, user_msg="Invalid name. Board names may contain a-z, 0-9, and a '-' (hyphen)"
" anywhere between the first and last characters ")
try:
board = Board.create_board(name=name)
except Board.DuplicateError:
return APIResponse(status=400, user_msg="A board with this name already exists")
return APIResponse(status=201, user_msg="Board created successfully", data=board.to_json())
@staticmethod
def get(request):
boards = Board.get_all_boards()
return APIResponse(status=200, data={'boards': [b.to_json() for b in boards]})
class BoardAPIView(APIView):
@staticmethod
def get(request, board_id):
try:
board = Board.get_board(board_id)
return APIResponse(status=200, data=board.to_json())
except ObjectDoesNotExist:
return APIResponse(status=404, user_msg=f'No board with ID {board_id} found')
<file_sep>/backend/missioncontrol/authentication.py
import jwt
from django.conf import settings
from rest_framework.authentication import BaseAuthentication, CSRFCheck
from rest_framework.exceptions import AuthenticationFailed, PermissionDenied
from .models import User
class JWTTokenAuthentication(BaseAuthentication):
model = None
def get_model(self):
return User
def authenticate(self, request):
token = request.COOKIES.get('authToken')
self.enforce_csrf(request)
if not token:
raise AuthenticationFailed('No auth token found in cookies')
try:
payload = jwt.decode(token, settings.SECRET_KEY)
email = payload['email']
userid = payload['id']
user = User.objects.get(email=email,
id=userid,
is_active=True)
except (jwt.ExpiredSignature, jwt.DecodeError, jwt.InvalidTokenError, jwt.exceptions.InvalidSignatureError):
raise AuthenticationFailed('Invalid auth token')
except User.DoesNotExist:
raise AuthenticationFailed('No such user')
return user, token
def enforce_csrf(self, request):
"""
Enforce CSRF validation for session based authentication.
"""
reason = CSRFCheck().process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise PermissionDenied('CSRF Failed: %s' % reason)
<file_sep>/frontend/src/services/api.ts
import * as Cookies from 'js-cookie'
import { Task } from "types";
enum METHOD {
POST = 'POST',
GET = 'GET',
PUT = 'PUT',
DELETE = 'DELETE',
}
export class APIError extends Error {
userMsg: string
data: any
constructor (userMsg='', data=null) {
super(userMsg)
this.userMsg = userMsg
this.data = data
}
}
class APIService {
rootUrl = `${process.env.API_URL}/api`
defaultErrMsg = 'Something went wrong'
_fillFormData (data: {[k: string]: string}) {
const formData = new FormData()
for (let [key, val] of Object.entries(data)) {
formData.append(key, val)
}
return formData
}
async _apiCall (method: METHOD, url: string, data={}) {
try {
const response = await fetch(this.rootUrl + url, {
method,
credentials: 'include',
body: [METHOD.POST, METHOD.PUT].includes(method) ? this._fillFormData(data) : undefined,
headers: {'X-CSRFToken': Cookies.get('csrftoken') || ''}
})
const respData = await response.json()
respData.userMsg = respData.userMsg || this.defaultErrMsg
if (response.ok) {
return respData
} else {
throw new APIError(respData.userMsg, respData)
}
} catch (e) {
// catch network errors and JSON parse errors
if (e instanceof TypeError || e instanceof SyntaxError) {
throw new APIError(this.defaultErrMsg)
} else {
throw e
}
}
}
async login (authCode: string, state: string) {
const resp = await fetch(this.rootUrl + '/login/github/', {
method: METHOD.POST,
body: this._fillFormData({code: authCode, state: state}),
credentials: 'include'
})
if (resp.ok) {
return true
} else {
return false
}
}
async getBoards () {
return (await this._apiCall(METHOD.GET, '/boards/')).boards
}
async getTasks (boardId: number) {
const tasks = (await this._apiCall(METHOD.GET, `/board/${boardId}/tasks/`)).tasks
return tasks
}
async getTask (boardId: number, taskId: number) {
return (await this._apiCall(METHOD.GET, `/board/${boardId}/task/${taskId}/`)).task
}
async changeTask (boardId: number, taskId: number, taskData: Partial<Task>) {
return (await this._apiCall(METHOD.PUT, `/board/${boardId}/task/${taskId}/`, taskData)).task
}
}
export const apiService = new APIService()
<file_sep>/backend/missioncontrol/migrations/0001_initial.py
# Generated by Django 2.1.2 on 2018-10-24 19:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Board',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.TextField(unique=True)),
],
),
migrations.CreateModel(
name='Task',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.TextField()),
('description', models.TextField()),
('status', models.CharField(choices=[('PENDING', 'PENDING'), ('IN_PROGRESS', 'IN_PROGRESS'), ('REVIEW', 'REVIEW'), ('DONE', 'DONE')], default='PENDING', max_length=20)),
('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tasks', to='missioncontrol.Board')),
],
),
]
<file_sep>/frontend/webpack.base.js
/* global require module __dirname */
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
function createConfig (options={}) {
const {
outputFilename = 'bundle.js',
fileOutputName = '[name].[ext]',
...merge // extra top-level keys to merge into the config
} = options
return {
entry: ['./src/index.tsx'],
output: {
filename: outputFilename,
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
modules: [path.join(__dirname, 'src'), 'node_modules'],
},
module: {
rules: [
{
test: /\.tsx?$|\.jsx?$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.(css|sass|scss)$/,
use: [
'style-loader',
'css-loader',
]
},
{
test: /\.(png|jpg|gif|svg|woff|woff2|eot|ttf|otf)$/,
use: [
{
loader: 'file-loader',
options: {
name: fileOutputName,
outputPath: 'assets/'
}
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
}),
new webpack.EnvironmentPlugin({
API_URL: 'http://localhost:8000',
}),
// new BundleAnalyzerPlugin(),
],
...merge
}
}
module.exports = {
createConfig: createConfig,
}
<file_sep>/backend/missioncontrol/settings_prod.py
from .settings import *
from .settings import REST_FRAMEWORK as REST_FRAMEWORK_COMMON
DEBUG = False
REST_FRAMEWORK = {
**REST_FRAMEWORK_COMMON,
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}<file_sep>/backend/missioncontrol/urls.py
"""missioncontrol URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from missioncontrol import api
board_api_urls = [
path('', api.BoardAPIView.as_view()),
path('tasks/', api.TaskListAPIView.as_view()),
path('task/<str:task_id>/', api.TaskAPIView.as_view()),
]
api_urls = [
path('boards/', api.BoardListAPIView.as_view()),
path('board/<int:board_id>/', include(board_api_urls)),
path('login/github/', api.github_login),
]
urlpatterns = [
path('healthcheck', api.health_check),
path('admin', admin.site.urls),
path('api/', include(api_urls))
]
<file_sep>/README.md
# mission-plan
A tool to manage and track tasks in a team
<file_sep>/backend/requirements.txt
Django==2.1.2
django-cors-headers==2.4.0
djangorestframework==3.8.2
psycopg2==2.7.5
PyJWT==1.6.4
pytz==2018.5
requests==2.20.0
<file_sep>/frontend/webpack.prod.js
const {createConfig} = require('./webpack.base')
module.exports = createConfig({
mode: 'production',
outputFilename: 'bundle.[contenthash].js',
fileOutputName: '[name].[hash].[ext]'
})
<file_sep>/frontend/src/types.ts
export type anyobject = {[key: string] : any}
export enum STATUS {
PENDING = 'PENDING',
IN_PROGRESS = 'IN_PROGRESS',
REVIEW = 'REVIEW',
DONE = 'DONE'
}
export interface Task {
id: number
name: string
desc: string
status: STATUS
}
export interface Board {
id: string
name: string
}
export interface State {
statusColumns: STATUS[]
boards: Board[]
tasks: Task[]
currentBoard?: Board
error: string | undefined
}
// Omit taken from https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;<file_sep>/backend/missioncontrol/models.py
import re
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models, IntegrityError
class Board(models.Model):
name = models.TextField(unique=True)
class DuplicateError(IntegrityError):
pass
@staticmethod
def is_name_valid(name):
m = re.match(r'^[a-z0-9][a-z0-9\-]+[a-z0-9]$', name)
if m is None:
return False
else:
return True
@classmethod
def create_board(cls, name):
if cls.is_name_valid(name):
try:
return cls.objects.create(name=name)
except IntegrityError as ex:
if 'UNIQUE constraint failed' in str(ex):
raise cls.DuplicateError from ex
else:
raise
else:
raise ValidationError('Invalid name')
@classmethod
def get_board(cls, board_id):
return cls.objects.get(id=board_id)
@classmethod
def get_all_boards(cls):
return cls.objects.all()
@classmethod
def get_tasks(cls, board_id):
return cls.get_board(board_id).tasks.all()
def to_json(self):
return {'id': self.id,
'name': self.name}
class BoardAccess(models.Model):
user = models.OneToOneField(to=User, on_delete=models.CASCADE)
board = models.ForeignKey(to=Board, on_delete=models.CASCADE)
@classmethod
def give_user_access_to_board(cls, user: User, board: Board):
cls.objects.create(user=user, board=board)
class Task(models.Model):
STATUS_PENDING = 'PENDING'
STATUS_IN_PROGRESS = 'IN_PROGRESS'
STATUS_REVIEW = 'REVIEW'
STATUS_DONE = 'DONE'
STATUS_CHOICES = {STATUS_PENDING: 'PENDING',
STATUS_IN_PROGRESS: 'IN_PROGRESS',
STATUS_REVIEW: 'REVIEW',
STATUS_DONE: 'DONE'}
board = models.ForeignKey(to=Board, on_delete=models.CASCADE, related_name='tasks')
name = models.TextField()
description = models.TextField()
status = models.CharField(max_length=20, choices=tuple(STATUS_CHOICES.items()), default=STATUS_PENDING)
class DuplicateError(IntegrityError):
pass
@classmethod
def is_status_valid(cls, status):
return status in cls.STATUS_CHOICES
@classmethod
def create_task(cls, board_id, name, desc):
board = Board.get_board(board_id)
return cls.objects.create(name=name, description=desc, board=board)
@classmethod
def get_task(cls, task_id):
return cls.objects.get(id=task_id)
@classmethod
def update_task(cls, task, *, name=None, desc=None, status=None):
if status:
if not cls.is_status_valid(status):
raise ValidationError('Invalid status')
task.status = status
if name:
task.name = name
if desc:
task.description = desc
task.save()
return task
@classmethod
def update_task_by_id(cls, task_id, **kwargs):
task = cls.get_task(task_id)
return cls.update_task(task, **kwargs)
def to_json(self):
return {'id': self.id,
'name': self.name,
'desc': self.description,
'status': self.status}
<file_sep>/backend/missioncontrol/settings_local.py
from .settings import *
GITHUB_OAUTH_CLIENT_ID = os.environ.get('GITHUB_OAUTH_CLIENT_ID', '50b5c3bbfe1a09d6ecf3')
GITHUB_OAUTH_CLIENT_SECRET = os.environ.get('GITHUB_OAUTH_CLIENT_SECRET', '3e8d0bd48a003c11c018d3217b9628bacec0370d')
<file_sep>/frontend/src/util.js
function handleError(err, ...errClasses) {
if (!errClasses.some(cls => err instanceof cls)) {
throw err
}
}<file_sep>/backend/missioncontrol/services/__init__.py
from django.core.exceptions import ObjectDoesNotExist
from django.db import IntegrityError
from missioncontrol.models import Task
def get_tasks(board_id):
tasks = Task.objects.filter(board_id=board_id)
return [t.to_json() for t in tasks]
def create_task(board_id, name, desc):
return Task.objects.create(name=name, description=desc, board_id=board_id).to_json()
class TaskStatusError(Exception):
pass
def change_task_status(task_id, to_status):
if to_status not in Task.STATUS_CHOICES:
raise TaskStatusError(f"'{to_status}' is not a valid status")
try:
task = Task.objects.get(id=task_id)
except ObjectDoesNotExist as ex:
raise TaskStatusError(f'Task with ID "{task_id}" not found') from ex
task.status = to_status
task.save()<file_sep>/frontend/src/modules.d.ts
declare module '*.png' {
const s: string
export default s
}
|
a170784db8df38786e774e493b7e0de1dda6bfa8
|
[
"JavaScript",
"Markdown",
"Python",
"Text",
"TypeScript"
] | 16 |
Python
|
niagr/mission-plan
|
9bec430104f59cc6872a2b3490e8dbbce393a224
|
f5eaecb81b1d57184ee901670ba9dcfa9b08fbbe
|
refs/heads/master
|
<repo_name>Lewuathe/tf-cluster<file_sep>/docker-compose.yml
version: "3.3"
services:
worker0:
image: lewuathe/tf-cluster
command: ["--job", "worker", "--task", "0"]
ports:
- "2222:2222"
volumes:
- ./config:/srv/tf-cluster/config
container_name: worker0
worker1:
image: lewuathe/tf-cluster
command: ["--job", "worker", "--task", "1"]
ports:
- "2223:2222"
volumes:
- ./config:/srv/tf-cluster/config
container_name: worker1
worker2:
image: lewuathe/tf-cluster
command: ["--job", "worker", "--task", "2"]
ports:
- "2224:2222"
volumes:
- ./config:/srv/tf-cluster/config
container_name: worker2
ps0:
image: lewuathe/tf-cluster
command: ["--job", "ps", "--task", "0"]
ports:
- "2225:2222"
volumes:
- ./config:/srv/tf-cluster/config
container_name: ps0
ps1:
image: lewuathe/tf-cluster
command: ["--job", "ps", "--task", "1"]
ports:
- "2226:2222"
volumes:
- ./config:/srv/tf-cluster/config
container_name: ps1
<file_sep>/Makefile
all: build
build:
docker build -t lewuathe/tf-cluster .
run:
docker-compose up -d
down:
docker-compose down
docker-compose rm
push: build
docker push lewuathe/tf-cluster
<file_sep>/job.py
import json
import tensorflow as tf
tf.flags.DEFINE_string(
'job', 'worker', 'Specify job type in your cluster spec'
)
tf.flags.DEFINE_integer(
'task', 0, 'Specify task with 0-based index'
)
FLAGS = tf.flags.FLAGS
def main(argv):
with open('./config/cluster_spec.json') as f:
spec = json.load(f)
cluster = tf.train.ClusterSpec(spec)
print("job_name: {}, task_index: {}".format(FLAGS.job, FLAGS.task))
server = tf.train.Server(cluster, job_name=FLAGS.job, task_index=FLAGS.task)
server.join()
if __name__ == '__main__':
tf.app.run()<file_sep>/README.md
tf-cluster [](https://travis-ci.org/Lewuathe/tf-cluster) [](https://hub.docker.com/r/lewuathe/tf-cluster/)
===
TensorFlow distributed cluster on Docker
## Usage
Launch a cluster by using docker compose
```
$ make run
```
Shutdown cluster
```
$ make down
```
## Example
```
$ python example/tf_dist_sample.py
Start session
[[ 3 10 21]
[ 6 15 28]]
```<file_sep>/Dockerfile
FROM tensorflow/tensorflow
MAINTAINER lewuathe
USER root
RUN mkdir -p /srv/tf-cluster
RUN mkdir /srv/tf-cluster/config
ADD job.py /srv/tf-cluster
EXPOSE 2222
WORKDIR /srv/tf-cluster
ENTRYPOINT ["python", "job.py"]
<file_sep>/example/tf_dist_sample.py
#!/usr/bin/env python
import sys
import json
import tensorflow as tf
def run_job():
with open('./config/cluster_spec.json') as f:
cluster_spec = json.load(f)
with tf.device('/job:ps/task:0'):
v = tf.Variable([1,2,3], dtype=tf.int32)
with tf.device('/job:worker/task:0'):
c = tf.constant([2,3,4])
x = v + c
with tf.device('/job:worker/task:1'):
ret = x * tf.constant([[1,2,3], [2,3,4]])
with tf.Session("grpc://localhost:2222") as sess:
init = tf.global_variables_initializer()
sess.run(init)
print("Start session")
res = sess.run(ret)
print(res)
if __name__ == '__main__':
run_job()
|
6345ffcc83b67622b79b8b9aa8e229fcf82f4c76
|
[
"YAML",
"Markdown",
"Makefile",
"Python",
"Dockerfile"
] | 6 |
YAML
|
Lewuathe/tf-cluster
|
70c2e2fee24775f4e861d7bf282de0dcb92fa281
|
c3d8fb5b42a892d878165cc41193f950114025d6
|
refs/heads/master
|
<file_sep>---
title: <NAME>
layout: default
---
http://personalskynet.blogspot.com/
* Hey Some scripts!
[de-provision Node Script](deprovision-node)
<file_sep>#!/usr/bin/python
# Name: deprovision-node
# Purpose: deprovision nodes from IT infrastructure and tools
# Version: 1.0
# <NAME>
# 1.30.2012
# Harvard University
#
## Links
# https://github.com/cobbler/cobbler/wiki/XMLRPC
# https://access.redhat.com/knowledge/docs/Red_Hat_Network/API_Documentation
#
## ToDo
# Puppet Certs
# Puppet DB
# /usr/share/puppet/ext/puppetstoredconfigclean.rb
# Func Certs
# Remove from kerberos
# RHN
# DNS
# Monitoring ( maybe be handled by Puppet DB)
#
import xmlrpclib
import sys, subprocess
import getpass
import argparse
import json
COBBLERURL = 'https://puppet.noc.harvard.edu/cobbler_api'
RHNURL = 'https://rhn.redhat.com/rpc/api'
parser = argparse.ArgumentParser(description='Deprovision a node (server) from service. This script allows you to list and remove nodes from managed resources and tools such as Cobbler, Puppet, Func and RedHat Network. NOTE: For any "clean" option you MUST define a node to be cleaned with the --node argument',
epilog='Example: deprovision-node --node foo.example.com ')
parser.add_argument('--node', dest='node', action='store', metavar='<name>',
help='Node name (Normally FQDN)')
parser.add_argument('--clean-all', dest='cleanall', action='store_true',
help='Remove Node from ALL Resources')
parser.add_argument('--clean-certs', dest='cleancerts', action='store_true',
help='Remove Certs from Puppet')
parser.add_argument('--clean-cobbler', dest='cleancobbler', action='store_true',
help='Remove Node from Cobbler')
parser.add_argument('--clean-rhn', dest='cleanrhn', action='store_true',
help='Remove Node from RHN (Defaults to Group: UNSG)')
parser.add_argument('--clean-puppetdb', dest='cleanpuppetdb', action='store_true',
help='Remove Node from Puppet Stored Configs DB')
parser.add_argument('--clean-func', dest='cleanfunc', action='store_true',
help='Remove Node from func/certmaster')
parser.add_argument('--rhn-list', dest='rhnlist', action='store_true',
help='List Servers in RHN (Defaults to Group: UNSG)')
parser.add_argument('--cobbler-list', dest='cobblerlist', action='store_true',
help='List Servers in Cobbler')
args = parser.parse_args()
def rhnservers(url):
SATELLITE_URL = url
SATELLITE_LOGIN = raw_input('RHN Account?: ')
SATELLITE_PASSWORD = <PASSWORD>(prompt='RHN Password?: ')
client = xmlrpclib.Server(SATELLITE_URL, verbose=0)
key = client.auth.login(SATELLITE_LOGIN, SATELLITE_PASSWORD)
list = client.systemgroup.listSystems(key, 'UNSG')
servers = {}
#Load RHN Data into a dict for later use
for group in list:
sysname = group.get('name')
sysid = group.get('id')
servers[sysname] = sysid
if args.rhnlist == True:
servernames = sorted(servers.keys())
for name in servernames:
print name
if args.cleanrhn == True and args.node != None:
id = int(servers[args.node])
print '#### Removing Node "' + args.node +'" from RHN ####'
client.system.deleteSystems(key,id)
client.auth.logout(key)
def listcobbler(url):
server = xmlrpclib.Server(url)
list = server.get_systems()
for node in list:
print node['name']
def cleancobbler(url):
COBBLER_LOGIN = raw_input('Cobbler Account?: ')
COBBLER_PASSWORD = <PASSWORD>(prompt='Cobbler Password?: ')
server = xmlrpclib.Server(url)
token = server.login(COBBLER_LOGIN, COBBLER_PASSWORD)
print '#### Removing Node from "' + args.node +'" Cobbler ####'
server.remove_system(args.node,token,False)
def cleancerts():
CMD = '/usr/bin/puppet cert clean '
CLEANCMD = CMD + args.node
print '#### Removing Node Cert from Puppet ####'
subprocess.call( CLEANCMD, shell=True )
def cleanfunc():
# This is just a ugly,ugly hack but hopefully we'll replace func with
# mcollective soon. The right way to do this would be with the python api
CMD = '/usr/bin/certmaster-ca --clean '
CLEANCMD = CMD + args.node
print '#### Removing Node Cert from func/certmaster ####'
subprocess.call( CLEANCMD, shell=True )
def cleanpuppetdb():
#CMD = '/bin/ls -l '
CMD = '/usr/share/puppet/ext/puppetstoredconfigclean.rb '
CLEANCMD = CMD + args.node
print args.node
print CLEANCMD
print '#### Removing Node from Puppet DB ####'
subprocess.call( CLEANCMD, shell=True )
def main():
# If called with no args print help
if len(sys.argv) < 2:
parser.print_help()
sys.exit(1)
# List Nodes
if args.rhnlist == True:
rhnservers(RHNURL)
sys.exit(0)
if args.cobblerlist == True:
listcobbler(COBBLERURL)
sys.exit(0)
# Clean Nodes
if args.cleanall == True and args.node != None:
print '#### Cleaning Node from ALL resources ####'
args.cleanrhn = True
rhnservers(RHNURL)
cleancobbler(COBBLERURL)
cleancerts()
cleanfunc()
cleanpuppetdb()
sys.exit(0)
if args.cleanpuppetdb == True and args.node != None:
cleanpuppetdb()
sys.exit(0)
if args.cleancerts == True and args.node != None:
cleancerts()
sys.exit(0)
if args.cleanfunc == True and args.node != None:
cleanfunc()
sys.exit(0)
if args.cleancobbler == True and args.node != None:
cleancobbler(COBBLERURL)
sys.exit(0)
if args.cleanrhn == True and args.node != None:
rhnservers(RHNURL)
sys.exit(0)
else:
parser.print_help()
main()
|
1378821212bd5dbac7f39a19b4e85b014402c961
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
melodie11/crimsonfu.github.com
|
be6eedfb0fe6df52343b031bc58b71c6463775bb
|
6933a06ef1aa86a6b04426b0e1e76966a8a5699b
|
refs/heads/master
|
<file_sep>def printBoard(chilli):
print(chilli['topl'] + '|' + chilli['topm'] + '|' + chilli['topr'])
print('------')
print(chilli['midl'] + '|' + chilli['midm'] + '|'+ chilli['midr'])
print('------')
print(chilli['lowl'] + '|' + chilli['lowm'] + '|' + chilli['lowr'])
theBoard = {'topl':' ','topm':' ','topr':' ', 'midl':' ', 'midm':' ', 'midr':' ', 'lowl':' ', 'lowm' :' ', 'lowr':' '}
printBoard(theBoard)
|
ad0b703409cc03dc43318fd134b06797643f03c3
|
[
"Python"
] | 1 |
Python
|
Silva-Shadow/newbie
|
5ee14ece6f3a4b2c5d311f6e6921758b4a235efe
|
616c980727048369b7cfc03b90c2f789adc81b2e
|
refs/heads/master
|
<repo_name>adam0000345/FinancialApplication<file_sep>/app/src/main/java/com/example/finance/googlesheetsexample/util/Keys.java
package com.example.finance.googlesheetsexample.util;
public class Keys {
//need to inspect below to see if needs to be removed
public static final String KEY_ENTRY = "entry";
public static final String KEY_YEAR = "year";
public static final String KEY_CFTOEQUITY = "cftoequity";
public static final String KEY_DIFFERENCE = "int(1-t)";
public static final String KEY_CFTOFIRM = "cftofirm";
public static final String KEY_TERMINALCFTOEQUITY = "terminalcftoequity";
public static final String KEY_TERMINALDIFFERENCE = "terminalint(1-t)";
public static final String KEY_TERMINALCFTOFIRM = "terminalcftofirm";
public static final String KEY_STOCKSYMBOL = "stocktickersymbol";
public static final String KEY_MODELTYPE= "modeltype";
}
<file_sep>/app/src/main/java/com/example/finance/googlesheetsexample/WACCDetailedPageResults.java
package com.example.finance.googlesheetsexample;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class WACCDetailedPageResults extends FirstScreenToShowMenu {
private double CurrentYearRevenue;
private double TaxRate;
private double CostOfGoodsSold;
private double CostOfGoodsSoldPercentage;
private double GrossProfit;
private double SellingGeneralAdministrativeExpensesAsPercentageOfRevenue;
private double InitialEBITPercentageOfRevenue;
private double LastPeriodEBITPercentageOfRevenue;
private double CapitalExpenditurePercentageOfRevenue;
private double CustomEBIT;
private double SGACostPercentage;
private double SGACost;
private double StraightLineDepreciationNumberOfYears;
private double BaseYearDepreciation;
private double ChangeInNonCashWorkingCapital;
private double YearEarlierWorkingCapital;
private double CurrentYearWorkingCapital;
private double FreeCashFlow;
private double WACC;
private double DiscountFactor;
private double Presentvalue;
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private MainAdapter mAdapter;
private Map<Integer, HashMap<String, String>> data;
private TextView WACCDetailedResultsYearNumber;
private TextView WACCDetailedResultsRevenueNumber;
private TextView WACCDetailedResultsCostOfGoodsNumber;
private TextView WACCDetailedResultsSGANumber;
private TextView WACCDetailedResultsEBITNumber;
private TextView WACCDetailedResultsDepreciationNumber;
private TextView WACCDetailedResultsOperatingCashFlowNumber;
private TextView WACCDetailedResultsCashExpenditureNumber;
private TextView WACCDetailedResultsChangeInNetWorkingCapitalNumber;
private TextView WACCDetailedResultsFreeCashFlowNumber;
private TextView WACCDetailedResultsWACCNumber;
private TextView WACCDetailedResultsDiscountFactorNumber;
private TextView WACCDetailedResultsPVNumber;
//decided to use card views instead of layout views
//because on every year, I wanted to leave the option
//to post comments or remarks to justify possible growth
//projections on any given year
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String text = WACCDetailedObject.getOperatingIncomeOption();
String text1 = WACCDetailedObject.getDepreciationOption();
String text2 = WACCDetailedObject.getWACCOption();
String text3 = WACCDetailedObject.getTerminalGrowthRateOption();
getLayoutInflater().inflate(R.layout.waccdetailedpageresults, frameLayout);
data = new HashMap<Integer, HashMap<String,String>>();
//USED FOR TESTING PURPOSES ONLY!!
WACCDetailedObject.setNumberOfForecastPeriods(4);
for (int i = 0; i < WACCDetailedObject.getNumberOfForecastPeriods(); i++) {
data.put(i, innerDataGenerator("WACCDetailedResultsYearNumber", ""));
data.put(i, innerDataGenerator("WACCDetailedResultsRevenueNumber", ""));
data.put(i, innerDataGenerator("WACCDetailedResultsCostOfGoodsNumber", ""));
data.put(i, innerDataGenerator("WACCDetailedPageResultsSGACostNumber", ""));
data.put(i, innerDataGenerator("WACCDetailedResultsEBITNumber", ""));
data.put(i, innerDataGenerator("WACCDetailedResultsDepreciationNumber", ""));
data.put(i, innerDataGenerator("WACCDetailedResultsOperatingCashFlowNumber", ""));
data.put(i, innerDataGenerator("WACCDetailedResultsCashExpenditureNumber", ""));
data.put(i, innerDataGenerator("WACCDetailedResultsChangeInNetWorkingCapitalNumber", ""));
data.put(i, innerDataGenerator("WACCDetailedResultsFreeCashFlowNumber", ""));
data.put(i, innerDataGenerator("WACCDetailedResultsWACCNumber", ""));
data.put(i, innerDataGenerator("WACCDetailedResultsDiscountFactorNumber", ""));
data.put(i, innerDataGenerator("WACCDetailedResultsWACCNumber", ""));
data.put(i, innerDataGenerator("WACCDetailedResultsPVVNumber", ""));
Log.d("TESTER", data.get(0).toString());
}
//http://pages.stern.nyu.edu/~adamodar/New_Home_Page/AccPrimer/accstate.htm
//http://people.stern.nyu.edu/adamodar/pdfiles/eqnotes/valenhdcf.pdf8
for (int currentyear = 0; currentyear < WACCDetailedObject.getNumberOfForecastPeriods();
currentyear++) {
//set current year
//TextView WACCDetailedResultsYearNumber =
// this.findViewById(R.id.WACCDetailedResultsYearNumber);
//WACCDetailedResultsYearNumber.setText(String.valueOf(currentyear));
data.get(currentyear).put("WACCDetailedResultsYearNumber",
"Year " + String.valueOf(currentyear));
TaxRate = WACCDetailedObject.getTaxRate();
//Free Cash Flows To Firm Calculation
//EBIT(1-t) - (Capital Expenditures- Depreciation) - Change in non-cash working capital=
//Free Cash Flow to Firm (FCFF)
//Cash Flows To Equity Investors
//Net income - (Capital Expenditures - Depreciation) - Change in non-cash
//Working Capital - (Principal Repaid - New Debt Issues) - Preferred Dividend
//-new Debt Issues = Free Cash Flow to Equity
if (currentyear == 0) {
CurrentYearRevenue = WACCDetailedObject.getCurrentYearRevenue();
//if we are just starting forecast, just use CurrentYearRevenue value
//Revenue
data.get(currentyear).
put("WACCDetailedResultsRevenueNumber", String.valueOf(CurrentYearRevenue));
} else {
CurrentYearRevenue = ((Double.parseDouble(data.get(currentyear-1)
.get("WACCDetailedResultsRevenueNumber")))
* (WACCDetailedObject.getAnnualRevenueGrowthPercentage() * .01) +
(Double.parseDouble(data.get(currentyear-1)
.get("WACCDetailedResultsRevenueNumber"))));
WACCDetailedObject.setCurrentYearRevenue(CurrentYearRevenue);
data.get(currentyear).
put("WACCDetailedResultsRevenueNumber",
String.valueOf(CurrentYearRevenue));
}
CapitalExpenditurePercentageOfRevenue =
WACCDetailedObject.getCapitalExpenditure();
//Calculate Cash Expenditure
data.get(currentyear).put("WACCDetailedResultsCashExpenditureNumber",
String.format("%.2f", CurrentYearRevenue * CapitalExpenditurePercentageOfRevenue * .01));
//Working capital, also known as net working capital, is the difference between a company’s current assets,
// like cash, accounts receivable (customers’ unpaid bills) and inventories of raw materials and finished
// goods, and its current liabilities, like accounts payable.
//Working Capital = Current Assets - Current Liabilities
//If CGS and SGA are inputted use to calculate EBIT, yearly SGA (R&D), and COGS,
// otherwise, just use
//the Ebit provided
if (WACCDetailedObject.getOperatingIncomeOption().
equals("Will input percent CGS and percent SGA"))
{
Log.i("Operating Income Option", WACCDetailedObject.getOperatingIncomeOption());
//Operating Profit Margin = Operating Income / Sales Revenue
//EBIT in period t = Revenues in period t * Expected operating margin in period t
//Thus, if you expect operating margins to change over time, you should not use the fundamental
// growth equation developed in the last section as your base growth rate. Instead, you should forecast
// revenues and margins over time, and estimate the operating income as the product of the two.
//in case COG changes over time, this is helpful
CostOfGoodsSoldPercentage =
WACCDetailedObject.getCostOfGoodsSoldAsPercentage();
//Cost Of Goods Sold
CostOfGoodsSold = CurrentYearRevenue * CostOfGoodsSoldPercentage;
//Calculate Gross Profit
//Gross Profit = Revenue - COGS
GrossProfit = CurrentYearRevenue - CostOfGoodsSold;
//get the current Cost of Goods percentage and times it against the current year
//revenue, display this number
data.get(currentyear).put("WACCDetailedResultsCostOfGoodsNumber",
String.valueOf(CostOfGoodsSold));
//SG&A is an initialism used in accounting to refer to
// Selling, General and Administrative Expenses
//, this includes Research and Development costs
SGACostPercentage =
WACCDetailedObject.getSGAValue();
//Cost of SG&A
SGACost = CurrentYearRevenue * SGACostPercentage;
//get the current Cost of Goods percentage and times it against the current year
//revenue, display this number
data.get(currentyear).put("WACCDetailedPageResultsSGACostNumber",
String.valueOf(SGACost));
//calculate initial EBIT and final EBIT here
//EBIT = Revenue - Cost of Goods Sold - Selling, General, & Admin Expense
//if depreciation charges are not included in CGS and SGA, then it would need to
//be additionally subtracted
data.get(currentyear).put("WACCDetailedResultsEBITNumber",
String.valueOf(CurrentYearRevenue - CostOfGoodsSold - SGACost));
}
//HANDLE THE TERMINAL PERIOD HERE
if (currentyear == (WACCDetailedObject.getNumberOfForecastPeriods()-1)
&& WACCDetailedObject.getDepreciationOption()
!= "Will assume Depreciation = Capex") {
//allows you to predict what the final EBIT would be in the last period, left to default at
//InitialEBIT
LastPeriodEBITPercentageOfRevenue =
WACCDetailedObject.getLastYearEBIT();
data.get(currentyear).put("WACCDetailedResultsEBITNumber",
String.valueOf(CurrentYearRevenue * LastPeriodEBITPercentageOfRevenue));
} else if (WACCDetailedObject.getDepreciationOption()
== "Will assume Depreciation = Capex" &&
WACCDetailedObject.getOperatingIncomeOption() ==
"Will input percent CGS and percent SGA") {
CustomEBIT = GrossProfit
- (SGACost + (CurrentYearRevenue * CapitalExpenditurePercentageOfRevenue));
//EBIT (Operating Income)
data.get(currentyear).put("WACCDetailedResultsEBITNumber",
String.valueOf(CustomEBIT));
} else if (WACCDetailedObject.getDepreciationOption()
== "Will use straight line rule" &&
WACCDetailedObject.getOperatingIncomeOption() ==
"Will input percent CGS and percent SGA"
) {
StraightLineDepreciationNumberOfYears
= WACCDetailedObject
.getStraightLineDepreciationYears();
BaseYearDepreciation
= WACCDetailedObject
.getBaseYearDepreciation();
//Depreciation
data.get(currentyear).put("WACCDetailedResultsDepreciationNumber",
String.valueOf(BaseYearDepreciation));
//OperatingIncome (EBIT) = Gross Income -
//(Operating Expenses + Depreciation & Amortization); if Straight-line approach is used
CustomEBIT = GrossProfit - (SGACost
+ (BaseYearDepreciation / StraightLineDepreciationNumberOfYears));
//EBIT (Operating Income)
data.get(currentyear).put("WACCDetailedResultsEBITNumber",
String.valueOf(CustomEBIT));
}
//FOCUS HERE FOR NOW
else if (WACCDetailedObject.getOperatingIncomeOption()
== "Will input percent EBIT (Operating Margin)"
&& WACCDetailedObject.getDepreciationOption()
== "Will use straight line rule") {
//use above
//given multiple year input, different forecasted revenue numbers, different operating NWC calculated
//as a result, different changes in non-cash working capital is calculated
ChangeInNonCashWorkingCapital =
CurrentYearWorkingCapital - YearEarlierWorkingCapital;
StraightLineDepreciationNumberOfYears
= WACCDetailedObject
.getStraightLineDepreciationYears();
BaseYearDepreciation
= WACCDetailedObject
.getBaseYearDepreciation();
//Depreciation
//Year T Depreciation as:
//DT = DT-1(last year Depreciation) + [CapexT/N] where CapexT is the
//Capital expenditure for Year T, and N is the assume average depreciable
//life of assets (e.g. 3), if the number of forecast periods exceeds N, the model
//fades Depreciation charges to account for the fact that capital
//expenditure incurred in early periods and will get fully depreciated,
//account for the fact that its book value fades to zero
if (currentyear == 0) {
double CurrentYearDepreciation = BaseYearDepreciation;
data.get(currentyear).put("WACCDetailedResultsDepreciationNumber",
String.valueOf(BaseYearDepreciation));
} else{
//Operating Income Calculation
InitialEBITPercentageOfRevenue =
WACCDetailedObject.getInitialEBIT();
//EBIT (Operating Income),
// Expected growth rate = Reinvestment Rate * ROIC
// pre-tax measure of operating profitability:
// Pre-tax Operating Margin = EBIT / Sales (Revenue)
//EBIT in period t = Revenues in period t * Expected operating margin in period t
//EBIT in period0 = 100mill * 5%, = 5 million
//Expected growth rate in operating income = Return on Capital * Reinvestment Rate + Efficiency growth
// (as a result of changing return on capital)
//INITIAL EBIT PERCENTAGE OF REVENUE IS OPERATING MARGIN FOR YEAR 1 of the valuation
//take the initial ebit and subtract it by the last period ebit, e.g. 25 percent - 20 percent
//it will get you 5 percent, take that amount and divide it by the amount of forecasted years
//subtract every year's ebit by .005 (.05/10 years) and every year multiply that ebit by that
//year's revenue, so year 0 will be nothing, year 1 will be 24.5%, year 2 will be 24% and so on
//calculate the ebit difference here
double EBITDifference = .01 * (WACCDetailedObject.getInitialEBIT() - WACCDetailedObject.getLastYearEBIT());
//numbers from .20 to .25, will be -.05
//calculate the ebit multiple here
double EBITAmount = (EBITDifference/WACCDetailedObject.getNumberOfForecastPeriods()) * currentyear;
//if initial ebit is greater than last year ebit, subtract
if (WACCDetailedObject.getInitialEBIT() > WACCDetailedObject.getLastYearEBIT()) {
double EBITMultiple = (.01 * WACCDetailedObject.getInitialEBIT()) - EBITAmount;
double EBITForTheYear = WACCDetailedObject.getCurrentYearRevenue() *
EBITMultiple;
data.get(currentyear).put("WACCDetailedResultsEBITNumber",
String.format("%.2f", EBITForTheYear));
//if initial ebit is less than last year ebit, add
}else{
double EBITMultiple = (.01 * WACCDetailedObject.getInitialEBIT()) + EBITAmount;
double EBITForTheYear = WACCDetailedObject.getCurrentYearRevenue() *
EBITMultiple;
data.get(currentyear).put("WACCDetailedResultsEBITNumber",
String.format("%.2f", EBITForTheYear));
FreeCashFlow = EBITForTheYear * (1 - TaxRate)
- ((CurrentYearRevenue * CapitalExpenditurePercentageOfRevenue) -
BaseYearDepreciation / StraightLineDepreciationNumberOfYears
) - ChangeInNonCashWorkingCapital;
}
//if the current year is less than or equal the avg number of depreciation years
//DepT = [DepT–1] + [(1/N)CapexT]
//otherwise, [DepT–1] + [(1/N)CapexT] – [DepT–N] for the years T > N
//where T is the number of proforma periods, and N is the average depreciable life
if (currentyear <= StraightLineDepreciationNumberOfYears) {
double CurrentYearDepreciation = Double.valueOf(data.get(currentyear - 1)
.get("WACCDetailedResultsDepreciationNumber")) +
(
((double) ((CurrentYearRevenue * CapitalExpenditurePercentageOfRevenue) /
StraightLineDepreciationNumberOfYears))
);
data.get(currentyear).put("WACCDetailedResultsDepreciationNumber",
String.format("%.2f", CurrentYearDepreciation));
} else {
double CurrentYearDepreciation = Double.valueOf(data.get(currentyear - 1)
.get("WACCDetailedResultsDepreciationNumber")) +
(
((double) ((CurrentYearRevenue * CapitalExpenditurePercentageOfRevenue) /
StraightLineDepreciationNumberOfYears))
) - (Double.valueOf(data.get(currentyear - StraightLineDepreciationNumberOfYears)
.get("WACCDetailedResultsDepreciationNumber")));
data.get(currentyear).put("WACCDetailedResultsDepreciationNumber",
String.format("%.2f", CurrentYearDepreciation));
}
}
////assumption EBIT is provided, depreciation = straightline
if ((WACCDetailedObject.getOperatingIncomeOption()
== "Will input percent EBIT (Operating Margin)"
&& WACCDetailedObject.getDepreciationOption()
== "Will use straight line rule") && (currentyear > 0)){
FreeCashFlow = (InitialEBITPercentageOfRevenue * CurrentYearRevenue)
* (1 - TaxRate)
- ((CurrentYearRevenue * CapitalExpenditurePercentageOfRevenue) -
BaseYearDepreciation / StraightLineDepreciationNumberOfYears
) - ChangeInNonCashWorkingCapital;
//Free Cash Flow (FCFF)
data.get(currentyear).put("WACCDetailedResultsFreeCashFlowNumber",
String.format("%.2f", FreeCashFlow));
}
}
//Set Change in Net Working Capital Here
data.get(currentyear).put("WACCDetailedResultsChangeInNetWorkingCapitalNumber",
String.valueOf(ChangeInNonCashWorkingCapital));
//Free Cash Flows To Firm Calculation
//Free Cash Flow to Firm (FCFF)
//EBIT(1-t) - (Capital Expenditures- Depreciation)
// //- Change in non-cash working capital
//assumption EBIT is provided, depreciation = capex
if (WACCDetailedObject
.getDepreciationOption() == "Will assume Depreciation = Capex"
&&
WACCDetailedObject.getOperatingIncomeOption()
== "Will input percent EBIT (Operating Margin)") {
FreeCashFlow = InitialEBITPercentageOfRevenue * (1 - TaxRate)
- (CapitalExpenditurePercentageOfRevenue - BaseYearDepreciation
) - ChangeInNonCashWorkingCapital;
//Free Cash Flow (FCFF)
data.get(currentyear).put("WACCDetailedResultsFreeCashFlowNumber",
String.valueOf(FreeCashFlow));
}
////assumption EBIT is not provided, CustomEBIT, depreciation = capex
if (WACCDetailedObject.getOperatingIncomeOption()
== "Will input percent EBIT (Operating Margin)"
&& WACCDetailedObject
.getDepreciationOption()
== "Will input percent CGS and percent SGA") {
//calculate EBIT here
FreeCashFlow = CustomEBIT * (1 - TaxRate)
- ((CurrentYearRevenue * CapitalExpenditurePercentageOfRevenue) -
BaseYearDepreciation
) - ChangeInNonCashWorkingCapital;
//Free Cash Flow (FCFF)
data.get(currentyear).put("WACCDetailedResultsFreeCashFlowNumber",
String.valueOf(FreeCashFlow));
}
//Operating Cash Flow, this is Free Cash Flow (FCFF) + cash or capital expenditure
//Free Cash Flows To Firm Calculation
//Free Cash Flow to Firm (FCFF)
//EBIT(1-t) - (Capital Expenditures- Depreciation)
// //- Change in non-cash working capital
data.get(currentyear).put("WACCDetailedResultsOperatingCashFlowNumber",
String.valueOf(FreeCashFlow +
(CurrentYearRevenue * CapitalExpenditurePercentageOfRevenue)));
//WACC Calculation
//https://www.investopedia.com/terms/w/wacc.asp
data.get(currentyear).put("WACCDetailedResultsWACCNumber",
String.valueOf(WACCDetailedObject.getWACC()));
//Discount Factor Calculation
if (currentyear > 0) {
//Factor = 1 / (1 x (1 + Discount Rate) ^ Period Number)
//Write info tap
//Calculating what discount rate to use in your discounted cash flow calculation is no easy choice.
// It's as much art as it is science. The weighted average cost of capital is one of
// the better concrete methods and a great place to start, but even that won't give you
// the perfect discount rate for every situation.
//
//Understanding that our discount rate is an educated guess and not a scientific
// certainty, we can still move forward with the calculation and obtain an estimate
// of this company's value. If our analysis estimates that the company is worth
// more than the stock currently trades, that means the stock could be undervalued
// and worth buying. If our estimation shows the stock is worth less than its stock
// currently trades, then it may be overvalued and a bad value investment.
//testing
Log.v("testerx", String.valueOf(WACCDetailedObject.getWACC()));
DiscountFactor = (1.0 / Math.pow(1.0 + (WACCDetailedObject.getWACC() *.01), (double) currentyear));
data.get(currentyear).put("WACCDetailedResultsDiscountFactorNumber",
String.format("%.2f", DiscountFactor));
//Discount future cash flows to their present values
//Presentvalue = Expected Cash Flow ÷ (1+Discount Rate)^Number of periods
Presentvalue = FreeCashFlow /
(1.0+Math.pow(WACCDetailedObject.getWACC(), (double)
WACCDetailedObject.getNumberOfForecastPeriods()));
data.get(currentyear).put("WACCDetailedResultsPVNumber",
String.format("%.2f", Presentvalue));
}
}
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MainAdapter(data);
mRecyclerView.setAdapter(mAdapter);
}
protected HashMap<String, String> innerDataGenerator(String key, String value) {
final HashMap<String, String> innerdata = new HashMap<String, String>();
innerdata.put(key,value);
return innerdata;
}
}
<file_sep>/app/src/main/java/com/example/finance/googlesheetsexample/WACCDetailedPageTerminalValue.java
package com.example.finance.googlesheetsexample;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
public class WACCDetailedPageTerminalValue extends FirstScreenToShowMenu {
private TextView WACCDetailedPageTerminalValueSubTitle;
private TextView WACCDetailedPageTerminalValueTerminalROIC;
private TextView WACCDetailedPageTerminalValueTerminalReinvestmentRate;
private TextView WACCDetailedPageTerminalValueTerminalGrowthRate;
private TextView WACCDetailedPageTerminalValueTerminalWACC;
private TextView WACCDetailedPageTerminalValueTerminalROICValue;
private TextView WACCDetailedPageTerminalValueTerminalReinvestmentRateValue;
private TextView WACCDetailedPageTerminalValueTerminalGrowthRateValue;
private TextView WACCDetailedPageTerminalValueTerminalWACCValue;
private WACCDetailedObject waccDetailedObject;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//waccDetailedObject = FirstScreenToShowMenu.WACCDetailedObjectGet();
getLayoutInflater().inflate(R.layout.waccdetailedpageterminalvalue,
frameLayout);
WACCDetailedPageTerminalValueSubTitle = (TextView) this.findViewById(R.id.
WACCDetailedPageTerminalValueSubTitle);
WACCDetailedPageTerminalValueSubTitle.setText("TERMINAL VALUE");
//Terminal ROIC
WACCDetailedPageTerminalValueTerminalROIC = (TextView) this.
findViewById(R.id.WACCDetailedPageTerminalValueTerminalROIC);
WACCDetailedPageTerminalValueTerminalROIC.setText("Terminal ROIC \n(%)");
WACCDetailedPageTerminalValueTerminalROIC.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopUpWindow popUpWindow = new PopUpWindow();
//TODO: look into setting text like above way
//Logic
Intent intent = new Intent(WACCDetailedPageTerminalValue.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "If you chose the option to calculate g using the " +
"formula ROICxRR in the 'Few Key Questions' page, you will input the ROIC assumption here. " +
"Otherwise, it will be grayed out. If you have a firm with exceptional competitive " +
"advantages, you can input an ROIC that is higher than your cost of capital.");
startActivity(intent);
}
});
WACCDetailedPageTerminalValueTerminalROICValue =
(EditText) this.findViewById(R.id.WACCDetailedPageTerminalValueTerminalROICValue);
WACCDetailedPageTerminalValueTerminalROICValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus) {
//SAVE THE DATA
//waccDetailedObject.setTerminalROIC(Double.parseDouble(WACCDetailedPageTerminalValueTerminalROICValue.getText().toString()));
//Log.d("TEST", getWaccDetailedObject().getCompanyName());
}
}
});
// Terminal reinvestment rate
WACCDetailedPageTerminalValueTerminalReinvestmentRate = (TextView) this.findViewById(R.id.
WACCDetailedPageTerminalValueTerminalReinvestmentRate);
WACCDetailedPageTerminalValueTerminalReinvestmentRate.setText("Terminal reinvestment rate \n(RR: %)");
//TODO: Get subscripts to work properly
WACCDetailedPageTerminalValueTerminalReinvestmentRate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Logic
Intent intent = new Intent(WACCDetailedPageTerminalValue.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "If you chose the option to calculate g using the " +
"formula ROICxRR in the 'Few Key Questions' page, you will input the reinvestment rate (RR) " +
"assumption here. Otherwise, it will be grayed out. Enter an RR that is consistent with a g " +
"equal to rF or to the long-run nominal growth rate of GDP.");
startActivity(intent);
//
}
});
WACCDetailedPageTerminalValueTerminalReinvestmentRateValue =
(EditText) this.findViewById(R.id.WACCDetailedPageTerminalValueTerminalReinvestmentRateValue);
WACCDetailedPageTerminalValueTerminalReinvestmentRateValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus) {
//SAVE THE DATA
// waccDetailedObject.setTerminalReinvestmentRate(
// Double.parseDouble(WACCDetailedPageTerminalValueTerminalReinvestmentRateValue
// .getText().toString()));
//Log.d("TEST", getWaccDetailedObject().getCompanyName());
}
}
});
// Terminal growth rate (g: %)
WACCDetailedPageTerminalValueTerminalGrowthRate = (TextView) this.findViewById
(R.id.WACCDetailedPageTerminalValueTerminalGrowthRate);
WACCDetailedPageTerminalValueTerminalGrowthRate.setText("Terminal growth rate \n(g: %)");
//TODO: Get subscripts to work properly
WACCDetailedPageTerminalValueTerminalGrowthRate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Logic
Intent intent = new Intent(WACCDetailedPageTerminalValue.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "Terminal Value (TV) is the continuing value of " +
"the business after the detailed forecast (or, 'proforma') period ends. It is " +
"calculated using the constant growth model: \n\n TV = FCFFr + (WACCr-g), \n\n" +
"where FCFFr is the cash flow in the first period after the forecast period ends " +
"(if the forecast period is seven years, this year 8), WACCr is the cost of capital " +
"in perpetuity after the forecast period, and g is the Terminal Growth Rate (the growth " +
"rate in free cash flow in perptuity).\n\nThe enterprise value, EV, is the present value " +
"of TV plus the present value of cash flows for each year of the proforma period. \n\n" +
"Some analysts use multiples (e.g. EV/EBITDA, EV/SALES) to estimate TV. However, g is " +
"implicit (and therefore, hidden) in a multiple, while it is made explicit in the " +
"constant growth model. Moreover, the danger with using this approach is that it undercuts " +
"the very notion of this being a discounted cash flow or an intrinsic valuation, and makes " +
"this instead a relative valuation.");
startActivity(intent);
//
}
});
WACCDetailedPageTerminalValueTerminalGrowthRateValue =
(EditText) this.findViewById(R.id.WACCDetailedPageTerminalValueTerminalGrowthRateValue);
WACCDetailedPageTerminalValueTerminalGrowthRateValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus) {
//SAVE THE DATA
// waccDetailedObject.setTerminalReinvestmentRate(
// Double.parseDouble(WACCDetailedPageTerminalValueTerminalGrowthRateValue
// .getText().toString()));
//Log.d("TEST", getWaccDetailedObject().getCompanyName());
}
}
});
//Terminal WACC
WACCDetailedPageTerminalValueTerminalWACC = (TextView) this.findViewById
(R.id.WACCDetailedPageTerminalValueTerminalWACC);
WACCDetailedPageTerminalValueTerminalWACC.setText("Terminal WACC \n(%)");
//TODO: Get subscripts to work properly
WACCDetailedPageTerminalValueTerminalWACC.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Logic
Intent intent = new Intent(WACCDetailedPageTerminalValue.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "You can choose to input a long-run terminal WACC " +
"that is different from the default WACC, which is the cost of capital for the proforma period. " +
"One option may be the industry average. Another, the market average.");
//
startActivity(intent);
}
});
WACCDetailedPageTerminalValueTerminalWACCValue =
(EditText) this.findViewById(R.id.WACCDetailedPageTerminalValueTerminalWACCValue);
WACCDetailedPageTerminalValueTerminalWACCValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus) {
//SAVE THE DATA
// waccDetailedObject.setTerminalReinvestmentRate(
// Double.parseDouble(WACCDetailedPageTerminalValueTerminalWACCValue
// .getText().toString()));
//Log.d("TEST", getWaccDetailedObject().getCompanyName());
}
}
});
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//leverage the Snackbar to make user aware of any errors in their data
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Data Submitted", null).show();
//Add all the model data here
WACCDetailedObject.setCash(Double.parseDouble(
WACCDetailedPageTerminalValueTerminalROICValue.getText().toString()));
WACCDetailedObject.setDebt(Double.parseDouble(
WACCDetailedPageTerminalValueTerminalReinvestmentRateValue.getText().toString()));
WACCDetailedObject.setMarketCapitalization(Double.parseDouble(
WACCDetailedPageTerminalValueTerminalGrowthRateValue.getText().toString()));
WACCDetailedObject.setEquityBeta(Double.parseDouble(
WACCDetailedPageTerminalValueTerminalWACCValue.getText().toString()));
}
});
}
}
<file_sep>/app/src/main/java/com/example/finance/googlesheetsexample/androidlabs/gsheets1/MyArrayAdapter.java
package com.example.finance.googlesheetsexample.androidlabs.gsheets1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.finance.googlesheetsexample.R;
import com.example.finance.googlesheetsexample.androidlabs.gsheets1.MyDataModel;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.List;
public class MyArrayAdapter extends ArrayAdapter<MyDataModel> {
List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
// Constructors
public MyArrayAdapter(Context context, List<MyDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
}
@Override
public MyDataModel getItem(int position) {
return modelList.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.layout_row_view, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
MyDataModel item = getItem(position);
if (item.getYear() == 0) {
vh.textViewYear.setText("Terminal Value: " + Integer.toString(item.getYear()));
vh.textViewCashFlowToEquity.setText(" Terminal CashFlow To Equity: " + Integer.toString(item.getTerminalCashFlowToEquity()));
vh.textViewDifference.setText("TerminalDifference Between Numbers Before & After: " + Integer.toString(item.getTerminaldifference()));
vh.textViewCashFlowToFirm.setText("Terminal CashFlow To Firm: " + Integer.toString(item.getTerminalcftofirm()));
} else {
vh.textViewYear.setText("Year: " + Integer.toString(item.getYear()));
vh.textViewCashFlowToEquity.setText("CashFlow To Equity: " + Integer.toString(item.getCashFlowToEquity()));
vh.textViewDifference.setText("Difference Between Numbers Before & After: " + Integer.toString(item.getDifference()));
vh.textViewCashFlowToFirm.setText("CashFlow To Firm: " + Integer.toString(item.getCashFlowToFirm()));
}
return vh.rootView;
}
/**
* ViewHolder class for layout.<br />
* <br />
* Auto-created on 2016-01-05 00:50:26 by Android Layout Finder
* (http://www.buzzingandroid.com/tools/android-layout-finder)
*/
private static class ViewHolder {
public final RelativeLayout rootView;
public final TextView textViewYear;
public final TextView textViewCashFlowToEquity;
public final TextView textViewDifference;
public final TextView textViewCashFlowToFirm;
private ViewHolder(RelativeLayout rootView, TextView textViewYear, TextView textViewCashFlowToEquity, TextView textViewDifference, TextView textViewCashFlowToFirm) {
this.rootView = rootView;
this.textViewYear = textViewYear;
this.textViewCashFlowToEquity = textViewCashFlowToEquity;
this.textViewDifference = textViewDifference;
this.textViewCashFlowToFirm = textViewCashFlowToFirm;
}
public static ViewHolder create(RelativeLayout rootView) {
//textViewYear and other variables can be reflective of terminal values
TextView textViewYear = (TextView) rootView.findViewById(R.id.textViewYear);
TextView textViewCashFlowToEquity = (TextView) rootView.findViewById(R.id.textViewCashFlowToEquity);
TextView textViewDifference = (TextView) rootView.findViewById(R.id.textViewDifference);
TextView textViewCashFlowToFirm = (TextView) rootView.findViewById(R.id.textView2CashFlowToFirm);
return new ViewHolder(rootView, textViewYear, textViewCashFlowToEquity, textViewDifference, textViewCashFlowToFirm);
}
}
}<file_sep>/app/src/main/java/com/example/finance/googlesheetsexample/PopUpWindow.java
package com.example.finance.googlesheetsexample;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.util.DisplayMetrics;
import android.widget.TextView;
public class PopUpWindow extends Activity{
private TextView TVmessage;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popupwindow);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
Intent intent = getIntent();
//String message = intent.getStringExtra("flagExcelViewer");
String isExcel = intent.getStringExtra("isExcelPopup");
if (isExcel.equals("false")) {
intent = getIntent();
isExcel = intent.getStringExtra("message");
TVmessage = (TextView) findViewById(R.id.PopUpMessage);
TVmessage.setText(isExcel);
}
else if (isExcel.equals("false")) {
}
//TODO troubleshoot here if the flag does not contain either message
else {
}
getWindow().setLayout((int) (width*.85), (int) (height *.85));
}
}
<file_sep>/app/src/main/java/com/example/finance/googlesheetsexample/androidlabs/gsheets1/JSONparser.java
package com.example.finance.googlesheetsexample.androidlabs.gsheets1;
import androidx.annotation.NonNull;
import android.util.Log;
import com.example.finance.googlesheetsexample.util.Keys;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
public class JSONparser {
private static final String MAIN_URL = "https://script.google.com/macros/s/AKfycbxw1d75kBSs7cPNPI0hlUSdwUrLNpfGw0eLUKkMjQitesAa7kfz/exec";
public static final String TAG = "TAG";
private static Response response;
private static final String myAPIKey = "";
public static JSONObject getDataFromWeb() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(MAIN_URL)
.build();
response = client.newCall(request).execute();
JSONObject test = new JSONObject(response.body().string());
return test;
} catch (@NonNull IOException | JSONException e) {
Log.e(TAG, "" + e.getLocalizedMessage());
}
return null;
}
public static JSONObject getDataByStockSymbol(String stocksymbol, String modelType) {
final String MAIN_URL = "https://script.google.com/macros/s/AKfycbzum_eIP1hMeE58ct1Y-l7WtXkN5-0sLxD6N1kZcxUXXFa_vwzr/exec";
String id= "1GYqw7C2fMv0qaPvrwnddtbwI1f4zRDh_9Fj-xyhV1gg";
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(MAIN_URL+"?"+(Keys.KEY_STOCKSYMBOL + "=" + stocksymbol + "&") +
(Keys.KEY_MODELTYPE + "=" + modelType + "&") + ("id" + "=" + id)).get()
.build();
System.out.println("REQUEST "+ request);
//info: Look into why calls to Google Sheets API can take a while and it
// does not stop at Terminal Value when it should
response = client.newCall(request).execute();
System.out.printf("TEST" + response.toString());
return new JSONObject(response.body().string());
} catch (IOException | JSONException e) {
Log.e(TAG, "" + e.getLocalizedMessage());
}
return null;
}
}<file_sep>/app/src/main/java/com/example/finance/googlesheetsexample/WACCDetailedPageCostOfCapitalInputs.java
package com.example.finance.googlesheetsexample;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
//test
public class WACCDetailedPageCostOfCapitalInputs extends FirstScreenToShowMenu {
private TextView WACCDetailedPageCostOfCapitalTitle;
private TextView WACCDetailedPageCostOfCapitalCash;
private TextView WACCDetailedPageCostOfCapitalDebt;
private TextView WACCDetailedPageCostOfCapitalMarketCap;
private TextView WACCDetailedPageCostOfCapitalEquityBeta;
private TextView WACCDetailedPageCostOfCapitalRiskFreeRate;
private TextView WACCDetailedPageCostOfCapitalCashValue;
private TextView WACCDetailedPageCostOfCapitalDebtValue;
private TextView WACCDetailedPageCostOfCapitalMarketCapValue;
private TextView WACCDetailedPageCostOfCapitalEquityBetaValue;
private TextView WACCDetailedPageCostOfCapitalRiskFreeRateValue;
private TextView WACCDetailedPageCostOfCapitalMarketRiskPremiumValue;
private TextView WACCDetailedPageCostOfCapitalMarketRiskPremium;
private TextView WACCDetailedPageCostOfCapitalLeveredCostOfEquity;
private TextView WACCDetailedPageCostOfCapitalCostOfDebt;
private TextView WACCDetailedPageCostOfCapitalWeightedAverageCostOfCapital;
private TextView WACCDetailedPageCostOfCapitalNumberOfShares;
private TextView WACCDetailedPageCostOfCapitalLeveredCostOfEquityValue;
private TextView WACCDetailedPageCostOfCapitalCostOfDebtValue;
private TextView WACCDetailedPageCostOfCapitalWeightedAverageCostOfCapitalValue;
private TextView WACCDetailedPageCostOfCapitalNumberOfSharesValue;
//TODO Figure out how to add $ and percent lines to suggestive text for input without crashing
//TODO Figure out how to handle bad input, probably will involve a popup message
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.waccdetailedpagecostofcapitalinputs, frameLayout);
WACCDetailedPageCostOfCapitalTitle = (TextView) this.findViewById(R.id.
WACCDetailedPageCostOfCapitalTitle);
WACCDetailedPageCostOfCapitalTitle.setText("'WACC: Detailed' Model Inputs: Cost of Capital " +
"and Terminal Value");
//Firm Cash Value
WACCDetailedPageCostOfCapitalCash = (TextView) this.
findViewById(R.id.WACCDetailedPageCostOfCapitalCash);
WACCDetailedPageCostOfCapitalCash.setText("Cash (C: $millions)");
WACCDetailedPageCostOfCapitalCash.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO: look into setting text like above way
Intent intent = new Intent(WACCDetailedPageCostOfCapitalInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "This is the sum of all cash and cash" +
"equivalents from the company's balance sheet, as of the end of the " +
"base year of valuation. Input the most recent value.");
//
startActivity(intent);
}
});
WACCDetailedPageCostOfCapitalCashValue =
(EditText) this.findViewById(R.id.WACCDetailedPageCostOfCapitalCashValue);
WACCDetailedPageCostOfCapitalCashValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject.setCash(
Double.parseDouble(WACCDetailedPageCostOfCapitalCashValue.getText().toString()));
//Log.d("TEST", WACCDetailedObject.getCompanyName());
}
}
});
//Firm Debt Value
WACCDetailedPageCostOfCapitalDebt = (TextView) this.findViewById(R.id.WACCDetailedPageCostOfCapitalDebt);
WACCDetailedPageCostOfCapitalDebt.setText("Debt (D: $ millions)");
//TODO: Get subscripts to work properly
WACCDetailedPageCostOfCapitalDebt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Logic
Intent intent = new Intent(WACCDetailedPageCostOfCapitalInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "This is, at a minimum, the sum of all" +
" interest-bearing debt - i.e., short-term debt, plus current portion of" +
" long-term debt, plus long-term debt. In addition, it may include " +
"the capitalized value of long-term leases.");
//
startActivity(intent);
}
});
WACCDetailedPageCostOfCapitalDebtValue =
(EditText) this.findViewById(R.id.WACCDetailedPageCostOfCapitalDebtValue);
WACCDetailedPageCostOfCapitalDebtValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject.setDebt(
Double.parseDouble(WACCDetailedPageCostOfCapitalDebtValue.getText().toString()));
//Log.d("TEST", WACCDetailedObject.getCompanyName());
}
}
});
//Market Capitalization
WACCDetailedPageCostOfCapitalMarketCap = (TextView)
this.findViewById(R.id.WACCDetailedPageCostOfCapitalMarketCap);
WACCDetailedPageCostOfCapitalMarketCap.setText("Market capitalization \n(E: $millions)");
WACCDetailedPageCostOfCapitalMarketCap
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Logic
Intent intent = new Intent(WACCDetailedPageCostOfCapitalInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "Market capitalization is" +
" the total market value of all common equity in your firm. " +
"While multiplying the current share price by the number of shares " +
"will usually give you this number, you should add the value of all" +
"classes of common stock (even non-traded common stock, with an estimated" +
"value per share).");
startActivity(intent);
}
});
WACCDetailedPageCostOfCapitalMarketCapValue =
(EditText) this.findViewById(R.id.WACCDetailedPageCostOfCapitalMarketCapValue);
WACCDetailedPageCostOfCapitalMarketCapValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject.setMarketCapitalization(
Double.parseDouble(WACCDetailedPageCostOfCapitalMarketCapValue.getText().toString()));
//Log.d("TEST", WACCDetailedObject.getCompanyName());
}
}
});
//Equity Beta
WACCDetailedPageCostOfCapitalEquityBeta = (TextView)
this.findViewById(R.id.WACCDetailedPageCostOfCapitalEquityBeta);
WACCDetailedPageCostOfCapitalEquityBeta.setText("Equity beta ß)");
WACCDetailedPageCostOfCapitalEquityBeta
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Logic
Intent intent = new Intent(WACCDetailedPageCostOfCapitalInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "Equity beta (ßE) measures " +
"the sensitivity of a stock's expected returns to that of the " +
"market as a whole. It measures the expected percent change in " +
"the value of an asset or every 1% change in the market index. " +
"For instance, a stock with a ßE = 1.5 would be expected to go up, " +
"on average, by 1.5% for every 1% increase in the value of the market. " +
"It is derived from the Capital Asset Pricing Model (CAPM), which " +
"says that the expected return on equity, rE, is: \n\n" +
"rE = rF + ßE x MRP \n\n where rF is the risk-free rate or return " +
"(proxied by yield on long-run US goverment Treasury bonds), " +
"ßE is as as above, and MRP the 'market risk premium' or " +
"'equity risk premium' is the excess return that investors demand to " +
" put their money into a diversified portfolio of stocks relative to a " +
"safe asset such as US government Treasury bonds (rF). \n\n" +
"You can use the beta that you find for your company on a service (YahooFinance," +
" Value Line, etc.). In many instances, a better choice may be an " +
"industry average.");
startActivity(intent);
}
});
WACCDetailedPageCostOfCapitalEquityBetaValue =
(EditText) this.findViewById(R.id.WACCDetailedPageCostOfCapitalEquityBetaValue);
WACCDetailedPageCostOfCapitalEquityBetaValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject.setEquityBeta(
Double.parseDouble(WACCDetailedPageCostOfCapitalEquityBetaValue
.getText().toString()));
//Log.d("TEST", WACCDetailedObject.getCompanyName());
}
}
});
//Risk-free rate (rF: %)
WACCDetailedPageCostOfCapitalRiskFreeRate = (TextView)
this.findViewById(R.id.WACCDetailedPageCostOfCapitalRiskFreeRate);
WACCDetailedPageCostOfCapitalRiskFreeRate.setText("Risk-free rate (rF: %)");
WACCDetailedPageCostOfCapitalRiskFreeRate
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Logic
Intent intent = new Intent(WACCDetailedPageCostOfCapitalInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "This is proxied by the yield" +
"on long-term US government Treasury bonds. It is recommended using at least a " +
"10-year bond, perhaps even a 30-year bond if you're " +
"assuming a constant long-run MRP. In Euros, use German " +
"government bonds. In other currencies, proceed with caution.");
startActivity(intent);
}
});
WACCDetailedPageCostOfCapitalRiskFreeRateValue =
(EditText) this.findViewById(R.id.WACCDetailedPageCostOfCapitalRiskFreeRateValue);
WACCDetailedPageCostOfCapitalRiskFreeRateValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject.setRiskFreeRate(
Double.parseDouble(WACCDetailedPageCostOfCapitalRiskFreeRateValue
.getText().toString()));
//Log.d("TEST", WACCDetailedObject.getCompanyName());
}
}
});
//Market risk premium (MRP: %)
WACCDetailedPageCostOfCapitalMarketRiskPremium = (TextView)
this.findViewById(R.id.WACCDetailedPageCostOfCapitalMarketRiskPremium);
WACCDetailedPageCostOfCapitalMarketRiskPremium.setText("Market risk premium \n(MRP: %)");
WACCDetailedPageCostOfCapitalMarketRiskPremium
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Logic
Intent intent = new Intent(WACCDetailedPageCostOfCapitalInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "Market risk premium (MRP) " +
"is the excess return that investors demand to put their money" +
"into a diversified portfolio of risky assets - the 'market' - relative to the " +
"return that they can get on a relatively safe asset such as Treasury" +
"bonds.\n\n It is a matter of considerable debate in academia, but there " +
"is agreement on the fact that: (i) MRP is time-varying; (ii) MRP is, " +
"on average, lower today than the estimates we have been using in the past." +
"\n\n If your company is an emerging market company (or has significant" +
"exposure to emerging markets)m you may want to augment this number." +
"\n\nIt can be argued that it's fine to use the current estimate, implied " +
"by where the market is.\n\nIt can also be argued that it makes sense to use " +
"a long-run estimate - around 5% to 6% - since MRP is mean-reverting.");
startActivity(intent);
}
});
WACCDetailedPageCostOfCapitalMarketRiskPremiumValue =
(EditText) this.findViewById(R.id.WACCDetailedPageCostOfCapitalMarketRiskPremiumValue);
WACCDetailedPageCostOfCapitalMarketRiskPremiumValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject.setMarketRiskPremium(
Double.parseDouble(WACCDetailedPageCostOfCapitalMarketRiskPremiumValue
.getText().toString()));
//Log.d("TEST", WACCDetailedObject.getCompanyName());
}
}
});
//Levered cost of equity
WACCDetailedPageCostOfCapitalLeveredCostOfEquity = (TextView)
this.findViewById(R.id.WACCDetailedPageCostOfCapitalLeveredCostOfEquity);
//WACCDetailedPageCostOfCapitalLeveredCostOfEquity.setText("Levered cost of equity \n(rE: %)");
WACCDetailedPageCostOfCapitalLeveredCostOfEquity
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Logic
Intent intent = new Intent(WACCDetailedPageCostOfCapitalInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "The levered cost of equity, rE, is " +
"calculated using CAPM with the equity beta, ßE:\n\n " +
"rE = rF + ßE x MRP \n\n (See 'Equity beta' above for the" +
" definition of variables in CAPM). It includes the effects of " +
"debt in the business.\n\n The rE is different from the 'unlevered' " +
"cost of equity, which is calculated using CAPM with the " +
"'unlevered' (or 'asset') beta, ßA. This cost of equity is used in APV " +
"valuations (see our APV model.)\n\n" + "You may choose to use industry " +
"averages as a starting point. If your firm is much smaller or riskier than the " +
"rest of the sector, you may want to add to this number.");
startActivity(intent);
}
});
WACCDetailedPageCostOfCapitalLeveredCostOfEquityValue =
(EditText) this.findViewById(R.id.WACCDetailedPageCostOfCapitalLeveredCostOfEquityValue);
WACCDetailedPageCostOfCapitalLeveredCostOfEquityValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject.setLeveredCostOfEquity(
Double.parseDouble(WACCDetailedPageCostOfCapitalLeveredCostOfEquityValue
.getText().toString()));
//Log.d("TEST", WACCDetailedObject.getCompanyName());
}
}
});
//Cost of debt
WACCDetailedPageCostOfCapitalCostOfDebt = (TextView)
this.findViewById(R.id.WACCDetailedPageCostOfCapitalCostOfDebt);
WACCDetailedPageCostOfCapitalCostOfDebt.setText("Cost of debt (rD: %)");
WACCDetailedPageCostOfCapitalCostOfDebt
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Logic
Intent intent = new Intent(WACCDetailedPageCostOfCapitalInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "Cost of debt, rD, is the answer to the " +
" question: If the company were to go out and issue longer-term bonds today, " +
"what would the bond markets demand as a required yield?" + "\n\n" +
"This can be inferred from what the bond market is demanding as the default " +
"spread over the risk-free rate for bonds with comparable credit rating. It should " +
"never be lower than the risk-free rate. You can also use an industry average. " +
"Avoid using 'book' costs of debt.");
startActivity(intent);
}
});
WACCDetailedPageCostOfCapitalCostOfDebtValue =
(EditText) this.findViewById(R.id.WACCDetailedPageCostOfCapitalCostOfDebtValue);
WACCDetailedPageCostOfCapitalCostOfDebtValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject.setCostOfDebt(
Double.parseDouble(WACCDetailedPageCostOfCapitalCostOfDebtValue
.getText().toString()));
//Log.d("TEST", WACCDetailedObject.getCompanyName());
}
}
});
//Weighted average cost of capital
WACCDetailedPageCostOfCapitalWeightedAverageCostOfCapital = (TextView)
this.findViewById(R.id.WACCDetailedPageCostOfCapitalWeightedAverageCostOfCapital);
WACCDetailedPageCostOfCapitalWeightedAverageCostOfCapital.setText("Weighted average cost of" +
" capital \n(WACC: %)");
WACCDetailedPageCostOfCapitalWeightedAverageCostOfCapital
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Logic
Intent intent = new Intent(WACCDetailedPageCostOfCapitalInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "WACC is 'weighted average cost of capital.' " +
"It captures the idea that we must provide a 'fair' rate of return to each type of " +
"investor in our business, weighted by the proportion in which they are supplying " +
"its capital. this rate is determined by the return on risk-equivalent assets " +
"- the notion is that, when investors give us their money, they are foregoing the " +
"opportunity to earn a risk-equivalent rate of return elsewhere; i.e., they are " +
"incurring an opportunity cost to the use of their capital. \n\n Capital" +
" is of two types: owners' money (Equity, E) or borrowed money (Debt, D). " +
"If E expects a return rE, and D expects rD, and 'f is the tax rate, then WACC " +
"is defined as: \n\n WACC = rE (E/(D+E)) + rD(1-t)(D/(D+E))\n\n" +
"We multiply rD by (1-t) to reflect the fact that tax laws allow for interest payments " +
"to debtholders to be deducted as a cost of doing business (while dividend payments " +
"to equityholders, with occasional exceptions, are not). As a result, the true cost " +
"of borrowing is not all of rD, but the after-tax rD. This provision in the tax laws is" +
" said to provide a 'tax shield benefit' to the company.\n\nWhat is the correct WACC " +
"to use? Always that of the asset under consideration and not that of the person " +
"considering the asset (e.g., in acquisition situations, the WACC of the target, not " +
"the acquirer).");
startActivity(intent);
}
});
WACCDetailedPageCostOfCapitalWeightedAverageCostOfCapitalValue =
(EditText) this.findViewById(R.id
.WACCDetailedPageCostOfCapitalWeightedAverageCostOfCapitalValue);
WACCDetailedPageCostOfCapitalWeightedAverageCostOfCapitalValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject.setWACC(
Double.parseDouble(WACCDetailedPageCostOfCapitalWeightedAverageCostOfCapitalValue
.getText().toString()));
//Log.d("TEST", WACCDetailedObject.getCompanyName());
}
}
});
//Number of shares (millions)
WACCDetailedPageCostOfCapitalNumberOfShares = (TextView)
this.findViewById(R.id.WACCDetailedPageCostOfCapitalNumberOfShares);
WACCDetailedPageCostOfCapitalNumberOfShares.setText("Number of shares \n(millions)");
WACCDetailedPageCostOfCapitalNumberOfShares
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Logic
Intent intent = new Intent(WACCDetailedPageCostOfCapitalInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "'This is the total number of common" +
" shares outstanding.");
startActivity(intent);
}
});
WACCDetailedPageCostOfCapitalNumberOfSharesValue =
(EditText) this.findViewById(R.id
.WACCDetailedPageCostOfCapitalNumberOfSharesValue);
WACCDetailedPageCostOfCapitalNumberOfSharesValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject.setNumberOfShares(
Double.parseDouble(WACCDetailedPageCostOfCapitalNumberOfSharesValue
.getText().toString()));
//Log.d("TEST", WACCDetailedObject.getCompanyName());
}
}
});
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//leverage the Snackbar to make user aware of any errors in their data
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Data Submitted", null).show();
//Add all the model data here
WACCDetailedObject.setCash(Double.parseDouble(
WACCDetailedPageCostOfCapitalCashValue.getText().toString()));
WACCDetailedObject.setDebt(Double.parseDouble(
WACCDetailedPageCostOfCapitalDebtValue.getText().toString()));
WACCDetailedObject.setMarketCapitalization(Double.parseDouble(
WACCDetailedPageCostOfCapitalMarketCapValue.getText().toString()));
WACCDetailedObject.setEquityBeta(Double.parseDouble(
WACCDetailedPageCostOfCapitalEquityBetaValue.getText().toString()));
WACCDetailedObject.setRiskFreeRate(Double.parseDouble(
WACCDetailedPageCostOfCapitalRiskFreeRateValue.getText().toString()));
WACCDetailedObject.setMarketRiskPremium(Double.parseDouble(
WACCDetailedPageCostOfCapitalMarketRiskPremiumValue.getText().toString()));
WACCDetailedObject.setLeveredCostOfEquity(Double.parseDouble(
WACCDetailedPageCostOfCapitalLeveredCostOfEquityValue.getText().toString()));
WACCDetailedObject.setCostOfDebt(Double.parseDouble(
WACCDetailedPageCostOfCapitalCostOfDebtValue.getText().toString()));
WACCDetailedObject.setWACC(Double.parseDouble(
WACCDetailedPageCostOfCapitalWeightedAverageCostOfCapitalValue
.getText().toString()));
WACCDetailedObject.setNumberOfShares(Integer.valueOf(
WACCDetailedPageCostOfCapitalNumberOfSharesValue
.getText().toString()));
}
});
}
}
<file_sep>/app/src/main/java/com/example/finance/googlesheetsexample/WACCDetailedFreeCashFlowInputs.java
package com.example.finance.googlesheetsexample;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.drawerlayout.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
public class WACCDetailedFreeCashFlowInputs extends FirstScreenToShowMenu {
private DrawerLayout mDrawerLayout;
private TextView WACCDetailedFreeCashFlowInputsTitle;
private TextView WACCDetailedFreeCashFlowInputsCompanyNameValue;
private TextView WACCDetailedFreeCashFlowInputsCompanyNameText;
private TextView WACCDetailedFreeCashFlowInputsBaseYear;
private TextView WACCDetailedFreeCashFlowInputsBaseYearValue;
private TextView WACCDetailedFreeCashFlowInputsNumberForecastPeriods;
private TextView WACCDetailedFreeCashFlowInputsNumberForecastPeriodsValue;
private TextView WACCDetailedFreeCashFlowInputsBaseYearRevenue;
private TextView WACCDetailedFreeCashFlowInputsCurrentYearRevenueValue;
private TextView WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRate;
private TextView WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateValue;
private TextView WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateToTerminal;
private TextView WACCDetailedFreeCashFlowInputsCostGoodsSold;
private TextView WACCDetailedFreeCashFlowInputsCostGoodsSoldValue;
private ToggleButton WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateToTerminalToggleButton;
private TextView WACCDetailedFreeCashFlowInputsCostGoodsSoldButton;
private TextView WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateButton;
private boolean WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateToTerminalToggleButtonCondition;
private TextView WACCDetailedFreeCashFlowInputsSGA;
private TextView WACCDetailedFreeCashFlowInputsSGAValue;
private TextView WACCDetailedFreeCashFlowInputsInitialEBIT;
private TextView WACCDetailedFreeCashFlowInputsInitialEBITValue;
private TextView WACCDetailedFreeCashFlowInputsLastPeriodEBIT;
private TextView WACCDetailedFreeCashFlowInputsLastPeriodEBITValue;
private TextView WACCDetailedFreeCashFlowInputsCapitalExpenditure;
private TextView WACCDetailedFreeCashFlowInputsCapitalExpenditureValue;
private TextView WACCDetailedFreeCashFlowInputsOperatingNWC;
private TextView WACCDetailedFreeCashFlowInputsOperatingNWCValue;
private TextView WACCDetailedFreeCashFlowInputsStraightLineYears;
private TextView WACCDetailedFreeCashFlowInputsStraightLineYearsValue;
private TextView WACCDetailedFreeCashFlowInputsTaxRate;
private TextView WACCDetailedFreeCashFlowInputsTaxRateValue;
private TextView WACCDetailedFreeCashFlowInputsBaseYearDepreciation;
private TextView WACCDetailedFreeCashFlowInputsBaseYearDepreciationValue;
private WACCDetailedObject WACCDetailedObject;
//TODO add ability to pull data from website
//TODO add a vertical scroll with an animated floating "Submit" button
//TODO use side scroll to go to next input section of model, for example:
// TODO Free Cash Flow inputs to Cost Of Capital Inputs
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.waccdetailedpagefreecashflowinputs, frameLayout);
WACCDetailedFreeCashFlowInputsTitle = (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsTitle);
WACCDetailedFreeCashFlowInputsTitle.setText("'WACC: Detailed' Model Inputs: Free Cash Flow " +
"(FCFF)");
WACCDetailedFreeCashFlowInputsCompanyNameText = (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsCompanyNameText);
WACCDetailedFreeCashFlowInputsCompanyNameText.setText("Company Name");
WACCDetailedFreeCashFlowInputsCompanyNameValue = (EditText) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsCompanyNameInput);
//do error checking, implement Excel here
WACCDetailedFreeCashFlowInputsBaseYear = (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsBaseYear);
WACCDetailedFreeCashFlowInputsBaseYear.setText("Base Year");
WACCDetailedFreeCashFlowInputsBaseYear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "If you are doing a valuation mid-year" +
", the base year may span two years. for instance, you may have a fiscal " +
"year that ends in June 2011, or use trailing 12-month data from July " +
"2010 to June 2011. The first year of the forecast will be labeled 2012 " +
"but it will represent the cash flow from July 2011 to " +
"June 2012.");
startActivity(intent);
}
});
WACCDetailedFreeCashFlowInputsBaseYearValue = (EditText)
this.findViewById
(R.id.
WACCDetailedFreeCashFlowInputsBaseYearValue);
//Number of Forecast Periods
WACCDetailedFreeCashFlowInputsNumberForecastPeriods = (TextView) this.findViewById
(R.id.WACCDetailedFreeCashFlowInputsNumberForecastPeriods);
WACCDetailedFreeCashFlowInputsNumberForecastPeriods.setText("Number of forecast periods");
WACCDetailedFreeCashFlowInputsNumberForecastPeriods.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "We recommend using at least five " +
"forecast periods, but perhaps no more than ten.");
startActivity(intent);
}
});
WACCDetailedFreeCashFlowInputsNumberForecastPeriodsValue = (EditText)
this.findViewById
(R.id.
WACCDetailedFreeCashFlowInputsNumberForecastPeriodsValue);
//Base year revenue input
WACCDetailedFreeCashFlowInputsBaseYearRevenue = (TextView) this.findViewById
(R.id.WACCDetailedFreeCashFlowInputsBaseYearRevenue);
WACCDetailedFreeCashFlowInputsBaseYearRevenue.setText("Base year revenue ($ millions)");
WACCDetailedFreeCashFlowInputsBaseYearRevenue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "This is the total revenue (sales) " +
"during the base year in US dollars (or in absolute terms). " +
"Once you have picked your units, make sure to stay consistent " +
"with those same units for your other inputs. \n\n " +
"In some instances, base year revenue may require to be " +
"'normalized.' This requries judgment, especially in " +
"cyclical businesses, industries whose revenues are " +
"dependent on commodity prices, or when base-year revenue " +
"and profits of the firms were subject to extraordinary " +
"exogenous shocks (e.g., a dotcom firm in the early 2000s, " +
"or a financial services firm in 2008-09).");
startActivity(intent);
}
});
WACCDetailedFreeCashFlowInputsCurrentYearRevenueValue = (EditText)
this.findViewById
(R.id.WACCDetailedFreeCashFlowInputsBaseYearRevenueValue);
//Annual revenue growth rate
WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRate = (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRate);
WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRate.setText("Annual revenue growth rate (%)");
WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "This is one where mistakes are often made! " +
"Just calculating the firm's past compounded annual growth rates (CAGR) " +
"in revenue, and treating that as a basis for a future forecast will " +
"likely over- or underestimate growth rates. \n\n " +
"For instance, past CAGRs reflect revenue gained from acquisitions " +
"(overestimate) or that lost from divestitures and asset sales " +
"(underestimate). Similarly, they could reflect the positive or " +
"negative effects of a home currency depreciation or appreciation. " +
"We recommend that revenue CAGR forecasts be based on organic (bolded) " +
"(i.e., non-acquisition), constant-currency (bolded) (i.e., no real " +
"exchange rate effects) growth rates. In some instances, " +
"the industry growth rate can give you a better estimate, but even then, " +
"recognize that currency or cross-border acquisition effects might be " +
"present. \n\n Also, note that you can input negative revenue growth rates " +
"(but note they can't be negative forever!). If you input a negative number " +
"here, a new screen will open up which will require you to input year-by-year " +
"growth rates (i.e., to allow you to change rates from negative to positive) " +
"during the forecast period.");
startActivity(intent);
}
});
WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRate.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, pdf_viewer.class);
startActivity(intent);
return false;
}
});
WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateValue = (EditText)
this.findViewById(R.id.WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateValue);
//Revenue growth fade to terminal growth
//TODO this can be changed to Different per-period revenue growth rates?
WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateToTerminal = (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateToTerminal);
WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateToTerminal.setText("Revenue growth fade to terminal growth?");
WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateToTerminalToggleButton =
(ToggleButton) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateToTerminalToggleButton);
WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateToTerminalToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateToTerminalToggleButtonCondition = true;
WACCDetailedObject.setRevenueGrowthFadeToTerminalGrowth(true);
} else {
WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateToTerminalToggleButtonCondition = false;
WACCDetailedObject.setRevenueGrowthFadeToTerminalGrowth(false);
}
}
});
//TO BE USED IN DIFFERENT PER_PERIOD REVENUE GROWTH RATES
// intent.putExtra("isExcelPopup", "false");
// intent.putExtra("message", "The default is set to 'NO'. If you wish to " +
// "input a different revenue growth rate for each period, touch the " +
// "button to change it to 'YES'. A new screen will open up which " +
// "will give you the option to do so. \n\n The screen will also " +
// "open up if you input a negative revenue growth rate in the previous " +
// "cell, requiring you to input year-by-year growth rates" +
// "(thereby allowing you to change rates from negative to positive) " +
// "during the forecast period.");
//
// startActivity(intent);
//Cost of goods sold as % revenue
//only show if option "Input % CGS and % SGA"
//TODO make textviews be dynamically be added based off previous input
TextView tvcostofgood = (TextView)findViewById(R.id.WACCDetailedFreeCashFlowInputsCostGoodsSold);
tvcostofgood.setVisibility(View.INVISIBLE);
TextView tvcostofgoodvalue = (TextView)findViewById(R.id.WACCDetailedFreeCashFlowInputsCostGoodsSoldValue);
tvcostofgoodvalue.setVisibility(View.INVISIBLE);
TextView tvFreeCashFlowInputsSGA = (TextView)findViewById(R.id.WACCDetailedFreeCashFlowInputsSGA);
tvFreeCashFlowInputsSGA.setVisibility(View.INVISIBLE);
TextView tvFreeCashFlowInputsSGAValue = (TextView)findViewById(R.id.WACCDetailedFreeCashFlowInputsSGAValue);
tvFreeCashFlowInputsSGAValue.setVisibility(View.INVISIBLE);
if (WACCDetailedObject.getOperatingIncomeOption() == "Will input percent CGS and percent SGA") {
tvcostofgood = (TextView)findViewById(R.id.WACCDetailedFreeCashFlowInputsCostGoodsSold);
tvcostofgood.setVisibility(View.VISIBLE);
tvcostofgoodvalue = (TextView)findViewById(R.id.WACCDetailedFreeCashFlowInputsCostGoodsSoldValue);
tvcostofgoodvalue.setVisibility(View.VISIBLE);
tvFreeCashFlowInputsSGA = (TextView)findViewById(R.id.WACCDetailedFreeCashFlowInputsSGA);
tvFreeCashFlowInputsSGA.setVisibility(View.VISIBLE);
tvFreeCashFlowInputsSGAValue = (TextView)findViewById(R.id.WACCDetailedFreeCashFlowInputsSGAValue);
tvFreeCashFlowInputsSGAValue.setVisibility(View.VISIBLE);
WACCDetailedFreeCashFlowInputsCostGoodsSold = (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsCostGoodsSold);
WACCDetailedFreeCashFlowInputsCostGoodsSold.setText("Cost of goods sold as % revenue");
WACCDetailedFreeCashFlowInputsCostGoodsSold.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "Cost of goods sold (CGS) captures, in principle, " +
"the direct costs of producing and selling the company's goods and services. " +
"In most financial reporting, CGS-typically includes associated Depreciation " +
" (make in italics) charges.");
startActivity(intent);
}
});
WACCDetailedFreeCashFlowInputsCostGoodsSold.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, pdf_viewer.class);
startActivity(intent);
return false;
}
});
WACCDetailedFreeCashFlowInputsCostGoodsSoldValue = (EditText) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsCostGoodsSoldValue);
//SG&A as % revenue
WACCDetailedFreeCashFlowInputsSGA
= (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsSGA);
WACCDetailedFreeCashFlowInputsSGA.setText("SG&A (incl. R&D) as % revenue");
WACCDetailedFreeCashFlowInputsSGA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "SG&A - selling, general, and administrative " +
"expenditures or SGA - captures, in principle, the indirect costs of producing " +
"and selling the company's goods and services. (R&D expenses are assumed to " +
"be included, so if it is reported separately in the company's financial " +
"statements, R&D should be included here.) In most financial reporting, SGA " +
"typically includes the associated Depreciation (make in italics) charges.");
startActivity(intent);
}
});
WACCDetailedFreeCashFlowInputsSGA.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, pdf_viewer.class);
startActivity(intent);
return false;
}
});
WACCDetailedFreeCashFlowInputsSGAValue
= (EditText) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsSGAValue);
//do error checking, implement Excel here
WACCDetailedFreeCashFlowInputsSGAValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject.setSGAValue(Double.parseDouble(WACCDetailedFreeCashFlowInputsSGAValue.getText().toString()));
//Log.d("TEST", WACCDetailedObject.);
}
}
});
}
//Initial EBIT
WACCDetailedFreeCashFlowInputsInitialEBIT
= (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsInitialEBIT);
WACCDetailedFreeCashFlowInputsInitialEBIT.setText("Initial EBIT as % revenue (Operating Income)");
WACCDetailedFreeCashFlowInputsInitialEBIT.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "EBIT = Operating Income = Revenue - CGS - SGA " +
"(if Depreciation (italics) is not already included in CGS and SGA, it has to be " +
"subtracted). \n\n The input here is the percent operating margin for Year 1 " +
"of the valuation. (Note that initial EBIT can be a negative number; in that event, " +
"last-period EBIT as % revenue should be input as a positive number; see below.)");
startActivity(intent);
}
});
WACCDetailedFreeCashFlowInputsInitialEBIT.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, pdf_viewer.class);
startActivity(intent);
return false;
}
});
WACCDetailedFreeCashFlowInputsInitialEBITValue
= (EditText) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsInitialEBITValue);
WACCDetailedFreeCashFlowInputsInitialEBITValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject
.setInitialEBIT(Double.
valueOf(WACCDetailedFreeCashFlowInputsInitialEBITValue.getText().toString()));
//Log.d("TEST", WACCDetailedObject.);
}
}
});
//Last-period EBIT
WACCDetailedFreeCashFlowInputsLastPeriodEBIT = (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsLastPeriodEBIT);
WACCDetailedFreeCashFlowInputsLastPeriodEBIT.setText("Last-period/last year EBIT as % revenue");
WACCDetailedFreeCashFlowInputsLastPeriodEBIT.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "This is the targeted operating margin for the " +
"last year of the forecast period. The defualt value is set to the initial EBIT as " +
"% revenue, but you can change it. \n\n The model changes the percent operating margin " +
"linearly between the first period and last. It is, therefore, possible to model a " +
"situation where the firm has negative initial EBIT but its EBIT grows positive over time" +
" ; or the firm has a supra-normal initial EBIT but its EBIT declines over time.");
startActivity(intent);
}
});
WACCDetailedFreeCashFlowInputsLastPeriodEBIT.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, pdf_viewer.class);
startActivity(intent);
return false;
}
});
WACCDetailedFreeCashFlowInputsLastPeriodEBITValue
= (EditText) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsLastPeriodEBITValue);
WACCDetailedFreeCashFlowInputsLastPeriodEBITValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject
.setLastYearEBIT(Double.
valueOf(
WACCDetailedFreeCashFlowInputsLastPeriodEBITValue
.getText().toString()));
//Log.d("TEST", WACCDetailedObject.);
}
}
});
//Capital expenditure as % revenue
WACCDetailedFreeCashFlowInputsCapitalExpenditure = (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsCapitalExpenditure);
WACCDetailedFreeCashFlowInputsCapitalExpenditure.setText("Capital expenditure as % revenue (Capex)");
WACCDetailedFreeCashFlowInputsCapitalExpenditure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "You have three choices for this input. You " +
"can divide the capital expenditure in the most recent period by revenues " +
"and use the value; while simple, it could be affected by unusually high or low" +
" numbers in the base year. You can choose an average value over 3-5 years to smooth " +
"the input. Or, you can use an industry average. (If you are using the Cash Flow " +
"Statement to get this number, know that is may how up with a negative sign!).");
startActivity(intent);
}
});
WACCDetailedFreeCashFlowInputsCapitalExpenditure.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, pdf_viewer.class);
startActivity(intent);
return false;
}
});
WACCDetailedFreeCashFlowInputsCapitalExpenditureValue
= (EditText) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsCapitalExpenditureValue);
WACCDetailedFreeCashFlowInputsCapitalExpenditureValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject
.setCapitalExpenditure(Double.
valueOf(
WACCDetailedFreeCashFlowInputsCapitalExpenditureValue
.getText().toString()));
//Log.d("TEST", WACCDetailedObject.);
}
}
});
//Operating NWC as % revenue
WACCDetailedFreeCashFlowInputsOperatingNWC = (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsOperatingNWC);
WACCDetailedFreeCashFlowInputsOperatingNWC.setText("Operating NWC (Non-cash working capital)" +
" as % revenue");
WACCDetailedFreeCashFlowInputsOperatingNWC.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "Operating net working capital (NWC) is " +
"the non-cash (needs to be underlined) current assets minus non-debt (underlined) " +
"current liabilities. You can use the last year's number, or a 'normalized' " +
"number for your company over time, or an industry average.\n\n" +
"In principle, NWC can be negative (i.e., a source of cash) if non-cash " +
"current assets are smaller than the non-debt current liabilities. In our " +
"model, we do not allow negative NWC. The reason is, allowing negative NWC " +
"to grow over time (as revenue grows) can not only inflate cash flows forecasts, " +
"but also make accounts payable unsustainable thereby impacting credit risk. " +
"Hence, we put a floor of zero for this input. \n\n" +
"When inputting the assumption for 'Operating NWC as % revenue', " +
"note that you are inputting the percentage for total (i.e., not " +
"incremental) revenue for the forecasted year. In other words, the " +
"input you provide will calculate the total NWC for the year, based on" +
" which, the model will calculate the Change in NWC.");
startActivity(intent);
}
});
WACCDetailedFreeCashFlowInputsOperatingNWCValue
= (EditText) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsOperatingNWCValue);
WACCDetailedFreeCashFlowInputsOperatingNWCValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject
.setOperatingNWC(Double.
valueOf(
WACCDetailedFreeCashFlowInputsOperatingNWCValue
.getText().toString()));
//Log.d("TEST", WACCDetailedObject.);
}
}
});
//Straight-line depreciation rule
//Straight-line method; Depreciation Expense = Depreciable Amount/ Useful Life
TextView tvStraightLine = (TextView)findViewById(R.id.WACCDetailedFreeCashFlowInputsStraightLineYears);
tvStraightLine.setVisibility(View.INVISIBLE);
TextView tvStraightLineValue = (TextView)findViewById(R.id.WACCDetailedFreeCashFlowInputsStraightLineValue);
tvStraightLineValue.setVisibility(View.INVISIBLE);
if (WACCDetailedObject.getDepreciationOption().equals("Will use straight line rule")) {
tvStraightLine = (TextView)findViewById(R.id.WACCDetailedFreeCashFlowInputsStraightLineYears);
tvStraightLine.setVisibility(View.VISIBLE);
tvStraightLineValue = (TextView)findViewById(R.id.WACCDetailedFreeCashFlowInputsStraightLineValue);
tvStraightLineValue.setVisibility(View.VISIBLE);
WACCDetailedFreeCashFlowInputsStraightLineYears = (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsStraightLineYears);
WACCDetailedFreeCashFlowInputsStraightLineYears.setText("Straight-line depreciation rule (#years)");
WACCDetailedFreeCashFlowInputsStraightLineYears.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "If you chose the option of 'straight line" +
" depreciation rule' in the 'Key Questions' page, the model will calculate " +
"Year T Depreciation (italics) as: \n\n Dt = Dt-1 + [Capext/N] " +
"\n\n where Capext is the Capital expenditure for Year T, and N is " +
"assumed average depreciable life of assets. (If the number of forecast " +
"periods exceeds N, the model fades Depreciation (italics) charges " +
"to account for the fact that capital expenditure incurred in the early " +
"periods will get fully depreciated, i.e., to account for the fact that " +
"its book value fades to zero.)");
startActivity(intent);
}
});
WACCDetailedFreeCashFlowInputsStraightLineYearsValue
= (EditText) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsStraightLineValue);
WACCDetailedFreeCashFlowInputsStraightLineYearsValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject
.setStraightLineDepreciationYears(Integer.
valueOf(
WACCDetailedFreeCashFlowInputsStraightLineYearsValue
.getText().toString()));
//Log.d("TEST", WACCDetailedObject.);
}
}
});
}
//Tax rate
WACCDetailedFreeCashFlowInputsTaxRate = (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsTaxRate);
WACCDetailedFreeCashFlowInputsTaxRate.setText("Tax rate (T; %)");
WACCDetailedFreeCashFlowInputsTaxRate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "Under the assumption that there are few " +
"long-run permanent differences, we recommend using a rate that is much " +
"closer to the statutory rate plus local tax rate (30% - 40% in the US) " +
"than to zero. \n\n In the case of firms that grant a lot of stock " +
"options, a somewhat lower rate (e.g., 25% - 30%) might be justified, " +
"assuming that the tax benefit associated with employee options " +
"exercise continues into the future.");
startActivity(intent);
}
});
WACCDetailedFreeCashFlowInputsTaxRateValue
= (EditText) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsTaxRateValue);
WACCDetailedFreeCashFlowInputsTaxRateValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject
.setTaxRate(Double.
valueOf(
WACCDetailedFreeCashFlowInputsTaxRateValue
.getText().toString()));
//Log.d("TEST", WACCDetailedObject.);
}
}
});
WACCDetailedFreeCashFlowInputsBaseYearDepreciation = (TextView) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsBaseYearDepreciation);
WACCDetailedFreeCashFlowInputsBaseYearDepreciation.setText("Base year depreciation ($ millions)");
WACCDetailedFreeCashFlowInputsBaseYearDepreciation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, PopUpWindow.class);
intent.putExtra("isExcelPopup", "false");
intent.putExtra("message", "The base year value for this can " +
"be found in the Cash Flow Statement.");
startActivity(intent);
}
});
WACCDetailedFreeCashFlowInputsBaseYearDepreciation.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent(WACCDetailedFreeCashFlowInputs.this, pdf_viewer.class);
startActivity(intent);
return false;
}
});
WACCDetailedFreeCashFlowInputsBaseYearDepreciationValue
= (EditText) this.findViewById(R.id.WACCDetailedFreeCashFlowInputsBaseYearDepreciationValue);
WACCDetailedFreeCashFlowInputsBaseYearDepreciationValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
//SAVE THE DATA
WACCDetailedObject
.setBaseYearDepreciation(Double.
valueOf(
WACCDetailedFreeCashFlowInputsBaseYearDepreciationValue
.getText().toString()));
//Log.d("TEST", WACCDetailedObject.);
}
}
});
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//leverage the Snackbar to make user aware of any errors in their data
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Data Submitted", null).show();
//Add all the model data here
WACCDetailedObject.
setCompanyName(WACCDetailedFreeCashFlowInputsCompanyNameValue.getText().toString());
WACCDetailedObject.setBaseYear(Integer.parseInt(
WACCDetailedFreeCashFlowInputsBaseYearValue.getText().toString()));
WACCDetailedObject.setNumberOfForecastPeriods(Integer.parseInt(
WACCDetailedFreeCashFlowInputsNumberForecastPeriodsValue.getText().toString()));
Double num = Double.parseDouble(
WACCDetailedFreeCashFlowInputsCurrentYearRevenueValue.getText().toString());
WACCDetailedObject.setCurrentYearRevenue(Double.parseDouble(
WACCDetailedFreeCashFlowInputsCurrentYearRevenueValue.getText().toString()));
String string = Double.toString(WACCDetailedObject.getCurrentYearRevenue());
Log.v("CurrentYearRevenue", String.valueOf(WACCDetailedObject.getCurrentYearRevenue()));
WACCDetailedObject.setAnnualRevenueGrowthPercentage(Double.parseDouble(
WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateValue.getText().toString()));
if (WACCDetailedObject.getOperatingIncomeOption() == "Will input percent CGS and percent SGA") {
WACCDetailedObject.setCostOfGoodsSoldAsPercentage(Double.parseDouble(
WACCDetailedFreeCashFlowInputsCostGoodsSoldValue.getText().toString()));
WACCDetailedObject.setSGAValue(Double.parseDouble(
WACCDetailedFreeCashFlowInputsSGAValue.getText().toString()));
}
WACCDetailedObject.setInitialEBIT(Double.parseDouble(
WACCDetailedFreeCashFlowInputsInitialEBITValue.getText().toString()));
WACCDetailedObject.setLastYearEBIT(Double.parseDouble(
WACCDetailedFreeCashFlowInputsLastPeriodEBITValue.getText().toString()));
WACCDetailedObject.setCapitalExpenditure(Double.parseDouble(
WACCDetailedFreeCashFlowInputsCapitalExpenditureValue.getText().toString()));
WACCDetailedObject.setOperatingNWC(Double.parseDouble(
WACCDetailedFreeCashFlowInputsOperatingNWCValue.getText().toString()));
WACCDetailedObject.setStraightLineDepreciationYears(Integer.valueOf(
WACCDetailedFreeCashFlowInputsStraightLineYearsValue.getText().toString()));
WACCDetailedObject.setBaseYearDepreciation(Double.parseDouble(
WACCDetailedFreeCashFlowInputsBaseYearDepreciationValue.getText().toString()));
WACCDetailedObject.setOperatingNWC(Double.parseDouble(
WACCDetailedFreeCashFlowInputsOperatingNWCValue.getText().toString()));
WACCDetailedObject.setTaxRate(Double.parseDouble(
WACCDetailedFreeCashFlowInputsOperatingNWCValue.getText().toString()));
}
});
}
}
<file_sep>/app/src/main/java/com/example/finance/googlesheetsexample/UserList.java
package com.example.finance.googlesheetsexample;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.finance.googlesheetsexample.androidlabs.gsheets1.JSONparser;
import com.example.finance.googlesheetsexample.androidlabs.gsheets1.MyArrayAdapter;
import com.example.finance.googlesheetsexample.androidlabs.gsheets1.MyDataModel;
import com.example.finance.googlesheetsexample.util.InternetConnection;
import com.example.finance.googlesheetsexample.util.Keys;
import com.facebook.drawee.backends.pipeline.Fresco;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class UserList extends FirstScreenToShowMenu {
private ListView listView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
private DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waitingscreentopullexceldata);
Fresco.initialize(this);
//!!!!!!!!!!!!!FORMAT THIS EVENTUALLY!!!!!!!!!!!!!!!!!!!!!
//Below is repeat code from the FirstScreenToShowMenu, FirstScreenToShowMenu and Userlist use
//the same code as below, see if there is a way to condense this
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.baseline_menu_black_18dp);
mDrawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.bringToFront();
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// set item as selected to persist highlight
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
return true;
}
});
/**
* Array List for Binding Data from JSON to this List
*/
list = new ArrayList<>();
/**
* Binding that List to Adapter
*/
adapter = new MyArrayAdapter(this, list);
/**
* Getting List and Setting List Adapter
*/
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//list.get(position).getPhone()
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Snackbar.make(findViewById(R.id.parentLayout), list.get(position).getYear() + " => " + list.get(position).getCashFlowToEquity(), Snackbar.LENGTH_LONG).show();
}
});
/**
* Just to know onClick and Printing Hello Toast in Center.
*/
Toast toast = Toast.makeText(getApplicationContext(), "Click on FloatingActionButton to Load JSON", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(@NonNull View view) {
/**
* Checking Internet Connection
*/
if (InternetConnection.checkConnection(getApplicationContext())) {
new GetDataTask().execute();
} else {
Snackbar.make(view, "Internet Connection Not Available", Snackbar.LENGTH_LONG).show();
}
}
});
}
/**
* Creating Get Data Task for Getting Data From Web
*/
class GetDataTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
int jIndex;
int x;
@Override
protected void onPreExecute() {
super.onPreExecute();
/**
* Progress Dialog for User Interaction
*/
x=list.size();
if(x==0)
jIndex=0;
else
jIndex=x;
dialog = new ProgressDialog(UserList.this);
dialog.setTitle("Hey Wait Please..."+x);
dialog.setMessage("I am getting your JSON");
dialog.show();
}
@Nullable
@Override
protected Void doInBackground(Void... params) {
/**
* Getting JSON Object from Web Using okHttp
*/
JSONObject jsonObject = JSONparser.getDataFromWeb();
try {
/**
* Check Whether Its NULL???
*/
if (jsonObject != null) {
/**
* Check Length...
*
*
*/
if(jsonObject.length() > 0) {
/**
* Getting Array named "contacts" From MAIN Json Object
*/
JSONArray array = jsonObject.getJSONArray(Keys.KEY_ENTRY);
/**
* Check Length of Array...
*/
int lenArray = array.length();
if(lenArray > 0) {
for(jIndex = 0; jIndex <= lenArray; jIndex++) {
/**
* Creating Every time New Object
* and
* Adding into List
*/
MyDataModel model = new MyDataModel();
/**
* Getting Inner Object from contacts array...
* and
* From that We will get Name of that Contact
*
*/
JSONObject innerObject = array.getJSONObject(jIndex);
//Log.e("MYAPP", "unexpected JSON exception", e);
try {
int year = innerObject.getInt(Keys.KEY_YEAR);
int cashflowtoequity = innerObject.getInt(Keys.KEY_CFTOEQUITY);
int cashflowtofirm = innerObject.getInt(Keys.KEY_CFTOFIRM);
int difference = innerObject.getInt(Keys.KEY_DIFFERENCE);
model.setYear(year);
model.setCashFlowToEquity(cashflowtoequity);
model.setCashFlowToFirm(cashflowtofirm);
model.setDifference(difference);
}
//probably not best practice here, this can be improved
catch (JSONException je) {
Log.i(JSONparser.TAG, "JSONPARSER error" + je.getLocalizedMessage());
//not needed
model.flipTerminalboolean();
try {
int terminalcashflowtoequity = innerObject.getInt(Keys.KEY_TERMINALCFTOEQUITY);
int terminalcashflowtofirm = innerObject.getInt(Keys.KEY_TERMINALCFTOFIRM);
int terminaldifference = innerObject.getInt(Keys.KEY_TERMINALDIFFERENCE);
model.setTerminalCashFlowToEquity(terminalcashflowtoequity);
model.setTerminalCashFlowToFirm(terminalcashflowtofirm);
model.setTerminaldifference(terminaldifference);
}
catch(JSONException JE){
Log.i(JSONparser.TAG, "JSONPARSER error" + JE.getLocalizedMessage());
}
}
/**
* Getting Object from Object "phone"
*/
//JSONObject phoneObject = innerObject.getJSONObject(Keys.KEY_PHONE);
//String phone = phoneObject.getString(Keys.KEY_MOBILE);
/**
* Adding numeric values from excel sheet to List...
*/
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONparser.TAG, "JSONPARSER error" + je.getLocalizedMessage());
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
/**
* Checking if List size if more than zero then
* Update ListView
*/
if(list.size() > 0) {
adapter.notifyDataSetChanged();
//use the fetched data for calculations here
double EquityValue = 0;
double ValueOfFirm = 0;
for (int i=0; i < adapter.getCount(); i++){
MyDataModel dataModel = adapter.getItem(i);
//int FreeCashFlowToEquity = Net Income - (Capital Expenditures - Depreciation) -
//(Change in Non-cash Working Capital)+ (New Debt Issued - Debt Repayments)
//assuming Two-stage FCFE model, designed to value a firm which is expected to grow
//much faster than a stable firm in the initial period and at a stable rate after that.
//calculate Return on Equity
//Return on Equity = Net Income/Shareholder's Equity
//int ReturnOnEquity = 0/0;
int TerminalValueCFToEquity = 0;
int TerminalValueDifference = 0;
int TerminalValueCFToFirm = 0;
//EquityValue = EquityValue += ((Double.valueOf(dataModel.getCashFlowToEquity()))/(Math.pow(1+CostOfEquity, i+1)));
//ValueOfFirm = ValueOfFirm += ((Double.valueOf(dataModel.getCashFlowToFirm()))/(Math.pow(1+CostOfEquity, i+1)));
}
} else {
Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
}<file_sep>/app/src/main/java/com/example/finance/googlesheetsexample/FirstScreenToShowMenu.java
package com.example.finance.googlesheetsexample;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.navigation.NavigationView;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.widget.Toolbar;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import com.example.finance.googlesheetsexample.post.PostData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by ADJ on 2/21/2017.
*/
public class FirstScreenToShowMenu extends AppCompatActivity{
//THIS IS THE MAIN ACTIVITY//
Button getData;
Button sendData;
FrameLayout frameLayout;
ExpandableListAdapter expandableListAdapter;
ExpandableListView expandableListView;
List<MenuModel> headerList = new ArrayList<>();
HashMap<MenuModel, List<MenuModel>> childList = new HashMap<>();
/**
* This flag is used just to check that launcher activity is called first time
* so that we can open appropriate Activity on launch and make list item position selected accordingly.
* */
private static boolean isLaunch = true;
//TODO check if protected and static is necessary
//TODO figure out a way to pass public data between activities
private DrawerLayout mDrawerLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navbarandtitle);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.baseline_menu_black_18dp);
frameLayout = (FrameLayout)findViewById(R.id.content_frame);
expandableListView = findViewById(R.id.expandableListView);
prepareMenuData();
populateExpandableList();
mDrawerLayout = findViewById(R.id.drawer_layout);
final NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.bringToFront();
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// set item as selected to persist highlight
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
//displaySelectedScreen(menuItem.getItemId());
return true;
}
});
if(isLaunch){
/**
*Setting this flag false so that next time it will not open our first activity.
*We have to use this flag because we are using this BaseActivity as parent activity to our other activity.
*In this case this base activity will always be call when any child activity will launch.
*/
isLaunch = false;
Intent intent = new Intent(getApplicationContext(), MainMenu.class);
startActivity(intent);
}
};
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed ();
}
}
private void displaySelectedScreen(String MenuName) {
//initializing the Activity object which is selected
switch (MenuName) {
case "EquityvalueFirmvalue":
Intent i = new Intent(getApplicationContext(), EquityValueFirmValue.class);
startActivity(i);
break;
}
//initializing the Activity object which is selected
switch (MenuName) {
case "WACCDetailedPageOne":
Intent i = new Intent(getApplicationContext(), WACCDetailedPageOne.class);
startActivity(i);
break;
}
switch (MenuName) {
case "WACCDetailedPageTwo":
Intent i = new Intent(getApplicationContext(), WACCDetailedPageTwo.class);
startActivity(i);
break;
}
switch (MenuName) {
case "WACCDetailedFreeCashFlowInputs":
Intent i = new Intent(getApplicationContext(), WACCDetailedFreeCashFlowInputs.class);
startActivity(i);
break;
}
switch (MenuName) {
case "WACCDetailedPageCostOfCapitalInputs":
Intent i = new Intent(getApplicationContext(), WACCDetailedPageCostOfCapitalInputs.class);
startActivity(i);
break;
}
switch (MenuName) {
case "WACCDetailedPageTerminalValue":
Intent i = new Intent(getApplicationContext(), WACCDetailedPageTerminalValue.class);
startActivity(i);
break;
}
switch (MenuName) {
case "WACCDetailedPageResults":
Intent i = new Intent(getApplicationContext(), WACCDetailedPageResults.class);
startActivity(i);
break;
}
//Blockly Options
switch (MenuName) {
case "Blockly Setup":
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
@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) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.viweruser:
Intent intent = new Intent(getApplicationContext(), UserList.class);
startActivity(intent);
return true;
case R.id.adduser:
intent = new Intent(getApplicationContext(), PostData.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
private void prepareMenuData() {
MenuModel menuModel = new MenuModel("EquityvalueFirmvalue", true, false);
headerList.add(menuModel);
if (!menuModel.hasChildren) {
childList.put(menuModel, null);
}
menuModel = new MenuModel("WACCDetailed", true, true);
headerList.add(menuModel);
List<MenuModel> childModelsList = new ArrayList<>();
MenuModel childModel = new MenuModel("WACCDetailedPageOne", false, false);
childModelsList.add(childModel);
childModel = new MenuModel("WACCDetailedPageTwo", false, false);
childModelsList.add(childModel);
childModel = new MenuModel("WACCDetailedFreeCashFlowInputs", false, false);
childModelsList.add(childModel);
childModel = new MenuModel("WACCDetailedPageCostOfCapitalInputs", false, false);
childModelsList.add(childModel);
childModel = new MenuModel("WACCDetailedPageTerminalValue", false, false);
childModelsList.add(childModel);
childModel = new MenuModel("WACCDetailedPageResults", false, false);
childModelsList.add(childModel);
if (menuModel.hasChildren) {
Log.d("API123","here");
childList.put(menuModel, childModelsList);
}
menuModel = new MenuModel("WACSimple", true, false);
headerList.add(menuModel);
if (!menuModel.hasChildren) {
childList.put(menuModel, null);
}
menuModel = new MenuModel("APVDetailed", true, false);
headerList.add(menuModel);
if (!menuModel.hasChildren) {
childList.put(menuModel, null);
}
menuModel = new MenuModel("APVSimple", true, false);
headerList.add(menuModel);
if (!menuModel.hasChildren) {
childList.put(menuModel, null);
}
menuModel = new MenuModel("Dividend Growth Model", true, false);
headerList.add(menuModel);
if (!menuModel.hasChildren) {
childList.put(menuModel, null);
}
menuModel = new MenuModel("Real Options Valuation", true, false);
headerList.add(menuModel);
if (!menuModel.hasChildren) {
childList.put(menuModel, null);
}
menuModel = new MenuModel("Not Sure", true, false);
headerList.add(menuModel);
if (!menuModel.hasChildren) {
childList.put(menuModel, null);
}
menuModel = new MenuModel("Blockly Setup", true, false);
headerList.add(menuModel);
if (!menuModel.hasChildren) {
childList.put(menuModel, null);
}
}
private void populateExpandableList() {
expandableListAdapter = new ExpandableListAdapter(this, headerList, childList);
expandableListView.setAdapter(expandableListAdapter);
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
if (headerList.get(groupPosition).isGroup) {
if (!headerList.get(groupPosition).hasChildren) {
// WebView webView = findViewById(R.id.webView);
// webView.loadUrl(headerList.get(groupPosition).url);
displaySelectedScreen(headerList.get(groupPosition).menuName);
onBackPressed();
// close drawer when item is tapped
//mDrawerLayout.closeDrawers();
}
}
return false;
}
});
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
if (childList.get(headerList.get(groupPosition)) != null) {
MenuModel model = childList.get(headerList.get(groupPosition)).get(childPosition);
//WebView webView = findViewById(R.id.webView);
//webView.loadUrl(model.url);
displaySelectedScreen(model.menuName);
onBackPressed();
}
return false;
}
});
}
}
<file_sep>/app/src/main/java/com/example/finance/googlesheetsexample/WACCDetailedPageTwo.java
package com.example.finance.googlesheetsexample;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class WACCDetailedPageTwo extends FirstScreenToShowMenu {
private TextView WACCDetailedPageTwoTitle;
private TextView WACCDetailedPageTwoOperatingIncome;
private Spinner WACCPageTwoOperatingIncomeSpinner;
private TextView WACCDetailedPageTwoDepreciation;
private Spinner WACCDetailedPageTwoDepreciationSpinner;
private TextView WACCDetailedPageTwoWACC;
private Spinner WACCDetailedPageTwoWACCSpinner;
private TextView WACCDetailedPageTwoTerminalGrowthRate;
private Spinner WACCDetailedPageTwoTerminalGrowthRateSpinner;
private TextView WACCDetailedPageTwoNotes;
private String SpinnerOneText;
private String SpinnerTwoText;
private String SpinnerThreeText;
private String SpinnerFourText;
//might have to use spinner adapters
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.waccdetailedpagetwo,
frameLayout);
WACCDetailedPageTwoOperatingIncome = (TextView) this.findViewById(R.id.WACCDetailedPageTwoOperatingIncome);
WACCDetailedPageTwoDepreciation = (TextView) this.findViewById(R.id.WACCDetailedPageTwoDepreciation);
WACCDetailedPageTwoWACC = (TextView) this.findViewById(R.id.WACCDetailedPageTwoWACC);
WACCDetailedPageTwoTerminalGrowthRate = (TextView) this.findViewById(R.id.WACCDetailedPageTwoTerminalGrowthRate);
WACCDetailedPageTwoNotes = (TextView) this.findViewById(R.id.WACCDetailedPageTwoNotes);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//leverage the Snackbar to make user aware of any errors in their data
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Data Submitted", null).show();
WACCDetailedObject.setOperatingIncomeOption(SpinnerOneText);
WACCDetailedObject.setDepreciationOption(SpinnerTwoText);
WACCDetailedObject.setWACCOption(SpinnerThreeText);
WACCDetailedObject.setTerminalGrowthRateOption(SpinnerFourText);
Log.v("Spinner", WACCDetailedObject.getDepreciationOption());
}
});
addItemsOnSpinner1();
addItemsOnSpinner2();
addItemsOnSpinner3();
addItemsOnSpinner4();
WACCDetailedPageTwoTitle = (TextView) this.findViewById(R.id.WACCDetailedPageTwoTitle);
WACCDetailedPageTwoTitle.setText("A Few Key Questions Before You Start" +
":Before putting in base-year numbers, think through how you wish " +
"to input: Operating Income (i.e., EBIT), Depreciation, WACC, and " +
"Terminal Growth Rate (g). Choose one option under each.");
WACCDetailedPageTwoNotes = (TextView) this.findViewById(R.id.WACCDetailedPageTwoNotes);
WACCDetailedPageTwoNotes.setText("* rE = Levered cost of equity; rD = Cost of debt" +
"; rF = Risk-free rate; ß = Equity beta; " +
"MRP = Market risk premium." +
"** If you choose this option, note that you must also " +
"input rF.");
WACCDetailedPageTwoOperatingIncome.setText("Operating Income");
WACCDetailedPageTwoOperatingIncome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedPageTwo.this, PopUpWindow.class);
intent.putExtra("message", "Terminal Value (TV) is the " +
"continuing value of the business after the detailed forecast (or, 'proforma' " +
") period ends. It is calculated using the constant growth model: " +
"\n\nTV = FCFFr + (WACCr - g)," +
"\n\nwhere FCFFr is the cash flow in the first period after the forecast " +
"period ends (if the forecast period is seven years, this year 8), WACCr " +
"is the cost of capital in perpetuity after the forecast period, and " +
"g is the Terminal Growth Rate (the growth rate in free cash flow in " +
"perpetuity)." +
"\n\n The enterprise value, EV, is the present value of TV plus the " +
"present value of cash flows for each year of the proforma period. " +
"\n\n Some analysts use multiples (e.g., EV/EBITDA, EV/Sales) " +
"to estimate TV. However, g is implicit (and therefore, hidden) " +
"in a multiple, while iti s made explicit in the constant growth model. " +
"Moreover, the danger with using multiples is that they undercut " +
"the very notion that we are undertaking a discounted cash flow " +
"(or intrinsic) valuation, making this instead a hybrid relative valuation.");
startActivity(intent);
}
});
WACCDetailedPageTwoDepreciation.setText("Depreciation");
WACCDetailedPageTwoDepreciation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedPageTwo.this, PopUpWindow.class);
intent.putExtra("message", "Under the accrual method of " +
"accounting, a company's Capex s not deducted as outflow " +
" in the year in which it was incurred. Rather, a " +
"Depreciation charge - a fraction of " +
"the Capex - is annually deducted. Depreciation " +
"is called a 'non-cash' charge since no cash leaves " +
"the firm even though it is booked as an 'expense.' " +
"\n\nThe most common method used in financial " +
"reporting is the 'straight-line' method. " +
"Thus, for example, if we spend $100 on an " +
"asset with a 5-year depreciable life, $20 " +
"is 'deducted' from revenue every year for the " +
"next five years as though money left the company, " +
" even though it did not (it left when " +
"we bought the asset)." +
"\n\nThe key to choosing here is to recognize that " +
"Depreciation comes from Capex in prior years " +
"and the two items are therefore joined at the " +
"hip. The first choice models this explicitly, " +
"by augmenting Capex in each year over the " +
"depreciable life and adding this Depreciation to " +
"the starting year's number. The alternative " +
"choice, Depreciation = Capex is easy to make, " +
"but is incompatible with a rapidly-growing firm " +
"since it keeps the fixed asset base unchanged while " +
"growing revenue and EBIT. It may be a reasonable " +
"choice for firms that are mature, or expect " +
"to grow from improvements in operating efficiencies " +
"(rather than revenue growth).");
startActivity(intent);
}
});
WACCDetailedPageTwoWACC.setText("WACC*");
WACCDetailedPageTwoDepreciation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedPageTwo.this, PopUpWindow.class);
intent.putExtra("message", "The concept of WACC, " +
"cost of capital is explained in the " +
"previous page. We will focus here on how to " +
"input it into the model. " +
"\n\nThe simplest choice is to enter it " +
"directly (you will get to that soon). You " +
"could use the cost of capital for the firm, or that " +
"for other firms in the sector to which the firm belongs. " +
"(Check the data set of indsutry averages for this " +
"estiamte. It is in US dollars. If you want " +
"to convert to a different currency, an approximation " +
"is to add the difference in inflation rates between the " +
"currency and the US dollar to this WACC). " +
"\n\nIn the secoond choice, you have to enter the " +
"cost of equtiy (rE) and the cost of debt (rD) for " +
"the firm. (For guidance, industry averages for these " +
"nubmers are available in the data set.) " +
"\n\nIn the third choice, you can use the Capital " +
"Asset Pricing Model (CAPM) to estimate rE: " +
"\n\nrE = rF + BE x MRP " +
"\n\nrF is the risk-free rate in the currency in which " +
"cash flows are denominated, BE measures the " +
"relative risk of your stock against a market index, and " +
"MRP is the market (or 'equity') risk premium, " +
"reflecting how risky investors percieve equity as an " +
"investment class to be, relative to a risk-free investment.");
startActivity(intent);
}
});
WACCDetailedPageTwoTerminalGrowthRate.setText("Terminal Growth Rate, g");
WACCDetailedPageTwoTerminalGrowthRate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WACCDetailedPageTwo.this, PopUpWindow.class);
intent.putExtra("message", "The Terminal Growth Rate, g, " +
"is the growth rate you anticipate " +
"for this firm in perpetuity. Since " +
"this growth rate goes into a terminal " +
"value equation, small changes in the growth " +
"rate - all else constant - " +
"can translate into large changes in value. " +
" Thus, casually changing the growth rate " +
"can lead to potentially large swings in DCF " +
"valuation." +
"\n\nTo anchor the growth rate, follow two " +
"simple rules. The first, ensure that g " +
"does not exceed the growth rate of the " +
"economy. In fact, a further simplication is " +
"this: g should not exceed the risk-free rate " +
"The second is to ensure that you are " +
"setting aside enough as reinvestment to " +
"sustain your growth rate. If the Terminal " +
"Reinvestment Rate is RR, and Terminal Return " +
"on Invested Capital is ROIC, then: " +
"\n\nRR = g + ROIC " +
"\n\n You are given three choices to input g. " +
"The first allows you to enter whatever " +
"growth rate you want The second sets the " +
"terminal growht rate to the risk-free rate. " +
"With either of these choices, make sure to " +
"follow the appropriate rules above. If " +
"you are concerned about potential " +
"inconsistencies, we strongly suggest " +
"you follow the third choice, where you " +
"input the terminal RR and terminal ROIC. We " +
"would suggest starting with the ROIC, and setting " +
"it at roughly the firm's WACC (mature firms " +
"do not earn a huge ROIC). Then choose " +
"an RR that will deliver a growth rate below " +
"or equal to the risk-free rate. (As an additional " +
"sanity check, you may wish to compare your chosen RR against " +
"the implied RR in the last proforma period).");
startActivity(intent);
}
});
}
// add items into spinner dynamically
public void addItemsOnSpinner1() {
WACCPageTwoOperatingIncomeSpinner =
(Spinner) findViewById(R.id.WACCPageTwoOperatingIncomeSpinner);
List<String> list = new ArrayList<String>();
list.add("Will input percent EBIT (Operating Margin)");
list.add("Will input percent CGS and percent SGA");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
WACCPageTwoOperatingIncomeSpinner.setAdapter(dataAdapter);
WACCPageTwoOperatingIncomeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
SpinnerOneText = item.toString();
}
public void onNothingSelected(AdapterView<?> parent) {
return;
}
});
}
// add items into spinner dynamically
public void addItemsOnSpinner2() {
WACCDetailedPageTwoDepreciationSpinner = (Spinner) findViewById(R.id.WACCDetailedPageTwoDepreciationSpinner);
List<String> list = new ArrayList<String>();
list.add("Will use straight line rule");
list.add("Will assume Depreciation = Capex");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
WACCDetailedPageTwoDepreciationSpinner.setAdapter(dataAdapter);
WACCDetailedPageTwoDepreciationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
SpinnerTwoText = item.toString();
}
public void onNothingSelected(AdapterView<?> parent) {
return;
}
});
}
// add items into spinner dynamically
public void addItemsOnSpinner3() {
WACCDetailedPageTwoWACCSpinner = (Spinner) findViewById(R.id.WACCDetailedPageTwoWACCSpinner);
List<String> list = new ArrayList<String>();
list.add("Will input WACC directly");
list.add("Will input rE, rD*");
list.add("Will input rF, ß, rD, and MRP*");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
WACCDetailedPageTwoWACCSpinner.setAdapter(dataAdapter);
WACCDetailedPageTwoWACCSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
SpinnerThreeText = item.toString();
}
public void onNothingSelected(AdapterView<?> parent) {
return;
}
});
}
// add items into spinner dynamically
public void addItemsOnSpinner4() {
WACCDetailedPageTwoTerminalGrowthRateSpinner = (Spinner)
findViewById(R.id.WACCDetailedPageTwoTerminalGrowthRateSpinner);
List<String> list = new ArrayList<String>();
list.add("Will input g directly");
list.add("Will assume that g=rF**");
list.add("Will input ROIC and RR for g = (ROIC)(RR)");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
WACCDetailedPageTwoTerminalGrowthRateSpinner.setAdapter(dataAdapter);
WACCDetailedPageTwoTerminalGrowthRateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
SpinnerFourText = item.toString();
}
public void onNothingSelected(AdapterView<?> parent) {
return;
}
});
}
}
<file_sep>/app/src/androidTest/java/com/example/finance/googlesheetsexample/DataGather.java
package com.example.finance.googlesheetsexample;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import androidx.test.espresso.ViewInteraction;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.Espresso.pressBack;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.replaceText;
import static androidx.test.espresso.action.ViewActions.scrollTo;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withClassName;
import static androidx.test.espresso.matcher.ViewMatchers.withContentDescription;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.is;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class DataGather {
@Rule
public ActivityTestRule<FirstScreenToShowMenu> mActivityTestRule = new ActivityTestRule<>(FirstScreenToShowMenu.class);
@Test
public void dataGather() {
ViewInteraction appCompatImageButton = onView(
allOf(withContentDescription("Navigate up"),
childAtPosition(
allOf(withId(R.id.toolbar),
childAtPosition(
withId(R.id.content_frametitle),
0)),
1),
isDisplayed()));
appCompatImageButton.perform(click());
ViewInteraction floatingActionButton = onView(
allOf(withId(R.id.fab),
childAtPosition(
childAtPosition(
withClassName(is("androidx.coordinatorlayout.widget.CoordinatorLayout")),
1),
0),
isDisplayed()));
floatingActionButton.perform(click());
ViewInteraction appCompatImageButton2 = onView(
allOf(withContentDescription("Navigate up"),
childAtPosition(
allOf(withId(R.id.toolbar),
childAtPosition(
withId(R.id.content_frametitle),
0)),
1),
isDisplayed()));
appCompatImageButton2.perform(click());
ViewInteraction appCompatEditText = onView(
allOf(withId(R.id.WACCDetailedFreeCashFlowInputsCompanyNameInput),
childAtPosition(
childAtPosition(
withId(R.id.scrollviewfreecashflow),
0),
1)));
appCompatEditText.perform(scrollTo(), replaceText("test"), closeSoftKeyboard());
ViewInteraction appCompatEditText2 = onView(
allOf(withId(R.id.WACCDetailedFreeCashFlowInputsBaseYearValue), withText("0"),
childAtPosition(
childAtPosition(
withId(R.id.scrollviewfreecashflow),
0),
4)));
appCompatEditText2.perform(scrollTo(), replaceText("1990"));
ViewInteraction appCompatEditText3 = onView(
allOf(withId(R.id.WACCDetailedFreeCashFlowInputsBaseYearValue), withText("1990"),
childAtPosition(
childAtPosition(
withId(R.id.scrollviewfreecashflow),
0),
4),
isDisplayed()));
appCompatEditText3.perform(closeSoftKeyboard());
ViewInteraction appCompatEditText4 = onView(
allOf(withId(R.id.WACCDetailedFreeCashFlowInputsNumberForecastPeriodsValue), withText("0"),
childAtPosition(
childAtPosition(
withId(R.id.scrollviewfreecashflow),
0),
6)));
appCompatEditText4.perform(scrollTo(), replaceText("4"));
ViewInteraction appCompatEditText5 = onView(
allOf(withId(R.id.WACCDetailedFreeCashFlowInputsNumberForecastPeriodsValue), withText("4"),
childAtPosition(
childAtPosition(
withId(R.id.scrollviewfreecashflow),
0),
6),
isDisplayed()));
appCompatEditText5.perform(closeSoftKeyboard());
ViewInteraction appCompatEditText6 = onView(
allOf(withId(R.id.WACCDetailedFreeCashFlowInputsBaseYearRevenueValue), withText("0.00"),
childAtPosition(
childAtPosition(
withId(R.id.scrollviewfreecashflow),
0),
8)));
appCompatEditText6.perform(scrollTo(), replaceText("100.00"));
ViewInteraction appCompatEditText7 = onView(
allOf(withId(R.id.WACCDetailedFreeCashFlowInputsBaseYearRevenueValue), withText("100.00"),
childAtPosition(
childAtPosition(
withId(R.id.scrollviewfreecashflow),
0),
8),
isDisplayed()));
appCompatEditText7.perform(closeSoftKeyboard());
ViewInteraction appCompatEditText8 = onView(
allOf(withId(R.id.WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateValue), withText("0.00"),
childAtPosition(
childAtPosition(
withId(R.id.scrollviewfreecashflow),
0),
10)));
appCompatEditText8.perform(scrollTo(), replaceText("4.00"));
ViewInteraction appCompatEditText9 = onView(
allOf(withId(R.id.WACCDetailedFreeCashFlowInputsAnnualRevenueGrowthRateValue), withText("4.00"),
childAtPosition(
childAtPosition(
withId(R.id.scrollviewfreecashflow),
0),
10),
isDisplayed()));
appCompatEditText9.perform(closeSoftKeyboard());
pressBack();
pressBack();
ViewInteraction floatingActionButton2 = onView(
allOf(withId(R.id.fab),
childAtPosition(
childAtPosition(
withId(R.id.main_content),
1),
0),
isDisplayed()));
floatingActionButton2.perform(click());
ViewInteraction appCompatImageButton3 = onView(
allOf(withContentDescription("Navigate up"),
childAtPosition(
allOf(withId(R.id.toolbar),
childAtPosition(
withId(R.id.content_frametitle),
0)),
1),
isDisplayed()));
appCompatImageButton3.perform(click());
ViewInteraction appCompatEditText10 = onView(
allOf(withId(R.id.WACCDetailedPageCostOfCapitalCashValue), withText("0.00"),
childAtPosition(
childAtPosition(
withClassName(is("android.widget.ScrollView")),
0),
2)));
appCompatEditText10.perform(scrollTo(), replaceText("10.00"));
ViewInteraction appCompatEditText11 = onView(
allOf(withId(R.id.WACCDetailedPageCostOfCapitalCashValue), withText("10.00"),
childAtPosition(
childAtPosition(
withClassName(is("android.widget.ScrollView")),
0),
2),
isDisplayed()));
appCompatEditText11.perform(closeSoftKeyboard());
ViewInteraction appCompatEditText12 = onView(
allOf(withId(R.id.WACCDetailedPageCostOfCapitalDebtValue), withText("0.00"),
childAtPosition(
childAtPosition(
withClassName(is("android.widget.ScrollView")),
0),
4)));
appCompatEditText12.perform(scrollTo(), replaceText("3.00"));
ViewInteraction appCompatEditText13 = onView(
allOf(withId(R.id.WACCDetailedPageCostOfCapitalDebtValue), withText("3.00"),
childAtPosition(
childAtPosition(
withClassName(is("android.widget.ScrollView")),
0),
4),
isDisplayed()));
appCompatEditText13.perform(closeSoftKeyboard());
ViewInteraction appCompatEditText14 = onView(
allOf(withId(R.id.WACCDetailedPageCostOfCapitalMarketCapValue), withText("0.00"),
childAtPosition(
childAtPosition(
withClassName(is("android.widget.ScrollView")),
0),
8)));
appCompatEditText14.perform(scrollTo(), replaceText("30.00"));
ViewInteraction appCompatEditText15 = onView(
allOf(withId(R.id.WACCDetailedPageCostOfCapitalMarketCapValue), withText("30.00"),
childAtPosition(
childAtPosition(
withClassName(is("android.widget.ScrollView")),
0),
8),
isDisplayed()));
appCompatEditText15.perform(closeSoftKeyboard());
pressBack();
pressBack();
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction appCompatEditText16 = onView(
allOf(withId(R.id.WACCDetailedPageCostOfCapitalNumberOfSharesValue), withText("0"),
childAtPosition(
childAtPosition(
withClassName(is("android.widget.ScrollView")),
0),
20)));
appCompatEditText16.perform(scrollTo(), replaceText(""));
ViewInteraction appCompatEditText17 = onView(
allOf(withId(R.id.WACCDetailedPageCostOfCapitalNumberOfSharesValue),
childAtPosition(
childAtPosition(
withClassName(is("android.widget.ScrollView")),
0),
20),
isDisplayed()));
appCompatEditText17.perform(closeSoftKeyboard());
pressBack();
ViewInteraction appCompatEditText18 = onView(
allOf(withId(R.id.WACCDetailedPageCostOfCapitalNumberOfSharesValue),
childAtPosition(
childAtPosition(
withClassName(is("android.widget.ScrollView")),
0),
20)));
appCompatEditText18.perform(scrollTo(), replaceText("55"), closeSoftKeyboard());
pressBack();
pressBack();
ViewInteraction appCompatEditText19 = onView(
allOf(withId(R.id.WACCDetailedPageCostOfCapitalRiskFreeRateValue), withText("0.00"),
childAtPosition(
childAtPosition(
withClassName(is("android.widget.ScrollView")),
0),
10)));
appCompatEditText19.perform(scrollTo(), replaceText("5.00"));
ViewInteraction appCompatEditText20 = onView(
allOf(withId(R.id.WACCDetailedPageCostOfCapitalRiskFreeRateValue), withText("5.00"),
childAtPosition(
childAtPosition(
withClassName(is("android.widget.ScrollView")),
0),
10),
isDisplayed()));
appCompatEditText20.perform(closeSoftKeyboard());
pressBack();
ViewInteraction appCompatEditText21 = onView(
allOf(withId(R.id.WACCDetailedPageCostOfCapitalWeightedAverageCostOfCapitalValue), withText("0.00"),
childAtPosition(
childAtPosition(
withClassName(is("android.widget.ScrollView")),
0),
19)));
appCompatEditText21.perform(scrollTo(), replaceText("5.00"));
ViewInteraction appCompatEditText22 = onView(
allOf(withId(R.id.WACCDetailedPageCostOfCapitalWeightedAverageCostOfCapitalValue), withText("5.00"),
childAtPosition(
childAtPosition(
withClassName(is("android.widget.ScrollView")),
0),
19),
isDisplayed()));
appCompatEditText22.perform(closeSoftKeyboard());
pressBack();
pressBack();
ViewInteraction floatingActionButton3 = onView(
allOf(withId(R.id.fab),
childAtPosition(
childAtPosition(
withId(R.id.main_content),
1),
0),
isDisplayed()));
floatingActionButton3.perform(click());
ViewInteraction appCompatImageButton4 = onView(
allOf(withContentDescription("Navigate up"),
childAtPosition(
allOf(withId(R.id.toolbar),
childAtPosition(
withId(R.id.content_frametitle),
0)),
1),
isDisplayed()));
appCompatImageButton4.perform(click());
ViewInteraction appCompatEditText23 = onView(
allOf(withId(R.id.WACCDetailedPageTerminalValueTerminalROICValue), withText("0.00"),
childAtPosition(
childAtPosition(
withId(R.id.content_frame),
0),
2),
isDisplayed()));
appCompatEditText23.perform(replaceText("5.00"));
ViewInteraction appCompatEditText24 = onView(
allOf(withId(R.id.WACCDetailedPageTerminalValueTerminalROICValue), withText("5.00"),
childAtPosition(
childAtPosition(
withId(R.id.content_frame),
0),
2),
isDisplayed()));
appCompatEditText24.perform(closeSoftKeyboard());
ViewInteraction appCompatEditText25 = onView(
allOf(withId(R.id.WACCDetailedPageTerminalValueTerminalReinvestmentRateValue), withText("0.00"),
childAtPosition(
childAtPosition(
withId(R.id.content_frame),
0),
6),
isDisplayed()));
appCompatEditText25.perform(replaceText("5.00"));
ViewInteraction appCompatEditText26 = onView(
allOf(withId(R.id.WACCDetailedPageTerminalValueTerminalReinvestmentRateValue), withText("5.00"),
childAtPosition(
childAtPosition(
withId(R.id.content_frame),
0),
6),
isDisplayed()));
appCompatEditText26.perform(closeSoftKeyboard());
pressBack();
ViewInteraction appCompatEditText27 = onView(
allOf(withId(R.id.WACCDetailedPageTerminalValueTerminalGrowthRateValue), withText("0.00"),
childAtPosition(
childAtPosition(
withId(R.id.content_frame),
0),
7),
isDisplayed()));
appCompatEditText27.perform(replaceText("3.00"));
ViewInteraction appCompatEditText28 = onView(
allOf(withId(R.id.WACCDetailedPageTerminalValueTerminalGrowthRateValue), withText("3.00"),
childAtPosition(
childAtPosition(
withId(R.id.content_frame),
0),
7),
isDisplayed()));
appCompatEditText28.perform(closeSoftKeyboard());
pressBack();
ViewInteraction appCompatEditText29 = onView(
allOf(withId(R.id.WACCDetailedPageTerminalValueTerminalWACCValue), withText("0.00"),
childAtPosition(
childAtPosition(
withId(R.id.content_frame),
0),
8),
isDisplayed()));
appCompatEditText29.perform(replaceText("3.00"));
ViewInteraction appCompatEditText30 = onView(
allOf(withId(R.id.WACCDetailedPageTerminalValueTerminalWACCValue), withText("3.00"),
childAtPosition(
childAtPosition(
withId(R.id.content_frame),
0),
8),
isDisplayed()));
appCompatEditText30.perform(closeSoftKeyboard());
pressBack();
}
private static Matcher<View> childAtPosition(
final Matcher<View> parentMatcher, final int position) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view) {
ViewParent parent = view.getParent();
return parent instanceof ViewGroup && parentMatcher.matches(parent)
&& view.equals(((ViewGroup) parent).getChildAt(position));
}
};
}
}
|
9aa0af382c8bc27c2554e6006e8a1fa51136c54b
|
[
"Java"
] | 12 |
Java
|
adam0000345/FinancialApplication
|
48b4cd7297248b6aa283eaaf523b10ed68f80236
|
cd46107c1aaf272e5749b47d6b77976cf8e43981
|
refs/heads/main
|
<repo_name>JamesAKing/pokestadium-retro-server<file_sep>/routes/logoutRoutes.js
const express = require('express');
const router = express.Router();
const RefreshTokens = require('../models/refreshTokens');
router
.route('/')
.delete((req, res) => {
const { token } = req.body;
RefreshTokens.deleteOne({ refreshToken : token }, (err) => {
if (err) {
console.log(err);
res.status(500).send(err);
}
console.log('token deleted');
});
res.status(204).send();
})
module.exports = router<file_sep>/utilities/authFunctions.js
const jwt = require('jsonwebtoken');
const generateAccessToken = user => {
return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn : '1h'})
};
const authenticateJWT = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (token == null) return res.status(401).send('no token provided');
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) {
console.log(err)
return res.status(403).send('no longer authrozed to view content');
}
req.user = user;
next()
});
};
module.exports = {
generateAccessToken,
authenticateJWT
};<file_sep>/models/userRecord.js
const mongoose = require('mongoose');
const UserRecordSchema = new mongoose.Schema({
playerId : String,
username : String,
email : String,
password : <PASSWORD>,
player : {
firstName : String,
lastName : String,
date : {
type : String,
default : Date.now()
}
// profilePic : String,
// Auth Info
},
battleRecord : {
total : Number,
won : Number
},
pokemonParties : [
{
partyId : String,
pokemon : [
{
pokemonId : String,
moves : Array,
exp : Number
}
]
}
]
});
const UserRecord = mongoose.model('UserRecord', UserRecordSchema);
module.exports = UserRecord;<file_sep>/utilities/functions.js
const { v4: uuidv4 } = require('uuid');
const createNewUser = (newUserObj) => {
return {
playerId : uuidv4(),
username : newUserObj.username,
email : newUserObj.email,
password : <PASSWORD>,
player : {
firstName : newUserObj.firstName,
lastName : newUserObj.lastName,
},
battleRecord : {
total : 0,
won : 0
}
};
};
module.exports = {
createNewUser
};<file_sep>/routes/loginRoutes.js
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const UserRecord = require('../models/userRecord');
const RefreshTokens = require('../models/refreshTokens');
const { generateAccessToken } = require('../utilities/authFunctions');
router
.route('/')
.post(async (req, res) => {
const rawLoginData = req.body;
// *** IMPROVE AUTHENTICATION METHODS TO BE SECURE ***
try {
const data = await UserRecord.find({ email: rawLoginData.email });
if (data.length === 0) return res.status(401).send('invalid username or password');
if (data[0].password !== rawLoginData.password) return res.status(401).send('invalid username or password');
const playerId = data[0].playerId;
const user = { playerId : playerId };
const accessToken = generateAccessToken(user);
const refreshToken = jwt.sign(user, process.env.REFRESH_TOKEN_SECRET);
// Client not currently not doing anything with refresh tokens.
const newRefreshTokens = new RefreshTokens({ refreshToken : refreshToken });
newRefreshTokens.save(err => {
if (err) {
console.log(err);
return res.status(500).send(err)
}
console.log('refresh token saved to DB');
})
res.header("authorization", `Bearer ${accessToken}`).status(200).json({ accessToken, refreshToken });
} catch (err) {
console.log(err);
res.status(400).send(err);
};
});
router
.route('/token')
.post(async (req, res) => {
const refreshToken = req.body.token;
if (refreshToken == null) return res.status(401).send('no token provded');
try {
const data = await RefreshTokens.find({ refreshToken: refreshToken });
if (data.length === 0) return res.status(403).send('invalid token');
jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if (err) {
console.log(err);
return res.status(403).send('invalid token');
}
const accessToken = generateAccessToken({ name: user.name })
res.status(200).json({ accessToken });
});
} catch (err) {
res.status(400).send(err);
};
});
module.exports = router;<file_sep>/routes/createUserRoutes.js
const express = require('express');
const router = express.Router();
const UserRecord = require('../models/userRecord');
const { createNewUser } = require('../utilities/functions');
router
.route('/')
.post(async (req, res) => {
// *** LOOK INTO HOW TO SECURLEY STORE USER DATA ***
const rawUserData = req.body;
try {
const data = await UserRecord.find({$or: [{email : rawUserData.email}, {username : rawUserData.username}]});
if (data.length !== 0) {
if (data[0].username === rawUserData.username && data[0].email === rawUserData.email) return res.status(409).send('a user with that email and username already exists');
if (data[0].email === rawUserData.email) return res.status(409).send('a user with that email already exists');
if (data[0].username === rawUserData.username) return res.status(409).send('a user with that username already exists');
}
const newUserRecord = new UserRecord(createNewUser(rawUserData));
newUserRecord.save(err => {
if (err) {
console.log(err)
return res.status(502).send('error savng new record');
}
console.log('added new user record');
})
res.status(201).send('new user added to DB');
} catch (err) {
console.log(err);
// Add correct status code
res.status(400).send(err);
};
})
module.exports = router;
|
270d0574e1f9b18194266f1926242b1057582639
|
[
"JavaScript"
] | 6 |
JavaScript
|
JamesAKing/pokestadium-retro-server
|
e77bf5412185561c7f8152bc553e28784e465a00
|
78e28ba7af632abb45cd1d886738a7312504ab0e
|
refs/heads/master
|
<repo_name>bvd/quickstart<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core';
import { HappyMoment } from './happymoment';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<h2>{{happymoment.title}} details</h2>
<div><label>id: </label>{{happymoment.id}}</div>
<div><label>name: </label>{{happymoment.name}}</div>
<div><label>email: </label>{{happymoment.email}}</div>
<div><label>title: </label>{{happymoment.title}}</div>
<div><label>location: </label>{{happymoment.location}}</div>
<div><label>description: </label>{{happymoment.description}}</div>
<div><label>image: </label>{{happymoment.image}}</div>
<h1>editor</h1>
<div>
<div><label>name: </label><input value="{{happymoment.name}}" placeholder="name"></div>
<div><label>email: </label><input value="{{happymoment.email}}" placeholder="name"></div>
<div><label>title: </label><input value="{{happymoment.title}}" placeholder="name"></div>
<div><label>location: </label><input value="{{happymoment.location}}" placeholder="name"></div>
<div><label>description: </label><input value="{{happymoment.description}}" placeholder="name"></div>
<div><label>image: </label><input value="{{happymoment.image}}" placeholder="name"></div>
</div>
`
})
export class AppComponent {
title = "Meldpunt Geluksmomenten";
// geluksmoment
happymoment: HappyMoment = {
id: 1,
name: "<NAME>",
email: "<EMAIL>",
title: "de rozenbotteljam",
location: "keukenkast",
description: "als ik mijn potten met rozenbotteljam zie",
image: "f92ndosiw02mvlw9w92pdmsp2840suw0.jpg"
};
}
<file_sep>/src/app/happymoment.ts
export class HappyMoment {
id: number;
name: string;
email: string;
title: string;
location: string;
description: string;
image: string;
}
|
bc2b15be7a8d8563108416338263d53a641e8ca0
|
[
"TypeScript"
] | 2 |
TypeScript
|
bvd/quickstart
|
76823136811ab97885e207742bc90f8c54fb3053
|
9a565591a3f42e24f1e304f59036248e6ef68e22
|
refs/heads/master
|
<repo_name>robwhite4/Resume<file_sep>/README.md
# Resume Generator
I'm trying to figure out this tool. And this is where I'll keep my notes.
## Technologies
References to technologies used / researched here.
* [HackMyResume - Resume Generator](https://github.com/hacksalot/HackMyResume)
## Other Things for Reference
### FRESH Standard
* [Fresh Standard](https://github.com/fresh-standard)
* [Fresh Themes - Installed with HackMyResume](https://github.com/fresh-standard/fresh-themes)
### JSON Resumes
* [jsonresume.org](http://jsonresume.org/)
* [jsonresume/theme-manager](https://github.com/jsonresume/theme-manager)<file_sep>/scripts/classy.sh
hackmyresume BUILD r1.json TO dist/resume.all -t themes/jsonresume-theme-classy
|
60a72cf355ee5d540786d0c15a3854951974f692
|
[
"Markdown",
"Shell"
] | 2 |
Markdown
|
robwhite4/Resume
|
ad12d9ba2ba757f6756490054d169d43a2ebf8ee
|
a4128247aa67eda0034ca9e80fee1f6c17b03cea
|
refs/heads/master
|
<file_sep>###############################
# STA 412 - Group Project #
# <NAME>, Pete #
# #
# Facebook Data Analysis #
###############################
### Import Data ###
# Set working directory - change to your PCs project location
setwd("C:/GitProjects/Facebook_BuzzFeed_Analysis")
# Read in Dataset - change to your PCs data location
fb_data = read.csv("Data/facebook-fact-check.csv")
# Drop unnessary columns
fb_data = as.data.frame(fb_data[,c(3,4,7,8,10,11,12)])
# Omit NaNs
fb_data = na.omit(fb_data)
head(fb_data)
# Display feature types and classes
sapply(fb_data, mode)
sapply(fb_data, class)
# Fix levels of Rating variable for plots
fb_data$Rating = factor(fb_data$Rating, levels = c("mostly true",
"mixture of true and false",
"mostly false",
"no factual content"))
# Descriptive Statistics
# Histogram for share_count, reaction count, and comment_count
attach(fb_data)
par(mfrow=c(1,2))
hist(share_count)
hist(reaction_count)
# Max, Min, Median values and Means for each rating for share_count
# share_count max
max(share_count)
# share_count min
min(share_count)
# share_count median
median(share_count)
# share_count means for each rating
aggregate(share_count~Rating,fb_data,mean)
# share_count variances for each rating
aggregate(share_count~Rating,fb_data,var)
# share_count standard deviation for each rating
aggregate(share_count~Rating,fb_data,sd)
# Max, Min, Median values and Means for each rating for reaction_count
# reaction_count max
max(reaction_count)
# reaction_count min
min(reaction_count)
# reaction_count median
median(reaction_count)
# reaction_count means for each rating
aggregate(reaction_count~Rating,fb_data,mean)
# reaction_count variances for each rating
aggregate(reaction_count~Rating,fb_data,var)
# reaction_count standard deviation for each rating
aggregate(reaction_count~Rating,fb_data,sd)
## Q-Q Plots for Normality
par(mfrow=c(1,2))
attach(fb_data)
qqnorm(share_count)
qqline(share_count)
qqnorm(reaction_count)
qqline(reaction_count)
# Logarithmic Transformation
fb_data$log_share_count= log(fb_data$share_count)
fb_data$log_reaction_count= log(fb_data$reaction_count)
# New Q-Q Plots
par(mfrow=c(1,2))
attach(fb_data)
qqnorm(log_share_count)
qqline(log_share_count)
qqnorm(log_reaction_count)
qqline(log_reaction_count)
### Our First Hypothesis
##### Hypothesis 1: Test 1
# One-Way Analysis of Means for share_count
# Test Using Logarithmic Transformation
oneway.test(log_share_count~Rating, fb_data, var.equal = F)
##### Hypothesis 1: Test 2
# One-Way Analysis of Means for reaction_count
# Test Using Logarithmic Transformation
oneway.test(log_reaction_count~Rating, fb_data, var.equal = F)
### Our Second Hypothesis
# Plots for Linear Relationships
par(mfrow=c(1,2))
plot(log_share_count~Rating, data=fb_data)
plot(log_reaction_count~Rating, data=fb_data)
### F Test for Nested Models
# F Test for Nested Models -> share_count
shares.lm = lm(log_share_count ~ Rating, data = fb_data)
shares_full = shares.lm
shares_reduced = lm(log_share_count ~ 1, data = fb_data)
anova(shares_reduced, shares_full)
#F Test for Nested Models -> reaction_count
reactions.lm = lm(log_reaction_count ~ Rating, data = fb_data)
reactions_full = reactions.lm
reactions_reduced = lm(log_reaction_count ~ 1, data = fb_data)
### Linear Regression
# Predict share count based on rating
summary(shares.lm)
contrasts(fb_data$Rating)
plot(fb_data$Rating, fb_data$log_share_count)
abline(shares.lm)
# Predict reaction count based on rating
summary(reactions.lm)
contrasts(fb_data$Rating)
plot(fb_data$Rating, fb_data$log_reaction_count)
abline(reactions.lm)
### Confidence Intervals
#Confidence Intervals for share_count model
# 95% CI for beta0 and beta1
confint(shares.lm)
#Confidence Interval for reaction_count model
# 95% CI for beta0 and beta1
confint(reactions.lm)
### Multiple Regression
shares.multlm = lm(log_share_count ~ Category + Page + Post.Type + Rating, data = fb_data)
summary(shares.multlm)
<file_sep>---
title: "STA 412 Group Project Step 3"
author: "<NAME>, Pete"
date: "4/17/2020"
output: word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
# Set working directory - change to your PCs project location
setwd("C:/GitProjects/Facebook_BuzzFeed_Analysis")
```
# Facebook Data Project
Our group has decided to research the topic of “Fake News” on Facebook and how much it is reacted to and shared on the social media site. We stumbled upon this dataset on Kaggle, and with the 2020 election approaching, we thought a topic like this would be both relevant and informative. We hope we can shed light on how false information can be spread through social media.
Our dataset comes from Kaggle, and contains one csv file with over 2000 data points. The source of the data is from BuzzFeed News, who analyzed stories from hyperpartisan political Facebook pages. These pages contain right and left wing sources, and mainstream news sites, giving us a great mix of viewpoints. The dataset can be found at the following link: https://www.kaggle.com/mrisdal/fact-checking-facebook-politics-pages
### Import Data and Data Processing
```{r}
# Read in Dataset - change to your PCs data location
fb_data = read.csv("Data/facebook-fact-check.csv")
# Drop unnecessary columns
fb_data = as.data.frame(fb_data[,c(3,4,7,8,10,11,12)])
# Omit NaNs
fb_data = na.omit(fb_data)
head(fb_data)
# Display feature types and classes
sapply(fb_data, mode)
sapply(fb_data, class)
# Fix levels of Rating variable for plots
fb_data$Rating = factor(fb_data$Rating, levels = c("mostly true",
"mixture of true and false",
"mostly false",
"no factual content"))
```
# Descriptive Statistics
Histogram for share_count and reaction count
```{r}
attach(fb_data)
par(mfrow=c(1,2))
hist(share_count)
hist(reaction_count)
```
Max, Min, Median values and Means for each rating for share_count
```{r}
# share_count max
max(share_count)
# share_count min
min(share_count)
# share_count median
median(share_count)
# share_count means for each rating
aggregate(share_count~Rating,fb_data,mean)
# share_count variances for each rating
aggregate(share_count~Rating,fb_data,var)
# share_count standard deviation for each rating
aggregate(share_count~Rating,fb_data,sd)
```
Max, Min, Median values and Means for each rating for reaction_count
```{r}
# reaction_count max
max(reaction_count)
# reaction_count min
min(reaction_count)
# reaction_count median
median(reaction_count)
# reaction_count means for each rating
aggregate(reaction_count~Rating,fb_data,mean)
# reaction_count variances for each rating
aggregate(reaction_count~Rating,fb_data,var)
# reaction_count standard deviation for each rating
aggregate(reaction_count~Rating,fb_data,sd)
```
Q-Q Plots for Normality
```{r}
par(mfrow=c(1,3))
attach(fb_data)
qqnorm(share_count)
qqline(share_count)
qqnorm(reaction_count)
qqline(reaction_count)
```
Logarithmic Transformation
```{r}
fb_data$log_share_count= log(fb_data$share_count)
fb_data$log_reaction_count= log(fb_data$reaction_count)
```
New Q-Q Plots
```{r}
attach(fb_data)
par(mfrow=c(1,2))
qqnorm(log_share_count)
qqline(log_share_count)
qqnorm(log_reaction_count)
qqline(log_reaction_count)
```
### Our First Hypothesis
Facebook posts, regardless of what political viewpoint, are shared and reated to differently for each level of factual content. In other words, posts with at least one level of factual content have different mean values of shares and reactions.
In order to test our first hypothesis, we will use a One-Way Analysis of Means. This will test whether the mean values of share_count and reaction_count are different for each individual rating.
H0: mu1 = mu2 = mu3 = mu4
Ha: at least one muk is different
This test will show us if, on average, posts are shared, reacted to, and commented on more for each rating.
##### Hypothesis 1: Test 1
```{r}
# One-Way Analysis of Means for share_count
# Test Using Logarithmic Transformation
oneway.test(log_share_count~Rating, fb_data, var.equal = F)
```
This one-way analysis of means gives significant evidence that there is at least one different mean value of share_count of a rating. This is significant to us because it concludes that at least one of the ratings are receiving more or less shares than the others.
##### Hypothesis 1: Test 2
```{r}
# One-Way Analysis of Means for reaction_count
# Test Using Logarithmic Transformation
oneway.test(log_reaction_count~Rating, fb_data, var.equal = F)
```
This one-way analysis of means gives significant evidence that there is at least one different mean value of reaction_count of a rating. This is significant to us because it concludes that at least one of the ratings are receiving more or less reactions than the others.
#### First Hypotheses Conclusion
We have significant evidence to reject the null hypothesis in each test. This is great for our research, in that it concludes that based on the rating of the post, it may be shared or reacted to more or less than posts with other ratings. We still have yet to find out how a rating of false or true may influence these response variables, however we will address this in the next hypotheses.
### Our Second Hypothesis
For our second question, we want to see how the factual content rating levels affect the number of shares and reactions Facebook posts receive. So our main question is, can the factual content rating level of a Facebook post determine how many shares and reactions it receives? First, we will use the F Test for Nested Models to determine if a linear regression model that includes the Rating predictor is more significant than a linear regression model with no predictors. We will conduct this for both of our response variables. If the conclusion of that test is that the model with the Rating predictor is significant, then we will see how the individual ratings affect the count of shares and reactions.
H0: Beta_1 = 0
Ha: Beta_1 does not equal zero
Our significance level (alpha) will be 0.05
### Plots for Linear Relationships
```{r}
par(mfrow=c(1,2))
plot(log_share_count~Rating, data=fb_data)
plot(log_reaction_count~Rating, data=fb_data)
```
### F Test for Nested Models
F Test for Nested Models -> share_count
```{r}
shares.lm = lm(log_share_count ~ Rating, data = fb_data)
shares_full = shares.lm
shares_reduced = lm(log_share_count ~ 1, data = fb_data)
anova(shares_reduced, shares_full)
```
F Test for Nested Models -> reaction_count
```{r}
reactions.lm = lm(log_reaction_count ~ Rating, data = fb_data)
reactions_full = reactions.lm
reactions_reduced = lm(log_reaction_count ~ 1, data = fb_data)
anova(reactions_reduced, reactions_full)
```
### Linear Regression
```{r}
# Summary of shares.lm
summary(shares.lm)
contrasts(fb_data$Rating)
```
```{r}
# Plot shares.lm
plot(fb_data$Rating, fb_data$log_share_count)
abline(shares.lm)
```
```{r}
# Summary of reactions.lm
summary(reactions.lm)
contrasts(fb_data$Rating)
```
```{r}
# Plot reactions.lm
plot(fb_data$Rating, fb_data$log_reaction_count)
abline(reactions.lm)
```
### Confidence Intervals
Confidence Intervals for share_count model
```{r}
# 95% CI for beta0 and beta1
confint(shares.lm)
```
Confidence Interval for reaction_count model
```{r}
# 95% CI for beta0 and beta1
confint(reactions.lm)
```
<file_sep># Facebook BuzzFeed Analysis
#### URI STA 412 Group Project
This project was completed by the following students:
- <NAME>
- <NAME>
- <NAME>
The professor of the course:
- <NAME>, Ph.D.
#### Abstract
Our group decided to research the topic of “Fake News” on Facebook and how much it is shared and reacted to. We stumbled upon this dataset on Kaggle, and with the 2020 election approaching we thought analyzing a topic like this would be both relevant and informative. We hope we can shed light on how easily false information can be spread through Facebook and encourage people to be cautious of the information they read.
Our dataset comes from Kaggle, and contains one csv file with over 2000 data points. The source of the data is from BuzzFeed News, who analyzed stories from hyperpartisan political Facebook pages. These pages contain right and left wing sources and mainstream news sites, giving us a great mix of viewpoints. The dataset can be found at the following link:
https://www.kaggle.com/mrisdal/fact-checking-facebook-politics-pages
|
d14ad1d2793a39f257e2227af986935c641fe4ba
|
[
"Markdown",
"R",
"RMarkdown"
] | 3 |
R
|
mark-data5814/Facebook_BuzzFeed_Analysis
|
5a58f7d6bc01d816601afff68503b8e517b0fccd
|
279ba01dcc764d09218c3b2bf6fdf28f6d06e887
|
refs/heads/master
|
<repo_name>bismarckjunior/CUDA_Example<file_sep>/CUDA_Example/CudaVector.h
/*******************************************************************************
| Project: CUDA Example |
| Author: <NAME> <<EMAIL>> |
\******************************************************************************/
#ifndef _CUDAVECTOR_H_
#define _CUDAVECTOR_H_
#include <cuda_runtime.h>
#include <vector>
template <typename T>
class CudaVector {
private:
T* data; ///< Variable in device memory
int size; ///< Size of device vector
public:
CudaVector() : size(0) {};
CudaVector(int size_) { AllocateMemory(size_); };
CudaVector(int size_, T value) : CudaVector(size_) { SetUniqueValue(value); };
~CudaVector() { cudaFree((void *)data); };
/**
* Allocate memory in device with a alredy specified class.
*/
void AllocateMemory() { cudaMalloc((void **)&data, sizeof(T)*size); };
/**
* Allocate memory in device with a know size.
*
* @param size_ Size in device
*/
void AllocateMemory(int size_) { size = size_; AllocateMemory(); };
/**
* Sets the unique value for vector.
*
* @param value Unique value
*/
void SetUniqueValue(T value) {
cudaMemset((void *)data, value, sizeof(T)*size);
};
/**
* Copy from host pointer to device memory.
*
* @param h_data Host data
*/
void CopyFromHost(T* h_data) {
cudaMemcpy(data, h_data, sizeof(T)*size, cudaMemcpyHostToDevice);
};
/**
* Copy from host vector to device memory.
*
* @param h_data Host data
*/
void CopyFromHost(std::vector<T> h_data){ CopyFromHost(&h_data[0]); };
/**
* Copy from device to host pointer.
*
* @param h_data Host data
*/
void CopyToHost(T* h_data){
cudaMemcpy(&h_data, data, sizeof(T)*size, cudaMemcpyDeviceToHost);
};
/**
* Copy from device to host vector.
*
* @param h_data Host data
*/
void CopyToHost(std::vector<T> &h_data) {
cudaMemcpy(&h_data[0], data, sizeof(T)*size, cudaMemcpyDeviceToHost);
};
/**
* Get vector size.
*
* @return size
*/
int Size() { return size; };
/**
* Get host vector from device memory.
*
* @return host vector
*/
std::vector<T> Get();
/**
* Get device value.
*
* @return device pointer
*/
T* operator() () { return data; };
// Overload operators
CudaVector<T>& operator = (const CudaVector &c1);
CudaVector<T>& operator = (std::vector<T> c1);
CudaVector<T>& operator = (T * c1);
//TODO: implementar ofstream overload operator
};
#endif<file_sep>/README.md
# CUDA_Example
A Visual Studio project example for CUDA. Visual Studio 2013.
Created the class *CudaVector* that manages a vector in the memory of the device
(GPU). Communication with the host (CPU) is simplified, see the [*main.cpp*][1]
file for more details.
[1]: ./CUDA_Example/main.cpp<file_sep>/CUDA_Example/CudaVector.cpp
/*******************************************************************************
| Project: CUDA Example |
| Author: <NAME> <<EMAIL>> |
\******************************************************************************/
#include "CudaVector.h"
template <typename T>
std::vector<T> CudaVector<T>::Get(){
std::vector<T> host(size);
CopyToHost(host);
return host;
}
template <typename T>
CudaVector<T>& CudaVector<T>::operator = (std::vector<T> c1){
CopyFromHost(c1);
return *this;
}
template <typename T>
CudaVector<T>& CudaVector<T>::operator = (T* c1){
CopyFromHost(c1);
return *this;
}
template <typename T>
CudaVector<T>& CudaVector<T>::operator = (const CudaVector &c1){
if (size != c1.size)
AllocateMemory(c1.size);
cudaMemcpy(data, c1.data, size*sizeof(T), cudaMemcpyDeviceToDevice);
return *this;
}
template class CudaVector<int>;
template class CudaVector<float>;
<file_sep>/CUDA_Example/example.h
/*******************************************************************************
| Project: CUDA Example |
| Author: <NAME> <<EMAIL>> |
\******************************************************************************/
#ifndef _CEXAMPLE_H_
#define _CEXAMPLE_H_
#include "CudaVector.h"
// Launch kernels
extern "C" {
void launch_kernel(int *a, int *b, unsigned int N);
}
// Example class
class CExample{
private:
int i;
public:
CExample() : i(0){};
void run(CudaVector<int> &a, CudaVector<int> &b){
i += 1;
launch_kernel(a(), b(), a.Size());
};
void run(int* a, int *b, int len){
i += 1;
launch_kernel(a, b, len);
};
};
#endif<file_sep>/CUDA_Example/main.cpp
/*******************************************************************************
| Project: CUDA Example |
| Author: <NAME> <<EMAIL>> |
\******************************************************************************/
#include <iostream>
#include <vector>
#include "CudaVector.h"
#include "example.h"
int main(void) {
// Declare variables
int len = 10;
int *b_gpu;
CudaVector<int> c1(len, 0), c2(len, 0), c3(2, 0);
std::vector<int> v_host(len, 0), v_host2(len, 0);
// Create vector in host: v_host
for (int i = 0; i<len; i++) {
v_host[i] = i;
}
// Copy from host to device
c2 = v_host;
// Run in device
CExample ab = CExample();
ab.run(c1, c2);
// Run in device
//launch_kernel(c1(), c2(), c1.Size());
// Copy in device
c3 = c1;
// Get variable in device memory
b_gpu = c3();
// Copy from device to host
c3.CopyToHost(v_host2);
// Get from device to host
v_host2 = c3.Get();
// Print v_host2
std::cout << "\nCPU: ";
for (int i = 0; i<v_host2.size(); i++) {
std::cout << v_host2[i] << " ";
}
std::cout << std::endl;
return 0;
}
|
e8c437067d8cf03789a7971a282f92d507982f52
|
[
"Markdown",
"C++"
] | 5 |
C++
|
bismarckjunior/CUDA_Example
|
f9c42be9831d5c98a10b8334bc7793c947a6bda0
|
46c9e517bdf5b851422c1d8836120f522034615c
|
refs/heads/main
|
<file_sep>import { Command } from '../command';
import { Message, MessageAttachment, MessageEmbed } from 'discord.js';
import { BOT_COLOR, ERROR_EMBED, getNumFromParam } from '../common';
import { db } from '../db';
import { Canvas, CanvasRenderingContext2D, createCanvas, Image, loadImage } from 'canvas';
import { roundedRect, PODIUM_COLORS } from '../drawing';
module.exports = {
name: "top",
command: new Command(top, new MessageEmbed({
color: BOT_COLOR,
title: 'top',
description: 'Fetch a top 10 leaderboard of TWR-XP.',
fields: [
{ name: 'page', value: 'Number referring to the leaderboard page to view.' },
{ name: 'Examples', value: '```bash\ns/top\ns/top 3\n```' }
]
}))
}
export async function top(msg: Message, args: string): Promise<void> {
let numRanks = await db.get(`SELECT COUNT() FROM userguildxp WHERE guild_id = ${msg.guildId}`)
.catch(_ => { return Promise.reject(ERROR_EMBED.setDescription('❌ Error fetching leaderboard data!')) });
let userRank = await db.get(`SELECT res.user_id, res.rank FROM (SELECT user_id, xp, ROW_NUMBER() OVER (ORDER BY xp DESC) rank FROM userguildxp) res WHERE user_id = ${msg.author.id}`)
// let userRank = await db.get(`SELECT user_id, ROW_NUMBER() OVER (ORDER BY xp) rank FROM userguildxp WHERE user_id = ${msg.author.id}`)
.catch(_ => { return Promise.reject(ERROR_EMBED.setDescription('❌ Error determining rank!')) });
let page: number = getNumFromParam(args.split(' ')[0]);
let lastPage: number = Math.floor(numRanks['COUNT()'] / 10) + 1;
if (page < 1 || isNaN(page)) page = 1;
if (page > Math.floor(numRanks['COUNT()'] / 10) + 1) {
page = Math.floor(numRanks['COUNT()'] / 10) + 1;
}
let topTen: any[] = await db.all(`SELECT user_id, xp FROM userguildxp WHERE guild_id = ${msg.guildId} ORDER BY xp DESC LIMIT ${(page - 1) * 10}, 10`)
.catch(_ => { return Promise.reject(ERROR_EMBED.setDescription('❌ Error fetching page members!')) });
if (!(topTen instanceof Array) || !msg.guild)
return Promise.reject(ERROR_EMBED.setDescription('❌ Unknown Guild error!'));
let list: string[][] = [];
for (let i = 0; i < 10; i++) {
let position = i + 1 + (10 * (page - 1));
// Default to no user at this position.
list[i] = [`#${position}`, ' -', '0'];
if (topTen[i]) {
let user = msg.guild.client.users.cache.get(topTen[i].user_id);
if (user) {
list[i] = [`#${position}`, `${user.username}`, topTen[i].xp];
}
}
}
// Text-only version.
let textOnly: boolean;
try {
let res = await db.get(`SELECT text_only FROM users WHERE user_id = ${msg.author.id}`);
textOnly = res.text_only;
}
catch {
textOnly = false;
}
if (textOnly) {
let topText: string = '';
// Podium.
for (let i = 0; i < list.length; i++) {
topText += `${list[i][0]} ${list[i][1]} - \`${list[i][2]}\``;
if (page === 1 && i < 3)
topText += ['🥇', '🥈', '🥉'][i];
topText += '\n';
}
msg.channel.send({
embeds: [new MessageEmbed({
color: BOT_COLOR,
title: `TWR-XP Leaderboard for ${msg.guild.name}`,
description: `You are rank \`#${userRank.rank}\`!\n\n${topText}`,
thumbnail: { url: `${msg.guild.iconURL()}` },
footer: { text: `Page ${page} of ${lastPage} - use s/top ${page + 1} to see page ${page + 1}` }
})],
});
return Promise.resolve();
}
const canvas: Canvas = createCanvas(600, 530);
const ctx: CanvasRenderingContext2D = canvas.getContext('2d');
await loadImage('../res/leaderboard_bg.png').then(img => ctx.drawImage(img, 0, 0, 600, 530)).catch();
for (let i = 0; i < list.length; i++) {
ctx.fillStyle = 'rgba(40, 40, 40, 0.5)';
roundedRect(ctx, 20, 20 + (i * 50), 560, 40, 15);
ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
// Podium colours.
if (page === 1 && i < 3)
ctx.fillStyle = PODIUM_COLORS[i];
ctx.textDrawingMode = 'path';
ctx.font = '24px "Montserrat ExtraBold"';
ctx.fillText(list[i][0] + ' ', 30, 48 + (i * 50), 100);
ctx.beginPath();
ctx.arc(30 + ctx.measureText(list[i][0] + ' ').width, 40 + (i * 50), 5, 0, 2 * Math.PI);
ctx.fill();
ctx.font = '22px "Montserrat Medium"';
ctx.fillText(list[i][1], 30 + ctx.measureText(list[i][0] + ' ').width, 48 + (i * 50), 360);
// Always draw TWR-XP in white.
ctx.font = '24px "Montserrat Bold"';
ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
ctx.fillText(list[i][2], 555 - ctx.measureText(list[i][2]).width, 48 + (i * 50), 100);
}
msg.channel.send({
embeds: [new MessageEmbed({
color: BOT_COLOR,
title: `TWR-XP Leaderboard for ${msg.guild.name}`,
description: `You are rank #${userRank.rank}!`,
image: { url: `attachment://top.png` },
thumbnail: { url: `${msg.guild.iconURL()}` },
footer: { text: `Page ${page} of ${lastPage} - use s/top ${page + 1} to see page ${page + 1}` }
})],
files: [new MessageAttachment(canvas.toBuffer(), 'top.png')]
});
}
<file_sep>import { Command } from '../command';
import { Message, MessageEmbed, User } from 'discord.js';
import { BOT_COLOR, ERROR_EMBED } from '../common';
import { db } from '../db';
module.exports = {
name: "funk",
command: new Command(funk, new MessageEmbed({
color: BOT_COLOR,
title: 'funk',
description: 'Give a Funk Point to another user. They\'re nice for when someone\'s done or said something nice,' +
'like a measure of reputation, and you can only give 1 per day',
fields: [{ name: 'Example', value: '```bash\ns/funk @FuckThrust\n```' }]
}))
}
async function funk(msg: Message): Promise<void> {
let userId: string;
let username: string;
if (msg.mentions.users.size > 0) {
let user: User | undefined = msg.mentions.users.first();
let msgUser: User | undefined = msg.client.users.cache.get(msg.author.id);
if (user && msgUser && user !== msgUser) {
userId = user.id;
username = user.username;
// Command relies on someone else who may not have sent a message yet being in the DB,
// so ensure they are here.
await db.run(`INSERT OR IGNORE INTO users VALUES (${userId}, 0, False, False)`).catch(_ => {
return Promise.reject(ERROR_EMBED.setDescription('❌ User doesn\'t exist in database and can\'t be added!'));
});
}
else {
return Promise.reject(ERROR_EMBED.setDescription('❌ You can\'t funk yourself!'));
}
}
else {
return Promise.reject(ERROR_EMBED.setDescription('❌ You forgot to mention a user to funk!'));
}
try {
let cooldown = await db.get(`SELECT reputation_cooldown FROM users WHERE user_id = ${msg.author.id}`);
if (cooldown.reputation_cooldown === 1)
return Promise.reject(ERROR_EMBED.setDescription('❌ You\'ve already funked a user today!'));
let before = await db.get(`SELECT reputation FROM users WHERE user_id = ${userId}`);
await db.run(`UPDATE users SET reputation = reputation + 1 WHERE user_id = ${userId} AND reputation < 999`);
let after = await db.get(`SELECT reputation FROM users WHERE user_id = ${userId}`);
msg.channel.send({
embeds: [
new MessageEmbed({
color: BOT_COLOR,
title: '<:fuckthrust:914544341022814228> Success! <:fuckthrust:914544341022814228> ',
description: `You gave a Funk Point to ${username}!`
})
]
});
if (before.reputation === after.reputation)
return Promise.reject(ERROR_EMBED.setDescription('❌ That user\'s Funk Points are maxed out!'));
await db.run(`UPDATE users SET reputation_cooldown = True WHERE user_id = ${msg.author.id}`);
}
catch {
return Promise.reject(ERROR_EMBED.setDescription('❌ Unknown error updating Funk Points!'));
}
}
function daysIntoYear(date: Date): number {
return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(date.getFullYear(), 0, 0)) / 24 / 60 / 60 / 1000;
}
let currentDay: number = daysIntoYear(new Date());
db.initialiser.on('complete', async _ => {
setInterval(async function () {
let dayNow = daysIntoYear(new Date());
if (dayNow !== currentDay) {
try {
await db.run('UPDATE users SET reputation_cooldown = False');
currentDay = dayNow;
}
catch {
console.log('Failed to reset reputation point cooldown.')
}
}
}, 300000);
});<file_sep>import { Command } from '../command'
import { Message, MessageEmbed } from "discord.js";
import { getNumFromParam, BOT_COLOR, ERROR_EMBED } from '../common';
import { command as pollCommand } from './poll';
import { db } from '../db';
module.exports = {
name: 'sungshowdown',
command: new Command(sungshowdown, new MessageEmbed({
color: 0xffb900,
title: 'sungshowdown',
description: 'Automatically generates a Sung Showdown™.',
fields: [
{
name: '`numsongs`',
value: 'The number of songs.'
},
{
name: "`duration`",
value: "The duration before voting closes."
},
{
name: '**Examples**',
value: '```bash\n'
+ 's/sungshowdown 2 30sm\n'
+ 's/sungshowdown 4 5h\n'
+ 's/sungshowdown 12 7d\n'
+ '```'
}
]
}))
}
async function sungshowdown(msg: Message, args: string): Promise<void> {
let argsSplit: string[] = args.split(' ');
if (argsSplit.length < 2)
return Promise.reject(ERROR_EMBED.setDescription('❌ Missing arguments!'));
let numSongs: number = getNumFromParam(argsSplit[0]);
if (isNaN(numSongs) || numSongs < 2 || numSongs > 20)
return Promise.reject(ERROR_EMBED.setDescription('❌ Invalid number of songs! Please use a number of songs between 2 and 20 inclusive.'));
let songs: object[];
songs = await db.all(`SELECT name, emoji FROM songs ORDER BY RANDOM() LIMIT ${numSongs}`).catch();
// Songs will be < 2 if it hasn't been populated.
if (songs.length < 2)
return Promise.reject(ERROR_EMBED.setDescription('❌ Requested more songs than there are registered in the database!'));
let pollArgs: string = '"It\'s Sung Showdown time! Vote for your ***favourite*** song!" ' +
`["${songs.map((song: any) => song.name).join('", "')}"] ` +
`["${songs.map((song: any) => song.emoji).join('", "')}"] ` +
argsSplit[1];
return await pollCommand.fn(msg, pollArgs);
}<file_sep>import { Command } from '../command';
import { Message, MessageAttachment, MessageEmbed } from 'discord.js';
import { BOT_COLOR, ERROR_EMBED } from '../common';
import { db } from '../db';
import { Canvas, CanvasRenderingContext2D, createCanvas, Image, loadImage } from 'canvas';
import { roundedRect, roundedImage, PANEL_COLOR, TEXT_COLOR, PODIUM_COLORS } from '../drawing';
module.exports = {
name: "rank",
command: new Command(rank, new MessageEmbed({
color: BOT_COLOR,
title: 'rank',
description: 'Show your server rank, TWR-XP and Funk Points.',
fields: [{ name: 'Examples', value: '```bash\ns/rank\n```' }]
}))
}
export async function rank(msg: Message, args: string): Promise<void> {
// Get your rank, TWR-XP and Funk Points.
let userxp: any;
let user: any;
let nextRole: any;
try {
userxp = await db.get(`SELECT res.xp, res.rank FROM (SELECT user_id, xp, ROW_NUMBER() OVER (ORDER BY xp DESC) rank FROM userguildxp) res WHERE user_id = ${msg.author.id}`)
user = await db.get(`SELECT reputation FROM users WHERE user_id = ${msg.author.id}`);
nextRole = await db.get(`SELECT role_id, xp FROM leveledroles WHERE (xp > ${userxp.xp} AND guild_id = ${msg.guildId}) ORDER BY xp ASC`);
}
catch {
return Promise.reject(ERROR_EMBED.setDescription('❌ Error fetching your rank details!'));
}
// Text-only version.
let textOnly: boolean;
try {
let res = await db.get(`SELECT text_only FROM users WHERE user_id = ${msg.author.id}`);
textOnly = res.text_only;
}
catch {
textOnly = false;
}
if (!msg.guild)
return Promise.reject(ERROR_EMBED.setDescription('❌ Unknown Guild error!'));
if (textOnly) {
let fields = [{ name: 'Rank', value: `#${userxp.rank}` },
{ name: 'TWRP-XP', value: `\`${userxp.xp}\`` },
{ name: 'Funk Points', value: `${user.reputation}` },
{ name: 'Next Role', value: `${(nextRole) ? msg.guild.roles.cache.get(nextRole.role_id) : 'None'} - **(${userxp.xp}/${nextRole.xp})**` }];
msg.channel.send({
embeds: [new MessageEmbed({
color: BOT_COLOR,
title: `Rank card for ${msg.author.username}`,
fields: fields,
thumbnail: { url: `${msg.author.avatarURL()}` },
})],
});
return Promise.resolve();
}
const canvas: Canvas = createCanvas(560, 256);
const ctx: CanvasRenderingContext2D = canvas.getContext('2d');
// Stores text that needs to be both measured and drawn to avoid duplicate strings.
let text: string;
// Background image.
await loadImage('../res/rank_bg.png').then(img => { ctx.drawImage(img, 0, 0, 560, 256); }).catch();
// Panel for the user's avatar and Funk Points.
ctx.fillStyle = PANEL_COLOR;
roundedRect(ctx, 14, 14, 188, 228, 20);
// Fetch and draw the user's avatar PNG.
await loadImage(msg.author.displayAvatarURL({ format: 'png' }))
.then(pfp => { roundedImage(ctx, pfp, 28, 28, 160, 160, 20); }).catch();
ctx.font = '30px "Montserrat Black"';
ctx.fillStyle = TEXT_COLOR;
text = `${user.reputation} FP`;
ctx.fillText(text, 105 - (ctx.measureText(text).width / 2), 225, 160);
// Panel for the user's username and rank.
ctx.fillStyle = PANEL_COLOR;
roundedRect(ctx, 216, 14, 330, 50, 20);
// Draw their username and rank.
ctx.font = '25px "Montserrat ExtraBold"';
ctx.fillStyle = TEXT_COLOR;
ctx.fillText(`${msg.author.username}`, 230, 47, 250);
// Top 3 gold, silver and bronze.
if (userxp.rank < 4)
ctx.fillStyle = PODIUM_COLORS[userxp.rank - 1];
ctx.font = '25px "Montserrat Black"';
ctx.fillText(`#${userxp.rank}`, 532 - ctx.measureText(`#${userxp.rank}`).width, 47, 200);
// Panel for XP progress bar and next leveled role.
ctx.fillStyle = PANEL_COLOR;
roundedRect(ctx, 216, 78, 330, 164, 20);
// Progress bar background.
ctx.fillStyle = 'rgba(80, 80, 80, 0.75)';
roundedRect(ctx, 230, 92, 302, 40, 22);
// Progress bar progress foreground.
ctx.fillStyle = 'rgba(140, 140, 140, 0.75)';
roundedRect(ctx, 230, 92, 302 * (userxp.xp / nextRole.xp), 40, 22);
ctx.font = '20px "Montserrat ExtraBold"';
ctx.fillStyle = TEXT_COLOR;
text = `${userxp.xp}/${nextRole.xp}`;
ctx.fillText(text, 381 - (ctx.measureText(text).width / 2), 120, 302);
ctx.font = '22px "Montserrat Black"';
text = 'Next Role';
ctx.fillText(text, 381 - (ctx.measureText(text).width / 2), 170, 302);
ctx.font = '30px "Montserrat Black"';
text = 'None';
let role = msg.guild.roles.cache.get(nextRole.role_id);
if (role)
text = role.name;
ctx.fillText(text, 381 - (ctx.measureText(text).width / 2), 210, 302);
msg.channel.send({ files: [new MessageAttachment(canvas.toBuffer(), 'rank.png')] });
}<file_sep>import { Command } from '../command';
import { Message, MessageEmbed } from "discord.js";
import { BOT_COLOR } from '../common';
let mw = require('nodemw');
const wt = require('wikitext2plaintext');
module.exports = {
name: 'wiki',
command: new Command(wiki, new MessageEmbed({
color: BOT_COLOR,
title: 'wiki',
description: 'Searches the TWRP Fandom Wiki for an article matching your search term.',
fields: [
{
name: '`search`',
value: 'The search term.'
},
{
name: '**Examples**',
value: '```bash\n'
+ 's/wiki Doctor Sung\n'
+ '```'
}
]
}))
}
let wclient = new mw({
protocol: 'https',
server: 'twrp.fandom.com',
path: '',
debug: false
});
let parser = new wt();
async function wiki(msg: Message, args: string): Promise<void> {
if (!args || args === '')
args = 'TWRP';
let title: string = await wikiSearchTitle(args).catch(_ => {
return Promise.reject(new MessageEmbed({
color: BOT_COLOR,
title: '❌ No Match Found'
}));
});
let imageName, imageUrl: string;
try {
imageName = await wikiGetTopArticleImageName(title);
imageUrl = await wikiGetImageUrl(imageName);
}
catch {
imageName = '';
imageUrl = '';
}
let summary: string;
try { summary = await wikiGetArticleSummary(title) }
catch { summary = 'No text found for this page.' };
if (!msg.channel.isVoice()) {
msg.channel.send({
embeds: [
{
color: BOT_COLOR,
title: title,
description: summary,
url: `http://twrp.fandom.com/${title.replace(/ /g, '_')}`,
thumbnail: { url: imageUrl }
}
]
});
}
}
// Promisifications
function wikiSearchTitle(key: string): Promise<string> {
return new Promise((resolve, reject) => {
wclient.search(key, (err: any, data: any) => {
if (err || !(data instanceof Array) || data.length === 0)
reject();
else
resolve(data[0].title);
});
});
}
function wikiGetTopArticleImageName(title: string): Promise<string> {
return new Promise((resolve, reject) => {
wclient.getImagesFromArticle(title, (err: any, images: any) => {
if (err || !(images instanceof Array) || images.length === 0) {
reject();
}
else
resolve(images[0].title);
});
});
}
function wikiGetImageUrl(name: string): Promise<string> {
return new Promise((resolve, reject) => {
wclient.getImageInfo(name, (err: any, data: any) => {
err ? reject() : resolve(data.url);
});
});
}
function wikiGetArticleSummary(title: string): Promise<string> {
return new Promise((resolve, reject) => {
wclient.api.call({ action: "parse", page: `${title}`, format: "json", prop: "wikitext", section: "0" }, (err: any, info: any, next: any, data: any) => {
err ? reject() : resolve(parser.parse(data.parse.wikitext['*']));
})
});
}<file_sep>import { Canvas, CanvasRenderingContext2D, Image, registerFont } from 'canvas';
export const TEXT_COLOR: string = 'rgba(255, 255, 255, 1.0)';
export const PANEL_COLOR: string = 'rgba(40, 40, 40, 0.5)';
export const PODIUM_COLORS = ['rgba(238, 185, 52, 1.0)', 'rgba(202, 202, 202, 1.0)', 'rgb(180, 115, 49, 1.0)'];
export function loadFonts() {
registerFont('../res/montserrat/Montserrat-Light.ttf', {family: 'Montserrat', weight: 'bold'});
registerFont('../res/montserrat/Montserrat-Medium.ttf', {family: 'Montserrat', weight: 'bold'});
registerFont('../res/montserrat/Montserrat-SemiBold.ttf', {family: 'Montserrat', weight: 'bold'});
registerFont('../res/montserrat/Montserrat-ExtraBold.ttf', {family: 'Montserrat', weight: 'bold'});
registerFont('../res/montserrat/Montserrat-Black.ttf', {family: 'Montserrat', weight: 'bold'});
}
export function roundedRect(ctx: CanvasRenderingContext2D, x: number, y: number, width: number, height: number, radius: number) {
if (!radius) {
radius = 5;
}
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.fill();
ctx.closePath();
}
export function roundedImage(ctx: CanvasRenderingContext2D, img: Image, x: number, y: number, width: number, height: number, radius: number) {
if (!radius) {
radius = 5;
}
ctx.save();
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.clip();
ctx.drawImage(img, x, y, width, height);
ctx.restore();
}<file_sep>import { MessageEmbed } from "discord.js";
export class Command {
fn: CallableFunction;
help: MessageEmbed;
constructor(fn: CallableFunction, help: MessageEmbed) {
this.fn = fn;
this.help = help;
}
}<file_sep>import { config } from 'dotenv'; config();
import { Client, GuildBasedChannel, GuildMember, Intents, MessageEmbed, PartialGuildMember, Role } from 'discord.js';
import * as fs from 'fs';
import { Command } from './command';
import { BOT_COLOR } from './common';
import { db } from './db';
import { giveMessageXP, updateLeveledRoles } from './xp';
import { loadFonts } from './drawing';
export const client: Client = new Client(
{
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS, Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_PRESENCES]
}
);
client.on('ready', async e => {
console.log(`SungBot connected!`);
});
db.initialiser.on('complete', async _ => {
loadFonts();
client.login(process.env.SUNGBOT_TOKEN).catch(err => {
console.error(err);
process.exit()
});
});
// Facilitate uptime monitors.
import { createServer, IncomingMessage, ServerResponse } from 'http';
const server = createServer((req: IncomingMessage, res: ServerResponse) => {
res.writeHead(200);
res.end('ok');
});
server.listen(3000);
// Fill a commands object with commands accessible
// by key via their command name/prefix.
let commands: Map<string, Command | undefined> = new Map<string, Command>();
// Populate commands map.
const jsFiles: string[] = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
jsFiles.forEach(commandFile => {
const commandModule = require(`./commands/${commandFile}`);
if (commandModule.name && commandModule.command)
commands.set(commandModule.name, commandModule.command);
});
let helpEmbed: MessageEmbed = new MessageEmbed({
color: BOT_COLOR,
title: 'SungBot - A TWRP-themed bot for the Ladyworld Discord server.',
description: 'Use s/help [command] for more detailed help.\n\nTip! Use `s/textonly` to force commands that output images to use 100% text instead, handy if you use a screen reader.',
fields: [{ name: 'Commands', value: '`' + Array.from(commands.keys()).join('`\n`') + '`', inline: false }]
});
// React to messages.
client.on('messageCreate',
async function (msg) {
if (!msg.author.bot) {
await giveMessageXP(msg).catch();
await updateLeveledRoles(msg).catch();
}
const prefixedCommand: string = msg.content.split(' ')[0];
let commandName: string = prefixedCommand.toLowerCase().split('s/')[1];
// If this is a testing instance
if (client.user && client.user.username.endsWith('-Testing'))
commandName = prefixedCommand.toLowerCase().split('st/')[1];
// Everything following the first space.
let args: string = msg.content.split(/ (.*)/s)[1];
args = (args === undefined) ? '' : args;
if (commandName === 'help') {
// No argument - main help.
if (!args) {
msg.channel.send({ embeds: [helpEmbed] });
}
else {
const command: Command | undefined = commands.get(args);
if (command !== undefined)
msg.channel.send({ embeds: [command.help] });
}
return;
}
const command: Command | undefined = commands.get(commandName);
// Filter out invalid commands and bot senders.
if (command && !msg.author.bot) {
try {
await command.fn(msg, args);
}
catch (errEmbed) {
if (errEmbed instanceof MessageEmbed)
msg.channel.send({ embeds: [errEmbed] });
}
}
});
client.on('guildMemberAdd', async function (member: GuildMember) {
// Get the join event for this guild.
let joinEvent: any = await db.get(`SELECT guild_id, channel_id, message, role_id FROM joinevents WHERE guild_id = ${member.guild.id}`)
.catch(_ => { console.log('Failed to get guild join event!'); return Promise.resolve(); });
// If this join event has a welcome message.
if (joinEvent.channel_id && joinEvent.message) {
let channel: GuildBasedChannel | undefined = member.guild.channels.cache.get(joinEvent.channel_id);
if (channel && channel.isText()) {
let message: string = joinEvent.message.replaceAll('${USER_MENTION}', `${member.user.toString()}`);
channel.send(message);
}
}
// If this join event has a role assignment.
if (joinEvent.role_id) {
let role: Role | undefined = member.guild.roles.cache.get(joinEvent.role_id);
if (role) {
try {
await member.roles.add(role.id);
}
catch {
console.log(`Failed to add role ${role.id} to user ${member.id}.`);
return Promise.resolve();
}
}
}
});
client.on('guildMemberRemove', async function (member: GuildMember | PartialGuildMember) {
// Get the join event for this guild.
let leaveEvent: any = await db.get(`SELECT guild_id, channel_id, message FROM leaveevents WHERE guild_id = ${member.guild.id}`);
// If this join event has a leave message.
if (leaveEvent.channel_id && leaveEvent.message) {
let channel: GuildBasedChannel | undefined = member.guild.channels.cache.get(leaveEvent.channel_id);
if (channel && channel.isText()) {
let message: string = leaveEvent.message.replaceAll('${USER_NAME}', `${member.user.username}`);
channel.send(message);
}
}
});<file_sep>import { Command } from '../command'
import { Guild, Message, MessageEmbed, MessageReaction } from "discord.js";
import { BOT_COLOR, convertTimeTextToSeconds, getEmoji, dateToUNIXTimestamp, ERROR_EMBED } from '../common';
import { db } from '../db';
import { client } from '../bot';
export let command = new Command(poll, new MessageEmbed({
color: BOT_COLOR,
title: 'poll',
description: 'Creates a timed poll, which automatically announces the winner upon ending.',
fields: [
{
name: '`message`',
value: 'Double-quoted string of body text.'
},
{
name: '`options`',
value: 'Square-bracketed array of double-quoted poll options.'
},
{
name: '`reactions`',
value: 'Square-bracketed array of double-quoted reaction emojis. Default emojis should be the unicode (e.g. "👍")'
+ 'and custom emojis should be the ID (e.g. "812799441164566528"). If this is empty or there are fewer emojis than poll options (up to 10),'
+ 'the emojis are automatically filled with number emojis.'
},
{
name: '`duration`',
value: 'Duration in millseconds, after which the poll automatically ends.'
},
{
name: '**Examples**',
value: '```bash\n'
+ 's/poll "Thumbs up or thumbs down?" ["Thumbs Up!", "Thumbs down."] ["👍", "👎"] 10m\n'
+ 's/poll "Which custom emoji?" ["The first!", "The second!"] ["812799441164566528", "215799448166564528"] 2.5h\n'
+ '```'
}
]
}));
module.exports = {
name: 'poll',
command: command
}
async function poll(msg: Message, args: string): Promise<void> {
// Split on all spaces except within "", '' and [].
let regex: RegExp = /(?:(["'])(\\.|(?!\1)[^\\])*\1|\[(?:(["'])(\\.|(?!\2)[^\\])*\2|[^\]])*\]|\((?:(["'])(\\.|(?!\3)[^\\])*\3|[^)])*\)|[^\s])+/g;
let parsedArgs: RegExpMatchArray | null = args.match(regex);
if (!parsedArgs || parsedArgs.length < 4)
return Promise.reject(ERROR_EMBED.setDescription('❌ Missing arguments!'));
if (parsedArgs.length > 4)
return Promise.reject(ERROR_EMBED.setDescription('❌ Too many arguments!'));
if (parsedArgs[0].charAt(0) !== '"' || parsedArgs[0].charAt(parsedArgs[0].length - 1) !== '"')
return Promise.reject(ERROR_EMBED.setDescription('❌ Invalid message! Please make the first argument a message enclosed in "".'));
let message: string = parsedArgs[0].substring(1, parsedArgs[0].length - 1);
// Attempt to parse arrays.
let options: string[] = JSON.parse(parsedArgs[1]);
let emojis: string[] = JSON.parse(parsedArgs[2]);
let duration: number | undefined = convertTimeTextToSeconds(parsedArgs[3]);
if (!duration || isNaN(duration))
return Promise.reject(ERROR_EMBED.setDescription('❌ Invalid duration! Please provide a valid duration e.g., 50s, 2m, 5.5h, 7d, etc.'));
emojis = emojis.concat(['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', '🔟']);
if (emojis.length <= options.length)
return Promise.reject(ERROR_EMBED.setDescription('❌ You didn\'t provide enough emojis to match your poll options,' +
' but you have more than 10 options; autofill only works up to 10. Please try again!'));
emojis = emojis.slice(0, options.length);
let endTime: Date = new Date(Date.now() + duration * 1000);
await msg.delete().catch(_ => console.log('Error deleting poll command message.'));
let pollMsg: string = createPollMessage(msg, message, options, emojis, endTime);
let sent: Message = await msg.channel.send(pollMsg).catch(_ => {
return Promise.reject(ERROR_EMBED.setDescription('❌ Failed sending the poll message!'));
});
try {
for (let i = 0; i < emojis.length; i++) {
await sent.react(getEmoji(msg.client, emojis[i]));
}
// Complete success, so add the poll to the database to be checked periodically
// and ended once its end time is reached.
await db.run(`INSERT INTO polls VALUES (${sent.id}, ${sent.guildId}, ${sent.channelId}, "${message}", '["${options.join('", "').replace(/'/g, "''")}"]',` +
` '${parsedArgs[2]}', ${Math.floor(endTime.getTime() / 1000)})`);
}
catch {
await sent.delete().catch();
return Promise.reject(ERROR_EMBED.setDescription('❌ Failed adding reactions to poll message! Probably an invalid emoji.'));
}
}
function createPollMessage(msg: Message, message: string, options: string[], emojis: string[], endTime: Date) {
let pollMsg = message + '\n\n';
for (let i = 0; i < options.length; i++)
pollMsg += `${getEmoji(msg.client, emojis[i])} ${options[i]}\n`;
pollMsg += `\nVoting ${(new Date() > endTime) ? 'closed' : 'closes'} ${dateToUNIXTimestamp(endTime)}.`;
return pollMsg;
}
db.initialiser.on('complete', async _ => {
setInterval(async function (): Promise<void> {
let current = Math.floor(new Date().getTime() / 1000);
let polls = await db.all(`SELECT msg_id, guild_id, channel_id, message, options, emojis, end_time FROM polls WHERE end_time < ${current}`)
.catch(_ => { return Promise.resolve() });
if (!(polls instanceof Array))
return Promise.resolve();
polls.forEach(async function (poll): Promise<void> {
let options = JSON.parse(poll.options);
let emojis = JSON.parse(poll.emojis);
// Always remove it even if the announcement etc. fails.
await db.run(`DELETE FROM polls WHERE guild_id = ${poll.guild_id} AND channel_id = ${poll.channel_id} AND msg_id = ${poll.msg_id}`).catch();
let guild: Guild | void = await client.guilds.fetch(poll.guild_id).catch(_ => { return Promise.resolve() });
if (!guild) return Promise.resolve();
let channel = await guild.channels.fetch(poll.channel_id).catch(_ => { return Promise.resolve() });
if (!channel || !channel.isText()) return Promise.resolve();
let msg = await channel.messages.fetch(poll.msg_id);
let reactCounts: number[] = [];
emojis.forEach(function (emoji: string) {
let fetchedReact: MessageReaction | undefined = msg.reactions.cache.get(emoji);
reactCounts.push((fetchedReact) ? fetchedReact.count : 0);
});
let maxes: number[] = [0];
for (let i = 1; i < reactCounts.length; i++) {
if (reactCounts[i] > reactCounts[maxes[0]]) {
maxes = [i];
}
else if (reactCounts[i] === reactCounts[maxes[0]])
maxes.push(i);
}
// Edit to refer to voting as having closed, past tense.
await msg.edit(createPollMessage(msg, poll.message, JSON.parse(poll.options),
JSON.parse(poll.emojis), new Date(poll.end_time * 1000))).catch();
// Send the winner announcement.
if (maxes.length === 1)
msg.channel.send(`The winner is ${getEmoji(msg.client, emojis[maxes[0]])} ${options[maxes[0]]}!`);
else {
// Build array of winner names.
let winners: string = `${getEmoji(msg.client, emojis[maxes[0]])} ${options[maxes[0]]}`;
for (let i = 1; i < maxes.length; i++) {
// 'and' before final winner.
winners += (i < maxes.length - 1) ? ', ' : ' and ';
winners += `${getEmoji(msg.client, emojis[maxes[i]])} ${options[maxes[i]]}`;
}
msg.channel.send(`It's a draw! ${winners} came out on top!`);
}
});
}, 2000);
});<file_sep>import { Client, GuildEmoji, MessageEmbed } from "discord.js";
export const BOT_COLOR: number = 0xffb900;
export const ERROR_EMBED: MessageEmbed = new MessageEmbed({
color: BOT_COLOR,
title: 'Action Failed',
description: '❌ Error!'
});
export function getNumFromParam(param : number | string | boolean | undefined) : number {
let num: number = NaN;
if (typeof param === "string") {
if (param[0] === '"' && param[param.length - 1] === '"')
param = param.slice(1, -1);
num = parseInt(param);
}
else if (param !== undefined && typeof param !== "boolean")
num = param;
return num;
}
export function getFloatFromParam(param: number | string | boolean | undefined): number {
let num: number = NaN;
if (typeof param === "string") {
if (param[0] === '"' && param[param.length - 1] === '"')
param = param.slice(1, -1);
num = parseFloat(param);
}
else if (param !== undefined && typeof param !== "boolean")
num = param;
return num;
}
export function getEmoji(client: Client, emojiNameID: string) : GuildEmoji | string {
let emoji: GuildEmoji | undefined = client.emojis.cache.get(emojiNameID);
return (emoji) ? emoji : emojiNameID;
}
export function dateToUNIXTimestamp(date: Date) : string {
return `<t:${Math.floor(date.getTime() / 1000)}:R>`;
}
export function splitOnSpaceExceptQuotedBracketed(splitstr: string) : string[] {
let arr: RegExpMatchArray | null =
splitstr.match(/(?:(["'])(\\.|(?!\1)[^\\])*\1|\[(?:(["'])(\\.|(?!\2)[^\\])*\2|[^\]])*\]|\((?:(["'])(\\.|(?!\3)[^\\])*\3|[^)])*\)|[^ ])+/g);
return (arr === null) ? [] : arr;
}
export function formatStringArg(arg: string) : string {
if (arg[0] === '"' && arg[arg.length - 1] === '"')
arg = arg.slice(1, -1);
// Replace the text "\n" with newline characters.
arg = arg.replace(/\\n/g, '\n');
return arg;
}
export function convertTimeTextToSeconds(timeText: string): number | undefined {
// Separate number from the text i.e. 2m -> 2, 4d -> 4, 16h -> 16.
let time: number | undefined = getFloatFromParam(timeText);
// Isolate the text timescale modifier i.e. h, d, m.
let scale: string = timeText.replace(/[0-9]/g, '').replace(/\./g, '');
switch (scale) {
case 's': time *= 1; break;
case 'm': time *= 60; break;
case 'h': time *= 3600; break;
case 'd': time *= 86400; break;
case 'w': time *= 604800; break;
case 'mo': time *= 2419200; break;
case 'y': time *= 29030400; break;
default: time = undefined;
}
if (time)
// Cap at 1000 years.
if (time > 29030400000)
time = 29030400000;
return time;
}
export function setTimeoutSeconds(callback: Function, seconds: number) : void {
// 1000 ms in a second.
let msInSecond = 1000;
let secondCount = 0;
let timer = setInterval(function() {
secondCount++; // A second has passed.
if (secondCount === seconds) {
clearInterval(timer);
// @ts-ignore
callback.apply(this, []);
}
}, msInSecond);
}<file_sep>import { Command } from '../command'
import { Message, MessageEmbed } from "discord.js";
import { BOT_COLOR, ERROR_EMBED } from '../common';
import { db } from '../db';
module.exports = {
name: "rate",
command: new Command(rate, new MessageEmbed({
color: BOT_COLOR,
title: 'rate',
description: 'Get SungBot to rate something.',
fields: [
{ name: 'things', value: 'The thing to rate.' },
{ name: 'Example', value: '```bash\ns/rate Fuckthrust\n```' }
]
}))
}
async function rate(msg: Message, args: string): Promise<void> {
// Create the rating.
let rating = Math.floor(Math.random() * (11));
// Get the closest rating message at or below this rating value.
let message = await db.get(`SELECT message FROM ratemessages ` +
`WHERE guild_id = ${msg.guildId} AND rating <= ${rating} ORDER BY rating DESC`)
.catch(_ => { return Promise.reject(ERROR_EMBED.setDescription('❌ Rating database error!')); });
// Possibly no rating messages in the database for this guild.
if (!message)
return Promise.reject(ERROR_EMBED.setDescription('❌ I don\'t know enough to rate things!'));
// Send the rating message.
msg.channel.send(message.message.replace(/\${RATING}/g, rating).replace(/\${THING}/g, args));
}<file_sep>import * as sql from 'sqlite3';
import { EventEmitter } from 'events';
export class BotDatabase {
db: sql.Database;
initialiser: EventEmitter;
constructor(dbFilePath: string) {
this.db = new sql.Database(dbFilePath, (err) => {
if (err) {
console.log('Could not connect to DB.');
}
else {
console.log('Connected to DB.');
}
});
this.initialiser = new EventEmitter();
}
run(sql: string, params = []): Promise<any> {
return new Promise((resolve, reject) => {
this.db.run(sql, params, function (err) {
if (err) {
console.log('Error running sql ' + sql)
console.log(err)
reject(err)
} else {
resolve({ id: this.lastID })
}
});
});
}
get(sql: string, params = []): Promise<any> {
return new Promise((resolve, reject) => {
this.db.get(sql, params, (err, result) => {
if (err) {
console.log('Error running sql: ' + sql)
console.log(err)
reject(err)
} else {
resolve(result)
}
});
});
}
all(sql: string, params = []): Promise<any> {
return new Promise((resolve, reject) => {
this.db.all(sql, params, (err, rows) => {
if (err) {
console.log('Error running sql: ' + sql)
console.log(err)
reject(err)
} else {
resolve(rows)
}
});
});
}
}
export const db: BotDatabase = new BotDatabase('../db.sqlite3');
async function initDatabase(): Promise<void> {
try {
// Setup DB.
await db.run('CREATE TABLE IF NOT EXISTS users (user_id TEXT PRIMARY KEY, reputation INTEGER, reputation_cooldown BOOLEAN, text_only BOOLEAN)');
await db.run('CREATE TABLE IF NOT EXISTS guilds (guild_id TEXT PRIMARY KEY)');
await db.run('CREATE TABLE IF NOT EXISTS userguildxp (user_id TEXT NOT NULL, guild_id TEXT NOT NULL,' +
' xp INTEGER, cooldown BOOLEAN, PRIMARY KEY (user_id, guild_id), FOREIGN KEY (user_id) REFERENCES users(user_id),' +
' FOREIGN KEY (guild_id) REFERENCES guilds(guild_id))');
// Reset all cooldowns that may be left on from a crash.
await db.run('UPDATE userguildxp SET cooldown = False');
await db.run('CREATE TABLE IF NOT EXISTS leveledroles (guild_id TEXT NOT NULL,' +
' role_id TEXT NOT NULL, xp INTEGER NOT NULL, message TEXT, PRIMARY KEY(guild_id, role_id ))');
await db.run('CREATE TABLE IF NOT EXISTS albums (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT, emoji TEXT)');
await db.run('CREATE TABLE IF NOT EXISTS songs (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, emoji TEXT NOT NULL, album INTEGER NOT NULL, FOREIGN KEY (album) REFERENCES albums(id))');
await db.run('CREATE TABLE IF NOT EXISTS polls (msg_id TEXT NOT NULL, guild_id TEXT NOT NULL, channel_id TEXT NOT NULL, message TEXT, options TEXT, emojis TEXT, end_time BIGINT, PRIMARY KEY (msg_id, guild_id, channel_id))');
await db.run('CREATE TABLE IF NOT EXISTS joinevents (guild_id TEXT NOT NULL PRIMARY KEY, channel_id TEXT NOT NULL, message TEXT, role_id TEXT)');
await db.run('CREATE TABLE IF NOT EXISTS leaveevents (guild_id TEXT NOT NULL PRIMARY KEY, channel_id TEXT NOT NULL, message TEXT)');
await db.run('CREATE TABLE IF NOT EXISTS ratemessages (guild_id TEXT NOT NULL, rating INTEGER NOT NULL, message TEXT NOT NULL, PRIMARY KEY (guild_id, rating))')
}
catch (e: any) {
return Promise.reject('Database setup failed.');
}
}
initDatabase().then(_ => db.initialiser.emit('complete')).catch(err => {
console.error(err);
process.exit()
});
<file_sep>import { Command } from '../command'
import { Message, MessageEmbed } from "discord.js";
import { BOT_COLOR } from '../common';
module.exports = {
name: "ping",
command: new Command(ping, new MessageEmbed({
color: BOT_COLOR,
title: 'ping',
description: 'Responds with ping latency info.'
}))
}
async function ping(msg: Message, args: string) : Promise<void> {
msg.channel.send(`Latency is ${msg.createdTimestamp - msg.createdTimestamp}ms!\nAPI Latency is ${Math.round(msg.client.ws.ping)}ms.`);
}<file_sep>import { Command } from '../command';
import { Message, MessageEmbed } from 'discord.js';
import { BOT_COLOR, ERROR_EMBED } from '../common';
import { db } from '../db';
module.exports = {
name: "leveledroles",
command: new Command(leveledroles, new MessageEmbed({
color: BOT_COLOR,
title: 'leveledroles',
description: 'Fetch a list of the server TWR-XP leveled roles.',
fields: [{ name: 'Example', value: '```bash\ns/leveledroles\n```' }]
}))
}
export async function leveledroles(msg: Message): Promise<void> {
let roles: any[] = await db.all(`SELECT role_id, xp FROM leveledroles ORDER BY xp ASC`)
.catch(_ => { return Promise.reject(ERROR_EMBED.setDescription('❌ Error fetching leveled roles list!')); });
if (!(roles instanceof Array) || !msg.guild)
return Promise.reject(ERROR_EMBED.setDescription('❌ Error fetching leveled roles list!'));
let embed: MessageEmbed = new MessageEmbed({
title: `TWR-XP Leveled Roles for ${msg.guild.name}`,
thumbnail: { url: `${msg.guild.iconURL()}` },
description: '**Chat to earn TWR-XP and be awarded these roles!**\n'
});
for (let i = 0; i < roles.length; i++)
embed.description += `\n\`${(i + 1).toString().padStart(2, '0')}\` ● <@&${roles[i].role_id}> **(${roles[i].xp})**`;
msg.channel.send({ embeds: [embed] });
}
<file_sep>import { GuildMember, Message, Role } from 'discord.js';
import { db } from './db';
export async function giveMessageXP(msg: Message): Promise<void> {
// Resolve rather than reject on errors as they would happen on every message.
// Add anything not yet in the DB.
try {
await db.run(`INSERT OR IGNORE INTO guilds VALUES (${msg.guildId})`);
await db.run(`INSERT OR IGNORE INTO users VALUES (${msg.author.id}, 0, False, False)`);
await db.run(`INSERT OR IGNORE INTO userguildxp VALUES (${msg.author.id}, ${msg.guildId}, 0, false)`);
}
catch (e: any) {
console.log('Failed to add user to DB.\n');
Promise.resolve();
}
// Reward XP.
try {
let res: any = await db.get(`SELECT xp FROM userguildxp WHERE user_id = ${msg.author.id} AND guild_id = ${msg.guildId}`);
if (typeof res === 'object' && res && res.hasOwnProperty('xp') && !msg.author.bot) {
res['xp'] += Math.floor(Math.random() * (10 - 5 + 1) + 5);
await db.run(`UPDATE userguildxp SET xp = ${res['xp']}, cooldown = True` +
` WHERE user_id = ${msg.author.id} AND guild_id = ${msg.guildId} AND cooldown = False`);
// Can just use a timeout here as all cooldowns are cleared on starting the bot,
// so no need for a periodic event in case it goes offline before the cooldown ends.
setTimeout(_ => {
db.run(`UPDATE userguildxp SET cooldown = False WHERE user_id = ${msg.author.id} AND guild_id = ${msg.guildId}`);
}, 120000);
}
} catch (e) {
console.log('Failed to reward XP');
}
}
export async function updateLeveledRoles(msg: Message): Promise<void> {
// Resolve rather than reject on errors as they would happen on every message.
let xpObj: any = await db.get(`SELECT xp FROM userguildxp WHERE guild_id = ${msg.guildId} AND user_id = ${msg.author.id}`)
.catch(_ => { console.log('Failed to get user XP.'); return Promise.resolve() });
// Get an array of all roles with XP requirements below the user's current XP.
let roles: any[] = await db.all(`SELECT role_id, message FROM leveledroles WHERE guild_id = ${msg.guildId} AND xp < ${xpObj.xp}`)
.catch(_ => { console.log('Failed to fetched roles.'); return Promise.resolve(); })
// Type guards.
if (!(roles instanceof Array) || !msg.member || !msg.guild) return Promise.resolve();
for (let i = 0; i < roles.length; i++) {
if (!msg.member.roles.cache.has(roles[i].role_id)) {
let role: Role | undefined = msg.guild.roles.cache.get(roles[i].role_id);
if (role) {
await msg.member.roles.add(role.id)
.catch(_ => { console.log(`Failed to add role to user ${msg.author.id}.`); return Promise.resolve(); });
if (roles[i].message && msg.member.roles.cache.has(role.id))
msg.channel.send(`${roles[i].message.replaceAll('${USER_MENTION}', `${msg.author.toString()}`).replaceAll('${ROLE_MENTION}', `<@&${roles[i].role_id}>`)}`);
}
}
}
}
<file_sep># SungBot
SungBot is a TWRP-themed general purpose bot created for the [Ladyworld Discord server](https://discord.gg/NZGZJ2C), originally to replace existing 3rd party bots that began working with NFTs, cryptocurrency and other blockchain technology. TWRP is a Canadian band most recongisable for their costumed personas, concealing their real identities. You should check them out!
The hosted instance of this bot uses cropped album artfor background images of commands. For copyright reasons, the images in the `res` directory in this repository are just blank white - replace them with your own in practice. Additionally, the bot fills out its sqlite3 database on startup if it's empty, but you must provide the empty db.sqlite3 file and fill out the leveled roles list yourself.
**NOTE**: Due to some other complications, the original repository had to be abandoned, so the initial commit of this one is monolithic. All changes after that are done properly.
## Features
- TWR-XP experience system, giving users XP per message with a cooldown.
1 - Leveled roles awarded based on TWR-XP, with an optional custom message for each.
2 - A leaderboard command to generate a nice-looking image of the top 10 (or 20, 30, 40 etc.).
3 - Rank checking, with a generated image.
- Funk Points - similar to reputation points in other bots, where users can give one per 24 hours to another user. These are a global value, so persist across all servers a particular SungBot instance is in.
- TWRP Fandom Wiki searching with summary embeds.
- Timed polls, with a convenience command to auto-generate a poll of TWRP songs.
- Convenience and fun commands like avatar fetching, rating etc.
## Accessibility
Some commands generate images to show their content (leaderboard, user rank, etc.). To maintain accessibility for the blind or partially-sighted using screen readers, users can toggle a blanket setting forcing text-based versions of these commands. This is done with the command `s/textonly`. Feel free to open an issue for other accessibility improvements :)
## Usage
To run the bot, install the dependencies, compile the TypeScript to JavaScript with `tsc`, enter the `dist` directory and run `node bot.js` with the environment SUNGBOT_TOKEN set to your bot token.
```bash
git clone https://www.github.com/corvance/sungbot
cd sungbot
npm i --save-dev typescript dotenv discord.js canvas nodemw wikitext2plaintext sqlite3 @types/sqlite3
export SUNGBOT_TOKEN=<KEY>
npm run compile && npm run start
```
You can run a testing instance of the bot using a Discord application bot with a username ending in '-Testing', changing the prefix from s/ to st/.
## Dependencies
- `discord.js` - The Discord bot development library.
- `dotenv` - For loading the bot token from .env files in local development.
- `sqlite3` - Fro sqlite3 database usage.
- `nodemw` and `wikitext2plaintext` - For MediaWiki API use with the TWRP Fandom Wiki.
- `canvas` - For creating dynamic images.
## License
This repository is subject to the terms of the MIT License, available at the LICENSE file in the root directory.
<file_sep>import { Command } from '../command'
import { Message, MessageEmbed, User } from "discord.js";
import { BOT_COLOR, ERROR_EMBED } from '../common';
module.exports = {
name: 'avatar',
command: new Command(avatar, new MessageEmbed({
color: BOT_COLOR,
title: 'avatar',
description: 'Retrieves you or another user\'s\' profile picture.',
fields: [
{
name: '`users`',
value: 'A mention of a user to fetch the avatars of.'
},
{
name: '**Examples**',
value: '```bash\n'
+ 's/avatar\n'
+ 's/avatar @lazerhorse\n'
+ '```'
}
]
}))
}
async function avatar(msg: Message, args: string) : Promise<void> {
let username: string = 'User';
let url: string = '';
if (msg.mentions.users.size > 0) {
let user: User | undefined = msg.mentions.users.first();
if (user) {
username = user.username;
url = user.displayAvatarURL();
}
else {
return Promise.reject(ERROR_EMBED.setDescription('❌ Invalid user!'));
}
}
else {
username = msg.author.username;
url = msg.author.displayAvatarURL();
}
msg.channel.send(
{embeds: [new MessageEmbed({
color: BOT_COLOR,
title: `${username}'s Avatar`,
image: {url: url}
})]}
);
}<file_sep>import { Command } from '../command';
import { Message, MessageEmbed } from 'discord.js';
import { BOT_COLOR, ERROR_EMBED } from '../common';
import { db } from '../db';
module.exports = {
name: "textonly",
command: new Command(textonly, new MessageEmbed({
color: BOT_COLOR,
title: 'textonly',
description: 'Toggle your text only flag so that all commands with images in their output use 100% text instead. This is useful for screen readers.',
fields: [{ name: 'Example', value: '```bash\ns/textonly\n```' }] }))
}
async function textonly(msg: Message) : Promise<void> {
try {
await db.run(`UPDATE users SET text_only = NOT text_only WHERE user_id = ${msg.author.id}`);
let newRes: any = await db.get(`SELECT text_only FROM users WHERE user_id = ${msg.author.id}`);
let newVal: boolean = newRes.text_only;
msg.channel.send({embeds: [new MessageEmbed({
color: BOT_COLOR,
title: 'Success!',
description: `${newVal ? '📝' : '🖼️'} Text-only output has been ${newVal ? 'enabled' : 'disabled'}.` +
` To ${newVal ? 'disable' : 're-enable'} it, just use this command again.`
})]});
}
catch {
Promise.reject(ERROR_EMBED.setDescription('❌ Something went wrong updating your Text Only flag - try again!'));
}
}
|
fe20a73e426d48b2154d267d1093588972bd57a2
|
[
"Markdown",
"TypeScript"
] | 18 |
TypeScript
|
Corvance/sungbot
|
e57f49998ecf5ff740a30a327f979fd970b85ba4
|
ce8f7455df2769b047ae380d57f00f6ed024de09
|
refs/heads/master
|
<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/17
* Time: 00:41
*/
namespace core\lib;
class config
{
public static $conf = [];
public static function getConf($name, $file)
{
if (isset(self::$conf[$file])) {
return self::$conf[$file][$name]; //避免重复加载
} else {
//加载配置项
$fileName = CORE . '/config/' . $file . '.php';
if (isset($fileName)) {
$conf = include $fileName;
if (isset($conf[$name])) {
self::$conf[$file] = $conf;
return $conf[$name];
} else {
throw new \Exception('配置项' . $name . '不存在');
}
} else {
throw new \Exception('配置文件' . $fileName . '不存在');
}
}
}
public static function getConfAll($file)
{
if (isset(self::$conf[$file])) {
return self::$conf[$file]; //避免重复加载
} else {
//加载配置项
$fileName = CORE . '/config/' . $file . '.php';
if (is_file($fileName)) {
$conf = include $fileName;
self::$conf[$file] = $conf;
return $conf;
} else {
throw new \Exception('配置文件' . $file . '不存在');
}
}
}
}<file_sep><?php
/* repair/repair.html */
class __TwigTemplate_5dd79fe6024bbeea6d1408667f5e3bcbffeb5fbfe64586a807e0e92e4e7b2459 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
$this->parent = $this->loadTemplate("public/base.html", "repair/repair.html", 1);
$this->blocks = array(
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "public/base.html";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_content($context, array $blocks = array())
{
// line 4
echo " <div class=\"main\">
<div class=\"main1\">
<div class=\"boxes\">
<h2>why us importance of repair</h2>
<div class=\"repair\">
<section>
<ul class=\"lb-album\">
<li> <a href=\"#image-1\"> <img src=\"/static/index/images/r_pic1.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-1\"> <img src=\"/static/index/images/r_pic1.jpg\" alt=\"\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<li> <a href=\"#image-2\"> <img src=\"/static/index/images/r_pic2.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-2\"> <img src=\"/static/index/images/r_pic2.jpg\" alt=\"\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<li> <a href=\"#image-3\"> <img src=\"/static/index/images/r_pic3.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-3\"> <img src=\"/static/index/images/r_pic3.jpg\" alt=\"image03\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<li> <a href=\"#image-4\"> <img src=\"/static/index/images/r_pic4.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-4\"> <img src=\"/static/index/images/r_pic4.jpg\" alt=\"image04\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
</ul>
</section>
</div>
<div class=\"repair\">
<section>
<ul class=\"lb-album\">
<li> <a href=\"#image-5\"> <img src=\"/static/index/images/r_pic5.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-5\"> <img src=\"/static/index/images/r_pic5.jpg\" alt=\"image05\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<li> <a href=\"#image-6\"> <img src=\"/static/index/images/r_pic6.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-6\"> <img src=\"/static/index/images/r_pic6.jpg\" alt=\"image06\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<li> <a href=\"#image-7\"> <img src=\"/static/index/images/r_pic7.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-7\"> <img src=\"/static/index/images/r_pic7.jpg\" alt=\"image07\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<li> <a href=\"#image-8\"> <img src=\"/static/index/images/r_pic8.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-8\"> <img src=\"/static/index/images/r_pic8.jpg\" alt=\"image08\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<div class=\"clear\"></div>
</ul>
</section>
</div>
</div>
</div>
</div>
";
}
public function getTemplateName()
{
return "repair/repair.html";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 31 => 4, 28 => 3, 11 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{% extends \"public/base.html\" %}
{% block content %}
<div class=\"main\">
<div class=\"main1\">
<div class=\"boxes\">
<h2>why us importance of repair</h2>
<div class=\"repair\">
<section>
<ul class=\"lb-album\">
<li> <a href=\"#image-1\"> <img src=\"/static/index/images/r_pic1.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-1\"> <img src=\"/static/index/images/r_pic1.jpg\" alt=\"\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<li> <a href=\"#image-2\"> <img src=\"/static/index/images/r_pic2.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-2\"> <img src=\"/static/index/images/r_pic2.jpg\" alt=\"\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<li> <a href=\"#image-3\"> <img src=\"/static/index/images/r_pic3.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-3\"> <img src=\"/static/index/images/r_pic3.jpg\" alt=\"image03\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<li> <a href=\"#image-4\"> <img src=\"/static/index/images/r_pic4.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-4\"> <img src=\"/static/index/images/r_pic4.jpg\" alt=\"image04\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
</ul>
</section>
</div>
<div class=\"repair\">
<section>
<ul class=\"lb-album\">
<li> <a href=\"#image-5\"> <img src=\"/static/index/images/r_pic5.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-5\"> <img src=\"/static/index/images/r_pic5.jpg\" alt=\"image05\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<li> <a href=\"#image-6\"> <img src=\"/static/index/images/r_pic6.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-6\"> <img src=\"/static/index/images/r_pic6.jpg\" alt=\"image06\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<li> <a href=\"#image-7\"> <img src=\"/static/index/images/r_pic7.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-7\"> <img src=\"/static/index/images/r_pic7.jpg\" alt=\"image07\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<li> <a href=\"#image-8\"> <img src=\"/static/index/images/r_pic8.jpg\" alt=\"\"> <span> </span> </a>
<div class=\"lb-overlay\" id=\"image-8\"> <img src=\"/static/index/images/r_pic8.jpg\" alt=\"image08\"> <a href=\"#page\" class=\"lb-close\"> </a> </div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</li>
<div class=\"clear\"></div>
</ul>
</section>
</div>
</div>
</div>
</div>
{% endblock %}", "repair/repair.html", "/Users/qiuzhiwei/Documents/web/coer/app/view/repair/repair.html");
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/17
* Time: 01:48
*/
namespace core\lib\drive\log;
class file
{
}<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/17
* Time: 18:32
*/
namespace app\control;
use core\coer;
class repair extends coer
{
public function index()
{
$this -> display('repair/repair');
}
}<file_sep><?php
//函数库
function p($val)
{
if (is_bool($val)) {
var_dump($val);
} elseif (is_null($val)) {
var_dump(NULL);
} else {
echo '<pre style="position: relative; margin: 30px; padding: 20px 40px; border-radius: 0 10px 10px 0; background: #f5f5f5; border-left: 4px solid #00f; font-size: 14px; line-height: 18px; opacity: .8;">'.print_r($val, true).'</pre>';
}
}
function jump($url)
{
echo '<meta http-equiv="refresh" content="0; url='.$url.'">';
exit();
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/22
* Time: 10:50
*/
namespace core\lib;
class cookie
{
// 静态受保护成员属性
protected static $config = [
// cookie名前缀
'prefix' => '',
// cookie保存时间
'expire' => 0,
// cookie 保存路径
'path' => '/',
// cookie 有效域名
'domain' => '',
// cookie 启用安全传输
'secure' => false,
// httponly 设置
'httponly' => '',
// 是否使用 setcookie
'setcookie' => true,
];
protected static $init;
/**
* cookie初始化
* @param array $config
* @return void
*/
public static function init($config = [])
{
// 如果函数参数为空数组, 先获取配置参数赋值给函数参数
if (empty($config)) {
$config = \core\lib\config::getConf('cookie', 'cookie');
}
// 先把函数参数的数组键名转换成小写, 再跟成员属性合并成一个新数组, 覆盖成员属性
self::$config = array_merge(self::$config, array_change_key_case($config));
// 如果 httponly 不为空, 则设置.ini 文件的 session.cookie_httponly 配置项为 1
if (!empty(self::$config['httponly'])) {
ini_set('session.cookie_httponly', 1);
}
// 成员属性赋值为 true
self::$init = true;
}
/**
* 设置或者获取 cookie 前缀
* @param string $prefix
* @return string|void
*/
public static function prefix($prefix = '')
{
// 如果为空, 则返回成员属性的'prefix'项
if (empty($prefix)) {
return self::$config['prefix'];
}
// 如果不为空, 则把参数覆盖成员属性对应的项
self::$config['prefix'] = $prefix;
}
/**
* cookie 设置
* @param $name cookie 名称
* @param string $value cookie 值
* @param null $option 可选参数, 可能是 null|integer|string
*
* @return mixed
* @internal param mixed $option cookie 参数
*/
public static function set($name, $value = '', $option = null)
{
// 成员属性$init不存在 并且成员方法 init() 不存在
!isset(self::$init) && self::init();
// 如果参数$option 不为 null
if (!is_null($option)) {
// 判断是否为数字, 把参数赋值给保存时间 expire 项
if (is_numeric($option)) {
$option = ['expire' => $option];
} elseif (is_string($option)) {
// 判断是否为字符串, 把字符串解析到变量中
parse_str($option, $option); // 第一个参数是要解析的字符串, 第二个参数是存储变量的数组名称
}
// 把$option 数组的键转换为小写, 跟自身成员属性合并成新数组, 赋值给$config
$config = array_merge(self::$config, array_change_key_case($option));
} else {
// 如果参数$option 为 null, 则把自身成员属性赋值给$config
$config = self::$config;
}
// 将 cookie 名称和 cookie 前缀拼接
$name = $config['prefix'] . $name;
// 如果$value 是数组, 把数组的每个元素进行自定义转换, 转换成 json 格式
if (is_array($value)) {
array_walk_recursive($value, 'self::jsonFormatProtect', 'encode');
$value = 'coer:'.json_encode($value);
}
// 如果三元运算判断, 设置cookie 保存时间
$expire = !empty($config['expire']) ? $_SERVER['REQUEST_TIME'] + intval($config['expire']) : 0;
// 属性 setcookie 为 true, 则设置 cookie
if ($config['setcookie']) {
setcookie($name, $value, $expire, $config['path'], $config['domain'], $config['secure'], $config['httponly']);
}
$_COOKIE[$name] = $value;
}
/**
* 永久保存 cookie 数据
* @param $name
* @param string $value
* @param null $option
* @return void
*/
public static function forever($name, $value = '', $option = null) {
// 判断$option 参数的值
if (is_null($option) || is_numeric($option)) {
$option = [];
}
// 设置 cookie 保存时间: 好几年
$option['expire'] = 315360000;
self::set($name, $value, $option);
}
/**
* 判断 cookie 数据
* @param $name
* @param null $prefix
* @return bool
*/
public static function has($name, $prefix = null)
{
!isset(self::$init) && self::init();
// 获取 cookie 名称前缀
$prefix = !is_null($prefix) ? $prefix : self::$config['prefix'];
// cookie 名称拼接
$name = $prefix.$name;
// 返回$_COOKIE常量对应的 cookie 信息
return isset($_COOKIE[$name]);
}
/**
* 获取 cookie 数据
* @param string $name
* @param null $prefix
* @return array|mixed|string
*/
public static function get($name = '', $prefix = null)
{
!isset(self::$init) && self::init();
// 获取 cookie 名称前缀
$prefix = !is_null($prefix) ? $prefix : self::$config['prefix'];
// cookie 名称拼接
$key = $prefix.$name;
// 判断$name 参数为空, 或者存在, 或者别的
if ($name == '') {
// 获取全部 cookie, 遍历数组
if ($prefix) {
$value = [];
foreach ($_COOKIE as $k => $val) {
if (strpos($k, $prefix)) {
$value[$k] = $val;
}
}
} else {
$value = $_COOKIE;
}
} elseif (isset($_COOKIE[$key])) {
$value = $_COOKIE[$key];
if (strpos($value, 'coer:') === 0) {
$value = substr($value, 6);
$value = json_decode($value, true);
array_walk_recursive($value, 'self::jsonFormatProtect', 'decode');
}
} else {
$value = null;
}
return $value;
}
/**
* 删除 cookie
* @param $name
* @param null $prefix
* @return mixed
*/
public static function delete($name, $prefix = null)
{
!isset(self::$init) && self::init();
// 获取$config 成员属性
$config = self::$config;
// 获取 cookie 名称前缀
$prefix = !is_null($prefix) ? $prefix : $config['prefix'];
// cookie 名称拼接
$name = $prefix.$name;
// 如果 setcookie 为 true, 则设置 cookie, 把时间设置为过去的时间
if ($config['setcookie']) {
setcookie($name, '', $_SERVER['REQUEST_TIME'] - 3600, $config['path'], $config['domain'], $config['secure'], $config['httponly']);
}
// 删除指定 cookie
unset($_COOKIE[$name]);
}
/**
* 清空 cookie
* @param null $prefix
*/
public static function clear($prefix = null)
{
// 如果没有 cookie, 则返回
if (empty($_COOKIE)) {
return;
}
!isset(self::$init) && self::init();
// 删除指定 cookie 前缀的数据, 不指定则删除 config 配置项设置的指定前缀
$config = self::$config;
$prefix = !is_null($prefix) ? $prefix : $config['prefix'];
// 如果前缀参数$prefix 为空, 则不作处理直接返回
if ($prefix) {
foreach ($_COOKIE as $k => $val) {
if (strpos($k, $prefix) === 0) {
if ($config['setcookie']) {
setcookie($k, '', $_SERVER['REQUEST_TIME'] - 3600, $config['path'], $config['domain'], $config['secure'], $config['httponly']);
unset($_COOKIE[$k]);
}
}
}
}
return;
}
private static function jsonFormatProtect(&$val, $key, $type = 'encode')
{
if (!empty($val) && $val !== true) {
$val = 'decode' == $type ?urldecode($val) : urlencode($val);
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/17
* Time: 10:40
*/
namespace app\model;
use core\lib\model;
class user extends model
{
public $table = 'contact';
//获取数据库数据
public function lists()
{
$result = $this -> select($this -> table, '*');
return $result;
}
//插入数据
public function insertData($data)
{
$result = $this -> insert($this -> table, $data);
return $result;
}
//获取单条数据
public function getOne($id)
{
$result = $this -> get($this -> table, '*', [
'bb_id' => $id
]);
return $result;
}
//更新单条数据
public function setOne($id, $data)
{
$result = $this -> update($this -> table, $data, [
'bb_id' => $id
]);
return $result;
}
//删除单条数据
public function delOne($id)
{
$result = $this -> delete($this -> table, [
'bb_id' => $id
]);
return $result;
}
}<file_sep><?php
namespace core;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class coer
{
public static $classMap = [];
public $assign;
public function __construct()
{
$log = new Logger('monolog');
$log -> pushHandler(new StreamHandler('runtime/monolog/mono.log', Logger::WARNING));
$log -> addWarning('Foo');
$log -> addError('Bar');
$model = new \app\model\user();
$result = $model -> getOne('admin');
$this -> assign('is_login', $result);
}
//框架运行
public static function run()
{
$route = new \core\lib\route();
// \core\lib\log::init();
//加载控制器
$control = $route->control;
$action = $route->action;
$file = APP . '/control/' . $control . '.php';
$controlClass = '\app\control\\' . $control;
if (is_file($file)) {
include $file;
$class = new $controlClass();
$class->$action();
} else {
throw new \Exception('找不到' . $controlClass . '控制器');
}
}
//自动引入类文件
public static function load($class)
{
if (isset(self::$classMap[$class])) {
return true;
} else {
//转换字符
$repClasss = str_replace('\\', '/', $class);
//类文件名
$file = COER . '/' . $repClasss . '.php';
if (is_file($file)) {
include $file; //引入类文件
self::$classMap[$class] = $repClasss;
} else {
return false;
}
}
}
//渲染数据
public function assign($name, $value)
{
$this->assign[$name] = $value;
}
//渲染页面 ------ 原始方法
// public function display($file)
// {
// $file = APP . '/view/' . $file . '.html';
// if (is_file($file)) {
// extract($this->assign); //把变量数组打散为多个单一变量
// include $file;
// }
// }
//渲染页面 ---- twig方法
public function display($file)
{
$files = APP . '/view/' . $file . '.html';
if (is_file($files)) {
//注册 Twig 类方法
\Twig_Autoloader::register();
//模板路径
$loader = new \Twig_Loader_Filesystem(APP . '/view/');
//环境设置
$twig = new \Twig_Environment($loader, [
'cache' => COER . '/runtime/twig',
'debug' => DEBUG
]);
//加载模板
$tmp = $twig -> loadTemplate($file . '.html');
//显示模板
$tmp -> display($this -> assign ? $this -> assign : []);
}
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/17
* Time: 18:31
*/
namespace app\control;
use core\coer;
class maintain extends coer
{
public function index()
{
$this -> display('maintain/maintain');
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/17
* Time: 18:29
*/
namespace app\control;
use core\coer;
class detail extends coer
{
public function index()
{
$this -> display('detail/details');
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/17
* Time: 17:37
*/
namespace app\control;
use core\coer;
class contact extends coer
{
public function index()
{
$this -> display('contact/contact');
}
public function aa()
{
$data['name'] = $_POST['name'];
$data['email'] = $_POST['email'];
$data['mobile'] = $_POST['mobile'];
$data['subject'] = $_POST['subject'];
$model = new \app\model\contact();
$result = $model -> insertData($data);
if ($result) {
echo '<script> alert("提交成功"); </script>';
jump('/contact/index');
} else {
echo '<script> alert("提交失败, 请检查~~"); </script>';
jump('/index/index');
}
}
}<file_sep><?php
// >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// | PHP Framework Created by PhpStorm.
// >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// | Author: Wally <<EMAIL>>
// >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// | Date: 2017/7/7 - 2017/8/23
// >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// | Licensed < http://www.apache.org/licenses/LICENSE-2.0 >
// >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
require_once 'template.php';
$tpl = new template();
// 要开启设置为 true
$tpl -> is_cache = false;
$webname = 'webname';
$author = 'author';
$title = 'webtitle';
$content = 'test content';
$tpl -> assign('webname', $webname);
$tpl -> assign('author', $author);
$tpl -> assign('title', $title);
$tpl -> assign('content', $content);
$tpl -> display('demo');<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/17
* Time: 18:30
*/
namespace app\control;
use core\coer;
class login extends coer
{
public function index()
{
$this -> display('login/login');
}
public function login()
{
$data['username'] = $_POST['username'];
$data['password'] = md5($_POST['password']);
// dump($data);
$model = new \app\model\user();
$result = $model -> getOne($data['username']);
// dump($result);
if ($data['username'] == $result['username'] && $data['password'] == $result['password']) {
$model -> setOne($data['username'], ['is_login' => 1]);
echo '<script> alert("登录成功"); </script>';
$this -> assign('data', $data['username']);
jump('/index/index');
// $this -> display('login/login');
} else {
echo '<script> alert("登录失败, 请重新登录~~"); </script>';
jump('/login/index');
}
}
public function logout()
{
$name = $_POST['username'];
$model = new \app\model\user();
$result = $model -> setOne($name, ['is_login' => 0]);
if ($result) {
jump('/login/index');
}
}
}<file_sep><?php
// >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// | PHP Framework Created by PhpStorm.
// >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// | Author: Wally <<EMAIL>>
// >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// | Date: 2017/7/7 - 2017/8/23
// >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// | Licensed < http://www.apache.org/licenses/LICENSE-2.0 >
// >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
namespace core\lib;
class template
{
// 模板文件目录
protected static $temp_dir = APP . '/view/temp';
// 编译文件目录
protected static $comp_dir = APP . '/runtime/comp';
// 缓存文件目录
protected static $cache_dir = APP . '/runtime/cache';
// 模板变量
protected static $temp_var = [];
// 模板内容
protected static $content = '';
// 是否开启缓存
public $is_cache = false;
// 模板编译
private static function parse($parse_file)
{
// 解析变量正则表达式
$pattern = '/\{\$([\w\d]+)\}/';
// 变量名转换成对应的 PHP 语句
if (preg_match($pattern, self::$content)) {
self::$content = preg_replace($pattern, '<?php echo self::$temp_var["$1"] ?>', self::$content);
}
// 编译完成, 生成编译文件, 否则输出错误
if (!file_put_contents($parse_file, self::$content)) {
exit('编译文件生成失败, 请检查~');
}
}
// 模板变量注入
public function assign($var, $value = null)
{
// 如果第一参数存在且不为空, 则将第二参数赋值给数组, 以第一参数为键名
if (isset($var) && !empty($var)) {
self::$temp_var[$var] = $value;
} else {
// 否则输出错误
exit('模板变量未设置');
}
}
// 模板文件编译
public function display($file)
{
// 检测目录是否存在, 没有则创建指定文件夹
if (!is_dir(self::$temp_dir)) {
mkdir(APP . '/view/temp', 0777, true);
}
if (!is_dir(self::$comp_dir)) {
mkdir(APP . '/runtime/comp', 0777, true);
}
if (!is_dir(self::$cache_dir)) {
mkdir(APP . '/runtime/cache', 0777, true);
}
// 模板文件
$tpl_file = self::$temp_dir. '/' . $file . '.html';
// 判断模板文件是否存在
if (!file_exists($tpl_file)) {
exit('模板文件不存在!');
}
// 编译后的文件路径
$parse_file = self::$comp_dir. '/' . md5($file, true) . $file . '.php';
// 如果编译后的文件不存在或者模板文件被修改了, 重新编译文件
if (!file_exists($parse_file) || filemtime($parse_file) < filemtime($tpl_file)) {
// 模板内容赋值
self::$content = file_get_contents($tpl_file);
// 执行编译方法
self::parse($parse_file);
}
// 如果开启了缓存, 则首先判断缓存文件, 否则直接加载编译文件
if ($this -> is_cache) {
// 缓存文件
$cache_file = self::$cache_dir . '/' . md5($file, true) . $file . '.html';
// 如果存在文件不存在或者编译文件被修改, 重新生成缓存文件
if (!file_exists($cache_file) || filemtime($cache_file) < filemtime($parse_file)) {
// 打开缓存区
ob_start();
// 先引入编译后的文件
include $parse_file;
// 获取缓存区的内容并删除当前缓存区数据
$content = ob_get_clean();
// 把内容写入到缓存文件, 如果写入失败则输出错误, 否则引入缓存文件
if (!file_put_contents($cache_file, $content)) {
exit('缓存文件生成失败, 请检查~');
} else {
include $cache_file;
}
} else {
// 如果缓存文件已存在则直接引入
include $cache_file;
}
} else {
// 没开启缓存则直接引入编译后的文件
include $parse_file;
}
}
}<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo self::$temp_var["title"] ?></title>
</head>
<body>
<div>
<h1><?php echo self::$temp_var["webname"] ?></h1>
<p>Author: <?php echo self::$temp_var["author"] ?></p>
<p>Content: <?php echo self::$temp_var["content"] ?></p>
</div>
</body>
</html><file_sep><?php
/* index/index.html */
class __TwigTemplate_5705131da9fa2d276f7d44ab4e0b26e5cd849b2125963491faddcd6c0dfca651 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
$this->parent = $this->loadTemplate("public/base.html", "index/index.html", 1);
$this->blocks = array(
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "public/base.html";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_content($context, array $blocks = array())
{
// line 4
echo " <div class=\"container\">
<section id=\"dg-container\" class=\"dg-container\">
<div class=\"dg-wrapper\"> <a href=\"#\"><img src=\"/static/index/images/1.jpg\" alt=\"image1\" /></a> <a href=\"#\"><img src=\"/static/index/images/2.jpg\" alt=\"image2\" /></a> <a href=\"#\"><img src=\"/static/index/images/3.jpg\" alt=\"image3\" /></a> <a href=\"#\"><img src=\"/static/index/images/4.jpg\" alt=\"image4\" /></a> <a href=\"#\"><img src=\"/static/index/images/5.jpg\" alt=\"image5\" /></a> <a href=\"#\"><img src=\"/static/index/images/6.jpg\" alt=\"image1\" /></a> <a href=\"#\"><img src=\"/static/index/images/7.jpg\" alt=\"image2\" /></a> <a href=\"#\"><img src=\"/static/index/images/8.jpg\" alt=\"image3\" /></a> </div>
</section>
</div>
<div class=\"main\">
<div class=\"section group\">
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic1.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem Ipsum is</h3>
</a> </div>
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic3.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem is simply </h3>
</a> </div>
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic2.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem Ipsum is</h3>
</a> </div>
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic4.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem is simply </h3>
</a> </div>
<div class=\"clear\"></div>
</div>
<div class=\"section group btm\">
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic5.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem Ipsum is</h3>
</a> </div>
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic6.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem is simply </h3>
</a> </div>
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic7.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem Ipsum is</h3>
</a> </div>
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic8.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem is simply </h3>
</a> </div>
<div class=\"clear\"></div>
</div>
</div>
";
}
public function getTemplateName()
{
return "index/index.html";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 31 => 4, 28 => 3, 11 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{% extends \"public/base.html\" %}
{% block content %}
<div class=\"container\">
<section id=\"dg-container\" class=\"dg-container\">
<div class=\"dg-wrapper\"> <a href=\"#\"><img src=\"/static/index/images/1.jpg\" alt=\"image1\" /></a> <a href=\"#\"><img src=\"/static/index/images/2.jpg\" alt=\"image2\" /></a> <a href=\"#\"><img src=\"/static/index/images/3.jpg\" alt=\"image3\" /></a> <a href=\"#\"><img src=\"/static/index/images/4.jpg\" alt=\"image4\" /></a> <a href=\"#\"><img src=\"/static/index/images/5.jpg\" alt=\"image5\" /></a> <a href=\"#\"><img src=\"/static/index/images/6.jpg\" alt=\"image1\" /></a> <a href=\"#\"><img src=\"/static/index/images/7.jpg\" alt=\"image2\" /></a> <a href=\"#\"><img src=\"/static/index/images/8.jpg\" alt=\"image3\" /></a> </div>
</section>
</div>
<div class=\"main\">
<div class=\"section group\">
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic1.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem Ipsum is</h3>
</a> </div>
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic3.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem is simply </h3>
</a> </div>
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic2.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem Ipsum is</h3>
</a> </div>
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic4.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem is simply </h3>
</a> </div>
<div class=\"clear\"></div>
</div>
<div class=\"section group btm\">
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic5.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem Ipsum is</h3>
</a> </div>
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic6.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem is simply </h3>
</a> </div>
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic7.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem Ipsum is</h3>
</a> </div>
<div class=\"grid_1_of_4 images_1_of_4\"> <a href=\"/detail/index\"><img src=\"/static/index/images/pic8.jpg\"></a> <a href=\"/detail/index\">
<h3>Lorem is simply </h3>
</a> </div>
<div class=\"clear\"></div>
</div>
</div>
{% endblock %}
", "index/index.html", "/Users/qiuzhiwei/Documents/web/coer/app/view/index/index.html");
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/17
* Time: 01:43
*/
return [
'DRIVE' => 'file'
];<file_sep><?php
/* public/base.html */
class __TwigTemplate_1526875d2433f82ee9284c588e9d2783407253a9e3781a12d7cd10329dfa6374 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
'head' => array($this, 'block_head'),
'content' => array($this, 'block_content'),
'foot' => array($this, 'block_foot'),
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
$this->displayBlock('head', $context, $blocks);
// line 86
echo "
";
// line 87
$this->displayBlock('content', $context, $blocks);
// line 89
echo "
";
// line 91
$this->displayBlock('foot', $context, $blocks);
}
// line 1
public function block_head($context, array $blocks = array())
{
// line 2
echo "<!DOCTYPE html>
<html>
<head>
<title>The Auto-Tuning Website</title>
<meta charset=\"UTF-8\" />
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">
<link href=\"/static/index/css/style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />
<link href=\"/static/index/css/global.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />
<link href=\"/static/index/css/easy-responsive-tabs.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />
<!--slider-->
<script type=\"text/javascript\" src=\"/static/index/js/modernizr.custom.53451.js\"></script>
<script type=\"text/javascript\" src=\"/static/index/js/jquery.min.js\"></script>
<script type=\"text/javascript\" src=\"/static/index/js/jquery.gallery.js\"></script>
<script type=\"text/javascript\">
\$(function() {
\$('#dg-container').gallery({
autoplay\t:\ttrue
});
});
</script>
</head>
<body>
<div class=\"wrap\">
<div class=\"header\">
<div class=\"logo\">
<h1><a href=\"index.html\"><img src=\"/static/index/images/logo.png\" alt=\"\"></a></h1>
</div>
<div class=\"h_right\">
<div class=\"drp-dwn\">
<ul>
<li>
<h3>Select ur Language :</h3>
</li>
<li>
<select onChange=\"window.location=this.options[this.selectedIndex].value\">
<option value=\"\">English</option>
<option value=\"\">German</option>
<option value=\"\">French</option>
</select>
</li>
<li>
<h3 style=\"margin-left: 10px;\">Currency :</h3>
</li>
<li>
<select onChange=\"window.location=this.options[this.selectedIndex].value\">
<option value=\"\">US Dollar-USD</option>
<option value=\"\">Euro-EUR</option>
<option value=\"\">Indian Rupee-INR</option>
</select>
</li>
</ul>
</div>
<div class=\"header_top_right\">
";
// line 55
if (($this->getAttribute(($context["is_login"] ?? null), "is_login", array()) == "1")) {
// line 56
echo " <div class=\"login\" style=\"background: skyblue;\"> <span><a href=\"/login/index\"><img src=\"/static/index/images/login.png\" alt=\"\" title=\"login\"></a></span> </div>
";
} else {
// line 58
echo " <div class=\"login\"> <span><a href=\"/login/index\"><img src=\"/static/index/images/login.png\" alt=\"\" title=\"login\"></a></span> </div>
";
}
// line 60
echo " <div class=\"shopping_cart\">
<div class=\"cart_img\"> <img src=\"/static/index/images/header_cart.png\"> </div>
<div class=\"cart\"> <a href=\"#\" title=\"View my shopping cart\" rel=\"nofollow\"> <span class=\"cart_title\">Cart</span> <span class=\"no_product\">(empty)</span> </a> </div>
</div>
<div class=\"clear\"></div>
</div>
</div>
<div class=\"clear\"></div>
<div class=\"h_main\">
<ul class=\"nav\">
<li class=\"active\"><a href=\"/\">Home</a></li>
<li><a href=\"/maintain/index\">Maintains</a></li>
<li><a href=\"/repair/index\">Repairs</a></li>
<li><a href=\"/contact/index\">Contact</a></li>
</ul>
<div class=\"search\">
<form>
<input type=\"text\" value=\"\" placeholder=\"";
// line 78
echo twig_escape_filter($this->env, ($context["data"] ?? null), "html", null, true);
echo "\">
<input type=\"submit\" value=\"\">
</form>
</div>
<div class=\"clear\"></div>
</div>
</div>
";
}
// line 87
public function block_content($context, array $blocks = array())
{
}
// line 91
public function block_foot($context, array $blocks = array())
{
// line 92
echo " <div class=\"footer\">
<div class=\"f_left\">
<div class=\"f_nav\">
<ul>
<li><a href=\"\">about us</a></li>
<li><a href=\"\">site map</a></li>
<li><a href=\"\">customer Service</a></li>
<li><a href=\"\">search terms</a></li>
<li><a href=\"\">contact us</a></li>
</ul>
</div>
<div class=\"copy\">
<p class=\"w3-link\">© All Rights Reserved | Templates By <a href=\"http://www.cssmoban.com/\" target=\"_blank\" title=\"NULL\">QZW</a> - Collect from <a href=\"http://www.cssmoban.com/\" title=\"NULL\" target=\"_blank\">WEB</a> </p>
</div>
</div>
<div class=\"social-icons\">
<ul>
<li class=\"icon1\"><a href=\"#\" target=\"_blank\"> </a></li>
<li class=\"icon2\"><a href=\"#\" target=\"_blank\"> </a></li>
<li class=\"icon3\"><a href=\"#\" target=\"_blank\"> </a></li>
<li class=\"icon4\"><a href=\"#\" target=\"_blank\"> </a></li>
<div class=\"clear\"></div>
</ul>
</div>
<div class=\"clear\"></div>
</div>
</div>
</body>
</html>
";
}
public function getTemplateName()
{
return "public/base.html";
}
public function getDebugInfo()
{
return array ( 145 => 92, 142 => 91, 137 => 87, 125 => 78, 105 => 60, 101 => 58, 97 => 56, 95 => 55, 40 => 2, 37 => 1, 33 => 91, 29 => 89, 27 => 87, 24 => 86, 22 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{% block head %}
<!DOCTYPE html>
<html>
<head>
<title>The Auto-Tuning Website</title>
<meta charset=\"UTF-8\" />
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">
<link href=\"/static/index/css/style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />
<link href=\"/static/index/css/global.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />
<link href=\"/static/index/css/easy-responsive-tabs.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />
<!--slider-->
<script type=\"text/javascript\" src=\"/static/index/js/modernizr.custom.53451.js\"></script>
<script type=\"text/javascript\" src=\"/static/index/js/jquery.min.js\"></script>
<script type=\"text/javascript\" src=\"/static/index/js/jquery.gallery.js\"></script>
<script type=\"text/javascript\">
\$(function() {
\$('#dg-container').gallery({
autoplay\t:\ttrue
});
});
</script>
</head>
<body>
<div class=\"wrap\">
<div class=\"header\">
<div class=\"logo\">
<h1><a href=\"index.html\"><img src=\"/static/index/images/logo.png\" alt=\"\"></a></h1>
</div>
<div class=\"h_right\">
<div class=\"drp-dwn\">
<ul>
<li>
<h3>Select ur Language :</h3>
</li>
<li>
<select onChange=\"window.location=this.options[this.selectedIndex].value\">
<option value=\"\">English</option>
<option value=\"\">German</option>
<option value=\"\">French</option>
</select>
</li>
<li>
<h3 style=\"margin-left: 10px;\">Currency :</h3>
</li>
<li>
<select onChange=\"window.location=this.options[this.selectedIndex].value\">
<option value=\"\">US Dollar-USD</option>
<option value=\"\">Euro-EUR</option>
<option value=\"\">Indian Rupee-INR</option>
</select>
</li>
</ul>
</div>
<div class=\"header_top_right\">
{% if is_login.is_login == '1' %}
<div class=\"login\" style=\"background: skyblue;\"> <span><a href=\"/login/index\"><img src=\"/static/index/images/login.png\" alt=\"\" title=\"login\"></a></span> </div>
{% else %}
<div class=\"login\"> <span><a href=\"/login/index\"><img src=\"/static/index/images/login.png\" alt=\"\" title=\"login\"></a></span> </div>
{% endif %}
<div class=\"shopping_cart\">
<div class=\"cart_img\"> <img src=\"/static/index/images/header_cart.png\"> </div>
<div class=\"cart\"> <a href=\"#\" title=\"View my shopping cart\" rel=\"nofollow\"> <span class=\"cart_title\">Cart</span> <span class=\"no_product\">(empty)</span> </a> </div>
</div>
<div class=\"clear\"></div>
</div>
</div>
<div class=\"clear\"></div>
<div class=\"h_main\">
<ul class=\"nav\">
<li class=\"active\"><a href=\"/\">Home</a></li>
<li><a href=\"/maintain/index\">Maintains</a></li>
<li><a href=\"/repair/index\">Repairs</a></li>
<li><a href=\"/contact/index\">Contact</a></li>
</ul>
<div class=\"search\">
<form>
<input type=\"text\" value=\"\" placeholder=\"{{data}}\">
<input type=\"submit\" value=\"\">
</form>
</div>
<div class=\"clear\"></div>
</div>
</div>
{% endblock %}
{% block content %}
{% endblock %}
{% block foot %}
<div class=\"footer\">
<div class=\"f_left\">
<div class=\"f_nav\">
<ul>
<li><a href=\"\">about us</a></li>
<li><a href=\"\">site map</a></li>
<li><a href=\"\">customer Service</a></li>
<li><a href=\"\">search terms</a></li>
<li><a href=\"\">contact us</a></li>
</ul>
</div>
<div class=\"copy\">
<p class=\"w3-link\">© All Rights Reserved | Templates By <a href=\"http://www.cssmoban.com/\" target=\"_blank\" title=\"NULL\">QZW</a> - Collect from <a href=\"http://www.cssmoban.com/\" title=\"NULL\" target=\"_blank\">WEB</a> </p>
</div>
</div>
<div class=\"social-icons\">
<ul>
<li class=\"icon1\"><a href=\"#\" target=\"_blank\"> </a></li>
<li class=\"icon2\"><a href=\"#\" target=\"_blank\"> </a></li>
<li class=\"icon3\"><a href=\"#\" target=\"_blank\"> </a></li>
<li class=\"icon4\"><a href=\"#\" target=\"_blank\"> </a></li>
<div class=\"clear\"></div>
</ul>
</div>
<div class=\"clear\"></div>
</div>
</div>
</body>
</html>
{% endblock %}
", "public/base.html", "/Users/qiuzhiwei/Documents/web/coer/app/view/public/base.html");
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/22
* Time: 15:38
*/
return [
'cookie' => [
// cookie名前缀
'prefix' => '',
// cookie保存时间
'expire' => 0,
// cookie 保存路径
'path' => '/',
// cookie 有效域名
'domain' => '',
// cookie 启用安全传输
'secure' => false,
// httponly 设置
'httponly' => '',
// 是否使用 setcookie
'setcookie' => true,
],
];<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/17
* Time: 00:09
*/
namespace core\lib;
use core\lib\config;
//继承自带的\PDO类
//class model extends \PDO
//{
// public function __construct()
// {
// //连接数据库
// $database = config::getConfAll('database');
// try {
// parent::__construct($database['DSN'], $database['USERNAME'], $database['PASSWORD']);
// } catch (\PDOException $e) {
// p($e->getMessage());
// }
// }
//}
//继承 composer 第三方类库 medoo
class model extends \Medoo\Medoo
{
public function __construct()
{
$option = config::getConfAll('database');
parent::__construct($option);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/21
* Time: 15:58
*/
namespace core\lib;
class cookie
{
public $name = '';
public $time = '';
public $serialize = false;
public $path = '';
public function __construct($name, $time, $serialize = false, $path = '/')
{
$this -> name = $name;
$this -> time = $time;
$this -> serialize = $serialize;
$this -> path = $path;
$fixName = $this -> name . '_S';
if ($this -> serialize && !isset($_COOKIE[$name])) {
$cookieArr = [];
foreach ($_COOKIE as $name => $val) {
if (strpos($name, $this -> name) != false) {
$subName = substr($name, strlen($this -> name) + 1);
$cookieArr[$subName] = $val;
$this -> delCookie($name);
}
}
$this -> setCookie($cookieArr);
}
if (!$this -> serialize && isset($_COOKIE[$fixName])) {
$cookieArr = unserialize($_COOKIE[$fixName]);
$this -> delCookie($fixName);
$this -> setCookie($cookieArr);
}
}
public function destroyCookie($name)
{
foreach ($_COOKIE as $name => $val) {
if (strpos($name, $this -> name) != false) {
$_COOKIE[$name] = NULL;
$this -> delCookie($name);
}
}
}
public function getCookie($item)
{
if ($this -> serialize) {
$name = $this -> name . '_S';
if (isset($_COOKIE[$name])) {
$cookie = unserialize($_COOKIE[$name]);
if (isset($cookie[$item])) {
return $cookie[$item];
} else {
return NULL;
}
} else {
return NULL;
}
} else {
$name = $this -> name . '_' . $item;
if (isset($_COOKIE[$name])) {
return $_COOKIE[$name];
} else {
return NULL;
}
}
}
public function delCookie($name)
{
$tmp = time() - 432000;
setcookie($name, '', $tmp, $this -> path);
}
public function setCookie($itemArr)
{
if ($this -> serialize) {
$items = $this->serialize($itemArr);
$name = $this -> name . '_S';
$_COOKIE[$name] =$items;
$tmp = time() + $this -> time;
setcookie($name, $items, $tmp, $this -> path);
} else {
$tmp = time() + $this -> time;
foreach ($itemArr as $name => $val) {
$name = $this -> name . '_' . $name;
$_COOKIE[$name] = $val;
setcookie($name, $val, $tmp, $this -> path);
}
}
}
}<file_sep><?php
/* contact/contact.html */
class __TwigTemplate_d62c45d4217986d1ddc1a9c278ddb9ec319402a7ce2542118596499f97dd4d5b extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
$this->parent = $this->loadTemplate("public/base.html", "contact/contact.html", 1);
$this->blocks = array(
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "public/base.html";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_content($context, array $blocks = array())
{
// line 4
echo " <div class=\"main\">
<div class=\"main1\">
<div class=\"section group1\">
<div class=\"col span_1_of_3\">
<div class=\"contact_info\">
<h3>Find Us Here</h3>
<div class=\"map\" title=\"map\">
<iframe width=\"100%\" height=\"175\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"\" style=\"background-color: darkgrey;\"></iframe>
<br>
<small><a href=\"https://maps.google.co.in/maps?f=q&source=embed&hl=en&geocode=&q=Lighthouse+Point,+FL,+United+States&aq=4&oq=light&sll=26.275636,-80.087265&sspn=0.04941,0.104628&ie=UTF8&hq=&hnear=Lighthouse+Point,+Broward,+Florida,+United+States&t=m&z=14&ll=26.275636,-80.087265\" style=\"color: #5A5A5A;text-align:left;font-size:12px\">View Larger Map</a></small> </div>
</div>
<div class=\"company_address\">
<h3>Company Info :</h3>
<p>500 Lorem Ipsum Dolor Sit,</p>
<p>22-56-2-9 Sit Amet, Lorem,</p>
<p>USA</p>
<p>Phone:(00) 222 666 444</p>
<p>Fax: (000) 000 00 00 0</p>
<p>Email: <span>info(at)mycompany.com</span></p>
<p>Follow on: <span>Facebook</span>, <span>Twitter</span></p>
</div>
</div>
<div class=\"col span_2_of_3\">
<div class=\"contact-form\">
<h3>Contact Us</h3>
<form id=\"contact-form\" method=\"post\" action=\"/contact/aa\">
<div> <span>
<label>NAME</label>
</span> <span>
<input name=\"name\" type=\"text\" class=\"textbox\">
</span> </div>
<div> <span>
<label>E-MAIL</label>
</span> <span>
<input name=\"email\" type=\"text\" class=\"textbox\">
</span> </div>
<div> <span>
<label>MOBILE</label>
</span> <span>
<input name=\"mobile\" type=\"text\" class=\"textbox\">
</span> </div>
<div> <span>
<label>SUBJECT</label>
</span> <span>
<textarea name=\"subject\"> </textarea>
</span> </div>
<div> <span>
<input type=\"submit\" value=\"Send me\">
</span> </div>
</form>
</div>
</div>
<div class=\"clear\"></div>
</div>
</div>
</div>
";
}
public function getTemplateName()
{
return "contact/contact.html";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 31 => 4, 28 => 3, 11 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{% extends \"public/base.html\" %}
{% block content %}
<div class=\"main\">
<div class=\"main1\">
<div class=\"section group1\">
<div class=\"col span_1_of_3\">
<div class=\"contact_info\">
<h3>Find Us Here</h3>
<div class=\"map\" title=\"map\">
<iframe width=\"100%\" height=\"175\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"\" style=\"background-color: darkgrey;\"></iframe>
<br>
<small><a href=\"https://maps.google.co.in/maps?f=q&source=embed&hl=en&geocode=&q=Lighthouse+Point,+FL,+United+States&aq=4&oq=light&sll=26.275636,-80.087265&sspn=0.04941,0.104628&ie=UTF8&hq=&hnear=Lighthouse+Point,+Broward,+Florida,+United+States&t=m&z=14&ll=26.275636,-80.087265\" style=\"color: #5A5A5A;text-align:left;font-size:12px\">View Larger Map</a></small> </div>
</div>
<div class=\"company_address\">
<h3>Company Info :</h3>
<p>500 Lorem Ipsum Dolor Sit,</p>
<p>22-56-2-9 Sit Amet, Lorem,</p>
<p>USA</p>
<p>Phone:(00) 222 666 444</p>
<p>Fax: (000) 000 00 00 0</p>
<p>Email: <span>info(at)mycompany.com</span></p>
<p>Follow on: <span>Facebook</span>, <span>Twitter</span></p>
</div>
</div>
<div class=\"col span_2_of_3\">
<div class=\"contact-form\">
<h3>Contact Us</h3>
<form id=\"contact-form\" method=\"post\" action=\"/contact/aa\">
<div> <span>
<label>NAME</label>
</span> <span>
<input name=\"name\" type=\"text\" class=\"textbox\">
</span> </div>
<div> <span>
<label>E-MAIL</label>
</span> <span>
<input name=\"email\" type=\"text\" class=\"textbox\">
</span> </div>
<div> <span>
<label>MOBILE</label>
</span> <span>
<input name=\"mobile\" type=\"text\" class=\"textbox\">
</span> </div>
<div> <span>
<label>SUBJECT</label>
</span> <span>
<textarea name=\"subject\"> </textarea>
</span> </div>
<div> <span>
<input type=\"submit\" value=\"Send me\">
</span> </div>
</form>
</div>
</div>
<div class=\"clear\"></div>
</div>
</div>
</div>
{% endblock %}", "contact/contact.html", "/Users/qiuzhiwei/Documents/web/coer/app/view/contact/contact.html");
}
}
<file_sep><?php
/* login/login.html */
class __TwigTemplate_88d0179bfaa88302a12432858ff93662b7f2320afa8c606a91d6ed412262f100 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
$this->parent = $this->loadTemplate("public/base.html", "login/login.html", 1);
$this->blocks = array(
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "public/base.html";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_content($context, array $blocks = array())
{
// line 4
echo "<div class=\"main\">
<div class=\"main1\">
";
// line 6
if (($this->getAttribute(($context["is_login"] ?? null), "is_login", array()) == "1")) {
// line 7
echo " <form class=\"form-4\" method=\"post\" action=\"/login/logout\">
<h1 style=\"text-align: center\">Welcome ";
// line 8
echo twig_escape_filter($this->env, $this->getAttribute(($context["is_login"] ?? null), "username", array()), "html", null, true);
echo "</h1>
<p>
<input type=\"submit\" name=\"submit\" value=\"Log out\" style=\"color: skyblue;\">
</p>
<input type=\"hidden\" name=\"username\" value=\"";
// line 13
echo twig_escape_filter($this->env, $this->getAttribute(($context["is_login"] ?? null), "username", array()), "html", null, true);
echo "\">
</form>
";
} else {
// line 16
echo " <form class=\"form-4\" method=\"post\" action=\"/login/login\">
<h1>Login Or Register</h1>
<p>
<label for=\"login\">Username or email</label>
<input type=\"text\" name=\"username\" placeholder=\"Username or email\" required autofocus>
</p>
<p>
<label for=\"password\">Password</label>
<input type=\"password\" name='password' placeholder=\"<PASSWORD>\" required>
</p>
<p>
<input type=\"submit\" name=\"submit\" value=\"Log in\">
</p>
</form>
";
}
// line 31
echo " </div>
</div>
";
}
public function getTemplateName()
{
return "login/login.html";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 71 => 31, 54 => 16, 48 => 13, 40 => 8, 37 => 7, 35 => 6, 31 => 4, 28 => 3, 11 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{% extends \"public/base.html\" %}
{% block content %}
<div class=\"main\">
<div class=\"main1\">
{% if is_login.is_login == '1' %}
<form class=\"form-4\" method=\"post\" action=\"/login/logout\">
<h1 style=\"text-align: center\">Welcome {{is_login.username}}</h1>
<p>
<input type=\"submit\" name=\"submit\" value=\"Log out\" style=\"color: skyblue;\">
</p>
<input type=\"hidden\" name=\"username\" value=\"{{is_login.username}}\">
</form>
{% else %}
<form class=\"form-4\" method=\"post\" action=\"/login/login\">
<h1>Login Or Register</h1>
<p>
<label for=\"login\">Username or email</label>
<input type=\"text\" name=\"username\" placeholder=\"Username or email\" required autofocus>
</p>
<p>
<label for=\"password\">Password</label>
<input type=\"password\" name='password' placeholder=\"<PASSWORD>\" required>
</p>
<p>
<input type=\"submit\" name=\"submit\" value=\"Log in\">
</p>
</form>
{% endif %}
</div>
</div>
{% endblock %}", "login/login.html", "/Users/qiuzhiwei/Documents/web/coer/app/view/login/login.html");
}
}
<file_sep><?php
namespace app\control;
use core\coer;
use core\lib\cookie;
use core\lib\model;
use core\lib\session;
class index extends coer
{
public function index()
{
//PDO 写法
// $model = new \core\lib\model();
// $sql = 'select * from bb';
// $result = $model->query($sql); //查询数据库
// p($result->fetchAll());
//medoo 写法
// $model = new \app\model\user();
// $result = $model -> lists();
// $setOne = $model -> setOne('7', [
// 'bb_name' => 'setOne',
// 'bb_pd' => 'setpd'
// ]);
// $insertData = $model -> insertData([
// 'bb_name' => 'insert',
// 'bb_pd' => 'sinetepd',
// 'date' => date('Y-m-d')
// ]);
// cookie::init(['prefix' => 'coer_', 'expire' => 3600, 'path' => '/']);
// cookie::prefix('coer_');
// cookie::set('cooname', 'value', 3600);
// cookie::set('name', 'coer_value', ['prefix' => 'coer_', 'expire' => 3600]);
// cookie::clear('coer_');
//
// $res = cookie::get('coer_cooname');
// $result = cookie::get('name', 'coer_');
// dump($res);
// dump($result);
// $results = cookie::get();
// dump($results);
// session::set('session', 'testSession', 'coer_');
// session::set('session', 'session', 'test_');
// session::clear('test_');
// $res = session::get();
// dump($res);
// exit();
$this -> assign('data', 'input');
$this -> display('index/index');
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/22
* Time: 23:15
*/
return [
'session' => [
// session ID
'id' => '',
// session ID 的提交变量, 解决 flash 上传跨域
'var_session_id' => '',
// session 前缀
'prefix' => 'coer',
// 驱动方式, redis/memcache/memcached
'type' => '',
// 是否自动开启 session
'auto_start' => true,
],
];<file_sep><?php
/* maintain/maintain.html */
class __TwigTemplate_a3dd3a1461118f199795ee9653234a49a2a767fda974eb88c4d9c1d10303ac0e extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
$this->parent = $this->loadTemplate("public/base.html", "maintain/maintain.html", 1);
$this->blocks = array(
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "public/base.html";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_content($context, array $blocks = array())
{
// line 4
echo " <div class=\"main\">
<div class=\"main1\">
<h2 class=\"hdr_s\">Why us importance of maintaince</h2>
<div class=\"image group\">
<div class=\"images_2_of_2\"> <a href=\"details.html\"> <img src=\"/static/index/images/8.jpg\" alt=\"\"></a> </div>
<div class=\"span_2_of_2\">
<h3>Lorem Ipsum is simply dummy text </h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</div>
<div class=\"clear\"></div>
</div>
<div class=\"image group\">
<div class=\"images_2_of_2\"> <a href=\"details.html\"> <img src=\"/static/index/images/2.jpg\" alt=\"\"></a> </div>
<div class=\"span_2_of_2\">
<h3>Lorem Ipsum is simply dummy text </h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</div>
<div class=\"clear\"></div>
</div>
<div class=\"image group1\">
<div class=\"images_2_of_2\"> <a href=\"details.html\"> <img src=\"/static/index/images/3.jpg\" alt=\"\"></a> </div>
<div class=\"span_2_of_2\">
<h3>Lorem Ipsum is simply dummy text </h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</div>
<div class=\"clear\"></div>
</div>
</div>
</div>
";
}
public function getTemplateName()
{
return "maintain/maintain.html";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 31 => 4, 28 => 3, 11 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{% extends \"public/base.html\" %}
{% block content %}
<div class=\"main\">
<div class=\"main1\">
<h2 class=\"hdr_s\">Why us importance of maintaince</h2>
<div class=\"image group\">
<div class=\"images_2_of_2\"> <a href=\"details.html\"> <img src=\"/static/index/images/8.jpg\" alt=\"\"></a> </div>
<div class=\"span_2_of_2\">
<h3>Lorem Ipsum is simply dummy text </h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</div>
<div class=\"clear\"></div>
</div>
<div class=\"image group\">
<div class=\"images_2_of_2\"> <a href=\"details.html\"> <img src=\"/static/index/images/2.jpg\" alt=\"\"></a> </div>
<div class=\"span_2_of_2\">
<h3>Lorem Ipsum is simply dummy text </h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</div>
<div class=\"clear\"></div>
</div>
<div class=\"image group1\">
<div class=\"images_2_of_2\"> <a href=\"details.html\"> <img src=\"/static/index/images/3.jpg\" alt=\"\"></a> </div>
<div class=\"span_2_of_2\">
<h3>Lorem Ipsum is simply dummy text </h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<div class=\"rd_more\"> <a href=\"details.html\" class=\"button button-rounded\">Read More</a> </div>
</div>
<div class=\"clear\"></div>
</div>
</div>
</div>
{% endblock %}", "maintain/maintain.html", "/Users/qiuzhiwei/Documents/web/coer/app/view/maintain/maintain.html");
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/17
* Time: 01:41
*/
namespace core\lib;
class log
{
public static $class;
public static function init()
{
$drive = config::getConf('DRIVE', 'log');
$class = '\core\lib\drive\log\\'.$drive;
self::$class = new $class;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/22
* Time: 23:14
*/
namespace core\lib;
class session
{
protected static $prefix = 'coer_';
/**
* 设置 session 名称前缀
* @param string $prefix
* @return string
*/
public static function prefix($prefix = '')
{
// 如果为空且不等于 null, 则返回自身成员属性
if (empty($prefix) && $prefix !== null) {
return self::$prefix;
} else {
// 否则将参数赋值给自身成员属性
self::$prefix = $prefix;
}
}
/**
* session 设置
* @param $name session 名称
* @param string $value session 值
* @param null $prefix session 前缀
* @return void
*/
public static function set($name, $value = '', $prefix = null)
{
// 获取 session 前缀
$prefix = !is_null($prefix) ? $prefix : self::$prefix;
// 如果$name 参数包含'.' 则转换成二维数组
if (strpos($name, '.')) {
// 二维数组赋值
list($name1, $name2) = explode('.', $name);
// 如果前缀存在, 则设置 session 数组名称加上前缀
if ($prefix) {
$_SESSION[$prefix][$name1][$name2] = $value;
} else {
$_SESSION[$name1][$name2] = $value;
}
} elseif ($prefix) {
// 如果$prefix 存在且$name 不包含'.' 则设置 session 名称加上前缀
$_SESSION[$prefix][$name] = $value;
} else {
// 否则直接设置 session 值
$_SESSION[$name] = $value;
}
}
/**
* 获取 session 数据
* @param string $name
* @param null $prefix
* @return array|null
*/
public static function get($name = '', $prefix = null)
{
// 获取 session 前缀
$prefix = !is_null($prefix) ? $prefix : self::$prefix;
// 判断参数值
if ($name == '') {
// 获取全部 session 值
$value = $prefix ? (!empty($_SESSION[$prefix]) ? $_SESSION[$prefix] : []) : $_SESSION;
} elseif ($prefix) {
if (strpos($name, '.')) {
// 二维数组赋值
list($name1, $name2) = explode('.', $name);
$value = isset($_SESSION[$prefix][$name1][$name2]) ? $_SESSION[$prefix][$name1][$name2] : null;
} else {
$value = isset($_SEESION[$prefix][$name]) ? $_SESSION[$prefix][$name] : null;
}
} else {
if (strpos($name, '.')) {
list($name1, $name2) = explode('.', $name);
$value = $_SESSION[$name1][$name2] ? $_SESSION[$name1][$name2] : null;
} else {
$value = isset($_SESSION[$name]) ? $_SESSION[$name] : null;
}
}
// 返回 session 值
return $value;
}
/**
* 删除 session 数据
* @param $name
* @param null $prefix
* @return void
*/
public static function delete($name, $prefix = null)
{
$prefix = !is_null($prefix) ? $prefix : self::$prefix;
if (is_array($name)) {
foreach ($name as $key) {
// 如果$name 为数组, 则遍历数组然后再次调用删除方法
self::delete($key, $prefix);
}
} elseif (strpos($name, '.')) {
list($name1, $name2) = exp('.', $name);
if ($prefix) {
unset($_SESSION[$prefix][$name1][$name2]);
} else {
unset($_SESSION[$name1][$name2]);
}
} else {
if ($prefix) {
unset($_SESSION[$prefix][$name]);
} else {
unset($_SESSION[$name]);
}
}
}
/**
* 清空 session 数据
* @param $prefix
* @return void
*/
public static function clear($prefix = null)
{
$prefix = !is_null($prefix) ? $prefix : self::$prefix;
if ($prefix) {
// 如果存在前缀, 则删除指定前缀的 session 数据
unset($_SESSION[$prefix]);
} else {
// 否则全部设置为空数组
$_SERVER = [];
}
}
/**
* 判断 session 数据
* @param $name
* @param $prefix
* @return bool
*/
public static function has($name, $prefix)
{
$prefix = !is_null($prefix) ? $prefix : self::$prefix;
if (strpos($name, '.')) {
// 如果$name 参数是二维数组形式, 则返回对应的 session 数据
list($name1, $name2) = explode('.', $name);
return $prefix ? isset($_SESSION[$prefix][$name1][$name2]) : isset($_SESSION[$name1][$name2]);
} else {
// 否则直接返回对应的 session 数据
return $prefix ? isset($_SESSION[$prefix][$name]) : isset($_SESSION[$name]);
}
}
/**
* 添加数据到 session 数组
* @param $key
* @param $val
* @return void
*/
public static function push($key, $val)
{
$arr = self::get($key);
if (is_null($arr)) {
$arr = [];
}
$arr[] = $val;
self::set($key, $arr);
}
/**
* 销毁 session 会话
* @return void
*/
public static function destory()
{
if (!empty($_SESSION)) {
$_SESSION = [];
}
session_unset();
session_destroy();
}
/**
* 暂停 session 会话
* @return void
*/
public static function pause()
{
session_write_close();
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: qiuzhiwei
* Date: 2017/8/17
* Time: 00:45
*/
return [
'CONTROL' => 'index',
'ACTION' => 'index',
'STATIC' => '/static'
];
|
de33a80d3caddfd0e5c671f71795637032b3bddc
|
[
"PHP"
] | 29 |
PHP
|
halowodcloud/coer
|
64105859bc2cbc6c1ad922d51d97e5ad906e10b1
|
b0fd9c409bd144b6ee248d9631c6dade867b5ab6
|
refs/heads/master
|
<file_sep>print('Hello kind World!!!')
print('No buddy its a cruel world!!!')
|
33eef90338c0432aac0060c071eaf94b7c184400
|
[
"Python"
] | 1 |
Python
|
AzimEjMhd/green-thumb
|
019facbc3fc9164ed34f5e5a5d3de568fe0dc6ac
|
d419692d7074718b6a3a20515362b06495be5d6f
|
refs/heads/master
|
<file_sep>// This .c file is to test aodf.c
// I used this to generate a program called ./testfile1
// the ouput of ./testfile1 is saved under "test"
// which I used to test the program, like this: ./aodf test
#include <stdio.h>
int main(void){
putchar(0x01);
putchar(0xEF);
putchar(0xCF);
return 0;
}
<file_sep>//file name: aodf.c
#include <stdio.h> //defines 3 variable types, several macros and functions for performing i/o
#include <stdlib.h> // similar to stdio but contains info for memory allocation/freeing
// Main function for the program to run
//
// This program does the same output when doing "od -tx1 filename" except
// the left column is in decimal ( not octal )
//
// in man od : dump files in octal or indicated format
// -t : select hexadecimal 2-byte units
// x1: hexadecimal, size bytes per integer
//
int main( int argc, char *argv[] )
{
// checks if terminal input has less/more than 2 arguments
if( argc != 2 )
{
printf("Incorrect Usage, please input: ./program filename\n");
exit(-1); // indicates program unsuccessful
}
FILE *f; // FILE object
f = fopen( argv[1], "r" );
// "r" == read
//reading file object i.e. the second agrument in the command line
//agrv[0] indicates the program itself
// Check if input file was opened successfully
if( f == NULL )
{
printf("Cannot open %s\n", argv[1] ); // %s == string i.e. name of the file
exit(-1); // indicates program unsuccessful
}
int counter = 0; //counts the number of hex characters
int read = getc( f ); // takes reading content from the file variable "f" ( initializes )
// if( counter % 16 == 0 )
// {
// printf( "\n%08d", counter ); // make sure 8 digits
// }
while ( read != EOF ) // Read until End of File
{
if( counter == 0 ) // this if else block is used so that the first empty line is not printed because of "\n" e.g. when just stating printf( "\n%08", counter ) instead of block
{
printf( "%08d" , counter );
}
else if( counter % 16 == 0 )
{
printf( "\n%08d" , counter ); //format to print an integer in decimal with a minimum width of 8 characters using 0 to fill the left
}
printf( " %02x", read );
counter++;
read = getc(f);
}
printf("\n%08d\n", counter ); //prints out counter increments
if( feof(f) )
{
printf( "\nEnd of File Reached.\n" ); // prints when EOF reached
}
else
{
printf( "\nOther Error ?" ); //otherwise some sort of error
}
fclose(f); // CLOSE FILE
return 0; // indicates program successful
}
<file_sep># alternate-dump-files
## Description:
This program displays the content of a file to stdout that is similar to doing: the following below. The difference is that the offset is in decimal and not in octal for the last two of the mentioned processes. This program does the same as doing "hd filename".
```
$ hd filename
$ od -tx1 filename
$ hexdump filename
// hexdump displays/orders bytes depending on the endianess of your machine
```
The code in this repository called ["detect_endianess"](https://github.com/Bubblemelon/detect_endianess "Bubblemelon's Detect Endianess") can determine the endianess of your computer.
The file titled "printcap" is generated automatically by printer configurations in "/etc". A description of this file can be found in the file "printcap". I used this file as a sample to run my program.
### Program usage:
(1) fopen/fclose
(2) End of File: EOF and feof
(3) Command-line arguments of index 0 and 1
### For example:
When doing ```od -tx1 printcap```
The left most column is in octal:
```
0000000 23 20 54 68 69 73 20 66 69 6c 65 20 77 61 73 20
0000020 61 75 74 6f 6d 61 74 69 63 61 6c 6c 79 20 67 65
0000040 6e 65 72 61 74 65 64 20 62 79 20 63 75 70 73 64
```
When doing ``` $ ./aodf printcap ```
The left most column is in decimal:
```
00000000 23 20 54 68 69 73 20 66 69 6c 65 20 77 61 73 20
00000016 61 75 74 6f 6d 61 74 69 63 61 6c 6c 79 20 67 65
00000032 6e 65 72 61 74 65 64 20 62 79 20 63 75 70 73 64
```
## Note:
Look at aodf.c for comments on usage.
I saved the output of ``` $ ./aodf printcap ``` in a file called output.txt
testfile1.c is created to produce a program called " ./testfile1 " ; the output of this program is saved under the filed called " test ". The purpose of this file is to see whehter if aodf.c is correct.
|
9545329525c5690f915557109ceaacaece3e3cf2
|
[
"Markdown",
"C"
] | 3 |
C
|
Bubblemelon/alternate-dump-files
|
b74a83ac5ccfde9ccaf789c4d154c08fb7fb3aca
|
965719224290c9ebf22ba40848cf5437342b2ceb
|
refs/heads/main
|
<repo_name>matrixrk/demo-front<file_sep>/src/app/login-page/login-page.component.ts
import { Component, OnInit } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import { Router} from "@angular/router";
@Component({
selector: 'app-login-page',
templateUrl: './login-page.component.html',
styleUrls: ['./login-page.component.css']
})
export class LoginPageComponent implements OnInit {
email: string | undefined ;
password: string | undefined ;
constructor(private http: HttpClient,private route: Router) { }
ngOnInit(): void {
}
submit() {
console.log(this.email)
console.log(this.password)
this.http.post("http://localhost:8080/authenticate",{email:this.email,password:this.password}).subscribe(
data=>{
this.route.navigate(["profile"])
}
)
}
}
|
792330c613e98172897c53a36607e54c4ebf1748
|
[
"TypeScript"
] | 1 |
TypeScript
|
matrixrk/demo-front
|
06fcd52ef0a55997a76fa96f180aaff8e4bf636b
|
e98dd6db3136d7d5e5948291863235f0965c755a
|
refs/heads/main
|
<file_sep>import React, { useState, useEffect } from "react";
import EmployList from "./EmployList";
function Experience() {
const [employ, setEmploy] = useState({
company: "",
position: "",
year_start: "",
year_end: "",
description: "",
});
const [creatingEmploy, setCreatingEmploy] = useState(true);
const [employArray, setEmployArray] = useState([]);
function addEmploy() {
setCreatingEmploy(true);
}
function setEmployData(e) {
const userInput = e.target.value;
const prop = e.target.id;
setEmploy({ ...employ, [prop]: userInput });
}
function saveEmploy() {
setEmployArray([...employArray, employ]);
}
useEffect(() => {
clearEmploy(); //Avoid this when removing item: comparing prevEmploy > employArray
if (employArray.length == 0) addEmploy();
}, [employArray]);
function removeEmploy(e) {
const toRemove = e.target.parentNode.id;
if (employArray.length === 1) {
setCreatingEmploy(true);
}
setEmployArray(
employArray.filter((element, index) => index != toRemove)
);
}
function clearEmploy() {
setEmploy({
company: "",
position: "",
year_start: "",
year_end: "",
description: "",
});
setCreatingEmploy(false);
}
return (
<div>
<h3>
<i className="fas fa-briefcase"> Experience</i>
</h3>
<ul id="employList">
<EmployList
employArray={employArray}
saveEmploy={saveEmploy}
removeEmploy={removeEmploy}
creatingEmploy={creatingEmploy}
setEmployData={setEmployData}
section="employ"
employValues={employ}
></EmployList>
</ul>
{creatingEmploy === false && (
<button onClick={addEmploy}>
<i className="fas fa-plus"></i>
</button>
)}
</div>
);
}
export default Experience;
<file_sep>import React from "react";
import EmployEducationForm from "./EmployEducationForm";
function EducationList(props) {
let educationElements;
if (props.educationArray.length > 0) {
educationElements = props.educationArray.map((element, index) => {
return (
<div key={index} id={index}>
<li>
<h4 id="educationTitle">
{element.title_}, {element.institution}
</h4>
<div id="yearsEducation">
{element.year__start} to {element.year__end}
</div>
<p>{element.description_}</p>
</li>
<button
type="button"
onClick={props.removeEducation}
></button>
</div>
);
});
}
if (props.creatingEducation) {
return (
<div>
{educationElements}
<EmployEducationForm
section={props.section}
setEducationData={props.setEducationData}
saveEducation={props.saveEducation}
educationValues={props.educationValues}
></EmployEducationForm>
</div>
);
} else if (!props.creatingEducation) return educationElements;
}
export default EducationList;
<file_sep>import React from "react";
import EmployEducationForm from "./EmployEducationForm";
function EmployList(props) {
let employElements;
if (props.employArray.length > 0) {
employElements = props.employArray.map((element, index) => {
return (
<div key={index} id={index}>
<li>
<h4 id="employTitle">
{element.position} in {element.company}
</h4>
<div id="yearsEmploy">
{element.year_start} to {element.year_end}
</div>
<p>{element.description}</p>
</li>
<button type="button" onClick={props.removeEmploy}></button>
</div>
);
});
}
if (props.creatingEmploy) {
return (
<div>
{employElements}
<EmployEducationForm
section={props.section}
setEmployData={props.setEmployData}
saveEmploy={props.saveEmploy}
employValues={props.employValues}
></EmployEducationForm>
</div>
);
} else if (!props.creatingEmploy) return employElements;
}
export default EmployList;
<file_sep>import React from "react";
function EmployEducationForm(props) {
if (props.section === "employ") {
return (
<form>
<input
id="company"
placeholder="Company..."
value={props.employValues.company}
onChange={props.setEmployData}
></input>
<input
id="position"
placeholder="Position..."
value={props.employValues.position}
onChange={props.setEmployData}
></input>
From:{" "}
<input
id="year_start"
type="month"
value={props.employValues.year_start}
onChange={props.setEmployData}
></input>
To:{" "}
<input
id="year_end"
type="month"
value={props.employValues.year_end}
onChange={props.setEmployData}
></input>
<input
id="description"
placeholder="Comments..."
value={props.employValues.description}
onChange={props.setEmployData}
></input>
<button type="button" onClick={props.saveEmploy}>
<i
className="fas fa-save"
style={{ pointerEvents: "none" }}
></i>
</button>
</form>
);
} else if (props.section === "education") {
return (
<form>
<input
id="institution"
placeholder="Institution..."
value={props.educationValues.institution}
onChange={props.setEducationData}
></input>
<input
id="title_"
placeholder="Title..."
value={props.educationValues.title_}
onChange={props.setEducationData}
></input>
From:{" "}
<input
id="year__start"
type="month"
value={props.educationValues.year_start}
onChange={props.setEducationData}
></input>
To:{" "}
<input
id="year__end"
type="month"
value={props.educationValues.year_end}
onChange={props.setEducationData}
></input>
<input
id="description_"
placeholder="Comments..."
value={props.educationValues.description_}
onChange={props.setEducationData}
></input>
<button type="button" onClick={props.saveEducation}>
<i
className="fas fa-save"
style={{ pointerEvents: "none" }}
></i>
</button>
</form>
);
}
}
export default EmployEducationForm;
<file_sep>import React, { useState } from "react";
import InputFieldText from "./InputField";
function General() {
const [generalInfo, setGeneralInfo] = useState({
name: { data: "", editing: true },
title: { data: "", editing: true },
birth: { data: "", editing: true },
cel: { data: "", editing: true },
email: { data: "", editing: true },
country: { data: "", editing: true },
city: { data: "", editing: true },
address: { data: "", editing: true },
profile: { data: "", editing: true },
});
function setInfo(e) {
const userInput = e.target.value;
const prop = e.target.id;
setGeneralInfo((generalInfo) => ({
...generalInfo,
[prop]: { ...generalInfo[prop], data: userInput },
}));
}
function saveEditInput(e) {
const prop = e.target.parentNode.firstChild.id;
const editState = generalInfo[prop].editing;
setGeneralInfo((generalInfo) => ({
...generalInfo,
[prop]: { ...generalInfo[prop], editing: editState ? false : true },
}));
}
return (
<div>
<h1>
<InputFieldText
value={generalInfo.name}
id="name"
placeholder="Your Name..."
setInfo={setInfo}
saveEditInput={saveEditInput}
state={generalInfo}
></InputFieldText>
</h1>
<h2>
<InputFieldText
id="title"
placeholder="Rol..."
setInfo={setInfo}
saveEditInput={saveEditInput}
state={generalInfo}
></InputFieldText>
</h2>
<div id="profileContainer">
<h3>
<i className="fas fa-user-circle"> Profile</i>
</h3>
<InputFieldText
id="profile"
placeholder="Introduce yourself..."
setInfo={setInfo}
saveEditInput={saveEditInput}
state={generalInfo}
></InputFieldText>
</div>
<div id="detailsContainer">
<InputFieldText
type="text"
id="birth"
placeholder="Birth..."
setInfo={setInfo}
saveEditInput={saveEditInput}
onFocus={(e) => (e.target.type = "date")}
state={generalInfo}
></InputFieldText>
<InputFieldText
type="number"
id="cel"
placeholder="Celphone Number..."
setInfo={setInfo}
saveEditInput={saveEditInput}
state={generalInfo}
></InputFieldText>
<InputFieldText
type="text"
id="country"
placeholder="Country..."
setInfo={setInfo}
saveEditInput={saveEditInput}
state={generalInfo}
></InputFieldText>
<InputFieldText
type="text"
id="city"
placeholder="City..."
setInfo={setInfo}
saveEditInput={saveEditInput}
state={generalInfo}
></InputFieldText>
<InputFieldText
type="text"
id="address"
placeholder="Address..."
setInfo={setInfo}
saveEditInput={saveEditInput}
state={generalInfo}
></InputFieldText>
</div>
</div>
);
}
export default General;
<file_sep># CV Builder
App built with React
Remaining:
<br>
Form validation
<br>
CSS
<br>
PDF download
<file_sep>import React from "react";
import Education from "./components/EducationExperience/Education";
import Experience from "./components/EducationExperience/Experience";
import General from "./components/General/General";
function App() {
return (
<div className="App">
<General></General>
<Experience></Experience>
<Education></Education>
</div>
);
}
export default App;
|
6777829fa393c370685646fa03221921965ffb89
|
[
"JavaScript",
"Markdown"
] | 7 |
JavaScript
|
fl-martin/cv-application
|
2c5728e76625342493e4a6176ee184b3920f7113
|
f6ea647a4350b547aad8d6ccca3a46f3e2c4bc2c
|
refs/heads/master
|
<repo_name>koljakub/coursera-r-programming<file_sep>/week-3/cachematrix.R
#' Creates a vector of the following four functions which can be used for effective manipulations with a
#' matrix (denoted by X) and it's inverse (denoted by X'):
#'
#' 1. setMatrix(mat) - Sets the value of the matrix X. X must be invertible.
#' 2. getMatrix() - Returns the value of the matrix X.
#' 3. setInverse(matInverse) - Sets the value of the inverse matrix X'.
#' 4. getInverse() - Returns the value of the inverse matrix X'.
#'
#' @param x Invertible matrix.
#' @return A list of the functions specified above.
makeCacheMatrix <- function(x = matrix()) {
matrixInverse <- NULL
setMatrix <- function(mat) {
x <<- mat
matrixInverse <<- NULL
}
getMatrix <- function() {
x
}
setInverse <- function(matInverse) {
matrixInverse <<- matInverse
}
getInverse <- function() {
matrixInverse
}
list(setMatrix = setMatrix,
getMatrix = getMatrix,
setInverse = setInverse,
getInverse = getInverse)
}
#' Computes the inverse (denoted by X') of an invertible matrix (denoted by X).
#' @param x A list of functions provided by the makeCacheMatrix function.
#' @return Inverse of a matrix X.
cacheSolve <- function(x, ...) {
matrixInverse <- x$getInverse()
if(is.null(matrixInverse)) {
matrixInverse <- solve(x$getMatrix())
x$setInverse(matrixInverse)
}
matrixInverse
}
|
76977d68f8cdf64490aef1cfac538ae6d3ea80e9
|
[
"R"
] | 1 |
R
|
koljakub/coursera-r-programming
|
c75ac8e51c38cc607c924157334447f7a024ae62
|
a4ded4e9a513dbb77a8ca314a2a411228070c434
|
refs/heads/master
|
<file_sep>rm(list=ls())
require(gstudio)
freqs <- data.frame( Locus="Loc1", Allele=c("A","B"), Frequency=0.5)
pop <- make_population(freqs,N,F=0)<file_sep># Plotting Diversity
> Here we plot levels of allelic and genetic diversity on maps.
```{r warning=FALSE,message=FALSE}
require(gstudio)
require(ggmap)
data(arapat)
diversity <- genetic_diversity(arapat, stratum="Population", mode="Ae")
coords <- strata_coordinates(arapat)
coords <- merge( coords, diversity[ diversity$Locus == "AML", ] )
map <- population_map(coords)
ggmap(map) + geom_point( aes(x=Longitude,y=Latitude,size=Ae), data=coords) + xlab("Longitude") + ylab("Latitude")
```
```{r}
gen.div <- genetic_diversity(arapat, stratum="Population", mode="He")
coords <- merge( coords, gen.div[ gen.div$Locus=="EN",c(1,3)])
ggmap(map) + geom_point( aes(x=Longitude,y=Latitude,size=He), data=coords) + xlab("Longitude") + ylab("Latitude")
```
<file_sep># R Data Containers
We almost never work with a single piece of datum, rather we keep lots of data. Moreover, the kinds of data are often heterogeneous, including categorical (Populations, Regions), continuous (coordinates, rainfall, elevation), and genetic (this is after all a population genetics textbook). `R` has a very rich set of containers into which we can stuff our data as we work with it. Here these container types are examined and the restrictions and benefits associated with each type are explained.
## Vector
We have already seen several examples of several vectors in action (see Numeric data types, ). A vector of objects is simply a collection of them, often created using the c() function. Vectorized data is restricted to having homogeneous data types—you cannot mix character and numeric types in the same vector. If you do try, `R` will either coerce your data into a reasonable type
```{r}
x <- c(1,2,3)
x
y <- c(TRUE,TRUE,FALSE)
y
z <- c("I","am","not","a","looser")
z
```
or at least one that is amenable to all the types of data that you have given it.
```{r}
w <- c(TRUE, "1", pi, ls())
w
class(w)
```
Accessing elements within a vector are done using the square bracket ‘[]’ notation. All indices (for vectors and matrices) start at 1 (not zero as is the case for some languages). Getting and setting the components within a vector are accomplished using numeric indices.
```{r}
x
x[1] <- 2
x[3] <- 1
x
```
Another category of vectors are sequences. We use sequences all the time, going through a list, counting generations, etc. There are a few ways to generate sequences, depending upon the step sequence. The easiest is through the use of the colon operator.
```{r}
x <- 1:6
x
```
This provides a nice shorthand for getting the values X:Y from X to Y, inclusive. It is also possible to go backwards using this operator, counting down from X to Y as in:
```{r}
x <- 5:2
x
```
The only constraint here is that we are limited to a step size of 1.0. It is possible to use non-integers as the bounds, it will just count up by 1.0 each time.
```{r}
x <- 3.2:8.4
x
```
If you are interested in making a sequence with a step other than 1.0, you can use the `seq()` function. If you do not provide a step value, it defaults to 1.0.
```{r}
y <- seq(1,6)
y
```
But if you do, it will use that instead.
```{r}
z <- seq(1,20,by=2)
z
```
It is also possible to create vectors of non-numeric values using the rep() (for repeat) function.
```{r}
rep("Beetlejuice",3)
```
If you pass a vector of items to rep(), it can repeat these as either a vector being repeated (the default value)
```{r}
x <- c("No","Free","Lunch")
rep(x,time=3)
```
or as each item in the vector repeated.
```{r}
rep(x,each=3)
```
## Matrix
A matrix is a 2- or multiple dimensional container, most commonly used to store numeric data types. There are some libraries that use matrices in more than two dimensions (rows and columns and sheets), though you will not run across them too often. Here I restrict myself to only 2-dimensional matrices.
You can define a matrix by giving it a set of values and an indication of the number of rows and columns you want. The easiest matrix to try is one with empty values:
```{r}
matrix(nrow=2, ncol=2)
```
Perhaps more useful is one that is pre-populated with values.
```{r}
matrix(1:4, nrow=2 )
```
By default the ‘filling-in’ of the matrix will proceed down column (by-column). In this example, we have the first column with the first two entries and the last two entries down the second column. If you want it by row, you can pass the optional argument
```{r}
matrix(1:4, nrow=2, byrow=TRUE)
```
and it will fill row-wise.
When filling matrices, the default size and the size of the data being added to the matrix are critical. For example, I can create a matrix as:
```{r}
Y <- matrix(c(1,2,3,4,5,6),ncol=2,byrow=TRUE)
Y
```
or
```{r}
X <- matrix(c(1,2,3,4,5,6),nrow=2)
X
```
and both produce a similar matrix, only transposed.
```{r}
X == t(Y)
```
The dimensionality of a matrix (and data.frame as we will see shortly) is returned by the dim() function. This will provide the number of rows and columns as a vector.
```{r}
dim(X)
```
Accessing elements to retrieve or set their values within a matrix is done using the square brackets just like for a vector but you need to give [row,col] indices. Again, these are 1-based so that
```{r}
X[1,3]
```
is the entry in the 1<sup>st</sup> row and 3<sup>rd</sup> column.
You can also use ‘slices’ through a matrix to get the rows
```{r}
X[1,]
```
or columns
```{r}
X[,3]
```
of data. Here you just omit the index for the entity you want to span. Notice that when you grab a slice, even if it is a column, is given as a vector.
```{r}
length(X[,3])
```
You can grab a sub-matrix using slices if you give a range (or sequence) of indices.
```{r}
X[,2:3]
```
If you ask for values from a matrix that exceed its dimensions, `R` will give you an error.
```{r,eval=FALSE}
X[1,8]
```
There are a few cool extensions of the `rep()` function that can be used to create matrices as well. They are optional values that can be passed to the function.
* `times=x` This is the default option that was occupied by the ‘3’ in the example above and represents the number of times that first argument will be repeated.
* `each=x` This will take each element in the first argument are repeat them ‘each’ times.
* `length.out=x` This make the result equal in length to x.
In combination, these can be quite helpful. Here is an example using numeric sequences in which it is necessary to find the index of all entries in a 3x2 matrix. To make the indices, I bind two columns together using `cbind()`. There is a matching row binding function, denoted as `rbind()` (perhaps not so surprisingly). What is returned is a matrix
```{r}
indices <- cbind( rep(1:2, each=3), rep(1:3,times=2), rep(5,length.out=6) )
indices
```
## List
A list is a type of vector but is indexed by ‘keys’ rather than by numeric indices. Moreover, it can contain heterogeneous types of data, which is not possible in a vector type. For example, consider the list
```{r}
theList <- list( x=seq(2,40, by=2), dog=LETTERS[1:5], hasStyle=logical(5) )
summary(theList)
```
which is defined with a numeric, a character, and a logical component. Each of these entries can be different in length as well as type. Once defined, the entries may be observed as:
```{r}
theList
```
Once created, you can add variables to the list using the $-operator followed by the name of the key for the new entry.
```{r}
theList$my_favoriate_number <- 2.9 + 3i
```
or use double brackets and the name of the variable as a character string.
```{r}
theList[["lotto numbers"]] <- rpois(7,lambda=42)
```
The keys currently in the list are given by the names() function
```{r}
names(theList)
```
Getting and setting values within a list are done the same way using either the $-operator
```{r}
theList$x
theList$x[2] <- 42
theList$x
```
or the double brackets
```{r}
theList[["x"]]
```
or using a numeric index, but that numeric index is looks to the results of names() to figure out which key to use.
```{r}
theList[[2]]
```
The use of the double brackets in essence provides a direct link to the variable in the list whose name is second in the names() function (dog in this case). If you want to access elements within that variable, then you add a second set of brackets on after the double ones.
```{r}
theList[[1]][3]
```
This deviates from the matrix approach as well as from how we access entries in a `data.frame` (below). It is not a single square bracket with two indices, that gives you an error:
```{r,eval=FALSE}
theList[1,3]
```
List are rather robust objects that allow you to store a wide variety of data types (including nested lists). Once you get the indexing scheme down, it they will provide nice solutions for many of your computational needs.
<a id="data_frame"> </a>
## Data Frame
The data.frame is the default data container in R. It is analogous to both a spreadsheet, at least in the way that I have used spreadsheets in the past, as well as a database. If you consider a single spreadsheet, you may have many columns of data, each of which may be a different kind of data. There may be factors representing designations such as species, regions, populations, sex, and flower color. Other columns may contain numeric data types for items such as latitude, longitude, dbh, and nectar sugar content. You may also have specialized columns such as dates collected, genetic loci (you can bet we will have these in this text), and any other information you may be collecting.
On a spreadsheet, each column has a unified data type, either quantified or NA (e.g., missing) for each row. Rows typically represent the sampling unit, perhaps individual, along which all of these various items have been measured or determined. A data.frame is similar to this, at least conceptually. You define a data.frame by designating the columns of data to be used. The values passed can be sequences, collections of values, or computed parameters. For example:
```{r}
df <- data.frame( ID=1:5, Names=c("Bob","Alice","Vicki","John","Sarah"), Score=100 - rpois(5,lambda=10))
df
```
You can see that each column is a unified type of data and each row is equivalent to a record. Additional data columns may be added to an existing data.frame as:
```{r}
df$Passed_PopGen <- c(TRUE,TRUE,TRUE,FALSE,TRUE)
```
Since we may have many (thousands?) of rows of observations, a `summary()` of the data.frame can provide a more compact description.
```{r}
summary(df)
```
We can add columns of data to the data.frame after the fact using the $-operator to indicate the column name. Depending upon the data type, the summary will provide an overview of what is there.
### Indexing Data Frames
You can access individual items within a data.frame by numeric index such as:
```{r}
df[1,3]
```
You can slide indices along rows (which return a new data.frame for you)
```{r}
df[1,]
```
or along columns (which give you a vector of data)
```{r}
df[,3]
```
or use the $-operator as you did for the list data type to get direct access to a either all the data or a specific subset therein.
```{r}
df$Names[3]
```
Indices are ordered just like for matrices, rows first then columns. You can also pass a set of indices such as:
```{r}
df[1:3,]
```
It is also possible to use logical operators as indices. Here I select only those names in the data.frame whose score was >90 and they passed popgen.
```{r}
df$Names[df$Score < 90 & df$Passed_Popgen == TRUE ]
```
This is why `data.frame` objects are very database like. They can contain lots of data and you can extract from them subsets that you need to work on. This is a VERY important feature, one that is vital for reproducible research. Keep you data in one and only one place.
<file_sep>clean_directory <- function() {
files = list.files(".",pattern=".rmd")
for( file in files ) {
base = strsplit(file,".",fixed=T)[[1]][1]
# make .html version
html <- paste( base,".html", sep="" )
system( paste("rm",html) )
# make .md versions
md <- paste( base, ".md", sep="")
system( paste("rm",md) )
# make _file version
folder <- paste( base, "_files", sep="")
system( paste("rm -rf",folder,"2>/dev/null") )
}
}
build_book <- function() {
require(knitr)
files <- list.files(".", pattern=".rmd")
for( file in files ){
cat("File: ",file)
html <- paste( strsplit(file,".",fixed=TRUE)[[1]][1],".html",sep="")
# if it exists
if( file.exists(html) ) {
# check date of modification
rmd.info <- file.info(file)
html.info <- file.info( html )
# older modification for html than rmd
if( html.info$mtime < rmd.info$mtime ) {
rmarkdown::render(file)
cat(" rendered")
}
else {
cat(" existing")
}
}
else {
rmarkdown::render(file)
cat(" rendered")
}
cat("\n")
}
cat("Done\n")
}
show_book <- function() {
system("open ./index.html")
}
make_markdown <- function() {
require(knitr)
files <- list.files(".", pattern=".rmd")
for( file in files ){
knit(file)
}
cmd <- "pandoc -S -o applied_population_genetics.epub title.txt "
cmd <- cmd + "section_r.md"
}
<file_sep># Genetic Distance
```{r message=FALSE}
require(gstudio)
AA <- locus(c("A", "A"))
AB <- locus(c("A", "B"))
BB <- locus(c("B", "B"))
BC <- locus(c("B", "C"))
AC <- locus(c("A", "C"))
CC <- locus(c("C", "C"))
Locus <- c(AA, AB, AC, BB, BC, CC)
Locus
```
```{r}
mv.genos <- to_mv(Locus)
mv.genos
```
```{r}
D.euc <- dist( mv.genos )
D.euc
```
```{r}
class(D.euc)
```
```{r}
D.euc <- as.matrix( D.euc )
D.euc
```
```{r message=FALSE}
D.amova <- genetic_distance( Locus, mode="AMOVA" )
rownames(D.amova) <- colnames(D.amova) <- as.character( Locus )
D.amova
```
<file_sep># Allelic Diversity
> This activity will begin to explore some of the properties of genetic diversity in population genetics. Here we also get to start performing statistical tests on population structure.
## Overview
At a base level, genetic diversity is the fundamental components upon which evolution operates. Without diversity, as we will see later when we talk about selection, there is no evolution and as such populations cannot respond to selective pressures. Before we get into the particulars of how evolutionary processes influence diversity, we need to build up a bit of our toolset in understanding how to quantify it. This activity will be pretty short but focus on some specific measures of diversity measured at within and among group levels.
The terms collection of individuals, or group, or deme, or population, are somewhat nebulius terms. What they mean is dependent upon context and the kind of information you can get out of how you cluster individuals together depends upon the temporal scale underlying the evolutionary process. For example, if you are interested in looking at signal from phylogeograhic history, a sample of a few individuals from a single location may be yield no useable information, whereas a sample from a broad range of the species distribution would yield much better information. So when you pool individuals, you need to make sure that your sampling and the spatial effects of the underlying processes are reasonably congruent. We'll leave the discussion of scales for when we get to the specific processes later in the semester and here focus on quantitative measurements; there are seveal measures of genetic divesity that provide different qualitative interpretations.
At the base level, a collection of alelles (like we get from \code{alleles(theLoci)}), provides us an estimate of diversity for the data. There are three measures commonly used in population genetics, $A$, $A_{95}$, and $A_e$, each with increasing level of stringency.
In what follows below, I'm going to use data from *Araptus attenuatus* (the *data(arapat)* stuff) to illustrate how to perform these estimations.
```{r, message=FALSE}
require(gstudio)
data(arapat)
locus_names <- column_class( arapat, "locus")
locus_names
```
### Frequency Indepenent
Frequency independent is simply a count of the number of alleles at a locus. In the nomenclature I've used thus far, it is equal to $\ell$.
\[
A = \ell
\]
```{r}
genetic_diversity( arapat$LTRS, mode="A" )
genetic_diversity( arapat$MP20, mode="A" )
genetic_diversity( arapat, mode="A" )
is( arapat$LTRS, "locus")
```
A common concern with $A$ is that it treats all alleles equal. A population that has $n_{A} = 999$ and $n_{B}= 1$ has the same level of diversity as another one where $n_{A} = n_{B} = 500$. This may hide some of the underlying relationships among allele prevailence.
### Frequency Dependent
To overcome the 'one-off' allele problems with $A$, frequency dependent allelic divesity is used. Here diversity estimation is focused on only alleles whose frequencies are greater than some threshold, say 5%^The 5\% is relatively arbitrary, just as it is when we set $\alpha=0.05$ when we teach statistics. There is really no good reason for it other than convention.^.
\[
A_{95} = \ell_{f(\ell)>0.05}
\]
The use of 5% here is somewhat arbitrary but it does give us a comparison between all alleles and all those whose allele frequency is above some threshold. Here we would be able to differentiate between the two cases in the previous explanation by comparing $A$ and $A_e$.
```{r}
mp20.A <- genetic_diversity( arapat$MP20, mode="A")
mp20.A
mp20.A95 <- genetic_diversity( arapat$MP20, mode="A95")
mp20.A95
```
See the differences between $A$ and $A_{95}$ for the same *MP20* locus?
### Effective Allelic Diversity
Effective diversity, $A_e$, uses all alleles but weighs them by their frequency such that rare alleles do count but not as much as more common alleles.
\[
A_{e} = \frac{1}{\sum_{i=1}^K p_{i}^2}
\]
```{r}
genetic_diversity( arapat, mode="Ae")
```
Notice here that $A_e > A_{95}$, which is expected as the addition of all loci, but weighted by frequency, contains some information relevant to diversity.
None of these measures are perfect but all provide some level of information. It is common that when you report them, several are reported in tabular format so that the reader can interpret the differences in the data that cause these parameter to diverge.
## Making Maps
You can easily make maps in `R` using a few functions in `gstudio`. To do so, you will need to:
1. Grab the coordinates to the stratum you want to plot
```{r}
coords <- strata_coordinates( arapat )
summary(coords)
```
2. Ask Google for a map to plot it on.
```{r}
require(ggmap)
map <- population_map( coords )
```
3. Plot the points over the top of the google map.
```{r}
ggmap( map ) + geom_point( aes(x=Longitude, y=Latitude), data=coords)
```
<file_sep># Plotting With GGPlot2"
> The basic graphics capabilities in `R` provide an adequate set of tools for visualizing data. However, more sophisticated approaches to creating graphical output are also available. In this section, the ggplot2 library is introduced. This library is used extensively in this text and is a powerful tool you should be comfortable with using.
## Impetus
The `ggplot2` library was created by Dr. <NAME>, following the philosophy of graphics depicted in <NAME>'s (2005) book *The Grammar of Graphics*. As I understand it, the idea is that a graphical display consists of several layers of information. These include:
* The underlying data.
* Mapping of the data onto one or more axes.
* Geometric representations of data as points, lines, and/or areas.
* Transformations of the axes into different coordinate spaces (e.g., cartesian, polar, etc.) or the data onto different scales (e.g., logrithmic)
* Specification of subplots.
In the [normal plotting routines](r_basic_graphics.html) discussed before, configuration of these layers were specified as arguments passed to the plotting function (`plot()`, `boxplot()`, etc.). The ggplot2 library takes a different approach, allowing you to specify these components separately and literally add them together like a linear model.
## The Data Layer
The basic data input for all ggplot routines is a [data.frame](r_data_containers.html#data_frame) containing columns of data for both plotting as well as for applying geometries and colors. As in the previous examples, I'll be using the iris dataset that comes with `R` for the data as I did in the previous section.
```{r,echo=FALSE,message=FALSE}
require(DT)
datatable(iris,caption="The canonical iris data set containing floral measurments for three species of Iris.")
```
Here is a summary of this data set.
```{r}
summary(iris)
```
Since this is not a built-in library, you must first load it in.
```{r,message=FALSE,warning=FALSE}
require(ggplot2)
```
The main component that all of the following plotting routines posess is a `ggplot()` function call. To this function, you pass the name of the data.frame you are using. You will most likely also pass it a description of the 'aesthetics' as well. The aesthetics specify how to map the data on both the axes and onto the shapes and colors that will be presented.
```{r,eval=FALSE}
ggplot( theData, aes(x=theXvariable,y=theYvariable))
```
By itself, this call does nothing and presents no output. What it does is provide a data layer onto which you can 'add' geometric plotting layers, axes labels, color themes, coordinate transformations, etc. It sounds a bit complicated, but in practice, it is very easy. Lets jump into a few examples.
## Univariate Plots
For consistency, we will go through the same plots here as were covered in the previous section.
### Histograms
Historgrams
```{r}
ggplot( iris, aes(x=Sepal.Width)) + geom_histogram()
```
The warning given is to alert us to the fact that we did not set the size of the bins for each bar. By default, `geom_histogram()` divides the range of values into 30 equally spaced units. If you have a preferred width, you can specify that directly. Because the plots are additive, you can assign values to a variable and then add the subsequent components as you need to. This is nice when you start composing rather complicated plots spanning several lines of your scripts. Here is an example, where I assign the `ggplot()` part to a variable and then later add the `geom_histogram()` component later when showing it (Notice, it is not actually plot until the variable is 'print' to the screen).
```{r}
p <- ggplot( iris, aes(x=Sepal.Width))
p + geom_histogram( binwidth=0.1 )
```
### Density Plots
The density of a variable is similarily plot using `geom_density()`
```{r}
p + geom_density( )
```
If you want to fill in the density area, you can add a `fill=` argument to either the `ggplot()` or `geom_density()` component. If it is a simple plot with a single kind of data, it doesn't matter which one you use. However, if you are integrating several different data sets, you may want to inser the color or shape specifications into the `geom_` they are being associated with.
```{r}
p + geom_density( fill="red" )
```
### Overlaying Plots
Overlaying plots is much easier in `ggplot` as we can just add additional `geom_*` layers to the plot.
```{r}
p + geom_histogram( binwidth=0.1, fill="orange", color="grey") + geom_density( fill="red" )
```
The obvious problem here is that the histogram is plotting the y-axis as the count of the entires in each bin whereas the density plot is actually plotting as a percentage of the area under the curve. Not the same thing. If we want to plot them in the same corrdinate space. To do this, I'll reset the aesthetic of the y-axis for the histogram to plot as a density rather than a count. Notice how the way we tell it to do this is by adding an `aes()` to `geom_histogram()`. I also switched around the order of the plots, played with the transparency (via the `alpha` parameter), and added some x- and y-axis labels.
```{r}
p + geom_density( fill="red") + geom_histogram( binwidth=0.1, fill="orange", color="black", aes(y=..density..), alpha=0.9) + xlab("Sepal Width") + ylab("Frequency")
```
Notice how you literally just 'add' these components together. Very cool.
Here is the same thing but this time we categorize the data by species. Notice this time, I am filling the density plot by the variable called 'Species' (e.g., the column named in the data.frame). When you want to change the plot by accessing properties within the data.frame you gave to `ggplot()` (here we are using it for colors), you *must* have it within `aes()` because you are specifying a change to the aesthetics. Previously, we just used the `fill=` option to color the entire density plot.
```{r}
p + geom_density( aes(fill=Species), alpha=0.7 )
```
### Barplots
In the previous example using barplots, we partitioned the Sepal.Width among species as barplots. Here it is slightly easier to do this in ggplot.
```{r}
p + geom_histogram( aes(fill=Species), binwidth=0.1)
```
As before, these bars are stacked. If we want them to be next to eachother, we tell `geom_histogram()` to change the position. In this case, we want them to 'dodge' eachother rather than to stack (the default).
```{r}
p + geom_histogram( aes(fill=Species), binwidth=0.1, position="dodge")
```
## Bivariate Plots
### Boxplots
### Scatter Plots
## Multiple Plots
## References
<NAME>. 2005. *The Grammar of Graphics**. Springer. 691pg.
<ul class="pager">
<li class="previous"><a href="r_basic_graphics.html"><span aria-hidden="true">←</span> Previous</a></li>
<li class="next"><a href="section_r.html">Next <span aria-hidden="true">→</span></a></li>
</ul><file_sep>---
title: "Copyright"
---
© 2016 by <NAME>.
All rights reserved. No portion of this book may be reproduced in any form without written permission from <NAME>. The author assumes no responsibility for the use or misuse of information contained in this text.
ISBN: X-XXXXXXX-XX-X
ISBN-13: XXX-X-XXXXXX-XX-X
Dyer RJ. 2016. Population Genetics Applied. Perdedor Publishing. XXXpgs.
Dr. <NAME> is an Associate Professor in the Department of Biology and the Assistant Director for the Center for Environmental Studies at Virginia Commonwealth University in Richmond, Virginia, USA. His research focuses on genetic connectivity and structure and how the environment influences both. More information on his research can be found at [http://dyerlab.bio.vcu.edu](http://dyerlab.bio.vcu.edu). Dr Dyer can be contacted at either [mailto:<EMAIL>](mailto:<EMAIL>) or [@Dyerlab](http://twitter.com/Dyerlab)
<ul class="pager">
<li class="previous"><a href="section_logistics.html"><span aria-hidden="true">←</span> Previous</a></li>
<li class="next"><a href="dedication.html">Next <span aria-hidden="true">→</span></a></li>
</ul><file_sep><p> </p>
<div class="jumbotron">
# R
The R language is a unique, collaborative, open-source, tool that becomming a fundamental componet of modern biological training and analyses. The language has several built-in data types as well as the ability to import new data types and analyses through the package system.
This section of text is intended to act as an overview Chapter and hopefully you will already have seen this material before and are reasonably comfortable using R.
</div>
The folllowing components are available:
* [Getting R](getting_r.html)
* [Data Types](r_data_types.html)
* [Data Containers](r_data_containers.html)
* [Summary Stats](r_stats.html)
* [Graphics](r_basic_graphics.html)
* [GGPlot](r_ggplot.html)<file_sep># Getting R
The grammar of the `R` language was derived from another system called S-Plus. S-Plus was a proprietary analysis platform developed by AT&T and licenses were sold for its use, mostly in industry and education. The development of `R` was initiated by XXXX and XXX, whose goal was to create an interpreter that could read grammar similar to S-Plus but be available to the larger education community. The use of `R` has increased dramatically due to its open nature and the ability of people to share code solutions with relatively little barriers.
The main repository for `R` is located at [http://cran.r-project.org](http://cran.r-project.org), which is where you can download the latest version. It is in your best interests to make sure you update the underlying `R` system, changes are made continually (perhaps despite the outward appearance of the website). The current version of this book uses version 3.1.3. To get the correct version, open the page and there should be a link at the top for your particular computing platform. Download the appropriate version and install it following the instructions appropriate for your computer.
<img class="img-responsive" src="./images/CRAN.png" alt="CRAN Webpage" width="770" height="674">
## Packages
The base `R` system comes with enough functionality to get you going. By default, there is only a limited amount of functionality in R, which is a great thing. You only load and use the packages that you intend to use. There are just too many packages to have them all loaded into memory at all times and there is such a broad range of packages, it is not likely you’d need more than a small fraction of the packages during the course of all your analyses.
Once you have a package, you can tell `R` that you intend to use it by either
```{r, eval=FALSE}
library(package_name)
```
or
```{r, eval=FALSE}
require(package_name)
```
They are approximately equivalent, differing in only that the second one actually returns a TRUE or FALSE indicating the presence of that library on you machine. I prefer the later and use it throughout.
There are, at present, a few different places you can get packages. The packages can either be downloaded from these online repositories and installed into `R` or you can install them from within `R` itself. Again, I’ll prefer the latter as it is a bit more straightforward.
## CRAN
The main repository for packages is hosted by the r-project page itself. There are packages with solutions to analyses ranging from Approximate Bayesian Computation to Zhang & Pilon’s approaches to characterizing climatic trends. The list of these packages is large and ever growing. It can be found on CRAN under the packages menu. To install a package from this repository, you use the function
```{r, eval=FALSE}
install.packages("thePackageName")
```
Here is an example of the output of installing the ggplot2 library (a package you will love).
You can see that `R` went to the CRAN mirror site (I use the rstudio one), downloaded the package, look for particular dependencies that that package may have and download them as well for you. It should install these packages for you and give you an affirmative message indicating it had done so.
At times, there are some packages that are not available in binary form for all computer systems (the rgdal package is one that comes to mind for which we will provide a work around later) and the packages need to be compiled. This means that you need to have some additional tools and/or libraries on your machine to take the code, compile it, and link it together to make the package. In these cases, the internet and the documentation that the developer provide are key to your sanity.
## GitHub
There are an increasing number of projects that are being developed either in the open source community or shared among a set of developers. These projects are often hosted on [http://www.github.com](http://www.github.com) where you can get access to the latest code updates. The packages that I develop are hosted on Github at [http://github.com/dyerlab](http://github.com/dyerlab) and only pushed to CRAN when I make major changes.
<img class="img-responsive" src="./images/DyerlabGithub.png" alt="Dyerlab Github" width="994" height="751">
To install packages from Github you need to install the devtools library from CRAN first
```{r, eval=FALSE}
install.packages("devtools")
require(devtools)
```
Then you need to use the devtools function `install_github()` to go grab it. To do so you need two separate pieces of information, the name of the developer who is creating the repository and the name of the repository it is contained within. For the gstudio package, the develop is dyerlab and the repository name is gstudio. If you are comfortable with git, you can also check out certain branches of development if you like with optional arguments to the install_github() function. Here is an example of installing gstudio.
```{r,eval=FALSE}
install_github("dyerlab/gstudio")
## Downloading github repo dyerlab/gstudio@master
## Installing gstudio
## '/Library/Frameworks/R.framework/Resources/bin/R' --no-site-file \
## --no-environ --no-save --no-restore CMD INSTALL \
##
* installing *source* package ‘gstudio’ ...
** R
** data
** inst
** tests
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** installing ttes
** testing if installed package can be loaded
* DONE (gstudio)
```
If you are starting to work with `R` and intend to compile packages, there are some tools that you will need to have on your machine. For Windows machines, there is an rtools download EXE that you can get. On OSX, you need to download the developers tools from Apple (available on the Application Store for free). In either case, the developer (if they care about their code being used by others) should provide sufficient documentation.
## Bioconductor
The last main location to find packages is on the Bioconductor site, a collection of software for bioinformatic analyses. To install from the bioconductor site you need to download their own installer as:
```{r,eval=FALSE}
source("http://bioconductor.org/biocLite.R")
biocLite()
```
And then to install packages you use
```{r,eval=FALSE}
biocLite(c("GenomicFeatures", "AnnotationDbi"))
```
There are no libraries used in this text from bioconductor as this text is more focused on marker-based population genetics and not sequences, annotations, etc.
## The RStudio Environment
By itself, `R` can be used in the terminal or as the basic interface the installer provides. While both of these methods are sufficient for working in R, they are less than optimal (IMHO). I believe one of the most important tools you can use is a good IDE as it helps you organize and work with your data in ways that focus more on the outcome and less on the implementation. I’ve spent a lot of time in both Emacs and Vim and while they may be tools for the geek elite, RStudio has made me much more productive in terms of output per unit time.
<img class="img-responsive" src="./images/RStudioIDE.png" alt="RStudio IDE" width="1266" height="767">
The RStudio IDE can be can be downloaded directly from http://rstudio.org and comes in varieties for desktops and servers. The packages are easy to install and contain all the instructions you need. If you run your own server, you can install it and do your analyses via a web interface that looks identical to the desktop client (in fact it is more similar than you perhaps know).
The interface has four panes, two of which (the source code editor and the terminal output) you will work with the most often. The other panes have information on the history of your project, plot output, packages, help, and a file browser. You can type in `R` commands in the terminal window and receive responses directly, just as normal. However, you can also type in your code into a script file (files ending in *.R) and run them directly. You can also create Markdown and LaTeX documents embedding your code in with the verbiage, which is evaluated any time you make a html, rtf, docx, or pdf output. All the code from `R` for this book was written in RMarkdown and parsed as an html document. If you are a serious user of R, you can use LaTeX or RMarkdown to make documents, slides, presentations, posters, etc. It is a versatile tool and one worth looking into, especially as it pertains to reproducible research (something we all need to strive for).
The data we work with comes in many forms—integers, stratum, categories, genotypes, etc.—all of which we need to be able to work with in our analyses. In this chapter, the basic data types we will commonly use in population genetic analyses.
<file_sep><p> </p>
<div class="jumbotron">
# Genetic Drift
Genetic drift is the null case of evolutionary change, in that it is more of a stochastic process than any other type. Drift occurs because the size of the population is small enough that stochastic fluctuations in allele frequencies cause populations to diverge.
This section covers the theory behind genetic drift and explores the ways in which drift can influence diversity within and among populations. In doing so, the notion of an evolutionary relevant population size, $N_e$ is introduced and demonstrated.
</div>
The folllowing components are available:
* [Genetic Drift](drift_theory.html)
* [Allelic Diversity](diversity_allelic.html)
* [Genotypic Diversity](diversity_genotypic.html)
* [Rarefaction](diversity_rarefaction.html)
* [Effective Population Size](diversity_ne.html)
<file_sep><p> </p>
<div class="jumbotron">
# Logistics
This section contains materials related to the creation and maintainence of this textbook.
</div>
The folllowing components are available:
* [Copyright](copyright.html)
* [Dedication](dedication.html)
* [Foreward](foreward.html)
<file_sep># Genetic Drift
> Genetic drift is the stochastic process resulting from a reduction in the size of a population. If populations are infinite in size, both allele and genotype frequencies should remain constant through time. However, if populations are not infinite (reality knocking), then drift may act as a diversifying force. This chapter examines the process of drift how we can measure its consequences.
Genetic drift is the process by which random selections of gametes produced during mating events result in stochastic changes in allele frequencies through time. This is not a terribly ground shattering idea, and our understanding of random chance provides some great insights into the underlying mechanisms operating in populations.
As an example of how genetic drift works, consider the simulation scenario where we have two alleles, A and B, at a haploid locus (for simplicity).
```{r}
Alleles <- c("A","B")
```
We can create populations of different size that have loci made up of these alleles. We can create these *synthetic* populations by drawing alleles at random using these different samples sizes. Here I set up a `data.frame` to do this and from each sample of random individuals, we can extract the *observed* allele frequency.
```{r}
sample_size <- c(5,10,20,50,100)
df <- data.frame( N = rep( sample_size, each=50 ),FreqA = NA)
```
This gives us a total of
```{r}
nrow(df)
```
samples. We are implicitly assuming that the frequencies of these two alleles are identical (e.g., $p_A = p_B = 0.5$). We can see the effects of genetic drift by running this ‘simulation’ in which populations are randomly created selected and used to estimate the frequency of an allele and how sample size influences the stability of the allele frequency. If $N$ does not influence the estimation of allele frequencies then all examples should yield an estimated allele frequency equal to 0.5 (as they truly are).
We then go through data frame, each row in order, and pull out random collections from Alleles in sizes equal to `sample_size`. To do this, I’m going to use a `for()` loop. This is simply a function that repeats a set of code a specified number of times. In this case, I will need to take the first row, make a random sample of alleles given the value of `df$N[1]`, find the frequency of an allele in that random sample, and then store the frequency back into the data.frame at `df$FreqA[1]`. I then need to go to the second row and do the same thing again. And then the third row. Then the fourth. etc.
The format of a `for()` loop is pretty easy. You define a sequence of values to use (in this case I will use the variable named row to contain the sequence of integers from `1:nrow(df))`. Each time row is assigned a value, the code within the curly brackets ‘{}’ after the `for()` statement is executed and the value of row is constant during that iteration.
```{r}
for( row in 1:nrow(df) ) {
# make random selection from Alleles with replacement of a particular size
a <- sample( Alleles, size=df$N[row],replace = T)
# find the frequency
f <- sum( a == "A" ) / length(a)
# assign it back to the data.frame
df$FreqA[row] <- f
}
```
Here, row starts out at 1, then the code inside the brackets is run with `row=1`. After it reaches the end of the loop, row is incremented by one and the code is then run with `row=2`. This is repeated until `row = nrow(df)` and then the looping is finished. If you type this in and do it, you have done your first stochastic (some would call it Monte Carlo) simulation! Congratulations. That wasn’t so hard.
Lets now look at the data.
```{r}
summary(df)
```
The frequencies observed in each run are all over the place, basically covering the entire allowable range for an allele frequency. More importantly though lets look graphically at the allele frequencies using a boxplot where frequencies are grouped by sample size, `df$N`.
```{r,echo=FALSE,fig.cap="Allele frequencies estimated from random selections of alleles under varying sample sizes.",message=FALSE}
require(ggplot2)
p <- ggplot(df, aes(x=factor(N), y=FreqA)) + geom_boxplot()
p + xlab("Population Size") + ylab("Estimated Allele Frequency")
```
This is to be expected, as we sample more individuals, we will become more confident that the parameters we estimate are closer to the real value. In statistics, this is the law of large numbers or the Central Limit Theorem. It is the same thing here. If there is a small population, each mating event may have the opportunity to have a wide fluctuation in gamete allele frequencies. All other things being equal, the frequencies will change each generation, an amount inversely proportional to the size of the population.
Small populations are not rare, some organisms exist only at small densities (e.g., top predators). Others may have undergone population bottlenecks, exist in marginal habitats at the edge of their tolerance range, or have a life-history that goes through periodic outbreaks.
Algebraically, we can determine the probability of observing a specific number of alleles in the next generation given random mating assumptions and a small sample size. The selection of diploid alleles follows a binomial expansion.
$$ P(N_A|N,p_A) = \frac{2N!}{N_A!(2N-N_A)!}p_A^{N_A}(1-p_A)^{2N-N_A} $$
This expansion has two parts:
1. The binomial coefficient, $\frac{2N!}{N_A!(2N-N_A)!}$, that determines the number of different ways we can get two alleles by random draw and have $N_A$ samples of the $A$ allele.
2. The probability, $p_A^{N_A}(1-p_A)^{2N-N_A}$, of observing any each occurrence of the those samples based upon the frequency of the $A$ allele, $p_A$, in the population.
As an example, consider the idealized situation where we have $N=20$ individuals, all of which are heterozygotes. That means that for a diploid locus, $N_A = N_B = 20$. The probability of observing exactly $20$ $A$ alleles in the next generation can be calculated as:
```{r}
p <- 0.5
N <- 20
N.A <- 20
```
where the binomial coefficient is given by
```{r}
coef <- factorial(2*N)/ (factorial(N.A)*factorial(2*N - N.A))
coef
```
and the probability of each one of those is
```{r}
prob <- p^N.A * (1 - p)^(2*N-N.A)
prob
```
and the final probability associated with observing $N_A = 20$ after a single round of random mating is
```{r}
Prob.20.A <- coef*prob
Prob.20.A
```
Which is not so good, if you are interested in stability of allele frequencies. Only 12.5% of the time would the allele frequency stay the same and 87.5% of the time allele frequencies would change. This change is not so much an evolutionary forces as it is a stochastic process associated with low sample sizes.
So if it is not that likely that the allele frequencies will stay the same, what does the entire distribution of allele occurrences look like? Lets set a sequence of potential allele counts (from `0` to `2*N`) look at the distribution of probabilities for allele counts in the next generation.
```{r,eval=TRUE,echo=FALSE,fig.cap="Figure 4.2 Distribution of allele frequencies for the A allele expected from a randomly mating population of size N=20."}
N.A <- 0:(2*N)
Frequency <- factorial(2*N)/( factorial(N.A)*factorial(2*N-N.A)) * p^N.A * (1-p)^(2*N-N.A)
df <- data.frame(N.A,Frequency)
ggplot(df,aes(x=N.A,y=Frequency)) + geom_bar(stat="identity") + xlab(expression(N[a]))
```
Even for the tails of this distribution, the probabilities are not zero
```{r}
df[1:10,]
```
meaning that it is possible to start with everyone as a heterozygote and after a single random mating event, you are either fixed for the A allele or have lost it altogether. The shape of this distribution is not only influenced by $N$ but also by $p$. Here is what it looks like if the frequency of the allele is 0.10 instead of 0.50.
```{r,echo=FALSE,fig.cap="Expected allele frequencies for the A allele of lower frequency after a random mating event with N=20 individuals."}
p <- 0.1
Frequency <- factorial(2*N)/( factorial(N.A)*factorial(2*N-N.A)) * p^N.A * (1-p)^(2*N-N.A)
df <- data.frame(N.A,Frequency)
ggplot(df,aes(x=N.A,y=Frequency)) + geom_bar(stat="identity") + xlab(expression(N[a]))
```
This stochastic change, from one generation to the next can have significant effects on allele frequencies, available genetic diversity, and genotypic composition. The following sections tackle these topics and this chapter closes with an introduction to a parameter of evolutionary significance, $N_e$, the genetic effective population size.
<file_sep><p> </p>
<div class="jumbotron">
# Hardy Weinberg Equilibirum
In a perfectly mixing system, the genotype frequencies sampled at populations should conform to expectations based upon the allele frequencies alone. If there are forces operating, then genotype frequencies will deviate from expectations in ways that are predictable.
In this section, we examine the expectations for genotype frequencies, called Hardy Weinberg Equilibrium and determine how to statistically evaluate if a genotypes in a population conform to the expections given by HWE.
</div>
The folllowing components are available:
* [Hardy Wienberg Equilibrium](hwe_theory.html)
* [Testing HWE]
* [Allelic Diversity]
* [Genotypic Diversity]
* [Testing Diversity]
* [Effective Population Size]
<file_sep>---
title: "Rarefaction"
---
## Among Group Diversity
When we have more than one group, it is often interesting to compare the levels of diversity in different groups. Here we add to our quantitative analyses (the `frequency_tester()` from a few exercises ago) and look at a few different ways to examine differences in diversity.
### Statistical Tests of Diversity Differences
However, a final question may be posed with these observations. Are the differences due to differences in sample size or are they reflecting more realistic differenes?
### Rarfaction
Unless populations are the exact same size, differences in diversity may be biased by sample size. Consider the following example, where we are drawing making random populations.
```{r,message=FALSE}
require(gstudio)
data(arapat)
f <- data.frame( Allele=LETTERS[1:4], Frequency=0.25)
f
pop1 <- make_population( f,N=10)
ae1 <- genetic_diversity( pop1, mode="Ae" )
ae1
pop2 <- make_population( f,N=100)
ae2 <- genetic_diversity( pop2 )
ae2
```
Are the differences in $A_{e,1} - A_{e,2} =$ `r ae1$Ae[1] - ae2$Ae[1]` really different from each other? Numerically they do not equal zero but does this mean statistically, these populations are different? How could they be? Didn't we make them entirely randomly from the same allele frequencies? This is where rarefraction comes into play.
Rarefaction is the process of subsampling one population randomly, collecting a subset of samples and estimating a diversity parameter. Here is an example in the *arapat* dataset comparing diversity between the "mainland" population ($N_{mainland} = $ `r nrow( arapat[ arapat$Species=="Mainland",])`) and the "cape" population ($N_{mainland} = $`r nrow( arapat[ arapat$Species=="Cape",])`) for the *MP20* locus.
```{r}
ae.cape <- genetic_diversity( arapat[ arapat$Species=="Cape", "WNT"] )
ae.cape
ae.mainland <- genetic_diversity( arapat[ arapat$Species=="Mainland", "WNT"] )
ae.mainland
```
Is the difference of $\delta A_e =$ `r abs(ae.cape-ae.mainland)` due to the fact that the cape region is more diverse than the mainland or is it that the cape region has almost twice the amount of samples collected?
As outlined in the lecture, rarefaction follows the proceedure:
1. Select the size of the smallest population as $N$.
2.Randomly sample individuals, without replacement, from the big population in groups of size $N$.
3. Estimate diversity parameters on these sampled populations and repeat to create a 'null distribution' of values of permuted diversity under restricted sample sizes.
4. Compare your observed value in the smallest population to that distribution created by subsampling the larger population.
I think you could imagine writing a function like this. All these steps are things that you've done already. The function `rarefaction()` does this for you (a brief sigh of relief on all accounts, no?) and needs the full data set, the parameter to estimate, and the sample size of the smaller population. It will return a permuted set of diversity measurements.
```{r}
cape.pop <- arapat[ arapat$Species=="Cape","WNT"]
null.ae <- rarefaction( cape.pop, mode="Ae",size=36)
mean(null.ae)
range(null.ae)
ae.mainland
```
So the estimated $A_{e,mainland}$ is within the range of values estimated for the cape but it is on the low end. To look at how small it really is, compared to the rest, we need to consider the null distribution as a probability density function. We will see this again and again this semester, so lets take a minute to think about it a bit.
If the NULL hypothesis is correct, $H_O:\,A_{e,mainland}=A_{e,cape}$ then any sample of the cape population the same size as the mainland one should produce an estimate of diversity just as large as one sampled from the whole cape data set. Read over that a few times to make sure you really get it.
Our statistical test then is to accept the NULL and then permute as we did and estimate $A_e$ (or whatever parameter we are estimating) and fine where the observed value fits into that distribution. What follows is the probability of getting a value of $A_e$ in subsamples of the Cape larger than what we are seeing in the Mainland^[I add one to the denominator of this estimate because I am essentially adding the *ae.mainland* to the total count of observed estimates of $A_e$].
```{r}
null.ae <- c( null.ae, ae.mainland[1,1])
P <- sum( ae.mainland <= null.ae ) / ( length(null.ae) )
P
```
Another way of looking at it is to plot where the observed value is, in relation to the rest of the distribution. Here I use some overlays on basic R plotting routines.
```{r}
require(ggplot2)
Ae <- c( null.ae, ae.mainland[1,1])
Estimate <- c(rep("Null",length(null.ae)),"Observed")
df <- data.frame( Ae, Estimate )
ggplot( df, aes(x=Ae,fill=Estimate)) + geom_histogram( position="dodge", bin=0.05) + theme_bw() + xlab("Allelic Diversity (Ae)") + ylab("Frequency")
```
<file_sep>---
title: "Dedication"
---
I would like to dedicate this text and the motivations and inspirations that underly its creation, to my thesis advisor, Dr. <NAME>. She has an uncanny ability to see beyond the questions that we know how to answer to focus on the answers that we are really trying to find. And one of these days we will finally pubish that last chapter from my thesis...
<ul class="pager">
<li class="previous"><a href="copyright.html"><span aria-hidden="true">←</span> Previous</a></li>
<li class="next"><a href="foreward.html">Next <span aria-hidden="true">→</span></a></li>
</ul><file_sep># R Programming
```{r}
x <- c(1,2,3,4,5)
x
```
```{r}
for( val in x ){
print(val)
}
```
```{r}
for( i in 1:length(x)){
y <- x[i] * 23
print(y)
}
```
```{r}
x*23
```
```{r}
sm.func <- function(x) {
if( x %% 2 ) {
return(x)
}
else {
return(-1*x)
}
}
sapply(x,function(x) return( x^2 +23 ))
sapply(x,sm.func)
```
<file_sep># Inbreeding
```{r}
rm(list=ls())
require(ggplot2)
F <- seq(0,1,by=0.01)
p <- 0.5
freq.AA <- p^2*(1-F) + p*F
df <- data.frame( freq.AA, F )
ggplot(df,aes(F,freq.AA)) + geom_line() + geom_point()
```
```{r}
T <- 0:15
F <- 1 - 0.5^T
df <- data.frame( T, F)
ggplot(df,aes(T,F)) + geom_line() + geom_point() + xlab("Generation (t)") + ylab("Inbreeding (F)")
```
```{r message=FALSE}
require(gstudio)
AA <- locus( c("A","A") )
AB <- locus( c("A","B") )
BB <- locus( c("B","B") )
pop <- data.frame(ID=1:100, Locus1=c( rep(AA,25), rep(AB,50), rep(BB,25) ) )
frequencies(pop)
```
```{r}
genetic_diversity(pop,mode="Fis")
```
```{r cache=TRUE}
df$Category = "Expectations"
for( rep in 0:9 ) {
data <- pop
F <- rep(0, length(T) )
for(t in T){
# estimate F
F[(t+1)] <- genetic_diversity(data,mode="Fis")$Fis[1]
# self all adults to make offspring
data <- mate( data, data, N=1 )
}
df.rep <- data.frame( T, F, Category=paste("Replicate",rep))
df <- rbind( df, df.rep )
}
```
```{r}
ggplot() + geom_line(aes(T,F,color=Category),data=df[df$Category!="Expectations",]) + geom_point(aes(T,F,color=Category),data=df[df$Category!="Expectations",]) + geom_line(aes(T,F),data=df[df$Category=="Expectations",]) + geom_point(aes(T,F),data=df[df$Category=="Expectations",]) + xlab("Generation (t)") + ylab("Inbreeding (F)")
```
```{r}
p <- fAA <- fAB <- fBB <- rep(NA,10)
p[1] <- 0.25
fAA[1] <- p[1]^2
fAB[1] <- 2*p[1]*(1-p[1])
fBB[1] <- (1-p[1])^2
cbind(p,fAA,fAB,fBB)
```
```{r}
s <- 0.5
for(i in 2:10){
fAA[i] <- s*(fAA[i-1] + fAB[i-1]/4) + (1-s)*p[i-1]^2
fAB[i] <- s*fAB[i-1]/2 + (1-s)*2*p[i-1]*(1-p[i-1])
fBB[i] <- s*(fBB[i-1] + fAB[i-1]/4) + (1-s)*(1-p[i-1])^2
p[i] <- fAA[i] + fAB[i]/2
}
cbind(p,fAA,fAB,fBB)
```
```{r}
Genotype <- factor(rep(c("AA","AB","BB"),each=10), ordered=TRUE)
df <- data.frame( Genotype, Frequency=c(fAA,fAB,fBB), Generation=rep(1:10,times=3))
ggplot(df,aes(Generation,Frequency,color=Genotype)) + geom_line() + geom_point() + ylim(0,1) + ylab("Gentoype Frequency")
```
```{r}
fAA + fAB + fBB
```
```{r}
p <- fAA <- fAB <- fBB <- rep(NA,10)
p[1] <- 0.25
fAA[1] <- 0.0925
fAB[1] <- 0.405
fBB[1] <- 0.5025
s<-0
for(i in 2:10){
fAA[i] <- s*(fAA[i-1] + fAB[i-1]/4) + (1-s)*p[i-1]^2
fAB[i] <- s*fAB[i-1]/2 + (1-s)*2*p[i-1]*(1-p[i-1])
fBB[i] <- s*(fBB[i-1] + fAB[i-1]/4) + (1-s)*(1-p[i-1])^2
p[i] <- fAA[i] + fAB[i]/2
}
df <- data.frame( Genotype, Frequency=c(fAA,fAB,fBB), Generation=rep(1:10,times=3))
ggplot(df,aes(Generation,Frequency,color=Genotype)) + geom_line() + geom_point() + ylim(0,1) + ylab("Gentoype Frequency")
```
```{r}
pop <- data.frame(ID=1:100, Locus1=c( rep(AA,15), rep(AB,40), rep(BB,45) ) )
geno.freqs <- genotype_frequencies(pop$Locus1)
geno.freqs
```
```{r,cache=TRUE}
fAA <- fAB <- fBB <- rep(NA,100)
fAA[1] <- geno.freqs$Observed[1]/100
fAB[1] <- geno.freqs$Observed[2]/100
fBB[1] <- geno.freqs$Observed[3]/100
for( i in 2:100){
pop <- mixed_mating(pop,F=0.12)
geno.freqs <- genotype_frequencies(pop$Locus1)
fAA[i] <- geno.freqs$Observed[1]/100
fAB[i] <- geno.freqs$Observed[2]/100
fBB[i] <- geno.freqs$Observed[3]/100
}
```
```{r}
df <- data.frame( Genotype, Frequency=c(fAA,fAB,fBB), Generation=rep(1:100,times=3))
ggplot(df,aes(Generation,Frequency,color=Genotype)) + geom_line() + geom_point() + ylim(0,1) + ylab("Gentoype Frequency")
```
```{r}
equilbrium.Q <- function(p,s){
q <- 1-p
return(((1 - s) * 4 * p * q)/(2 - s))
}
equilbrium.Q(0.5,1)
equilbrium.Q(0.5,0)
equilbrium.Q(0.25,0.25)
```
```{r}
s <- seq(0,1,by=0.02)
F <- s / (2-s)
df <- data.frame( F, s)
ggplot(df,aes(s,F)) + geom_line() + geom_point() + ylim(0,1) + xlab("Selfing Rate (s)") + ylab("Inbreeding Parameter (F)")
```
<file_sep>---
title: "Genotypic Diversity"
---
w
## Genotypic (Genic) Diversity
Above the level of the allele, diversity at the genotype level, what Nei called Genic diversity, is a measure of expected heterozygosity. This is from the old Hardy-Weinberg relationship, which we previously defined as equal to $Q = 2pq$. However, I'm going to be more general in the equation for it so that it covers all loci independent of the number of alleles. For example, a4 allele locus, $p + q + r + s = 1$ has the expected heterozygosity of $H_e = 2pq + 2pr + 2ps + 2qr + 2qs + 2rs$, which gets even more troublesome as the number of alleles increases. Instead I estimate heterozygosity as everything that is not a homozygote ($p_i^2$) as:
\[
H_e = 1 - \sum_{i=1}^K p_i^2
\]
In *gstudio* we estimate expected heterozygosity as:
```{r}
require(gstudio)
data(arapat)
He( arapat$LTRS )
He( arapat$MP20 )
```
In an ideal world, $H_e$ could be estimated without bias. However, in the world in which we live, $H_e$ is often measured on data that is limited in size. That is why we use statistics to estimate parameters. If we $N=\infty$, then there is no need for stats! However, given our limited research budgets, $N$ will always be way smaller than $\infty$. To correct for problems in small sample sizes (and you will continue to see this throughout the semester), a small correction factor is added to the estimation, whose effect is to minimize the effect of $N$ as $N$ gets larger. The formula is:
\[
\hat{H}_e = \frac{2N}{2N-1}\left( 1 - \sum_{i=1}^K p_i^2 \right)
\]
You can see the effect of the correction factor as $N \to large$ in the plot blow. As it tends towards $1.0$, the effect disappears.
```{r,echo=FALSE,message=FALSE,fig.align='center'}
require(ggplot2)
N <- 1:100
df <- data.frame( N, Y = 2*N / ( 2*N - 1) )
ggplot(df, aes(x=N,y=Y)) + geom_line() + geom_point() + ylab("Correction Factor")
```
For the *arapat* data set, the sample size ($N =$\Sexpr{nrow(arapat)}) are pretty large, so the effect of $N$ is pretty small, though still present. For corrections due to sample size using `He()`, you tell it to do it...
```{r}
He( arapat$MP20, small.sample.correction=TRUE )
```
### Multilocus Diversity
Scaling out one more level, it is possible to estimate diversity across multiple loci. Here we consider all the loci together as if we printed them out on a piece of paper. The multilocus diversity is a ratio of the number of unique multilocus genotypes to the total number of individuals in the population.
\[
D_{m} = \frac{N_{unique}}{N}
\]
The values of $D_m$ are bound on the range of $[\frac{1}{N},1.0]$, with higher values meaning more diverse (e.g., there is a larger fraction of individuals in the population with unique combinations of alleles across loci), and lower values being less diverse.
```{r}
multilocus_diversity( arapat )
```
So we see here that across all loci, the beetle dataset has a high level of multilocus diversity.
<file_sep>---
title: "BIOL 516--Population Genetics"
author: "Dr. <NAME>"
preamble: |
\usepackage{longtable}
output: html_document
---
```{r,message=FALSE,echo=FALSE}
require(knitr)
opts_chunk$set( concordance=TRUE,
eps=FALSE,
size='footnotesize',
comment="#",
dev="pdf",
fig.path="syllabus/",
cache=TRUE
)
opts_knit$set(self.contained=FALSE)
options(width=80)
```
## Synopsis
Welcome to Population Genetics! This course focuses on the actual mechanisms of evolution. Analytical Population Genetics is an old field, beginning in the gardens of the Silesian monk Gregor Johan Mendel (1822-1844) and continuing today with genome scans and CODIS databases. This semester will push you to develop your analytically skills so that you have a **working** understanding of this topic. Along the way you will become rather comfortable with *R* as a tool set as well as some famous genetic data sets (OK, perhaps they are not so famous outside my lab but it sounds good).
## Course Logistics
When I am on campus, I am always available for discussion. I can be contacted at:
Office: LFSB 105
Phone: (804) 828-0874
Email: [<EMAIL>](<EMAIL>)
Office Hours: T/R 11-12 | Appt
If you pass by my office, I always have my door open and I am more than happy to chat about the course content or other population genetic topics.
## Class Format
You will find throughout this semester that I am an 'out-of-the-box' kind of person. Since theoretical population genetics is the focus of my research, I have done a lot of work evolving this course to where it currently is. As a result, you may find that this course will deviate from the normal courses you've taken in the following ways:
1. Standard Lectures are a historical holdover from the dark ages when there was only one, or a few, copies of a text. As such, it was the job of the lecturer to stand in front of people and read from the text to pass along information. It is my opinion that this is a terrible paradigm to follow, particularly for something like population genetics. While I was a graduate student, I received the 'lecture' that went through the book, and at the end of the semester I was a well trained listener and knew a lot about the mathematical expectations of population genetics. However, if you gave me a data set, I was entirely lost! Books like the reference one for this course *fail* to address the application of population genetics. As I started here at VCU, I trained three years of graduate students in the way I learned it, producing students who had a great intuitive understanding of what would be expected to happen in ideal situations but entirely *useless practitioners*. Lame.
2. If you are going to go onto the job market or continue in academia using the tools of population genetics, you will be much more competitive if you know the theory and how to *actually* work with real data. Competition is hard and analytical fluency is paramount to a successful career.
3. The best way I have found to make sure students can work with real data is to actually have them *work with data*! I know, very revolutionary, they don't just hand out PhD's these days... To achieve this lofty goal this course will be taught as a 'flipped' course. This means that I will not spend my time standing in front of you lecturing every day. In fact, I will not provide direct lectures to you any day. Rather, I dissected this course into small chunks, unified in focus, and for each of them I will:
+ Give you a lecture, recorded and annotated, that you will view **prior** to class.
+ Extract a few quick questions via Blackboard just to make sure you will be watching the lecture **prior** to class.
+ Give you an opportunity to work with real data during the class period wherein you will have access to your classmates and myself so that we can all prosper.
+ Provide a link between the theory & practice and its application in the primary literature.
## Course Components
I have dissected the content for this course into small, digestible chunks, 26 in total. Each of these items is less than what would be considered a 'Chapter' from a normal text book; some are very short and others are longer. Each class period will focus on one of these chunks and they are arranged in a way to be incremental in building your skills and understanding of population genetic processes.
Each chunk will have:
1. A pre-recorded lecture (or set of lectures) that you will view prior to class. This will give you the background and the theory. These lectures range in length from 15-45 minutes.
A few quick questions on the material just to make sure you will be watching the lecture prior to class.
2. If necessary, one or more short recorded sessions or live material that will aid in the applied aspects of the topic. You should also view these prior to class as well in preparation of working with the data.
3. A worksheet that provides you with some hands-on activities with the data. This will give you an opportunity to work with real data during the class period wherein you will have access to your classmates and myself so that we can all prosper.
Once we get into actual population genetic topics (the first three lectures in Section 1 are mostly background), you (yes you the students) will also have a single activity to add to the course content. Each student will choose one of the chunks (first come/first serve) and will provide:
1. An example manuscript that uses the analytical topic being discussed in some way. This does not have to be the entirety of the paper, but it should be a component of the research. These papers must come from the primary literature.
2. A short presentation (<15 minutes total) that will be recorded *a priori* and put on this webpage just like I have done. This short presentation must:
+ Cover the general gist of the manuscript such that we all understand why it was chosen and how it relates to the topic at hand. I want rationale and context to be highlighted, not just the mechanics of what was done.
+ Provides an example exercise using real or fictitious data that shows how you would actually DO an analysis and get biologically meaningful inferences from these analyses. This must include an example data set and a R script that performs the analysis. You should walk the users through the script so we understand it and provide *copious* amounts of comments so that when we come back to the script next month, we will remember how it works.
I will assist in providing instruction on how to record a lecture and what should be provided. The data and scripts will be made available to everyone and will constitute a nice library of population genetic analyses for all of us at the end of the semester in case we need to perform these tasks again.
### Schedule of Topics
The following table denotes the topics and the dates on which we will be discussing them. You **must** view the material for that topic **before** class on the scheduled date.
**Date** | **Section** | **Topic**
---------------|-------------|----------------------------
8/21/2014 | 0 | Logistics
8/26/2014 | 1 | Basic Genetics
8/28/2014 | 1 | Basic R
9/2/2014 | 1 | Statistics & Graphics
9/4/2014 | 1 | Hardy-Weinberg Equilibrium
9/9/2014 | 1 | Testing HWE
9/11/2014 | 1 | Genetic Diversity
9/16/2014 | 1 | Selfing & Inbreeding
9/18/2014 | 1 | Mixed Mating Systems
9/23/2014 | 1 | Genetic Distance
9/25/2014 | 1 | Exam1
9/30/2014 | 2 | Relatedness
10/2/2014 | 2 | Parent Offspring Analytics
10/7/2014 | 2 | Pedigree Analyses
10/9/2014 | 2 | Coalescence & Neutral Theory
10/14/2014 | 2 | Migration
10/21/2014 | 2 | Genetic Structure
10/23/2014 | 2 | Population Assignment Tests
10/28/2014 | 2 | Genetic Drift
10/30/2014 | 2 | Effective Population Size
11/4/2014 | 2 | Exam2
11/6/2014 | 3 | Linkage & Recombination
11/11/2014 | 3 | Mutation
11/13/2014 | 3 | Spatial Genetic Structure
11/18/2014 | 3 | Landscape Resistance
11/20/2014 | 3 | X-Linked Analyses
11/25/2014 | 3 | Selection 1
12/2/2014 | 3 | Selection 2
12/4/2014 | 3 | Simulation
### Grading & Evaluations
Your grade in this course will be determined by the percentage of all possible points you accumulate over the term of the semester. Mapping of percentages to grades is indicated in the table below (all scores will be rounded as shown in table).
Grade | Percentage
------|-----------
A | 90+
B | 80 - 89
C | 70 - 79
D | 60 - 69
F | <60
The content of the course is outlined here. The breakdown of the class with respect to graded material is as follows:
1. The course is divided into three Sections, aptly denoted by the integers 1, 2, and 3.
2. Each section is roughly five weeks in duration and will be terminated by an Exam.
3. There is no 'comprehensive' examination at the end of the term, but it would be foolish to think that the things that you learned early in the semester do not form the foundation on which the latter topics rest.
4. Each exam will be a 'take-home' exam. You will have 1 week to complete the exam and turn it in.
5. There is no make-up on the exams and there are no extensions. If you do not turn it in, you get a *0*.
6. All exam materials will be turned in electronically, some of the analytical output may be lengthy and we do not need to be wasting trees.
7. Each topic will consist of its own webpage with:
+ A synopsis of the topic with learning objectives and goals.
+ One or more recorded lectures that you will watch before class. These lectures will cover the theory and application of the material being discussed providing you a broad understanding of the why and how relevant to that topic.
+ A short overview of how one analyzes data relevant to that topic in R.
+ A graded set of quick questions derived from the lectures on content and analyses. This will be due before class as well. If you do not complete these quick question, you will be given a zero.
+ Some example data and homework questions that will be tackled in-class. Answers to these example data materials will be turned in, electronically, in one week.
8. As outlined in the class philosophy page, much of the focus of this course will be placed on working with actual data. This means you will have to get your hands dirty and get comfortable using modern analysis tools, namely R, on a daily basis. One of the components of this course is for you to provide a short presentation and tutorial on data analysis that will be presented to the rest of the class. This will require you to:
+ Identify a manuscript relevant to a topic being covered.
+ Create a short presentation covering the manuscript and an example of how one would do an analysis like the one one the paper. This should include both a data set and the R code for the analysis.
+ Record this presentation and have it available for upload at least 1 class period prior to class it is going to be used in for all to view.
+ Your evaluation on this will be determined by peer review.
If you do not 'like' math or analyses, this course or any other one covering the field of population genetics are probably not for you. I will do everything in my power to help you on your path towards analytical mastery but you have to put in the time and effort.
Component | Relative Weight
--------------------|----------------
Exams | 45%
Topic Quiz/Homework | 45%
Presentation | 10%
### Late Assignments, Extra Credit & Makeup Materials
Assignments and tests are more than sufficient time, *1 week each*, for completion. The presentation is scheduled and performed well in advance of the class in which it will be used that there is also no need for any leeway here. The quizzes aimed at making sure you watched the recorded lecture prior to class are no longer relevant after class.
Consequently, my policy in this course is as follows:
1. You will receive **0** points for all late material.
2. There is **no** make-up or extra credit offered.
## Honor System
Virginia Commonwealth University recognizes that honesty, truth, and integrity are values central to its mission as an institution of higher education. The Honor System is built on the idea that a person’s honor is his/her most cherished attribute. A foundation of honor is essential to a community devoted to learning. Within this community, respect and harmony must coexist. The Honor System is the policy of VCU that defines the highest standards of conduct in academic affairs.
VCU Honor System: Plagiarism and Academic Integrity
The VCU honor system policy describes the responsibilities of students, faculty, and administration in upholding academic integrity, while at the same time respecting the rights of individuals to the due process offered by administrative hearings and appeals. According to his policy, "members of the academic community are required to conduct themselves in accordance with the highest standards of academic honesty and integrity." In addition, "All members of the VCU community are presumed to have an understanding of the VCU Honor System and are required to:
* Agree to be bound by the Honor System policy and its procedures;
* Report suspicion or knowledge of possible violations of the Honor System;
* Support an environment that reflects a commitment to academic integrity;
* Answer truthfully when called upon to do so regarding Honor System cases;
* Maintain confidentiality regarding specific information in Honor System cases;
* Most importantly, "All VCU students are presumed upon enrollment to have acquainted themselves with and have an understanding of the Honor System." (The VCU Insider).
The Honor System in its entirety can be reviewed on the Web at:
http://www.provost.vcu.edu/pdfs/Honor_system_policy.pdf, or
http://www.students.vcu.edu/insider.html
In this class, because coursework will be collaborative at times, particular issues of integrity arise. You should not copy or print another student's work without permission. Any material (this includes IDEAS and LANGUAGE) from another source must be credited, whether that material is quoted directly, summarized, or paraphrased. In other words, you should respect the work of others and in no way present it as their own.
The Honor System states that faculty members are responsible for:
* Understanding the procedures whereby faculty handles suspected instances of academic dishonesty. Faculty are to report any infraction of the VCU Honor System according to the procedures outlined in our policy.
* Developing an instructional environment that reflects a commitment to maintaining and enforcing academic integrity. Faculty should discuss the VCU Honor System at the onset of each course and mention it in course syllabus.
* Handling every suspected or admitted instance of violation of the provisions of this policy in accordance with procedures set forth in the policy.
### Dyer's Stance on Honor Violations
If you violate the Honor Code, you will get an **F** in this course.
## University Calendar & Important Dates
The VCU Academic Calendar is posted at:
http://www.google.com/url?q=http%3A%2F%2Facademiccalendars.vcu.edu%2Fac_fullViewAll.asp%3Fterm%3DFall%2B2014&sa=D&sntz=1&usg=AFrqEzfh-34Gop5ilfQgKBO4FVWgb2WlXQ
## Email Policy
Electronic mail or "email" is considered an official method for communication at VCU because it delivers information in a convenient, timely, cost effective, and environmentally aware manner. This policy ensures that all students have access to this important form of communication. It ensures students can be reached through a standardized channel by faculty and other staff of the University as needed. Mail sent to the VCU email address may include notification of University-related actions, including disciplinary action.
Please read the policy in its entirety: http://www.ts.vcu.edu/kb/3407.html
For you to participate in *this class*, you must use your VCU email address to log into the Google Site. I **will not** share these assets with a non-VCU email account.
## Student Conduct
According to the Faculty Guide to Student Conduct in Instructional Settings,
> The instructional program at VCU is based upon the premise that students enrolled in a class are entitled to receive instruction free from interference by other students. Accordingly, in classrooms, laboratories, studies, and other learning areas, students are expected to conduct themselves in an orderly and cooperative manner so that the faculty member can proceed with their [sic] customary instruction. Faculty members (including graduate teaching assistants) may set reasonable standards for classroom behavior in order to serve these objectives. If a student believes that the behavior of another student is disruptive, the instructor should be informed.
Among other things, cell phones and beepers should be turned off while in the classroom. Also, the University Rules and Procedures prohibit anyone from having
> in his possession any firearm, other weapon, or explosive, regardless of whether a license to possess the same has been issued, without the written authorization of the President of the university...
For more information, visit the VCU Insider online at:
http://www.students.vcu.edu/insider.html
Certainly the expectation in this course is that students will attend class with punctuality, proper decorum, required course material, and studious involvement.
The VCU Insider contains additional important information about a number of other policies with which students should be familiar, including Guidelines on Prohibition of Sexual Harassment, Grade Review Procedure, and Ethics Policy on Computing. It also contains maps, phone numbers, and information about resources available to VCU students.
## Students With Disabilities
SECTION 504 of the Rehabilitation Act of 1973 and the Americans with Disabilities Act of 1990 as amended, require that VCU provides "academic adjustments " or "reasonable accommodations" to any student who has a physical or mental impairment that substantially limits a major life activity. To receive accommodations, students must request them by contacting the Disability Support Services Office (DSS) on the Monroe Park Campus (828-2253) or the Division for Academic Success on the MCV campus (828-9782). More information is available at the Disability Support Services webpage:
http://www.students.vcu.edu/dss/
or the Division for Academic Success webpage at
http://healthsciences.vcu.edu/DAS
If you have a disability that requires an academic accommodation, please schedule a meeting with me at your earliest convenience. Additionally, if your coursework requires you to work in a lab environment, you should advise me or department chairperson of any concerns you may have regarding safety issues related to your disability. This statement applies not only to this course but also to every other course in this University.
## Military Short-Term Training or Deployment
Military students may receive orders for short-term training or deployment. These students are asked to inform and present their orders to Military Student Services and to their professor(s). For further information on policies and procedures contact Military Services at 828-5993 or access the corresponding policies at:
http://www.pubapps.vcu.edu/bulletins/about/?Default.aspx?uid=10096&iid=30704
and
http://www.pubapps.vcu.edu/BULLETINS/undergraduate/?uid=10096&iid=30773
## Campus Emergency Information
What to Know and Do To Be Prepared for Emergencies at VCU:
* Sign up to receive VCU text messaging alerts (http://www.vcu.edu/alert/notify). Keep your information up-to-date. Within the classroom, the professor will keep his or her phone on to receive any emergency transmissions.
* Know the safe evacuation route from each of your classrooms. Emergency evacuation routes are posted in on-campus classrooms.
* Know where to go for additional emergency information (http://www.vcu.edu/alert).
* Know the emergency phone number for the VCU Police (828-1234). Report suspicious activities and objects.
<file_sep># Basic Graphics
> One of the best features of `R` is its ability to use produce a wide array of graphical displays raning from quick scatter plots to rather complex overlays. This section covers the basic plotting types that come with `R` showing how to use them and how to get the most informative displays of your data.
For this section we are going to use the venerable iris dataset that was used by Anderson (1935) and Fisher (1936). These data are measurements of four morphological variables (*Sepal Length*, *Sepal Width*, *Petal Length*, and *Petal Width*) measured on fifty individual iris plants in three species. Here is the raw data
```{r,echo=FALSE,message=FALSE}
require(DT)
datatable(iris,caption="The canonical iris data set containing floral measurments for three species of Iris.")
```
Here is a summary of this data set.
```{r}
summary(iris)
```
## Univariate Plots
Here we will examine the distribution of univariate data.
### Histograms
One way to visualize the distribution of data is to use a histogram (via `hist()`). The basic output from this is:
```{r}
hist(iris$Sepal.Length)
```
There are many options that we can add to the plot command to make it more informative and/or conformative to your publication. Common ones include:
* **xlab** Change the label on the x-axis
* **ylab** Change the lable on the y-axis
* **main** Change the title of the graph
* **col** Either a single value, or a vector of values, indicating the color to be plot.
* **xlim**/**ylim** The limits for the x- and y-axes.
```{r}
x <- hist( iris$Sepal.Length,xlab="Sepal Length (cm)", ylab="Count", main="", col="lightblue")
```
You notice here I assigned the value of the plot to the variable `x`. I did this because the `hist()` function can return some informative information.
```{r}
x
```
In particular, it gives you the specifics on how the function broke the continuous data into bins. It is possible for you to specify specific values for many of these parameters. Here are some additional items that may be of intersest when creating histograms that you can pass to the `hist()` function.
* **freq** Specifies the scaling of the y-axis as either raw counts or percentage of the total distribution.
* **border** Color of the border around the bars
* **labels** Flag (TRUE/FALSE) to add the counts of observations on top of each bar.
* **breaks** Where to put the breaks in the raw data. This can be one of:
+ A single number indicating how many bins you want,
+ A vector of values to indicate where the breakpoints are,
+ The name of a function to use to determine where the breaks should be or the number of bins,
+ The name of one of the built-in functions ("Sturges","Scott","Freedman-Diaconis")
### Density Plots
Another way to visualize this is to estiamte a density function for the set of data.
```{r}
d <- density( iris$Sepal.Length)
plot(d, col="red", lwd=2, bty="n")
```
* **lwd** The width of the line
* **lty** The type of line to use.
* **bty** Indicates the type of box to be drawn around the plot. Personally, I dislike boxes around my output so I typically use 'n' to indicate none.
### Overlaying Plots
Since these data are composed of three different species, it makes sense to partition the plotting of characteristics by species and then look at the distributions.
```{r}
d.setosa <- iris$Sepal.Length[ iris$Species=="setosa" ]
d.versicolor <- iris$Sepal.Length[ iris$Species=="versicolor" ]
d.virginica <- iris$Sepal.Length[ iris$Species=="virginica" ]
c( mean(d.setosa), mean(d.versicolor), mean(d.virginica) )
```
We can overlay `density()` plots of these three densities by plotting the first one and the overlaying `lines()` for the remaining ones. It is also nice to add a legend to the plot so you can tell what the data mean.
```{r}
d.se <- density( d.setosa )
d.ve <- density( d.versicolor )
d.vi <- density( d.virginica )
plot(d.se,xlim=c(4,8),col="red", lwd=2, bty="n", xlab="Sepal Length (cm)", main="Sepal Lengths")
lines( d.ve, xlim=c(4,8), col="green",lwd=2, bty="n")
lines( d.vi, xlim=c(4,8), col="blue", lwd=2, bty="n")
legend( 6.5,1.1,c("I. setosa", "I. versicolor", "I. virginica"), col=c("red","green","blue"), lwd=2,bty="n")
```
### Barplots
Similar in approach to the density example, it is also possible to interdigitate the distributions using a boxplot. The `boxplot()` function takes either a single vector of values or a matrix of values where each column is a different set of data to plot. You can think of the histogram plot above as a boxplot of bin counted data. We can do the same thing here directly for each species by:
1. Define a set of breakpoints (bins) for all the data
2. Recover the counts of observations in each bin for each species
3. Put them into a matrix (columnwise)
4. Plot.
```{r}
breaks <- seq(4,8,by=0.2)
h.se <- hist(d.setosa, breaks=breaks, plot = FALSE)
h.ve <- hist(d.versicolor, breaks=breaks, plot=FALSE)
h.vi <- hist(d.virginica, breaks=breaks, plot=FALSE)
vals <- rbind( h.se$counts, h.ve$counts, h.vi$counts )
rownames(vals) <- levels(iris$Species)
colnames(vals) <- breaks[1:20]
vals
```
Now you can plot them as stacked
```{r}
barplot(vals,xlab="Sepal Length", ylab="Frequency")
```
or beside
```{r}
barplot(vals,xlab="Sepal Length", ylab="Frequency", col=c("red","green","blue"), beside=TRUE)
legend(60,10,c("I. setosa", "I. versicolor", "I. virginica"), fill=c("red","green","blue"), bty="n")
```
<alert>Notice:</alert> For plotting onto a barplot object, the x-axis number is not based upont he lables on the x-axis. It is an integer that relates to the number of bar-widths and separations. In this example, there are three bars for each category plus one seapration (e.g., the area between two categories). So I had to plot the legend as $60$ which put it at the 15<sup>th</sup> category (e.g., $15*4=60$).
## Bivariate Plots
Bivariate plots are those that have more than one kind of data associated with each point. I suppose that the previous sections work with differences in distributions between species could also be considered as a bivariate plot but lets not get picky.
### Boxplots
For univariate data that is collected across a range of *factors*, it is easy to display the mean and distribution of values using a boxplot. Box plots (sometimes called box-and-whisker plots) indicate several components:
1. The median of the distribution for each factor,
2. An optional confidence around that median, indicated by passing `notch=TRUE` to the function, that indicates a 5% confidence interval,
3. The first and third quartile of the data, and
4. Outlier points.
Here is an example.
```{r}
boxplot(Sepal.Length ~ Species, data=iris, notch=TRUE, xlab="Species", ylab="Sepal Length (cm)", frame.plot=FALSE)
```
In this plot, I used the `frame.plot=FALSE` optional argument because the authors of the function thought it was best to deviate from the normal `bty='n'` option.
### Scatter Plots
The most basic form of bivariate plot is that of a scatter plot. Here we have two coordiantes for every data point.
```{r}
plot( iris$Sepal.Length, iris$Sepal.Width, pch=as.numeric(iris$Species), bty="n", xlab="Sepal Length (cm)", ylab="Sepal Width (cm)")
legend( 6.75, 4.3, c("I. setosa", "I. versicolor", "I. virginica"), pch=1:3, bty="n")
```
In addition to the normal plotting options, I also change the type of symbol to use for each species using the `pch` option. This is a categorical *factor* variable contained in `iris$Species` but the `pch` option needs a numerical value. By passing the factor through `as.numeric()` it did the translation for me. Here are the set of normal plot characters.
```{r}
plot(1:25,1:25,pch=1:25, bty="n", xlab="pch", ylab="pch")
```
## Multiple Plots
At times, it is very helpful to break up complicated plots to aid in interpretation. One way to do this is to have many plots in a single graphic. This can be done by changing the plotting parameters using the `par()` command.
By default, each graphic has a set of parameters associated with it. In creating these plots above, we manipulated many of these values. You can see the default parameters by:
```{r}
names( par() )
```
Some of these are obvious, others less so. To create a 'matrix' of plots, we can adjust the 'mfrow' or 'mfcol' parameter.
```{r}
par()$mfrow
```
## References
* <NAME>. 1935. The irises of the Gaspe Peninsula. *Bulletin of the American Iris Society*, **59**, 2-5.
* Fisher RA. 1936. The use of multiple measurements in taxonomic problems. *Annals of Eugenics*, **7**, 179-188.
<ul class="pager">
<li class="previous"><a href="r_data_containters.html"><span aria-hidden="true">←</span> Previous</a></li>
<li class="next"><a href="r_advanced_graphics.html">Next <span aria-hidden="true">→</span></a></li>
</ul>
|
f3942ae64811d7e3b10f68656c82435c5216bd89
|
[
"R",
"RMarkdown"
] | 21 |
R
|
dyerlab/APG
|
845ede31af9a004fe4ce9e9f25f23fac0afd4d16
|
12c2d601b31b1019eccf53c4f3cda670edc80901
|
refs/heads/master
|
<file_sep>import { combineReducers } from 'redux';
import axios from 'axios';
//const initialState = {}
// ACTION TYPES
const FIND = 'FIND_STUDENT';
// ACTION CREATORS
const findStudent = (student) => ({ type: FIND, student });
// THUNK
export const findStudentThunk = (id) => dispatch => {
return axios.get(`/api/student/${id}`)
.then(student => {
console.log('in selected student thunk: ', student);
dispatch(findStudent(student.data));
});
};
// REDUCER
export default function studentReducer(student = null, action) {
switch (action.type) {
case FIND:
return action.student;
default:
return student;
}
}
<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router';
import { connect } from 'react-redux';
import { deleteStudentThunk } from '../reducers/student';
import { findCampusThunk } from '../reducers/selectedCampus';
export class StudentList extends Component{
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(id) {
this.props.deleteStudentThunk(id);
if (this.props.hideCampus) { this.props.findCampusThunk(this.props.hideCampus); }
}
render(){
const students = this.props.students;
const hideCampus = this.props.hideCampus ? this.props.hideCampus : false;
return !students ? null : (
<table className="table studentlist">
<thead>
<tr>
<th />
<th>Name</th>
{hideCampus ? null : <th>Campus</th> }
<th>Email</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{students.map(student => (
<tr key={student.id}>
<td>
<Link to={`/student/${student.id}`} className="fa fa-info-circle" />
</td>
<td>{student.name}</td>
{hideCampus ? false : <td>
{ student.campus ?
<Link to={`/campus/${student.campus.id}`}>{student.campus.name}</Link>
: <Link to={`/campus/`}>Not Assigned</Link> }
</td> }
<td><a className="fa fa-envelope" href={`mailto:${student.email}`} /></td>
<td><Link to={`/student/${student.id}`} className="fa fa-pencil" /></td>
<td><a className="fa fa-trash" onClick={() => this.handleClick(student.id)} /></td>
</tr>
)
)}
<tr>
<td>
<Link to="/student/add">
<i className="fa fa-sm fa-plus" aria-hidden="true" />
</Link>
</td>
</tr>
</tbody>
</table>
);
}
}
const mapToProps = ( _ , ownProps) => ({ownProps});
const mapToDispatch = {deleteStudentThunk, findCampusThunk};
export default withRouter(connect(mapToProps, mapToDispatch)(StudentList));
<file_sep>const Sequelize = require('sequelize');
const {STRING} = Sequelize;
const db = require('../index');
const Student = db.define('student', {
name: {
type: STRING,
allowNull: false
},
email: {
type: STRING, // is there more specific?
allowNull: false,
validate: {
isEmail: true
} // is that a thing?
}
}, {
hooks: {
beforeValidate: (user) => {
if (user.email.indexOf('.') < 0){
user.email = user.email.concat('.com');
}
}
},
defaultScope: {
include: [{model: db.model('campus')}]
},
scopes: {
populated: () => ({
include: [{
model: db.model('campus')
}]
})
}
}
);
module.exports = Student;
<file_sep>import axios from 'axios';
import { getStudentsThunk } from './student';
//const initialState = {}
// ACTION TYPES
const GET = 'GET_CAMPUSES';
const ADD = 'ADD_CAMPUS';
//const EDIT = 'EDIT_CAMPUS';
// const DELETE = 'DELETE_CAMPUS';
// ACTION CREATORS
const getCampuses = (campuses) => ({ type: GET, campuses });
const addCampus = (campus) => ({type: ADD, campus});
// const deleteCampus = (campus) => ({type: DELETE, campus});
// THUNK
export const getCampusesThunk = () => dispatch => {
return axios.get('/api/campus')
.then(campuses => {
dispatch(getCampuses(campuses.data));
});
};
export const addCampusThunk = (campus) => dispatch => {
console.log('in add campus thunk');
return axios.post('/api/campus/add', campus)
.then(campus => {
dispatch(addCampus(campus.data));
});
};
export const deleteCampusThunk = (id) => dispatch => {
return axios.delete(`/api/campus/${id}`)
.then(() => {
axios.get('/api/campus')
.then(campuses => {
dispatch(getCampuses(campuses.data));
dispatch(getStudentsThunk());
});
});
};
export const updateCampusThunk = (campus) => dispatch => {
return axios.put('/api/campus', campus)
.then( () => {
axios.get('/api/campus')
.then(campuses => {
dispatch(getCampuses(campuses.data));
});
});
};
// REDUCER
export default function campusReducer(campuses = [], action) {
switch (action.type) {
case GET:
return action.campuses;
case ADD:
return [...campuses, action.campus];
default:
return campuses;
}
}
<file_sep>import { combineReducers } from 'redux';
import axios from 'axios';
//const initialState = {}
// ACTION TYPES
const FIND = 'FIND_CAMPUS';
// ACTION CREATORS
const findCampus = (campus) => ({ type: FIND, campus });
// THUNK
export const findCampusThunk = (id) => dispatch => {
return axios.get(`/api/campus/${id}`)
.then(campus => {
console.log('in campus thunk: ', campus);
dispatch(findCampus(campus.data));
});
};
// REDUCER
export default function campusReducer(campus = null, action) {
switch (action.type) {
case FIND:
return action.campus;
default:
return campus;
}
}
<file_sep>import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router';
import React, { Component } from 'react';
import { findCampusThunk } from '../reducers/selectedCampus';
import { updateCampusThunk } from '../reducers/campus';
import StudentList from './StudentList';
export class OneCampus extends Component{
constructor(props){
super(props);
this.state = {name: '', image: '', id: '', sunside: '', darkside: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount(){
this.props.findCampusThunk(this.props.ownProps.match.params.id)
.then(() => { this.setState(this.props.selectedCampus); });
}
handleChange(evt){
const target = evt.target;
this.setState({[target.name]: target.value});
}
handleSubmit(evt){
evt.preventDefault();
this.props.updateCampusThunk(this.state);
this.props.history.push(`/campus`);
}
render(){
const {selectedCampus} = this.props;
const campus = this.state;
return (!selectedCampus) ? null : (
<div className="single-campus-page" >
<div className="single-campus row">
<div className="campus-info column box">
<input
className="title is-4"
type="text"
name="name"
value={campus.name}
onChange={this.handleChange} />
<img src={selectedCampus.image} />
<h1>Sunside</h1>
<textarea
className="textarea"
type="text"
name="sunside"
value={campus.sunside}
onChange={this.handleChange} />
<h1>Darkside</h1>
<textarea
className="textarea"
type="text"
name="darkside"
value={campus.darkside}
onChange={this.handleChange} />
<button type="submit" onClick={this.handleSubmit}>Update Campus</button>
</div>
<div className="student-info box">
<h5 className="title is-4">Students</h5>
<StudentList students={selectedCampus.students} hideCampus={selectedCampus.id} />
</div>
</div>
</div>
);
}
}
const mapToProps = ({campuses, selectedCampus}, ownProps) => ({campuses, selectedCampus, ownProps});
const mapToDispatch = { findCampusThunk, updateCampusThunk };
export default withRouter(connect(mapToProps, mapToDispatch)(OneCampus));
<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import store from '../store';
import StudentList from './StudentList';
class AllStudent extends Component {
render(){
const students = this.props.students;
return (
<div>
<div className="titlerow">
<h2 className="title is-2 allstudents">All Students</h2>
</div>
<StudentList students={students} />
</div>
);
}
}
const mapToProps = () => ({students}) => ({students});
const mapToDispatch = null;
export default connect(mapToProps, mapToDispatch)(AllStudent);
<file_sep>const Sequelize = require('sequelize');
const {STRING, TEXT} = Sequelize;
const db = require('../index');
const Campus = db.define('campus', {
name: {
type: STRING,
allowNull: false
},
image: {
type: STRING, // look up options
allowNull: false
},
darkside: {
type: TEXT
},
sunside: {
type: TEXT
}
}, {
hooks: {
beforeValidate: (campus) => {
if (campus.image === ''){
campus.image = 'https://pbs.twimg.com/profile_images/599535734865797122/HtkgkbNv_400x400.jpg';
}
}
},
scopes: {
populated: () => ({
include: [{
model: db.model('student')
}]
})
}
}
);
/*
images for campuses came from : https://www.appannie.com/en/apps/google-play/app/com.Horoscope.LibraLiveWallpaper/
*/
module.exports = Campus;
<file_sep>import React, { Component } from 'react';
function Home() {
return (
<div className="homepage" >
<h1 className="title is-1">Welcome to</h1>
<h1 className="title is-1">Zodiac University</h1>
<img src="https://s-media-cache-ak0.pinimg.com/originals/a7/fc/e5/a7fce58ea87dd8b0c818bea2745cedff.png" />
</div>
);
}
export default Home;
<file_sep>import { combineReducers } from 'redux';
import students from './student';
import campuses from './campus';
import selectedCampus from './selectedCampus';
import selectedStudent from './selectedStudent';
//const initialState = {}
// const rootReducer = function(state = initialState, action) {
// switch(action.type) {
// default: return state
// }
// };
export default combineReducers({students, campuses, selectedCampus, selectedStudent});
<file_sep>import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import { withRouter } from 'react-router';
import React, { Component } from 'react';
import { findStudentThunk } from '../reducers/selectedStudent';
import { updateStudentThunk } from '../reducers/student';
export class OneStudent extends Component{
constructor(props){
super(props);
this.state = {name: '', campusId: '', id: '', email: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount(){
this.props.findStudentThunk(this.props.ownProps.match.params.id)
.then(() => {
this.setState(this.props.selectedStudent);
});
}
handleChange(evt){
const target = evt.target;
this.setState({[target.name]: target.value});
}
handleSubmit(evt){
evt.preventDefault();
this.props.updateStudentThunk(this.state);
this.props.history.push(`/student`);
}
render(){
const student = this.props.selectedStudent;
const campuses = this.props.campuses;
return (!student) ? (<h1>Loading</h1>) : (
<div className="singlestudent">
<input
className="input"
type="text"
name="name"
value={this.state.name}
onChange={this.handleChange} />
<input
className="input"
type="text"
name="email"
value={this.state.email}
onChange={this.handleChange} />
<select
name="campusId"
value={this.state.campusId || undefined}
onChange={this.handleChange} >
{campuses.map(campus => (
<option key={campus.id} value={campus.id}>{campus.name}</option>
))}
</select>
{ (!student.campus) ? <h1>Not Assigned To A Campus</h1> :
<NavLink to={`/campus/${student.campus.id}`}>
<img className="student-image" src={student.campus.image} />
</NavLink>
}
<button type="submit" onClick={this.handleSubmit}>Update Student</button>
</div>
);
}
}
const mapToProps = ({ selectedStudent, campuses }, ownProps) => ({ selectedStudent, campuses, ownProps});
const mapToDispatch = { findStudentThunk, updateStudentThunk };
export default withRouter(connect(mapToProps, mapToDispatch)(OneStudent));
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { NavLink, Link } from 'react-router-dom';
import { deleteCampusThunk } from '../reducers/campus';
class AllCampus extends Component {
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(id) {
this.props.deleteCampusThunk(id);
}
render(){
const campuses = this.props.campuses;
return (
<div className="allcampuscomp">
<div className="titlerow">
<h2 className="title is-2">All Campuses</h2>
<Link to="/campus/add">
<i className="fa fa-sm fa-plus" aria-hidden="true" />
</Link>
</div>
<div className="campuses row">
{campuses.map(campus => (
<div className="allcampus onecampus" key={campus.id}>
<NavLink to={`/campus/${campus.id}`} className="campus">
<img src={campus.image} />
</NavLink>
<div className="row">
<NavLink to={`/campus/${campus.id}`} className="campus">
<h2>{campus.name}</h2>
</NavLink>
<i onClick={() => this.handleClick(campus.id)} name={campus.id} className="delete" />
</div>
</div>
))}
</div>
</div>
);
}
}
const mapToProps = () => ({campuses}) => ({campuses});
const mapToDispatch = { deleteCampusThunk };
export default connect(mapToProps, mapToDispatch)(AllCampus);
<file_sep>const router = require('express').Router();
const studentRouter = require('./student');
const campusRouter = require('./campus');
router.use('/student', studentRouter);
router.use('/campus', campusRouter);
module.export = router;
// SEEMINGLY UNNECESSARY
<file_sep>import { combineReducers } from 'redux';
import axios from 'axios';
//const initialState = {}
// ACTION TYPES
const GET = 'GET_STUDENTS';
const ADD = 'ADD_STUDENT';
//const EDIT = 'EDIT_STUDENT';
// ACTION CREATORS
const getStudents = (students) => ({ type: GET, students });
const addStudent = (student) => ({type: ADD, student});
//const editStudent = (student) => ({type: EDIT, student});
// THUNK
export const getStudentsThunk = () => dispatch => {
return axios.get('/api/student')
.then(students => {
dispatch(getStudents(students.data));
});
};
export const addStudentThunk = (info) => dispatch => {
return axios.post('/api/student/add', info)
.then(student => {
dispatch(addStudent(student.data));
});
};
export const deleteStudentThunk = (id) => dispatch => {
return axios.delete(`/api/student/${id}`)
.then( () => {
axios.get('/api/student')
.then(students => {
dispatch(getStudents(students.data));
});
});
};
export const updateStudentThunk = (student) => dispatch => {
return axios.put('/api/student', student)
.then(() => {
axios.get('/api/student')
.then(students => {
dispatch(getStudents(students.data));
});
});
};
// REDUCER
export default function studentReducer(students = [], action) {
switch (action.type) {
case GET:
return action.students;
case ADD:
return [...students, action.student];
default:
return students;
}
}
|
6b9b2bd255e6adbbb7a68c814b295e34022c4a35
|
[
"JavaScript"
] | 14 |
JavaScript
|
cmccarthy15/senior-enrichment
|
d5677aa13f036b9d919ec7b7788d3a723a52c696
|
3c299edecf527b9f0e578b904693fabbe8551c59
|
refs/heads/master
|
<file_sep>#pragma once
#include "d3dApp.h"
#include "ThridParty/Geometry.h"
#include "Transform.h"
#include "CBuffer.h"
#include "Camera.h"
/********************************************************************
Ex10:
渲染了可以自由移动的环境,设置了三种观察模式,FPS,TPS,和自由观察模式
还没有阴影。
*********************************************************************/
class Ex10Camera :
public D3DApp
{
public:
class GameObject
{
public:
GameObject();
// 获取物体变换
Transform& GetTransform();
// 获取物体变换
const Transform& GetTransform() const;
// 设置缓冲区
template<class VertexType, class IndexType>
void SetBuffer(ID3D11Device* device, const Geometry::MeshData<VertexType, IndexType>& meshData);
// 设置纹理
void SetTexture(ID3D11ShaderResourceView* texture);
// 绘制
void Draw(ID3D11DeviceContext* deviceContext);
private:
Transform m_Transform; // 世界矩阵
ComPtr<ID3D11ShaderResourceView> m_pTexture; // 纹理
ComPtr<ID3D11Buffer> m_pVertexBuffer; // 顶点缓冲区
ComPtr<ID3D11Buffer> m_pIndexBuffer; // 索引缓冲区
UINT m_VertexStride; // 顶点字节大小
UINT m_IndexCount; // 索引数目
};
// 摄像机模式
enum class CameraMode { FPS, TPS, Free, Observe };
public:
Ex10Camera(HINSTANCE hInstance);
virtual ~Ex10Camera();
bool Init();
void OnResize();
void UpdateScene(float dt);
void DrawScene();
protected:
bool InitEffect();
bool InitResource();
ComPtr<ID3D11InputLayout> m_pVertexLayout2D; // 2D顶点输入布局
ComPtr<ID3D11InputLayout> m_pVertexLayout3D; // 3D顶点输入布局
ComPtr<ID3D11Buffer> m_pConstantBuffers[4]; // 常量缓冲区
GameObject m_WoodCrate;
GameObject m_Floor;
std::vector<GameObject> m_Walls;
ComPtr<ID3D11VertexShader> m_pVertexShader2D; // 2D顶点着色器
ComPtr<ID3D11VertexShader> m_pVertexShader3D; // 3D顶点着色器
ComPtr<ID3D11PixelShader> m_pPixelShader2D; // 2D像素着色器
ComPtr<ID3D11PixelShader> m_pPixelShader3D; // 3D像素着色器
CBChangesEveryFrame m_CBFrame; // 帧缓冲区
CBChangesOnResize m_CBOnResize; // 改变大小缓冲区
CBChangesRarely m_CBRarely; // 几乎不变缓冲区
ComPtr<ID3D11SamplerState> m_pSamplerState; // 采样器
// 光照模型
PointLight m_PointLight;
ComPtr<ID3D11RasterizerState> m_pRSWireframe; //光栅化状态,切换线框模式
std::shared_ptr<Camera> m_pCamera;
CameraMode m_CameraMode;
};
<file_sep>#include "Model.h"
#include "ThridParty/DXTrace.h"
#include "ThridParty/d3dUtil.h"
using namespace DirectX;
Model::Model() :modelParts(), boundingBox(), vertexStride() {}
Model::Model(ID3D11Device* device, const ObjReader& model) :
modelParts(), boundingBox(), vertexStride()
{
SetModel(device, model);
}
Model::Model(ID3D11Device* device,
const void* vertices,
UINT vertexSize,
UINT vertexCount,
const void* indices,
UINT indexCount,
DXGI_FORMAT indexFormat) : modelParts(), boundingBox(), vertexStride() {
SetMesh(device, vertices, vertexSize, vertexCount, indices, indexCount, indexFormat);
}
/*
将读取出的ObjParts 转存到modelParts中
*/
void Model::SetModel(ID3D11Device* device, const ObjReader& model) {
vertexStride = sizeof(VertexPosNormalTangentTex);
modelParts.resize(model.objParts.size());
// 创建包围盒
BoundingBox::CreateFromPoints(boundingBox, XMLoadFloat3(&model.vMin), XMLoadFloat3(&model.vMax));
/*****************
创建顶点和索引
******************/
for (size_t i = 0; i < model.objParts.size(); i++) {
auto part = model.objParts[i];
modelParts[i].vertexCount = (UINT)part.vertices.size();
// 设置顶点缓冲区描述
D3D11_BUFFER_DESC vbd;
ZeroMemory(&vbd, sizeof(vbd));
vbd.Usage = D3D11_USAGE_IMMUTABLE;
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbd.ByteWidth = (UINT)sizeof(VertexPosNormalTangentTex) * modelParts[i].vertexCount;
vbd.CPUAccessFlags = 0;
// 新建顶点缓冲区
D3D11_SUBRESOURCE_DATA InitData;
ZeroMemory(&InitData, sizeof(InitData));
InitData.pSysMem = part.vertices.data();
HR(device->CreateBuffer(&vbd, &InitData, modelParts[i].vertexBuffer.ReleaseAndGetAddressOf()));
// 设置索引缓冲区描述
D3D11_BUFFER_DESC ibd;
ZeroMemory(&ibd, sizeof(ibd));
ibd.Usage = D3D11_USAGE_IMMUTABLE;
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
if (modelParts[i].vertexCount > 65535) {
modelParts[i].indexCount = (UINT)part.indices32.size();
modelParts[i].indexFormat = DXGI_FORMAT_R32_UINT;
ibd.ByteWidth = (UINT)sizeof(DWORD) * modelParts[i].indexCount;
InitData.pSysMem = part.indices32.data();
}
else {
modelParts[i].indexCount = (UINT)part.indices16.size();
modelParts[i].indexFormat = DXGI_FORMAT_R16_UINT;
ibd.ByteWidth = (UINT)sizeof(WORD) * modelParts[i].indexCount;
InitData.pSysMem = part.indices16.data();
}
// 创建索引缓冲区
HR(device->CreateBuffer(&ibd, &InitData, modelParts[i].indexBuffer.ReleaseAndGetAddressOf()));
/************
读取Texture
*************/
auto& strD = part.texStrDiffuse;
modelParts[i].texDiffuse = part.texStrDiffuse;
if (strD.size() > 4 && TexDiffuseMap.count(part.texStrDiffuse) == 0) {
TexDiffuseMap.insert(std::pair<std::wstring, ComPtr<ID3D11ShaderResourceView>>(part.texStrDiffuse, ComPtr<ID3D11ShaderResourceView>()));
auto& ptexDiffuse = TexDiffuseMap.find(part.texStrDiffuse)->second;
// Read texture from .dds file
if (strD.substr(strD.size() - 3, 3) == L"dds") {
HR(CreateDDSTextureFromFile(device, strD.c_str(), nullptr,
ptexDiffuse.GetAddressOf()));
}
// Read texture from .wic file
else {
HR(CreateWICTextureFromFile(device, strD.c_str(), nullptr,
ptexDiffuse.GetAddressOf()));
}
}
/******************
读取NormalMap
*******************/
auto& normalMap = part.normalMap;
modelParts[i].normalMap = part.normalMap;
if (normalMap.size() > 0 && NormalmapMap.count(part.normalMap) == 0) {
NormalmapMap.insert(std::pair<std::wstring, ComPtr<ID3D11ShaderResourceView>>(part.normalMap, ComPtr<ID3D11ShaderResourceView>()));
auto& pNormalmap = NormalmapMap.find(part.normalMap)->second;
// Read texture from .dds file
if (normalMap.substr(normalMap.size() - 3, 3) == L"dds") {
HR(CreateDDSTextureFromFile(device, normalMap.c_str(), nullptr,
pNormalmap.GetAddressOf()));
}
// Read texture from .wic file
else {
HR(CreateWICTextureFromFile(device, normalMap.c_str(), nullptr,
pNormalmap.GetAddressOf()));
}
}
modelParts[i].material = part.material;
}
}
void Model::SetMesh(ID3D11Device* device,
const void* vertices,
UINT vertexSize,
UINT vertexCount,
const void* indices,
UINT indexCount,
DXGI_FORMAT indexFormat) {
vertexStride = vertexSize;
modelParts.resize(1);
modelParts[0].vertexCount = vertexCount;
modelParts[0].indexCount = indexCount;
modelParts[0].indexFormat = indexFormat;
modelParts[0].material.ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
modelParts[0].material.diffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
modelParts[0].material.specular = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
// 设置顶点缓冲区描述
D3D11_BUFFER_DESC vbd;
ZeroMemory(&vbd, sizeof(vbd));
vbd.Usage = D3D11_USAGE_IMMUTABLE;
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbd.ByteWidth = vertexSize * vertexCount;
vbd.CPUAccessFlags = 0;
// 新建顶点缓冲区
D3D11_SUBRESOURCE_DATA InitData;
ZeroMemory(&InitData, sizeof(InitData));
InitData.pSysMem = vertices;
HR(device->CreateBuffer(&vbd, &InitData, modelParts[0].vertexBuffer.ReleaseAndGetAddressOf()));
// 设置索引缓冲区描述
D3D11_BUFFER_DESC ibd;
ZeroMemory(&ibd, sizeof(ibd));
ibd.Usage = D3D11_USAGE_IMMUTABLE;
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
if (indexFormat == DXGI_FORMAT_R16_UINT) {
ibd.ByteWidth = indexCount*(UINT)sizeof(WORD);
}
else {
ibd.ByteWidth = indexCount * (UINT)sizeof(DWORD);
}
InitData.pSysMem = indices;
// 创建索引缓冲区
HR(device->CreateBuffer(&ibd, &InitData, modelParts[0].indexBuffer.ReleaseAndGetAddressOf()));
}
<file_sep>#pragma once
#include "d3dApp.h"
#include "Transform.h"
#include "Camera.h"
#include "GameObject.h"
#include "Importer.h"
class RenderSponza :public D3DApp
{
public:
// 摄像机模式
enum class CameraMode { FPS, TPS, Free, Observe };
public:
RenderSponza(HINSTANCE hInstance);
virtual ~RenderSponza();
bool Init();
void OnResize();
void UpdateScene(float dt);
void DrawScene();
void VisualizeVLM();
protected:
bool InitResource();
bool InitVLM();
GameObject m_Sponza;
GameObject m_Box;
GameObject m_plane;
std::vector<Transform> m_DynamicTransform;
GameObject m_Sample;
GameObject m_Sphere;
std::vector<std::vector<Transform>> m_TransformData;
Material m_ShadowMat;
Material m_Material;
BasicEffect m_BasicEffect;
std::vector<PointLight> m_PointLightArray;
std::shared_ptr<Camera> m_pCamera;
CameraMode m_CameraMode;
ObjReader m_ObjReader;
Importer m_Importer;
bool m_IsWireframeMode;
bool m_UseSH;
bool m_UseTexture;
bool m_UseLight;
bool m_UseDirLight;
bool m_UsePointLight;
bool m_isVisulizeVLM;
int m_SHMode;
bool m_ShowHelp;
bool m_isControlObj;
wchar_t m_Text[1024];
DirectX::XMVECTORF32 m_BackGroundColor;
INT32 m_Speed;
INT32 m_SphereSpeed;
INT32 m_TargetDistance;
std::vector<INT8> m_SpheresDirection;
std::vector<const wchar_t*> m_SHRepositoies;
INT32 m_SHFileIndex;
ComPtr<ID3D11Texture3D> m_pTex3D;
};
<file_sep>#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
#include <filesystem>
#include <DirectXPackedVector.h>
#include <DirectXMath.h>
#include <wrl/client.h>
#include "ThridParty/DXTrace.h"
#include "Vertex.h"
#include "light.h"
/** Settings for the volumetric lightmap. */
struct FVolumetricLightmapSettings
{
/** Size of the top level grid covering the volumetric lightmap, in bricks. */
DirectX::XMINT3 TopLevelGridSize;
/** World space size of the volumetric lightmap. */
DirectX::XMFLOAT3 VolumeMin;
DirectX::XMFLOAT3 VolumeSize;
/**
* Size of a brick of unique lighting data. Must be a power of 2.
* Smaller values provide more granularity, but waste more memory due to padding.
*/
INT32 BrickSize;
/** Maximum number of times to subdivide bricks around geometry. */
INT32 MaxRefinementLevels;
/**
* Fraction of a cell's size to expand it by when voxelizing.
* Larger values add more resolution around geometry, improving the lighting gradients but costing more memory.
*/
float VoxelizationCellExpansionForSurfaceGeometry;
float VoxelizationCellExpansionForVolumeGeometry;
float VoxelizationCellExpansionForLights;
/** Bricks with RMSE below this value are culled. */
float MinBrickError;
/** Triangles with fewer lightmap texels than this don't cause refinement. */
float SurfaceLightmapMinTexelsPerVoxelAxis;
/** Whether to cull bricks entirely below landscape. This can be an invalid optimization if the landscape has holes and caves that pass under landscape. */
bool bCullBricksBelowLandscape;
/** Subdivide bricks when a static point or spot light affects some part of the brick with brightness higher than this. */
float LightBrightnessSubdivideThreshold;
/** Maximum desired curvature in the lighting stored in Volumetric Lightmaps, used to reduce Spherical Harmonic ringing via a windowing filter. */
float WindowingTargetLaplacian;
};
struct Texture_t {
std::vector<UINT8> data;
size_t FormatSize;
DXGI_FORMAT Format;
void Resize(size_t size) {
data.resize(size * FormatSize);
}
};
struct BrickDataImported {
DirectX::XMINT3 IndirectionTexturePosition;
INT32 TreeDepth;
float AverageClosestGeometryDistance;
std::vector<DirectX::PackedVector::XMFLOAT3PK> AmbientVector;
std::vector<DirectX::PackedVector::XMCOLOR> SHCoefficients[6];
BrickDataImported() = default;
};
struct BrickData {
DirectX::XMINT3 IndirectionTexturePosition;
INT32 TreeDepth;
float AverageClosestGeometryDistance;
std::vector<DirectX::PackedVector::XMFLOAT3PK> AmbientVector;
std::vector<DirectX::PackedVector::XMCOLOR> SHCoefficients[6];
std::vector<DirectX::PackedVector::XMFLOAT3PK> LQLightColor;
std::vector<DirectX::PackedVector::XMCOLOR> LQLightDirection;
std::vector<DirectX::PackedVector::XMCOLOR> SkyBentNormal;
std::vector<UINT8> DirectionalLightShadowing;
BrickData() = default;
};
struct VLMBrickData {
Texture_t AmbientVector;
Texture_t SHCoefficients[6];
Texture_t LQLightColor;
Texture_t LQLightDirection;
Texture_t SkyBentNormal;
Texture_t DirectionalLightShadowing;
};
struct VLMData {
DirectX::XMINT3 textureDimension;
Texture_t indirectionTexture;
DirectX::XMINT3 brickDataDimension;
VLMBrickData brickData;
void SetBrickDimension(const DirectX::XMINT3& dimension) {
brickDataDimension.x = dimension.x;
brickDataDimension.y = dimension.y;
brickDataDimension.z = dimension.z;
}
VLMData() = default;
};
class Importer
{
public:
/** Data used by the editor import process and not uploaded into textures. */
struct FIrradianceVoxelImportProcessingData
{
bool bInsideGeometry;
bool bBorderVoxel;
float ClosestGeometryDistance;
};
VLMData vlmData;
std::vector<std::vector<BrickDataImported>> m_BricksByDepth;
INT32 m_BricksNum;
FVolumetricLightmapSettings VLMSetting;
Importer() = default;
virtual ~Importer();
bool Read();
//template<class T>
//void ReadArray(std::vector<T>& arr);
template<class T>
void ReadArray(std::vector<T>& arr, std::ifstream& importer);
void TransformData();
bool ImportFile(
const wchar_t* bricksByDepthFile,
const wchar_t* vlmSettingFile,
const wchar_t* indirectTextureFilename = nullptr,
const wchar_t* ambientVectorFilename = nullptr,
const wchar_t* SH0CoefsFilename = nullptr,
const wchar_t* SH1CoefsFilename = nullptr,
const wchar_t* SH2CoefsFilename = nullptr,
const wchar_t* SH3CoefsFilename = nullptr,
const wchar_t* SH4CoefsFilename = nullptr,
const wchar_t* SH5CoefsFilename = nullptr);
void BuildIndirectionTexture(
const std::vector<std::vector<BrickDataImported>>& BricksByDepth,
const INT32 maxLayoutDimension,
const DirectX::XMINT3 Layout,
const INT32 formatSize,
VLMData& vlmData);
void CopyBrickToTexture(
INT32 formatSize,
const DirectX::XMINT3& brickDataDimension,
const DirectX::XMINT3& layoutPos,
const UINT8* srcPtr,
UINT8* destPtr
);
private:
std::unique_ptr<std::ifstream> pBrickByDepthImporter;
std::unique_ptr<std::ifstream> pVLMSettingImporter;
std::unique_ptr<std::ifstream> pIndirectionTextureImporter;
std::unique_ptr<std::ifstream> pAmbientVectorImporter;
std::unique_ptr<std::ifstream> pSH0CoefsImporter;
std::unique_ptr<std::ifstream> pSH1CoefsImporter;
std::unique_ptr<std::ifstream> pSH2CoefsImporter;
std::unique_ptr<std::ifstream> pSH3CoefsImporter;
std::unique_ptr<std::ifstream> pSH4CoefsImporter;
std::unique_ptr<std::ifstream> pSH5CoefsImporter;
bool hasAllSHCoefsTextures;
};
<file_sep>#include "Importer.h"
#include <assert.h>
using namespace std;
Importer::~Importer() {
}
bool Importer::Read() {
if (!pVLMSettingImporter->is_open()) {
std::cout << "open VLMSettingImporter failed";
return false;
}
pVLMSettingImporter->read(reinterpret_cast<char*>(&VLMSetting.VolumeMin), sizeof(float) * 3);
pVLMSettingImporter->read(reinterpret_cast<char*>(&VLMSetting.VolumeSize), sizeof(float) * 3);
pVLMSettingImporter->read(reinterpret_cast<char*>(&VLMSetting.TopLevelGridSize.x), sizeof(INT32));
pVLMSettingImporter->read(reinterpret_cast<char*>(&VLMSetting.TopLevelGridSize.y), sizeof(INT32));
pVLMSettingImporter->read(reinterpret_cast<char*>(&VLMSetting.TopLevelGridSize.z), sizeof(INT32));
pVLMSettingImporter->read(reinterpret_cast<char*>(&VLMSetting.BrickSize), sizeof(INT32));
VLMSetting.MaxRefinementLevels = 3;
if (!pBrickByDepthImporter->is_open()) {
std::cout << "open BrickByDepthImporter failed";
return false;
}
m_BricksByDepth.resize(VLMSetting.MaxRefinementLevels);
for (INT32 depth = 0; depth < VLMSetting.MaxRefinementLevels; depth++) {
m_BricksByDepth[depth].clear();
}
pBrickByDepthImporter->read(reinterpret_cast<char*>(&m_BricksNum), sizeof(INT32));
for (int depth = 0; depth < VLMSetting.MaxRefinementLevels; depth++) {
int numAtDepth;
pBrickByDepthImporter->read(reinterpret_cast<char*>(&numAtDepth), sizeof(INT32));
for (int i = 0; i < numAtDepth; i++) {
m_BricksByDepth[depth].push_back(BrickDataImported());
auto& brick = m_BricksByDepth[depth].back();
pBrickByDepthImporter->read(reinterpret_cast<char*>(&brick.IndirectionTexturePosition), sizeof(brick.IndirectionTexturePosition));
pBrickByDepthImporter->read(reinterpret_cast<char*>(&brick.TreeDepth), sizeof(INT32));
pBrickByDepthImporter->read(reinterpret_cast<char*>(&brick.AverageClosestGeometryDistance), sizeof(float));
ReadArray(brick.AmbientVector, *(pBrickByDepthImporter.get()));
for (int j = 0; j < 6; j++) {
ReadArray(brick.SHCoefficients[j], *(pBrickByDepthImporter.get()));
}
}
}
return true;
}
template<class T>
void Importer::ReadArray(vector<T>& arr, std::ifstream& importer) {
INT32 numArray = 0;
importer.read(reinterpret_cast<char*>(&numArray), sizeof(INT32));
arr.resize(numArray);
for (INT32 i = 0; i < numArray; i++) {
importer.read(reinterpret_cast<char*>(&arr[i]), sizeof(T));
}
}
const DirectX::XMINT3 computePositionByLayout(int index, DirectX::XMINT3 layout) {
DirectX::XMINT3 res;
res.x = index % layout.x;
res.y = index / layout.x % layout.y;
res.z = index / (layout.x * layout.y);
return res;
}
INT32 inline divideRoundUp(INT32 x, INT32 y) {
return x % y == 0 ? x / y : x / y + 1;
}
void Importer::BuildIndirectionTexture(
const vector<vector<BrickDataImported>>& BricksByDepth,
const INT32 maxLayoutDimension,
const DirectX::XMINT3 Layout,
const INT32 formatSize,
VLMData& vlmData) {
int BrickIndex = 0;
for (int i = 0; i < VLMSetting.MaxRefinementLevels; i++) {
for (int j = 0; j < BricksByDepth[i].size(); j++) {
const auto& brick = BricksByDepth[i][j];
DirectX::XMINT3 layoutPos = computePositionByLayout(BrickIndex, Layout);
assert(layoutPos.x < maxLayoutDimension&& layoutPos.y < maxLayoutDimension&& layoutPos.z < maxLayoutDimension);
const INT32 DetailCellsPerCurrentLevelBrick = pow(VLMSetting.BrickSize, VLMSetting.MaxRefinementLevels - brick.TreeDepth);
const INT32 NumBottomLevelBricks = DetailCellsPerCurrentLevelBrick / VLMSetting.BrickSize;
assert(NumBottomLevelBricks < maxLayoutDimension);
auto& texture = vlmData.indirectionTexture;
for (int z = 0; z < NumBottomLevelBricks; z++) {
for (int y = 0; y < NumBottomLevelBricks; y++) {
for (int x = 0; x < NumBottomLevelBricks; x++) {
const DirectX::XMINT3 IndirectionDestDataCoordinate = DirectX::XMINT3(brick.IndirectionTexturePosition.x + x, brick.IndirectionTexturePosition.y + y, brick.IndirectionTexturePosition.z + z);
const INT32 IndirectionDestDataIndex = ((IndirectionDestDataCoordinate.z * vlmData.textureDimension.x * vlmData.textureDimension.y)
+ (IndirectionDestDataCoordinate.y * vlmData.textureDimension.x) + IndirectionDestDataCoordinate.x) * texture.FormatSize;
texture.data[IndirectionDestDataIndex] = layoutPos.x;
texture.data[IndirectionDestDataIndex + 1] = layoutPos.y;
texture.data[IndirectionDestDataIndex + 2] = layoutPos.z;
texture.data[IndirectionDestDataIndex + 3] = NumBottomLevelBricks;
}
}
}
BrickIndex++;
}
}
}
void Importer::CopyBrickToTexture(
INT32 formatSize,
const DirectX::XMINT3& brickDataDimension,
const DirectX::XMINT3& layoutPos,
const UINT8* srcPtr,
UINT8* destPtr
) {
INT32 brickSize = VLMSetting.BrickSize;
const INT32 SourcePitch = brickSize * formatSize;
const INT32 Pitch = brickDataDimension.x * formatSize;
const INT32 DepthPitch = brickDataDimension.x * brickDataDimension.y * formatSize;
// Copy each row into the correct position in the global volume texture
for (INT32 ZIndex = 0; ZIndex < brickSize; ZIndex++)
{
const INT32 DestZIndex = (layoutPos.z + ZIndex) * DepthPitch + layoutPos.x * formatSize;
const INT32 SourceZIndex = ZIndex * brickSize * SourcePitch;
for (INT32 YIndex = 0; YIndex < brickSize; YIndex++)
{
const INT32 DestIndex = DestZIndex + (layoutPos.y + YIndex) * Pitch;
const INT32 SourceIndex = SourceZIndex + YIndex * SourcePitch;
memcpy(destPtr + DestIndex, srcPtr + SourceIndex, SourcePitch);
}
}
}
bool Importer::ImportFile(
const wchar_t* bricksByDepthFile,
const wchar_t* vlmSettingFile,
const wchar_t* indirectTextureFilename,
const wchar_t* ambientVectorFilename,
const wchar_t* SH0CoefsFilename,
const wchar_t* SH1CoefsFilename,
const wchar_t* SH2CoefsFilename,
const wchar_t* SH3CoefsFilename,
const wchar_t* SH4CoefsFilename,
const wchar_t* SH5CoefsFilename) {
pBrickByDepthImporter = std::move(unique_ptr<ifstream>(new std::ifstream(bricksByDepthFile, std::ios::in | std::ios::binary)));
if (!pBrickByDepthImporter->is_open())
return false;
pVLMSettingImporter = std::move(unique_ptr<ifstream>(new ifstream(vlmSettingFile, std::ios::in | std::ios::binary)));
pIndirectionTextureImporter = std::move(unique_ptr<ifstream>(new std::ifstream(indirectTextureFilename, std::ios::in | std::ios::binary)));
pAmbientVectorImporter = std::move(unique_ptr<ifstream>(new std::ifstream(ambientVectorFilename, std::ios::in | std::ios::binary)));
pSH0CoefsImporter = std::move(unique_ptr<ifstream>(new std::ifstream(SH0CoefsFilename, std::ios::in | std::ios::binary)));
pSH1CoefsImporter = std::move(unique_ptr<ifstream>(new std::ifstream(SH1CoefsFilename, std::ios::in | std::ios::binary)));
pSH2CoefsImporter = std::move(unique_ptr<ifstream>(new std::ifstream(SH2CoefsFilename, std::ios::in | std::ios::binary)));
pSH3CoefsImporter = std::move(unique_ptr<ifstream>(new std::ifstream(SH3CoefsFilename, std::ios::in | std::ios::binary)));
pSH4CoefsImporter = std::move(unique_ptr<ifstream>(new std::ifstream(SH4CoefsFilename, std::ios::in | std::ios::binary)));
pSH5CoefsImporter = std::move(unique_ptr<ifstream>(new std::ifstream(SH5CoefsFilename, std::ios::in | std::ios::binary)));
hasAllSHCoefsTextures =
pIndirectionTextureImporter->is_open() &&
pAmbientVectorImporter->is_open() &&
pSH0CoefsImporter->is_open() &&
pSH1CoefsImporter->is_open() &&
pSH2CoefsImporter->is_open() &&
pSH3CoefsImporter->is_open() &&
pSH4CoefsImporter->is_open() &&
pSH5CoefsImporter->is_open();
return true;
}
void ConvertB8G8R8A8ToR8G8B8A8(Texture_t& tex) {
if ((tex.Format != DXGI_FORMAT_B8G8R8A8_UNORM) && (tex.FormatSize != 4)) return;
for (int i = 0; i < tex.data.size() / 4; i++) {
UINT8 r, g, b, a;
b = tex.data[i * 4 + 0];
g = tex.data[i * 4 + 1];
r = tex.data[i * 4 + 2];
a = tex.data[i * 4 + 3];
tex.data[i * 4 + 0] = r;
tex.data[i * 4 + 1] = g;
tex.data[i * 4 + 2] = b;
tex.data[i * 4 + 3] = a;
}
tex.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
}
void Importer::TransformData() {
INT32 LayoutAllocator = m_BricksNum;
const INT32 MaxBricksInLayoutOneDim = 1 << 8;
DirectX::XMINT3 BrickLayoutDimensions;
BrickLayoutDimensions.x = DirectX::XMMin(LayoutAllocator, MaxBricksInLayoutOneDim);
LayoutAllocator = divideRoundUp(LayoutAllocator, BrickLayoutDimensions.x);
BrickLayoutDimensions.y = DirectX::XMMin(LayoutAllocator, MaxBricksInLayoutOneDim);
LayoutAllocator = divideRoundUp(LayoutAllocator, BrickLayoutDimensions.y);
BrickLayoutDimensions.z = DirectX::XMMin(LayoutAllocator, MaxBricksInLayoutOneDim);
const INT32 DetailCellsPerTopLevelBrick = pow(VLMSetting.BrickSize, VLMSetting.MaxRefinementLevels); // 64
const INT32 IndirectionCellsPerTopLevelCell = DetailCellsPerTopLevelBrick / VLMSetting.BrickSize; // 16
auto& inTexture = vlmData.indirectionTexture;
inTexture.FormatSize = sizeof(DirectX::PackedVector::XMCOLOR);
inTexture.Format = DXGI_FORMAT_R8G8B8A8_UINT;
vlmData.textureDimension.x = VLMSetting.TopLevelGridSize.x * IndirectionCellsPerTopLevelCell;
vlmData.textureDimension.y = VLMSetting.TopLevelGridSize.y * IndirectionCellsPerTopLevelCell;
vlmData.textureDimension.z = VLMSetting.TopLevelGridSize.z * IndirectionCellsPerTopLevelCell;
size_t TotalTextureSize = vlmData.textureDimension.x * vlmData.textureDimension.y * vlmData.textureDimension.z;
inTexture.Resize(TotalTextureSize);
const INT32 PaddedBrickSize = VLMSetting.BrickSize + 1;
vlmData.brickDataDimension.x = BrickLayoutDimensions.x * PaddedBrickSize;
vlmData.brickDataDimension.y = BrickLayoutDimensions.y * PaddedBrickSize;
vlmData.brickDataDimension.z = BrickLayoutDimensions.z * PaddedBrickSize;
const INT32 TotalBrickData = vlmData.brickDataDimension.x * vlmData.brickDataDimension.y * vlmData.brickDataDimension.z;
vlmData.brickData.AmbientVector.FormatSize = sizeof(DirectX::PackedVector::XMFLOAT3PK);
vlmData.brickData.AmbientVector.Format = DXGI_FORMAT_R11G11B10_FLOAT;
vlmData.brickData.AmbientVector.Resize(TotalBrickData);
for (INT32 i = 0; i < 6; i++)
{
vlmData.brickData.SHCoefficients[i].FormatSize = sizeof(DirectX::PackedVector::XMCOLOR);
vlmData.brickData.SHCoefficients[i].Format = DXGI_FORMAT_R8G8B8A8_UNORM;
vlmData.brickData.SHCoefficients[i].Resize(TotalBrickData);
}
vlmData.brickData.DirectionalLightShadowing.FormatSize = sizeof(UINT8);
vlmData.brickData.DirectionalLightShadowing.Format = DXGI_FORMAT_A8_UNORM;
vlmData.brickData.DirectionalLightShadowing.Resize(TotalBrickData);
if (hasAllSHCoefsTextures) {
pIndirectionTextureImporter->read(reinterpret_cast<char*>(inTexture.data.data()), TotalTextureSize * inTexture.FormatSize);
pAmbientVectorImporter->read(reinterpret_cast<char*>(vlmData.brickData.AmbientVector.data.data()), vlmData.brickData.AmbientVector.data.size());
std::vector<std::ifstream*> SHCoefsImporter{ pSH0CoefsImporter.get(), pSH1CoefsImporter.get(), pSH2CoefsImporter.get(), pSH3CoefsImporter.get(), pSH4CoefsImporter.get(), pSH5CoefsImporter.get() };
for (int i = 0; i < 6; i++) {
SHCoefsImporter[i]->read(reinterpret_cast<char*>(vlmData.brickData.SHCoefficients[i].data.data()), vlmData.brickData.SHCoefficients[i].data.size());
}
}
else {
BuildIndirectionTexture(m_BricksByDepth, MaxBricksInLayoutOneDim, BrickLayoutDimensions, inTexture.FormatSize, vlmData);
INT32 BrickIndex = 0;
for (INT32 depth = 0; depth < VLMSetting.MaxRefinementLevels; depth++) {
for (INT32 indexCurrentDepth = 0; indexCurrentDepth < m_BricksByDepth[depth].size(); indexCurrentDepth++) {
const BrickDataImported& brick = m_BricksByDepth[depth][indexCurrentDepth];
DirectX::XMINT3 layoutPos = computePositionByLayout(BrickIndex + indexCurrentDepth, BrickLayoutDimensions);
layoutPos.x *= PaddedBrickSize; layoutPos.y *= PaddedBrickSize; layoutPos.z *= PaddedBrickSize;
CopyBrickToTexture(
vlmData.brickData.AmbientVector.FormatSize,
vlmData.brickDataDimension,
layoutPos,
(UINT8*)(brick.AmbientVector.data()),
(UINT8*)(vlmData.brickData.AmbientVector.data.data())
);
for (INT32 i = 0; i < 6; i++) {
const auto& SHCoef = brick.SHCoefficients[i];
CopyBrickToTexture(
vlmData.brickData.SHCoefficients[i].FormatSize,
vlmData.brickDataDimension,
layoutPos,
(UINT8*)(SHCoef.data()),
(UINT8*)(vlmData.brickData.SHCoefficients[i].data.data())
);
}
}
BrickIndex += m_BricksByDepth[depth].size();
}
ConvertB8G8R8A8ToR8G8B8A8(vlmData.brickData.SkyBentNormal);
for (int i = 0; i < 6; i++)
ConvertB8G8R8A8ToR8G8B8A8(vlmData.brickData.SHCoefficients[i]);
}
}
<file_sep>#pragma once
/********************************************************************************************
* ObjReader.h *
* ObjReader类读取Obj文件并写入自定义二进制文件.mbo,这样可以避免反复读取.obj文件耗时的情况 *
* 由于ObjReader类对.obj格式的文件要求比较严格,如果出现不能正确加载的现象, *
* 请检查是否出现下面这些情况,否则需要自行修改.obj/.mtl文件,或者给ObjReader实现更多的功能: *
* *
* 使用了/将下一行的内容连接在一起表示一行 *
* 存在索引为负数 *
* 使用了类似1//2这样的顶点(即不包含纹理坐标的顶点) *
* 使用了绝对路径的文件引用 *
* 相对路径使用了.和..两种路径格式 *
* 若.mtl材质文件不存在,则内部会使用默认材质值 *
* 若.mtl内部没有指定纹理文件引用,需要另外自行加载纹理 *
* f的顶点数不为3(网格只能以三角形构造,即一个f的顶点数只能为3) *
********************************************************************************************/
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <unordered_map>
#include <map>
#include <algorithm>
#include <locale>
#include <filesystem>
#include "Vertex.h"
#include "light.h"
struct ObjPart {
Material material; // 材质
std::vector<VertexPosNormalTangentTex> vertices; // 顶点集合
std::vector<WORD> indices16; // 顶点数不超过65535时使用
std::vector<DWORD> indices32; // 顶点数超过65535时使用
std::wstring texStrDiffuse;
std::wstring normalMap;
ObjPart() = default;
};
class ObjReader
{
public:
// 有指定.mbo文件时直接读取.mbo, 否则得先都.obj
bool Read(const wchar_t* mboFilename, const wchar_t* objFileName);
bool ReadObj(const wchar_t* objFileName);
bool ReadMbo(const wchar_t* mboFileName);
bool WriteMbo(const wchar_t* mboFileName);
public:
std::vector<ObjPart> objParts;
DirectX::XMFLOAT3 vMin, vMax; // AABB盒双顶点
private:
void AddVertex(const VertexPosNormalTangentTex& vertex, DWORD vpi, DWORD vti, DWORD vni);
// 储存 v/vt/vn 顶点信息
std::unordered_map<std::wstring, DWORD> vertexCache;
};
class MtlReader {
public:
bool ReadMtl(const wchar_t* mtlFileName);
public:
std::map<std::wstring, Material> materials;
std::map<std::wstring, std::wstring> mapKaStrs;
std::map<std::wstring, std::wstring> mapKdStrs;
std::map<std::wstring, std::wstring> mapKsStrs;
std::map<std::wstring, std::wstring> mapDStrs;
std::map<std::wstring, std::wstring> mapBumpStrs;
std::map<std::wstring, std::wstring> BumpStrs;
};
<file_sep>#pragma once
#include <DirectXCollision.h>
#include "Effects.h"
#include "ObjReader.h"
#include "ThridParty/Geometry.h"
#include <map>
/********************************************************************************************
* Model.h *
* 用于管理从.obj文件中读取的模型 *
*********************************************************************************************/
struct ModelPart
{
template<class T>
using ComPtr = Microsoft::WRL::ComPtr<T>;
Material material;
std::wstring texDiffuse;
std::wstring normalMap;
ComPtr<ID3D11ShaderResourceView> pTexDiffuse;
ComPtr<ID3D11ShaderResourceView> pNormalmap;
ComPtr<ID3D11Buffer> vertexBuffer;
ComPtr<ID3D11Buffer> indexBuffer;
UINT indexCount;
UINT vertexCount;
DXGI_FORMAT indexFormat;
ModelPart() : material(), texDiffuse(), vertexBuffer(), indexBuffer(),
indexCount(), vertexCount(), indexFormat() {};
ModelPart(const ModelPart&) = default;
ModelPart& operator=(const ModelPart&) = default;
ModelPart(ModelPart &&) = default;
ModelPart& operator=(ModelPart&&) = default;
};
struct Model {
template<class T>
using ComPtr = Microsoft::WRL::ComPtr<T>;
std::vector<ModelPart> modelParts;
std::map<std::wstring, ComPtr<ID3D11ShaderResourceView>> TexDiffuseMap;
std::map<std::wstring, ComPtr<ID3D11ShaderResourceView>> NormalmapMap;
DirectX::BoundingBox boundingBox;
UINT vertexStride;
Model();
Model(ID3D11Device* device, const ObjReader& model);
// 设置缓冲区
template<class VertexType, class IndexType>
Model(ID3D11Device* device,
const Geometry::MeshData<VertexType, IndexType>& meshData);
template<class VertexType, class IndexType>
Model(ID3D11Device* device,
const std::vector<VertexType>& vertices,
const std::vector<IndexType>& indices);
Model(ID3D11Device* device,
const void * vertices,
UINT vertexSize,
UINT vertexCount,
const void * indices,
UINT indexCount,
DXGI_FORMAT indexFormat);
// 设置模型
void SetModel(ID3D11Device* device, const ObjReader& model);
// 设置网格
template<class VertexType, class IndexType>
void SetMesh(ID3D11Device * device,
const Geometry::MeshData<VertexType, IndexType>& meshData);
template<class VertexType, class IndexType>
void SetMesh(ID3D11Device* device,
const std::vector<VertexType>& vertices,
const std::vector<IndexType>& indices);
void SetMesh(ID3D11Device* device,
const void* vertices,
UINT vertexSize,
UINT vertexCount,
const void* indices,
UINT indexCount,
DXGI_FORMAT indexFormat);
};
// 设置缓冲区
template<class VertexType, class IndexType>
Model::Model(ID3D11Device* device,
const Geometry::MeshData<VertexType, IndexType>& meshData):modelParts(), boundingBox(), vertexStride() {
SetMesh(device, meshData);
}
template<class VertexType, class IndexType>
Model::Model(ID3D11Device* device,
const std::vector<VertexType>& vertices,
const std::vector<IndexType>& indices): modelParts(), boundingBox(), vertexStride() {
SetMesh(device, vertices, indices);
}
template<class VertexType, class IndexType>
inline void Model::SetMesh(ID3D11Device* device, const std::vector<VertexType>& vertices, const std::vector<IndexType>& indices)
{
static_assert(sizeof(IndexType) == 2 || sizeof(IndexType) == 4, "The size of IndexType must be 2 bytes or 4 bytes!");
static_assert(std::is_unsigned<IndexType>::value, "IndexType must be unsigned integer!");
SetMesh(device, vertices.data(), sizeof(VertexType),
(UINT)vertices.size(), indices.data(), (UINT)indices.size(),
(sizeof(IndexType) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT));
}
template<class VertexType, class IndexType>
inline void Model::SetMesh(ID3D11Device* device,
const Geometry::MeshData<VertexType, IndexType>& meshData) {
SetMesh(device, meshData.vertexVec, meshData.indexVec);
}
<file_sep>#include "ObjReader.h"
using namespace DirectX;
bool ObjReader::Read(const wchar_t* mboFilename, const wchar_t* objFileName) {
if ((mboFilename) && ReadMbo(mboFilename)) {
return true;
}
else if (objFileName) {
bool status = ReadObj(objFileName);
if (status && mboFilename) {
return WriteMbo(mboFilename);
}
return status;
}
return false;
}
bool ObjReader::ReadObj(const wchar_t* objFileName) {
// 清楚之前读取的缓存
objParts.clear();
vertexCache.clear();
MtlReader mtlReader;
std::vector<XMFLOAT3> positions;
std::vector<XMFLOAT3> normals;
std::vector<XMFLOAT2> texCoords;
XMVECTOR vecMin = g_XMInfinity, vecMax = g_XMNegInfinity;
// 宽字符输入流
std::wifstream wfin(objFileName);
if (!wfin.is_open()) return false;
std::locale china("chs");
china = wfin.imbue(china);
for (;;) {
std::wstring wstr;
if (!(wfin >> wstr)) break;
if (wstr[0] == '#') {
while (!wfin.eof() && wfin.get() != '\n') continue;
}
// o + objectName g + groupName
else if (wstr == L"o" || wstr == L"g") {
if (objParts.size() > 0 && objParts.back().vertices.size() == 0) {
objParts.pop_back();
}
ObjPart newPart;
// 提供默认材质
newPart.material.ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
newPart.material.diffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
newPart.material.specular = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
objParts.push_back(newPart);
vertexCache.clear();
}
else if (wstr == L"v") {
/************************************************
v:顶点位置, obj文件使用右手坐标系,需要反转z轴
*************************************************/
XMFLOAT3 pos;
wfin >> pos.x >> pos.y >> pos.z;
pos.z = -pos.z;
positions.push_back(pos);
XMVECTOR vecPos = XMLoadFloat3(&pos);
vecMax = XMVectorMax(vecPos, vecMax);
vecMin = XMVectorMin(vecPos, vecMin);
}
else if (wstr == L"vt") {
/************************************************
vertex texture, obj使用的使笛卡尔坐标, 不是纹理坐标系
*************************************************/
float u, v;
wfin >> u >> v;
v = 1.0f - v;
texCoords.push_back(XMFLOAT2(u, v));
}
else if (wstr == L"vn") {
/*************************************************
vertex normal, obj文件使用右手坐标系,需要反转z轴
*************************************************/
float x, y, z;
wfin >> x >> y >> z;
z = -z;
normals.push_back(XMFLOAT3(x, y, z));
}
else if (wstr == L"mtllib") {
// 指定某一文件的材质
std::wstring mtlFile;
wfin >> mtlFile;
//去掉前后空格
size_t beg = 0, ed = mtlFile.size();
while (iswspace(mtlFile[beg])) beg++;
while (ed > beg && iswspace(mtlFile[ed - 1])) ed--;
mtlFile = mtlFile.substr(beg, ed);
// 获取路径
std::wstring dir = objFileName;
size_t pos;
if ((pos = dir.find_last_of('/')) == std::wstring::npos &&
(pos = dir.find_last_of('\\')) == std::wstring::npos) {
pos = 0;
}
else {
pos += 1;
}
mtlReader.ReadMtl((dir.erase(pos) + mtlFile).c_str());
}
else if (wstr == L"usemtl") {
/*
使用之前指定文件内部的某一材质
*/
std::wstring mtlName;
std::getline(wfin, mtlName);
// 去掉前后空格
size_t beg = 0, ed = mtlName.size();
while (iswspace(mtlName[beg])) beg++;
while (ed > beg && iswspace(mtlName[ed - 1])) ed--;
mtlName = mtlName.substr(beg, ed - beg);
if (!objParts.back().texStrDiffuse.empty()) {
ObjPart newPart;
newPart.vertices = objParts.back().vertices;
objParts.push_back(newPart);
}
objParts.back().material = mtlReader.materials[mtlName];
if (mtlReader.mapKdStrs.count(mtlName) > 0) {
objParts.back().texStrDiffuse = mtlReader.mapKdStrs[mtlName];
}
else {
objParts.back().texStrDiffuse = L"";
}
if (mtlReader.mapBumpStrs.count(mtlName) > 0) {
objParts.back().normalMap = mtlReader.mapBumpStrs[mtlName];
}
else {
objParts.back().normalMap = L"";
}
}
else if (wstr == L"f") {
//
// 几何面
//
VertexPosNormalTangentTex vertex;
ZeroMemory(&vertex, sizeof(vertex));
DWORD vpi[3], vni[3], vti[3];
wchar_t ignore;
UINT32 validVertex = 0;
// 原来右手坐标系下顶点顺序是逆时针排布
// 现在需要转变为左手坐标系就需要将三角形顶点反过来输入
for (int i = 2; i >= 0; --i)
{
// 先读取4个字符,然后判断有没有纹理坐标索引
std::wstring tmp;
wfin >> tmp;
bool hasTexture = false;
// 顶点索引/纹理索引/法向量索引
size_t indexSep = tmp.find(L"//");
if (indexSep != std::wstring::npos) {
continue;
}
ULONG index1 = tmp.find(L"/");
std::wstring svpi = tmp.substr(0, index1);
vpi[i] = std::stoul(svpi);
ULONG index2 = tmp.find(L"/", index1 + 1);
std::wstring svti = tmp.substr(index1 + 1, index2 - index1 - 1);
vti[i] = std::stoul(svti);
std::wstring svni = tmp.substr(index2 + 1);
vni[i] = std::stoul(svni);
validVertex++;
}
if (validVertex != 3) {
std::cout << "objRead warning: validVertex !=3 on a same surface" << std::endl;
continue;
}
std::vector<VertexPosNormalTangentTex> triangle;
for (int i = 0; i < 3; ++i) {
vertex.pos = positions[vpi[i] - 1];
vertex.normal = normals[vni[i] - 1];
vertex.tex = texCoords[vti[i] - 1];
triangle.push_back(vertex);
}
CalculeTangent(triangle);
for (int i = 0; i < 3; i++) {
AddVertex(triangle[i], vpi[i], vti[i], vni[i]);
}
while (iswblank(wfin.peek())) wfin.get();
// 几何面顶点数可能超过了3,不支持该格式
if (wfin.peek() != '\n') return false;
}
}
for (auto& part : objParts) {
if (part.vertices.size() < 65535) {
for (auto& i : part.indices32) {
part.indices16.push_back((WORD)i);
}
part.indices32.clear();
}
}
XMStoreFloat3(&vMax, vecMax);
XMStoreFloat3(&vMin, vecMin);
return true;
}
bool ObjReader::ReadMbo(const wchar_t* mboFileName)
{
// [Part数目] 4字节
// [AABB盒顶点vMax] 12字节
// [AABB盒顶点vMin] 12字节
// [Part
// [漫射光材质文件名]520字节
// [hasNormalMap] 1 Byte
// [hasNormalMap ? 520 Bytes : 0 Bytes]
// [材质]64字节
// [顶点数]4字节
// [索引数]4字节
// [顶点]32*顶点数 字节
// [索引]2(或4)*索引数 字节,取决于顶点数是否不超过65535
// ]
// ...
std::ifstream fin(mboFileName, std::ios::in | std::ios::binary);
if (!fin.is_open())
return false;
UINT parts = (UINT)objParts.size();
// [Part数目] 4字节
fin.read(reinterpret_cast<char*>(&parts), sizeof(UINT));
objParts.resize(parts);
// [AABB盒顶点vMax] 12字节
fin.read(reinterpret_cast<char*>(&vMax), sizeof(XMFLOAT3));
// [AABB盒顶点vMin] 12字节
fin.read(reinterpret_cast<char*>(&vMin), sizeof(XMFLOAT3));
for (UINT i = 0; i < parts; ++i)
{
wchar_t filePath[MAX_PATH];
// [漫射光材质文件名]520字节
fin.read(reinterpret_cast<char*>(filePath), MAX_PATH * sizeof(wchar_t));
objParts[i].texStrDiffuse = filePath;
// hasNormalMap 1 byte
UINT8 hasNormalMap;
fin.read(reinterpret_cast<char*>(&hasNormalMap), sizeof(UINT8));
if (hasNormalMap) {
// [NormalMap 520 bytes]
ZeroMemory(filePath, MAX_PATH * sizeof(wchar_t));
fin.read(reinterpret_cast<char*>(filePath), MAX_PATH * sizeof(wchar_t));
objParts[i].normalMap = filePath;
}
// [材质]64字节
fin.read(reinterpret_cast<char*>(&objParts[i].material), sizeof(Material));
UINT vertexCount, indexCount;
// [顶点数]4字节
fin.read(reinterpret_cast<char*>(&vertexCount), sizeof(UINT));
// [索引数]4字节
fin.read(reinterpret_cast<char*>(&indexCount), sizeof(UINT));
// [顶点]32*顶点数 字节
objParts[i].vertices.resize(vertexCount);
fin.read(reinterpret_cast<char*>(objParts[i].vertices.data()), vertexCount * sizeof(VertexPosNormalTangentTex));
if (vertexCount > 65535)
{
// [索引]4*索引数 字节
objParts[i].indices32.resize(indexCount);
fin.read(reinterpret_cast<char*>(objParts[i].indices32.data()), indexCount * sizeof(DWORD));
}
else
{
// [索引]2*索引数 字节
objParts[i].indices16.resize(indexCount);
fin.read(reinterpret_cast<char*>(objParts[i].indices16.data()), indexCount * sizeof(WORD));
}
}
fin.close();
return true;
}
bool ObjReader::WriteMbo(const wchar_t* mboFileName)
{
// [Part数目] 4字节
// [AABB盒顶点vMax] 12字节
// [AABB盒顶点vMin] 12字节
// [Part
// [漫射光材质文件名]520字节
// [hasNormalMap] 1 Byte
// [hasNormalMap ? 520 Bytes : 0 Bytes]
// [材质]64字节
// [顶点数]4字节
// [索引数]4字节
// [顶点]32*顶点数 字节
// [索引]2(或4)*索引数 字节,取决于顶点数是否不超过65535
// ]
// ...
std::ofstream fout(mboFileName, std::ios::out | std::ios::binary);
UINT parts = (UINT)objParts.size();
// [Part数目] 4字节
fout.write(reinterpret_cast<const char*>(&parts), sizeof(UINT));
// [AABB盒顶点vMax] 12字节
fout.write(reinterpret_cast<const char*>(&vMax), sizeof(XMFLOAT3));
// [AABB盒顶点vMin] 12字节
fout.write(reinterpret_cast<const char*>(&vMin), sizeof(XMFLOAT3));
// [Part
for (UINT i = 0; i < parts; ++i)
{
wchar_t filePath[MAX_PATH];
wcscpy_s(filePath, objParts[i].texStrDiffuse.c_str());
// [漫射光材质文件名]520字节
fout.write(reinterpret_cast<const char*>(filePath), MAX_PATH * sizeof(wchar_t));
// hasNormalMap 1 byte
UINT8 hasNormalMap = objParts[i].normalMap.size() > 0;
fout.write(reinterpret_cast<const char*>(&hasNormalMap), sizeof(UINT8));
if (hasNormalMap) {
// [NormalMap 520 bytes]
ZeroMemory(filePath, MAX_PATH);
wcscpy_s(filePath, objParts[i].normalMap.c_str());
fout.write(reinterpret_cast<const char*>(filePath), MAX_PATH * sizeof(wchar_t));
}
// [材质]64字节
fout.write(reinterpret_cast<const char*>(&objParts[i].material), sizeof(Material));
UINT vertexCount = (UINT)objParts[i].vertices.size();
// [顶点数]4字节
fout.write(reinterpret_cast<const char*>(&vertexCount), sizeof(UINT));
UINT indexCount;
if (vertexCount > 65535)
{
indexCount = (UINT)objParts[i].indices32.size();
// [索引数]4字节
fout.write(reinterpret_cast<const char*>(&indexCount), sizeof(UINT));
// [顶点]32*顶点数 字节
fout.write(reinterpret_cast<const char*>(objParts[i].vertices.data()), vertexCount * sizeof(VertexPosNormalTangentTex));
// [索引]4*索引数 字节
fout.write(reinterpret_cast<const char*>(objParts[i].indices32.data()), indexCount * sizeof(DWORD));
}
else
{
indexCount = (UINT)objParts[i].indices16.size();
// [索引数]4字节
fout.write(reinterpret_cast<const char*>(&indexCount), sizeof(UINT));
// [顶点]32*顶点数 字节
fout.write(reinterpret_cast<const char*>(objParts[i].vertices.data()), vertexCount * sizeof(VertexPosNormalTangentTex));
// [索引]2*索引数 字节
fout.write(reinterpret_cast<const char*>(objParts[i].indices16.data()), indexCount * sizeof(WORD));
}
}
// ]
fout.close();
return true;
}
void ObjReader::AddVertex(const VertexPosNormalTangentTex& vertex, DWORD vpi, DWORD vti, DWORD vni)
{
std::wstring idxStr = std::to_wstring(vpi) + L"/" + std::to_wstring(vti) + L"/" + std::to_wstring(vni);
// 寻找是否有重复顶点
auto it = vertexCache.find(idxStr);
if (it != vertexCache.end())
{
objParts.back().indices32.push_back(it->second);
}
else
{
objParts.back().vertices.push_back(vertex);
DWORD pos = (DWORD)objParts.back().vertices.size() - 1;
vertexCache[idxStr] = pos;
objParts.back().indices32.push_back(pos);
}
}
inline void mapping_mat_texture(const wchar_t* mtlFileName, std::wifstream& wfin, std::map<std::wstring, std::wstring>& map, const std::wstring& curMatName) {
std::wstring fileName;
std::getline(wfin, fileName);
// 去掉前后空格
size_t beg = 0, ed = fileName.size();
while (iswspace(fileName[beg]))
beg++;
while (ed > beg && iswspace(fileName[ed - 1]))
ed--;
fileName = fileName.substr(beg, ed - beg);
// 追加路径
std::wstring dir = mtlFileName;
size_t pos;
if ((pos = dir.find_last_of('/')) == std::wstring::npos &&
(pos = dir.find_last_of('\\')) == std::wstring::npos)
pos = 0;
else
pos += 1;
map[curMatName] = dir.erase(pos) + fileName;
}
bool MtlReader::ReadMtl(const wchar_t* mtlFileName)
{
materials.clear();
mapKdStrs.clear();
std::wifstream wfin(mtlFileName);
std::locale china("chs");
china = wfin.imbue(china);
if (!wfin.is_open())
return false;
std::wstring wstr;
std::wstring currMtl;
for (;;) {
if (!(wfin >> wstr)) break;
if (wstr[0] == '#') {
//
// 忽略注释所在行
//
while (wfin.get() != '\n')
continue;
}
else if (wstr == L"newmtl") {
//
// 新材质
//
std::getline(wfin, currMtl);
// 去掉前后空格
size_t beg = 0, ed = currMtl.size();
while (iswspace(currMtl[beg]))
beg++;
while (ed > beg && iswspace(currMtl[ed - 1]))
ed--;
currMtl = currMtl.substr(beg, ed - beg);
}
else if (wstr == L"Ka")
{
//
// 环境光反射颜色
//
XMFLOAT4& ambient = materials[currMtl].ambient;
wfin >> ambient.x >> ambient.y >> ambient.z;
if (ambient.w == 0.0f)
ambient.w = 1.0f;
}
else if (wstr == L"Kd")
{
//
// 漫射光反射颜色
//
XMFLOAT4& diffuse = materials[currMtl].diffuse;
wfin >> diffuse.x >> diffuse.y >> diffuse.z;
if (diffuse.w == 0.0f)
diffuse.w = 1.0f;
}
else if (wstr == L"Ks")
{
//
// 镜面光反射颜色
//
XMFLOAT4& specular = materials[currMtl].specular;
wfin >> specular.x >> specular.y >> specular.z;
}
else if (wstr == L"Ns")
{
//
// 镜面系数
//
wfin >> materials[currMtl].specular.w;
}
else if (wstr == L"d" || wstr == L"Tr")
{
//
// d为不透明度 Tr为透明度
//
float alpha;
wfin >> alpha;
if (wstr == L"Tr")
alpha = 1.0f - alpha;
materials[currMtl].ambient.w = alpha;
materials[currMtl].diffuse.w = alpha;
}
else if (wstr == L"map_Ka")
{
mapping_mat_texture(mtlFileName, wfin, mapKaStrs, currMtl);
}
else if (wstr == L"map_Kd")
{
mapping_mat_texture(mtlFileName, wfin, mapKdStrs, currMtl);
}
else if (wstr == L"map_Ks")
{
mapping_mat_texture(mtlFileName, wfin, mapKsStrs, currMtl);
}
else if (wstr == L"map_d")
{
mapping_mat_texture(mtlFileName, wfin, mapDStrs, currMtl);
}
else if (wstr == L"map_bump") {
mapping_mat_texture(mtlFileName, wfin, mapBumpStrs, currMtl);
}
else if (wstr == L"bump") {
mapping_mat_texture(mtlFileName, wfin, BumpStrs, currMtl);
}
}
return true;
}
<file_sep>#include "Ex13Shadow.h"
using namespace DirectX;
Ex13Shadow::Ex13Shadow(HINSTANCE hInstance)
:D3DApp(hInstance),
m_CameraMode(CameraMode::TPS),
m_ShadowMat(),
m_WoodCrateMat(){
}
Ex13Shadow::~Ex13Shadow() {
}
bool Ex13Shadow::Init() {
if (!D3DApp::Init()) return false;
RenderStates::InitAll(m_pd3dDevice.Get());
if (!m_BasicEffect.SetVSShader3D(m_pd3dDevice.Get(), L"HLSL\\Ex13_VS3D.hlsl")) return false;
if (!m_BasicEffect.SetPSShader3D(m_pd3dDevice.Get(), L"HLSL\\Ex13_PS3D.hlsl")) return false;;
if (!m_BasicEffect.InitAll(m_pd3dDevice.Get()))
return false;
if (!InitResource()) return false;
m_pMouse->SetWindow(m_hMainWnd);
m_pMouse->SetMode(Mouse::MODE_RELATIVE);
return true;
}
void Ex13Shadow::OnResize() {
D3DApp::OnResize();
if (m_pCamera != nullptr) {
m_pCamera->SetFrustum(XM_PI / 3, AspectRatio(), 0.5f, 1000.0f);
m_pCamera->SetViewPort(0.0f, 0.0f, (float)m_ClientWidth, (float)m_ClientHeight);
m_BasicEffect.SetProjMatrix(m_pCamera->GetProjXM());
}
}
void Ex13Shadow::UpdateScene(float dt)
{
// 获取鼠标状态
Mouse::State mouseState = m_pMouse->GetState();
Mouse::State lastMouseState = m_MouseTracker.GetLastState();
// 获取键盘状态
Keyboard::State keyState = m_pKeyboard->GetState();
Keyboard::State lastKeyState = m_KeyboardTracker.GetLastState();
m_MouseTracker.Update(mouseState);
m_KeyboardTracker.Update(keyState);
Transform& woodCrateTransform = m_WoodCrate.GetTransform();
auto cam1st = std::dynamic_pointer_cast<FPSCamera>(m_pCamera);
auto cam3rd = std::dynamic_pointer_cast<TPSCamera>(m_pCamera);
if (m_CameraMode == CameraMode::FPS || m_CameraMode == CameraMode::Free) {
// FPS mode
if (keyState.IsKeyDown(Keyboard::W)) {
if (m_CameraMode == CameraMode::FPS) {
cam1st->Walk(dt * 5.0f);
}
else {
cam1st->MoveForward(dt * 5.0f);
}
}
if (keyState.IsKeyDown(Keyboard::S)) {
if (m_CameraMode == CameraMode::FPS) {
cam1st->Walk(-dt * 5.0f);
}
else {
cam1st->MoveForward(-dt * 5.0f);
}
}
if (keyState.IsKeyDown(Keyboard::D)) cam1st->Strafe(dt * 5.0f);
if (keyState.IsKeyDown(Keyboard::A)) cam1st->Strafe(-dt * 5.0f);
// 限制摄像机在固定范围内 x(-8.9, 8.9), z(-8.9, 8.9), y(0, 8.9) y不能为负
XMFLOAT3 adjustPos;
// XMVectorClamp(V, min, max) 将V的每个分量限定在[min, max]范围
XMStoreFloat3(&adjustPos, XMVectorClamp(cam1st->GetPositionXM(), XMVectorSet(-8.9f, 0.0f, -8.9f, 0.0f), XMVectorReplicate(8.9f)));
cam1st->SetPosition(adjustPos);
// 只有第一人称才是摄像机和箱子都移动
if (m_CameraMode == CameraMode::FPS) woodCrateTransform.SetPosition(adjustPos);
if (mouseState.positionMode == Mouse::MODE_RELATIVE) {
cam1st->Pitch(mouseState.y * dt * 2.5f);
cam1st->RotateY(mouseState.x * dt * 2.5f);
}
}
else if (m_CameraMode == CameraMode::Observe) {
// 更新摄像机目标位置
cam3rd->SetTarget(woodCrateTransform.GetPosition());
// 摄像机绕目标旋转
cam3rd->RotateX(mouseState.y * dt * 2.5f);
cam3rd->RotateY(mouseState.x * dt * 2.5f);
cam3rd->Approach(mouseState.scrollWheelValue / 120 * 1.0f);
}
else if (m_CameraMode == CameraMode::TPS) {
if (keyState.IsKeyDown(Keyboard::W)) {
woodCrateTransform.Translate(woodCrateTransform.GetForwardAxis(), dt * 5.0f);
}
if (keyState.IsKeyDown(Keyboard::S)) {
woodCrateTransform.Translate(woodCrateTransform.GetForwardAxis(), -dt * 5.0f);
}
if (keyState.IsKeyDown(Keyboard::D))
woodCrateTransform.Translate(woodCrateTransform.GetRightAxis(), dt * 5.0f);
if (keyState.IsKeyDown(Keyboard::A))
woodCrateTransform.Translate(woodCrateTransform.GetRightAxis(), -dt * 5.0f);
XMFLOAT3 adjustPos;
XMStoreFloat3(&adjustPos, XMVectorClamp(woodCrateTransform.GetPositionXM(), XMVectorSet(-8.9f, 0.0f, -8.9f, 0.0f), XMVectorReplicate(8.9f)));
woodCrateTransform.SetPosition(adjustPos);
cam3rd->SetTarget(woodCrateTransform.GetPosition());
woodCrateTransform.RotateAxis(XMFLOAT3(0.0f, 1.0f, 0.0f), mouseState.x * dt * 2.5f);
cam3rd->RotateX(mouseState.y * dt * 2.5f);
cam3rd->RotateY(mouseState.x * dt * 2.5f);
cam3rd->Approach(mouseState.scrollWheelValue / 120 * 1.0f);
}
// 更新观察矩阵
m_BasicEffect.SetViewMatrix(m_pCamera->GetViewXM());
m_BasicEffect.SetEyePos(m_pCamera->GetPositionXM());
// 重置滚轮
m_pMouse->ResetScrollWheelValue();
// 切换到FPS模式
if (keyState.IsKeyDown(Keyboard::D1) && m_CameraMode != CameraMode::FPS) {
if (!cam1st) {
cam1st.reset(new FPSCamera);
cam1st->SetFrustum(XM_PI / 3, AspectRatio(), 0.5f, 1000.0f);
m_pCamera = cam1st;
}
cam1st->LookTo(woodCrateTransform.GetPosition(),
XMFLOAT3(0.0f, 0.0f, 1.0f),
XMFLOAT3(0.0f, 1.0f, 0.0f));
m_CameraMode = CameraMode::FPS;
}
// 切换到TPS模式
else if (m_KeyboardTracker.IsKeyPressed(Keyboard::D2) && m_CameraMode != CameraMode::Observe) {
if (!cam3rd) {
cam3rd.reset(new TPSCamera);
cam3rd->SetFrustum(XM_PI / 3, AspectRatio(), 0.5f, 1000.0f);
m_pCamera = cam3rd;
}
XMFLOAT3 target = woodCrateTransform.GetPosition();
cam3rd->SetTarget(target);
cam3rd->SetDistance(8.0f);
cam3rd->SetDistMinMax(3.0f, 20.0f);
m_CameraMode = CameraMode::Observe;
}
else if (m_KeyboardTracker.IsKeyPressed(Keyboard::D3) && m_CameraMode != CameraMode::Free) {
if (!cam1st) {
cam1st.reset(new FPSCamera);
cam1st->SetFrustum(XM_PI / 3, AspectRatio(), 0.5f, 1000.0f);
m_pCamera = cam1st;
}
XMFLOAT3 pos = woodCrateTransform.GetPosition();
XMFLOAT3 to = XMFLOAT3(0.0f, 0.0f, 1.0f);
XMFLOAT3 up = XMFLOAT3(0.0f, 1.0f, 0.0f);
pos.y += 3;
cam1st->LookTo(pos, to, up);
m_CameraMode = CameraMode::Free;
}
else if (m_KeyboardTracker.IsKeyPressed(Keyboard::D4) && m_CameraMode != CameraMode::TPS) {
if (!cam3rd) {
cam3rd.reset(new TPSCamera);
cam3rd->SetFrustum(XM_PI / 3, AspectRatio(), 0.5f, 1000.0f);
m_pCamera = cam3rd;
}
XMFLOAT3 target = woodCrateTransform.GetPosition();
cam3rd->SetTarget(target);
cam3rd->SetDistance(8.0f);
cam3rd->SetDistMinMax(3.0f, 20.0f);
m_CameraMode = CameraMode::TPS;
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::Escape)) {
SendMessage(MainWnd(), WM_DESTROY, 0, 0);
}
}
void Ex13Shadow::DrawScene()
{
assert(m_pd3dImmediateContext);
assert(m_pSwapChain);
m_pd3dImmediateContext->ClearRenderTargetView(m_pRenderTargetView.Get(), reinterpret_cast<const float*>(&DirectX::Colors::White));
m_pd3dImmediateContext->ClearDepthStencilView(m_pDepthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
/************************
1. 绘制物体
*************************/
m_BasicEffect.SetRenderDefault(m_pd3dImmediateContext.Get());
m_BasicEffect.SetTextureUsed(true);
for (auto& wall : m_Walls)
wall.Draw(m_pd3dImmediateContext.Get(), m_BasicEffect);
m_Floor.Draw(m_pd3dImmediateContext.Get(), m_BasicEffect);
m_WoodCrate.Draw(m_pd3dImmediateContext.Get(), m_BasicEffect);
/************************
2. 绘制阴影
*************************/
m_WoodCrate.SetMaterial(m_ShadowMat);
m_BasicEffect.SetShadowState(true); // 反射关闭,阴影开启
m_BasicEffect.SetTextureUsed(false);
m_BasicEffect.SetRenderNoDoubleBlend(m_pd3dImmediateContext.Get(), 0);
m_WoodCrate.Draw(m_pd3dImmediateContext.Get(), m_BasicEffect);
m_BasicEffect.SetShadowState(false); // 阴影关闭
m_WoodCrate.SetMaterial(m_WoodCrateMat);
HR(m_pSwapChain->Present(0, 0));
}
bool Ex13Shadow::InitResource()
{
/*******************
初始化纹理
********************/
ComPtr<ID3D11ShaderResourceView> texture;
// 初始材质
Material material{};
material.ambient = XMFLOAT4(0.4f, 0.4f, 0.4f, 1.0f);
material.diffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
material.specular = XMFLOAT4(0.1f, 0.1f, 0.1f, 16.0f);
// 阴影材质,形成阴影效果
m_WoodCrateMat = material;
m_ShadowMat.ambient = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
m_ShadowMat.diffuse = XMFLOAT4(0.0f, 0.0f, 0.0f, 0.5f);
m_ShadowMat.specular = XMFLOAT4(0.0f, 0.0f, 0.0f, 16.0f);
// 读取木箱贴图,设置木箱的材质和贴图以及所处的世界空间位置
HR(CreateDDSTextureFromFile(m_pd3dDevice.Get(), L"Texture\\WoodCrate.dds", nullptr, texture.GetAddressOf()));
m_WoodCrate.SetModel(Model(m_pd3dDevice.Get(), Geometry::CreateBox()));
m_WoodCrate.GetTransform().SetPosition(0.0f, 0.01f, 0.0f);
m_WoodCrate.SetTexture(texture.Get());
m_WoodCrate.SetMaterial(material);
// 读取地板贴图,设置地板的材质和贴图,以及地板的位置
HR(CreateDDSTextureFromFile(m_pd3dDevice.Get(), L"Texture\\floor.dds", nullptr, texture.GetAddressOf()));
m_Floor.SetModel(Model(m_pd3dDevice.Get(),
Geometry::CreatePlane(XMFLOAT2(20.0f, 20.0f), XMFLOAT2(5.0f, 5.0f))));
m_Floor.SetTexture(texture.Get());
m_Floor.SetMaterial(material);
m_Floor.GetTransform().SetPosition(0.0f, -1.0f, 0.0f);
/*************************************
g_Walls[0]
初始化墙壁 (0, 3, 10)
________________
/ | / |
/ | / |
/___|___________/ |
| |_ _ _ _ _ _|_ _|
| / | / g_Walls[1]
(-10, 3, 0) | / | / (10, 3, 0)
g_Walls[3] |/______________|/
(0, 3, -10)
width g_Walls[2]
*************************************/
m_Walls.resize(4);
HR(CreateDDSTextureFromFile(m_pd3dDevice.Get(), L"Texture\\brick.dds", nullptr, texture.GetAddressOf()));
for (int i = 0; i < m_Walls.size(); i++) {
m_Walls[i].SetModel(Model(m_pd3dDevice.Get(),
Geometry::CreatePlane(XMFLOAT2(20.0f, 8.0f), XMFLOAT2(5.0f, 1.5f))));
m_Walls[i].SetMaterial(material);
m_Walls[i].SetTexture(texture.Get());
Transform& transform = m_Walls[i].GetTransform();
transform.SetRotation(-XM_PIDIV2, XM_PIDIV2 * i, 0.0f);
transform.SetPosition(i % 2 ? -10.0f * (i - 2) : 0.0f, 3.0f, i % 2 == 0 ? -10.0f * (i - 1) : 0.0f);
}
/*******************************
初始化摄像机, 默认第三人称视角
********************************/
m_CameraMode = CameraMode::TPS;
auto camera = std::shared_ptr<TPSCamera>(new TPSCamera);
m_pCamera = camera;
camera->SetViewPort(0.0f, 0.0f, (float)m_ClientWidth, (float)m_ClientHeight);
camera->SetDistance(5.0f);
camera->SetDistMinMax(2.0f, 14.0f);
camera->SetRotationX(XM_PIDIV2);
/**********************************************
设置观察矩阵和观察位置,设置平截头体和投影矩阵
***********************************************/
m_BasicEffect.SetViewMatrix(m_pCamera->GetViewXM());
m_BasicEffect.SetEyePos(m_pCamera->GetPositionXM());
m_pCamera->SetFrustum(XM_PI / 3, AspectRatio(), 0.5f, 1000.0f);
m_BasicEffect.SetProjMatrix(m_pCamera->GetProjXM());
//m_BasicEffect.SetReflectionMatrix(XMMatrixReflect(XMVectorSet(0.0f, 0.0f, -1.0f, 10.0f)));
/******************
* 初始化默认光照 *
*******************/
// 环境光
DirectionalLight dirLight;
dirLight.ambient = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
dirLight.diffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
dirLight.specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
dirLight.direction = XMFLOAT3(0.0f, -1.0f, 0.0f);
m_BasicEffect.SetDirLight(0, dirLight);
// 灯光,range会阴影光圈的范围
PointLight pointLight;
pointLight.position = XMFLOAT3(0.0f, 10.0f, 20.0f);
pointLight.ambient = XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f);
pointLight.diffuse = XMFLOAT4(0.6f, 0.6f, 0.6f, 1.0f);
pointLight.specular = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
pointLight.att = XMFLOAT3(0.0f, 0.1f, 0.0f);
pointLight.range = 100.0f;
m_BasicEffect.SetPointLight(0, pointLight);
/*
设置阴影矩阵
稍微高一点位置以显示阴影
*/
m_BasicEffect.SetShadowMatrix(XMMatrixShadow(XMVectorSet(0.0f, 1.0f, 0.0f, 0.99f),
XMVectorSet(pointLight.position.x, pointLight.position.y, pointLight.position.z, 1.0f)));
//m_BasicEffect.SetRefShadowMatrix(XMMatrixShadow(XMVectorSet(0.0f, 1.0f, 0.0f, 0.99f), XMVectorSet(0.0f, 10.0f, 30.0f, 1.0f)));
return true;
}
<file_sep>//***************************************************************************************
// Effects.h by X_Jun(MKXJun) (C) 2018-2020 All Rights Reserved.
// Licensed under the MIT License.
//
// 简易特效管理框架
// Simple effect management framework.
//***************************************************************************************
#ifndef EFFECTS_H
#define EFFECTS_H
#include <memory>
#include "light.h"
#include "RenderStates.h"
class IEffect
{
public:
// 使用模板别名(C++11)简化类型名
template <class T>
using ComPtr = Microsoft::WRL::ComPtr<T>;
IEffect() = default;
virtual ~IEffect() = default;
// 不允许拷贝,允许移动
IEffect(const IEffect&) = delete;
IEffect& operator=(const IEffect&) = delete;
IEffect(IEffect&&) = default;
IEffect& operator=(IEffect&&) = default;
// 更新并绑定常量缓冲区
virtual void Apply(ID3D11DeviceContext* deviceContext) = 0;
};
class BasicEffect : public IEffect
{
public:
BasicEffect();
virtual ~BasicEffect() override;
BasicEffect(BasicEffect&& moveFrom) noexcept;
BasicEffect& operator=(BasicEffect&& moveFrom) noexcept;
// 获取单例
static BasicEffect& Get();
// 初始化所需资源
bool InitAll(ID3D11Device* device);
bool SetVSShader2D(ID3D11Device* device, const WCHAR* hlslFile);
bool SetVSShader3D(ID3D11Device* device, const WCHAR* hlslFile);
bool SetInstanceVS(ID3D11Device* device, const WCHAR* hlslFile);
bool SetInstancePS(ID3D11Device* device, const WCHAR* hlslFile);
bool SetPSShader2D(ID3D11Device* device, const WCHAR* hlslFile);
bool SetPSShader3D(ID3D11Device* device, const WCHAR* hlslFile);
//
// 渲染模式的变更
//
void SetRenderInstanceDefault(ID3D11DeviceContext* deviceContext);
// 默认状态来绘制
void SetRenderDefault(ID3D11DeviceContext* deviceContext);
// Alpha混合绘制
void SetRenderAlphaBlend(ID3D11DeviceContext* deviceContext);
// 无二次混合
void SetRenderNoDoubleBlend(ID3D11DeviceContext* deviceContext, UINT stencilRef);
// 仅写入模板值
void SetWriteStencilOnly(ID3D11DeviceContext* deviceContext, UINT stencilRef);
// 对指定模板值的区域进行绘制,采用默认状态
void SetRenderDefaultWithStencil(ID3D11DeviceContext* deviceContext, UINT stencilRef);
// 对指定模板值的区域进行绘制,采用Alpha混合
void SetRenderAlphaBlendWithStencil(ID3D11DeviceContext* deviceContext, UINT stencilRef);
// 2D默认状态绘制
void Set2DRenderDefault(ID3D11DeviceContext* deviceContext);
// 2D混合绘制
void Set2DRenderAlphaBlend(ID3D11DeviceContext* deviceContext);
// 线框模式
void SetWireFrameWode(ID3D11DeviceContext* deviceContext);
//
// 矩阵设置
//
void XM_CALLCONV SetWorldMatrix(DirectX::FXMMATRIX W);
void XM_CALLCONV SetViewMatrix(DirectX::FXMMATRIX V);
void XM_CALLCONV SetProjMatrix(DirectX::FXMMATRIX P);
void XM_CALLCONV SetReflectionMatrix(DirectX::FXMMATRIX R);
void XM_CALLCONV SetShadowMatrix(DirectX::FXMMATRIX S);
void XM_CALLCONV SetRefShadowMatrix(DirectX::FXMMATRIX RefS);
//
// 光照、材质和纹理相关设置
//
// 各种类型灯光允许的最大数目
static const int maxDirLights = 1;
static const int maxPointLights = 22;
static const int maxSpotLights = 2;
bool isShadow;
bool useNormalmap;
void SetDirLight(size_t pos, const DirectionalLight& dirLight);
void SetPointLight(size_t pos, const PointLight& pointLight);
void SetSpotLight(size_t pos, const SpotLight& spotLight);
void SetDirLightNums(int num);
void SetPointLightNums(int num);
void SetSpotLightNums(int num);
void SetMaterial(const Material& material);
void SetNormalMap(ID3D11ShaderResourceView* normalMap);
void UseNormalMap(bool isUsed);
bool GetUseNormalMap();
void SetTexture(ID3D11ShaderResourceView* texture);
void SetTexture2D(ID3D11ShaderResourceView* texture);
void SetTexture3D(ID3D11ShaderResourceView* texture);
void SetRWTexture3D(ID3D11UnorderedAccessView* texture);
void ClearTexture3D();
void XM_CALLCONV SetEyePos(DirectX::FXMVECTOR eyePos);
// Volumetric Lightmap 设置
void SetVLMWorldToUVScale(DirectX::XMFLOAT3 VLMWorldToUVScale);
void SetVLMWorldToUVAdd(DirectX::XMFLOAT3 VLMWorldToUVAdd);
void SetVLMIndirectionTextureSize(DirectX::XMFLOAT3 indirectionTextureSize);
void SetVLMBrickSize(float brickSize);
void SetVLMBrickTexelSize(DirectX::XMFLOAT3 VLMBrickTexelSize);
void SetSHMode(int);
void SetSphereSpeed(int SphereSpeed);
//
// 状态开关设置
//
void SetReflectionState(bool isOn);
void SetShadowState(bool isOn);
void SetTextureUsed(bool isOn);
void SetSHUsed(bool isOn);
void SetLightUsed(bool isOn);
void SetDirLightUsed(bool isOn);
void SetPointLightUsed(bool isOn);
// 应用常量缓冲区和纹理资源的变更
void Apply(ID3D11DeviceContext* deviceContext);
void SetDebugName();
private:
class Impl;
std::unique_ptr<Impl> pImpl;
};
#endif<file_sep>#pragma once
#include <d3d11.h>
#include <DirectXMath.h>
#include <vector>
struct VertexPosNormalColor {
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT3 noraml;
DirectX::XMFLOAT4 color;
static const D3D11_INPUT_ELEMENT_DESC inputLayout[3];
};
struct VertexPosNormal {
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT3 noraml;
static const D3D11_INPUT_ELEMENT_DESC inputLayout[2];
};
struct VertexPosTex {
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT2 tex;
static const D3D11_INPUT_ELEMENT_DESC inputLayout[2];
};
struct VertexPosNormalTex {
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT3 normal;
DirectX::XMFLOAT2 tex;
static const D3D11_INPUT_ELEMENT_DESC inputLayout[3];
};
struct Instances {
DirectX::XMMATRIX world;
DirectX::XMMATRIX worldInvTranspose;
static const D3D11_INPUT_ELEMENT_DESC inputLayout[10];
};
struct VertexPosNormalTangentTex {
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT3 normal;
DirectX::XMFLOAT4 tangent;
DirectX::XMFLOAT2 tex;
static const D3D11_INPUT_ELEMENT_DESC inputLayout[4];
};
void CalculeTangent(std::vector<VertexPosNormalTangentTex>& triangle);
<file_sep>#ifndef Ex7Light_H
#define Ex7Light_H
#include "d3dApp.h"
#include "light.h"
#include "ThridParty/Geometry.h"
/*******************************************
Ex7:
能建立基础的几何图形,以及三种光照模型
********************************************/
class Ex7Light : public D3DApp {
public:
struct VSConstantBuffer {
DirectX::XMMATRIX world;
DirectX::XMMATRIX view;
DirectX::XMMATRIX proj;
DirectX::XMMATRIX worldInvTranspose;
};
struct PSConstantBuffer {
DirectionalLight dirLight;
PointLight pointLight;
SpotLight spotLight;
Material material;
DirectX::XMFLOAT4 eyePos;
};
public:
Ex7Light(HINSTANCE hInstance);
virtual ~Ex7Light();
bool Init();
void OnResize();
void UpdateScene(float dt);
void DrawScene();
protected:
bool InitEffect();
bool InitResource();
bool ResetMesh(const Geometry::MeshData<VertexPosNormalColor>& meshData);
ComPtr<ID3D11InputLayout> m_pVertexLayout; // 顶点输入布局
ComPtr<ID3D11Buffer> m_pVertexBuffer; // 顶点缓冲区
ComPtr<ID3D11Buffer> m_pIndexBuffer; // 索引缓冲区
ComPtr<ID3D11Buffer> m_pConstantBuffer[2]; // 常量缓冲区
UINT m_IndexCount;
ComPtr<ID3D11VertexShader> m_pVertexShader; // 顶点着色器
ComPtr<ID3D11PixelShader> m_pPixelShader; // 像素着色器
VSConstantBuffer m_VSConstantBuffer; // 储存了各种变换矩阵
PSConstantBuffer m_PSConstantBuffer;
// 光照模型
DirectionalLight m_DirLight;
PointLight m_PointLight;
SpotLight m_SpotLight;
ComPtr<ID3D11RasterizerState> m_pRSWireframe; //光栅化状态,切换线框模式
bool m_IsWireframeMode;
};
#endif<file_sep>#include "RenderSponza.h"
using namespace DirectX;
RenderSponza::RenderSponza(HINSTANCE hInstance)
:D3DApp(hInstance),
m_ShadowMat(),
m_Material(),
m_CameraMode(CameraMode::FPS),
m_ObjReader(),
m_Speed(500),
m_BackGroundColor(Colors::White),
m_IsWireframeMode(false),
m_UseSH(true),
m_UseTexture(true),
m_UseLight(false),
m_UseDirLight(false),
m_UsePointLight(false),
m_SHMode(2),
m_isVisulizeVLM(false),
m_SphereSpeed(200),
m_Text(L""),
m_SHRepositoies{ L"50_metal", L"200", L"150", L"100", L"50" },
m_SHFileIndex(0), m_isControlObj(false), m_TargetDistance(100){
}
RenderSponza::~RenderSponza() {
}
bool RenderSponza::Init() {
if (!D3DApp::Init()) return false;
RenderStates::InitAll(m_pd3dDevice.Get());
if (!m_BasicEffect.SetVSShader3D(m_pd3dDevice.Get(), L"HLSL\\RenderSponza_VS3D.hlsl")) return false;
if (!m_BasicEffect.SetPSShader3D(m_pd3dDevice.Get(), L"HLSL\\RenderSponza_PS3D.hlsl")) return false;
if (!m_BasicEffect.SetInstanceVS(m_pd3dDevice.Get(), L"HLSL\\InstancesVertexShader.hlsl")) return false;
if (!m_BasicEffect.SetInstancePS(m_pd3dDevice.Get(), L"HLSL\\InstancesPixelShader.hlsl")) return false;
if (!m_BasicEffect.InitAll(m_pd3dDevice.Get())) return false;
if (!InitVLM()) return false;
if (!InitResource()) return false;
m_BasicEffect.SetSHMode(m_SHMode);
m_BasicEffect.SetDebugName();
m_pMouse->SetWindow(m_hMainWnd);
m_pMouse->SetMode(Mouse::Mode::MODE_RELATIVE);
return true;
}
void RenderSponza::OnResize() {
assert(m_pd2dFactory);
assert(m_pdwriteFactory);
// 释放D2D的相关资源
m_pColorBrush.Reset();
m_pd2dRenderTarget.Reset();
D3DApp::OnResize();
// 为D2D创建DXGI表面渲染目标
ComPtr<IDXGISurface> surface;
HR(m_pSwapChain->GetBuffer(0, __uuidof(IDXGISurface), reinterpret_cast<void**>(surface.GetAddressOf())));
D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(
D2D1_RENDER_TARGET_TYPE_DEFAULT,
D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED));
HR(m_pd2dFactory->CreateDxgiSurfaceRenderTarget(surface.Get(), &props, m_pd2dRenderTarget.GetAddressOf()));
surface.Reset();
HR(m_pd2dRenderTarget->CreateSolidColorBrush(
D2D1::ColorF(D2D1::ColorF::White),
m_pColorBrush.GetAddressOf()));
HR(m_pdwriteFactory->CreateTextFormat(L"宋体", nullptr, DWRITE_FONT_WEIGHT_NORMAL,
DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 15, L"zh-cn",
m_pTextFormat.GetAddressOf()));
if (m_pCamera != nullptr) {
m_pCamera->SetFrustum(XM_PI / 3, AspectRatio(), 0.5f, 10000.0f);
m_pCamera->SetViewPort(0.0f, 0.0f, (float)m_ClientWidth, (float)m_ClientHeight);
m_BasicEffect.SetProjMatrix(m_pCamera->GetProjXM());
}
}
/*
每帧都会调用, 用于更新场景中各种变量
*/
void RenderSponza::UpdateScene(float dt) {
// 获取鼠标状态
Mouse::State mouseState = m_pMouse->GetState();
// 获取键盘状态
Keyboard::State keyState = m_pKeyboard->GetState();
m_MouseTracker.Update(mouseState);
m_KeyboardTracker.Update(keyState);
auto cam1st = std::dynamic_pointer_cast<FPSCamera>(m_pCamera);
auto& sampleTrans = m_Sphere.GetTransform();
XMFLOAT3 curPos;
if (m_CameraMode == CameraMode::Free) {
// FPS mode
if (keyState.IsKeyDown(Keyboard::W)) {
cam1st->MoveForward(dt * m_Speed);
}
if (keyState.IsKeyDown(Keyboard::S)) {
cam1st->MoveForward(-dt * m_Speed);
}
if (keyState.IsKeyDown(Keyboard::D)) {
cam1st->Strafe(dt * m_Speed);
}
if (keyState.IsKeyDown(Keyboard::A)) {
cam1st->Strafe(-dt * m_Speed);
}
// 限制摄像机在固定范围内
XMFLOAT3 adjustPos;
// XMVectorClamp(V, min, max) 将V的每个分量限定在[min, max]范围
XMVECTOR VolumeMinVec = XMLoadFloat3(&m_Importer.VLMSetting.VolumeMin);
XMVECTOR VolumeSizeVec = XMLoadFloat3(&m_Importer.VLMSetting.VolumeSize);
XMVECTOR VolumeMaxVec = XMVectorAdd(VolumeMinVec, VolumeSizeVec);
XMStoreFloat3(&adjustPos, XMVectorClamp(cam1st->GetPositionXM(), VolumeMinVec, VolumeMaxVec));
cam1st->SetPosition(adjustPos);
cam1st->Pitch(mouseState.y * dt * 1.25f);
cam1st->RotateY(mouseState.x * dt * 1.25f);
if (m_isControlObj) {
m_TargetDistance += 0.05 * mouseState.scrollWheelValue;
XMFLOAT3 forward = cam1st->GetLookAxis();
sampleTrans.SetPosition(adjustPos.x + m_TargetDistance * forward.x, adjustPos.y + m_TargetDistance * forward.y, adjustPos.z + m_TargetDistance * forward.z);
}
BoundingBox houseBox = m_Sponza.GetBoundingBox();
for (int i = 0; i < m_DynamicTransform.size(); i++) {
auto& trans = m_DynamicTransform[i];
curPos = trans.GetPosition();
if (curPos.x > 1160.0f) m_SpheresDirection[i] = -1;
else if (curPos.x < -1300.0f) m_SpheresDirection[i] = 1;
curPos.x += m_SpheresDirection[i] * dt * m_SphereSpeed;
trans.SetPosition(curPos);
}
}
// 更新观察矩阵
m_BasicEffect.SetViewMatrix(m_pCamera->GetViewXM());
m_BasicEffect.SetEyePos(m_pCamera->GetPositionXM());
// 重置滚轮
m_pMouse->ResetScrollWheelValue();
if (m_KeyboardTracker.IsKeyPressed(Keyboard::U)) {
m_Speed += 500;
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::Y)) {
m_Speed -= 500;
}
m_Speed = max(200, m_Speed);
if (m_KeyboardTracker.IsKeyPressed(Keyboard::R)) {
m_IsWireframeMode = !m_IsWireframeMode;
m_BackGroundColor = m_IsWireframeMode ? Colors::Black : Colors::White;
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::F)) {
m_UseSH = !m_UseSH;
m_BasicEffect.SetSHUsed(m_UseSH);
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::T)) {
m_UseTexture = !m_UseTexture;
m_BasicEffect.SetTextureUsed(m_UseTexture);
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::V)) {
m_isVisulizeVLM = !m_isVisulizeVLM;
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::N)) {
if (m_SHFileIndex < m_SHRepositoies.size() - 1) {
m_SHFileIndex += 1;
m_BasicEffect.ClearTexture3D();
InitVLM();
VisualizeVLM();
}
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::M)) {
if (m_SHFileIndex > 0) {
m_SHFileIndex -= 1;
m_BasicEffect.ClearTexture3D();
InitVLM();
VisualizeVLM();
}
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::L)) {
m_BasicEffect.useNormalmap = !m_BasicEffect.useNormalmap;
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::K)) {
m_isControlObj = !m_isControlObj;
if (m_isControlObj) {
XMFLOAT3 samplePos = m_Sphere.GetTransform().GetPosition();
cam1st->SetPosition(samplePos.x, samplePos.y + 100, samplePos.z - 100);
cam1st->LookAt(cam1st->GetPosition(), samplePos, XMFLOAT3(0.0f, 1.0f, 0.0f));
}
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::H)) {
m_ShowHelp = !m_ShowHelp;
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::D1)) {
m_UseDirLight = !m_UseDirLight;
m_BasicEffect.SetDirLightUsed(m_UseDirLight);
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::D2)) {
m_UsePointLight = !m_UsePointLight;
m_BasicEffect.SetPointLightUsed(m_UsePointLight);
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::D3)) {
m_SHMode = 0;
m_BasicEffect.SetSHMode(m_SHMode);
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::D4)) {
m_SHMode = 1;
m_BasicEffect.SetSHMode(m_SHMode);
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::D5)) {
m_SHMode = 2;
m_BasicEffect.SetSHMode(m_SHMode);
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::D9)) {
m_SphereSpeed += 200;
m_SphereSpeed = min(600, m_SphereSpeed);
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::D0)) {
m_SphereSpeed -= 200;
m_SphereSpeed = max(0, m_SphereSpeed);
}
if (m_ShowHelp) {
_snwprintf_s(m_Text, ARRAYSIZE(m_Text), ARRAYSIZE(m_Text) - 1, L"控制移动:WASD, VLM可视化:V, 线框模式:R, 控制摄像机速度:UY, 球谐光照开关:F, 纹理贴图开关:T, 法线贴图开关:L \
控制小球:K, 增加DetailCellSize:N, 减少DetailCellSize:M, 方向光开关:1, 点光开关:2, 二阶球谐VS计算:3, 二阶球谐PS计算:4, 三阶球谐:5, 控制动态球速度:9和0");
}
else {
_snwprintf_s(m_Text, ARRAYSIZE(m_Text), ARRAYSIZE(m_Text) - 1, L"SHMode=%d, 方向光开关=%d, 点光开关=%d, 位置(%.1f,%.1f,%.1f), \
VLM可视化=%d, 相机速度=%d, 动态球速度=%d, 法线贴图=%d, \
detailCellSize=%s, VolumeSize(%.1f, %.1f, %.1f), 控制小球模式=%d, bricksNum=%d, IndirectionTextureMemory=%.1fKB, VLMTextureMemory=%.1fKB,按H查看按钮事件",
m_SHMode, m_UseDirLight, m_UsePointLight, cam1st->GetPosition().x, cam1st->GetPosition().y, cam1st->GetPosition().z,
m_isVisulizeVLM, m_Speed, m_SphereSpeed, m_BasicEffect.useNormalmap,
m_SHRepositoies[m_SHFileIndex],
m_Importer.VLMSetting.VolumeSize.x, m_Importer.VLMSetting.VolumeSize.y, m_Importer.VLMSetting.VolumeSize.z, m_isControlObj, m_Importer.m_BricksNum, m_Importer.vlmData.indirectionTexture.data.size() / 1024.0f,
m_Importer.vlmData.brickData.AmbientVector.data.size() / 1024.0f * 7.0f);
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::Escape)) {
SendMessage(MainWnd(), WM_DESTROY, 0, 0);
}
}
/*
每帧都会调用, 用于绘制画面
*/
void RenderSponza::DrawScene() {
assert(m_pd3dImmediateContext);
assert(m_pSwapChain);
m_pd3dImmediateContext->ClearRenderTargetView(m_pRenderTargetView.Get(), reinterpret_cast<const float*>(&m_BackGroundColor));
m_pd3dImmediateContext->ClearDepthStencilView(m_pDepthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
{
/************************
1. 绘制场景
*************************/
if (m_IsWireframeMode) {
m_BasicEffect.SetWireFrameWode(m_pd3dImmediateContext.Get());
m_Sponza.Draw(m_pd3dImmediateContext.Get(), m_BasicEffect);
// 显示Volume的边界
m_Box.Draw(m_pd3dImmediateContext.Get(), m_BasicEffect);
}
else {
m_BasicEffect.SetRenderDefault(m_pd3dImmediateContext.Get());
m_Sponza.SetMaterial(m_Material);
m_Sponza.Draw(m_pd3dImmediateContext.Get(), m_BasicEffect);
}
}
// Draw observe Obj
m_BasicEffect.SetTextureUsed(false);
m_Sphere.Draw(m_pd3dImmediateContext.Get(), m_BasicEffect);
// Draw dynamic obj
m_BasicEffect.SetRenderInstanceDefault(m_pd3dImmediateContext.Get());
m_Sample.DrawInstance(m_pd3dImmediateContext.Get(), m_BasicEffect, m_DynamicTransform);
if (m_isVisulizeVLM) {
for (INT32 depth = 0; depth < m_TransformData.size(); depth++)
m_Sample.DrawInstance(m_pd3dImmediateContext.Get(), m_BasicEffect, m_TransformData[depth]);
}
m_BasicEffect.SetTextureUsed(m_UseTexture);
WriteInformation(std::wstring(m_Text));
HR(m_pSwapChain->Present(0, 0));
}
/*
将indirectionTexturePosition 转成 WorldPosition
*/
XMFLOAT3 IndTexPosToWorldPos(const XMINT3& indTexPos, const FVolumetricLightmapSettings& vlmSetting, const XMINT3& indTexDimension) {
XMVECTOR volumeMinVec = XMLoadFloat3(&vlmSetting.VolumeMin);
XMVECTOR volumeSizeVec = XMLoadFloat3(&vlmSetting.VolumeSize);
XMVECTOR indTexDimensionVec = XMLoadSInt3(&indTexDimension);
XMVECTOR indTexPosVec = XMLoadSInt3(&indTexPos);
// (indPos/indDimension * VolumeSize + VolumeMin)
XMVECTOR worldPosVec = XMVectorAdd(XMVectorMultiply(XMVectorDivide(indTexPosVec, indTexDimensionVec), volumeSizeVec), volumeMinVec);
XMFLOAT3 worldPos;
XMStoreFloat3(&worldPos, worldPosVec);
return worldPos;
}
void RenderSponza::VisualizeVLM() {
INT32 SampleIndex = 0;
m_TransformData.resize(m_Importer.m_BricksByDepth.size());
for (INT32 depth = 0; depth < m_Importer.m_BricksByDepth.size(); depth++) {
auto& TransformDataAtDepth = m_TransformData[depth];
TransformDataAtDepth.resize(m_Importer.m_BricksByDepth[depth].size());
for (INT32 index = 0; index < m_Importer.m_BricksByDepth[depth].size(); index++) {
const auto& brick = m_Importer.m_BricksByDepth[depth][index];
TransformDataAtDepth[index].SetScale(XMFLOAT3(3 - depth, 3 - depth, 3 - depth));
TransformDataAtDepth[index].SetPosition(IndTexPosToWorldPos(brick.IndirectionTexturePosition, m_Importer.VLMSetting, m_Importer.vlmData.textureDimension));
}
}
}
void CreateTexture3D(ID3D11Device* device, ID3D11DeviceContext* context, INT32 depth, INT32 width, INT32 height, DXGI_FORMAT format, const std::vector<UINT8>& srcData, ID3D11Texture3D** pTex3D, ID3D11ShaderResourceView** outSRV) {
D3D11_TEXTURE3D_DESC texDesc;
ZeroMemory(&texDesc, sizeof(texDesc));
texDesc.Width = width;
texDesc.Height = height;
texDesc.Depth = depth;
texDesc.MipLevels = 1;
texDesc.Format = format;
texDesc.Usage = D3D11_USAGE_IMMUTABLE;
texDesc.CPUAccessFlags = 0;
texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
D3D11_SUBRESOURCE_DATA subResData;
subResData.pSysMem = srcData.data();
subResData.SysMemPitch = width * 4;
subResData.SysMemSlicePitch = width * height * 4;
HR(device->CreateTexture3D(&texDesc, &subResData, pTex3D));
D3D11_SHADER_RESOURCE_VIEW_DESC tex3DViewDesc;
ZeroMemory(&tex3DViewDesc, sizeof(tex3DViewDesc));
tex3DViewDesc.Format = format;
tex3DViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
tex3DViewDesc.Texture3D.MipLevels = 1;
tex3DViewDesc.Texture3D.MostDetailedMip = 0;
HR(device->CreateShaderResourceView(*pTex3D, &tex3DViewDesc, outSRV));
}
bool RenderSponza::InitVLM() {
wchar_t VLMSettingRepo[128], brickByDepthRepo[128], indTexRepo[128], AmbientVecRepo[128], SH0Repo[128],
SH1Repo[128], SH2Repo[128], SH3Repo[128], SH4Repo[128], SH5Repo[128];
_snwprintf_s(brickByDepthRepo, ARRAYSIZE(brickByDepthRepo), ARRAYSIZE(brickByDepthRepo) - 1, L"Texture\\SHCoefs\\%s\\brickDataByDepth", m_SHRepositoies[m_SHFileIndex]);
_snwprintf_s(VLMSettingRepo, ARRAYSIZE(VLMSettingRepo), ARRAYSIZE(VLMSettingRepo) - 1, L"Texture\\SHCoefs\\%s\\vlmSetting", m_SHRepositoies[m_SHFileIndex]);
_snwprintf_s(indTexRepo, ARRAYSIZE(indTexRepo), ARRAYSIZE(indTexRepo) - 1, L"Texture\\SHCoefs\\%s\\indirectionTexture", m_SHRepositoies[m_SHFileIndex]);
_snwprintf_s(AmbientVecRepo, ARRAYSIZE(AmbientVecRepo), ARRAYSIZE(AmbientVecRepo) - 1, L"Texture\\SHCoefs\\%s\\AmbientVector", m_SHRepositoies[m_SHFileIndex]);
_snwprintf_s(SH0Repo, ARRAYSIZE(SH0Repo), ARRAYSIZE(SH0Repo) - 1, L"Texture\\SHCoefs\\%s\\SH0", m_SHRepositoies[m_SHFileIndex]);
_snwprintf_s(SH1Repo, ARRAYSIZE(SH1Repo), ARRAYSIZE(SH1Repo) - 1, L"Texture\\SHCoefs\\%s\\SH1", m_SHRepositoies[m_SHFileIndex]);
_snwprintf_s(SH2Repo, ARRAYSIZE(SH2Repo), ARRAYSIZE(SH2Repo) - 1, L"Texture\\SHCoefs\\%s\\SH2", m_SHRepositoies[m_SHFileIndex]);
_snwprintf_s(SH3Repo, ARRAYSIZE(SH3Repo), ARRAYSIZE(SH3Repo) - 1, L"Texture\\SHCoefs\\%s\\SH3", m_SHRepositoies[m_SHFileIndex]);
_snwprintf_s(SH4Repo, ARRAYSIZE(SH4Repo), ARRAYSIZE(SH4Repo) - 1, L"Texture\\SHCoefs\\%s\\SH4", m_SHRepositoies[m_SHFileIndex]);
_snwprintf_s(SH5Repo, ARRAYSIZE(SH5Repo), ARRAYSIZE(SH5Repo) - 1, L"Texture\\SHCoefs\\%s\\SH5", m_SHRepositoies[m_SHFileIndex]);
m_Importer.ImportFile(brickByDepthRepo, VLMSettingRepo,
indTexRepo, AmbientVecRepo, SH0Repo, SH1Repo, SH2Repo, SH3Repo, SH4Repo, SH5Repo);
/*{
// Should be deleted after test !!!!!!!
m_Importer.ImportFile(L"D:\\brickDataByDepth", L"D:\\vlmSetting",
L"D:\\indirectionTexture", L"D:\\AmbientVector",
L"D:\\SH0", L"D:\\SH1", L"D:\\SH2", L"D:\\SH3",
L"D:\\SH4", L"D:\\SH5");
}*/
if (!m_Importer.Read())
return false;
m_Importer.TransformData();
const VLMData& vlmData = m_Importer.vlmData;
m_BasicEffect.SetVLMBrickSize(m_Importer.VLMSetting.BrickSize);
m_BasicEffect.SetVLMIndirectionTextureSize(XMFLOAT3(vlmData.textureDimension.x, vlmData.textureDimension.y, vlmData.textureDimension.z));
m_BasicEffect.SetVLMBrickTexelSize(XMFLOAT3(1.0f / vlmData.brickDataDimension.x, 1.0f / vlmData.brickDataDimension.y, 1.0f / vlmData.brickDataDimension.z));
XMVECTOR VolumeSizeVec = XMLoadFloat3(&m_Importer.VLMSetting.VolumeSize);
XMVECTOR InvVolumeSizeVec = XMVectorReciprocal(VolumeSizeVec);
XMFLOAT3 InvVolumeSize;
XMStoreFloat3(&InvVolumeSize, InvVolumeSizeVec);
m_BasicEffect.SetVLMWorldToUVScale(InvVolumeSize);
XMVECTOR VolumeMinVec = XMLoadFloat3(&m_Importer.VLMSetting.VolumeMin);
XMFLOAT3 VLMWorldToUVAdd;
XMStoreFloat3(&VLMWorldToUVAdd, XMVectorMultiply(-VolumeMinVec, InvVolumeSizeVec));
m_BasicEffect.SetVLMWorldToUVAdd(VLMWorldToUVAdd);
ComPtr<ID3D11ShaderResourceView> SRV;
CreateTexture3D(m_pd3dDevice.Get(),
m_pd3dImmediateContext.Get(),
vlmData.textureDimension.z,
vlmData.textureDimension.x,
vlmData.textureDimension.y,
vlmData.indirectionTexture.Format,
vlmData.indirectionTexture.data,
m_pTex3D.ReleaseAndGetAddressOf(),
SRV.ReleaseAndGetAddressOf());
m_BasicEffect.SetTexture3D(SRV.Get());
CreateTexture3D(m_pd3dDevice.Get(),
m_pd3dImmediateContext.Get(),
vlmData.brickDataDimension.z,
vlmData.brickDataDimension.x,
vlmData.brickDataDimension.y,
vlmData.brickData.AmbientVector.Format,
vlmData.brickData.AmbientVector.data,
m_pTex3D.ReleaseAndGetAddressOf(),
SRV.ReleaseAndGetAddressOf());
m_BasicEffect.SetTexture3D(SRV.Get());
for (int i = 0; i < 6; i++) {
CreateTexture3D(m_pd3dDevice.Get(),
m_pd3dImmediateContext.Get(),
vlmData.brickDataDimension.z,
vlmData.brickDataDimension.x,
vlmData.brickDataDimension.y,
vlmData.brickData.SHCoefficients[i].Format,
vlmData.brickData.SHCoefficients[i].data,
m_pTex3D.ReleaseAndGetAddressOf(),
SRV.ReleaseAndGetAddressOf());
m_BasicEffect.SetTexture3D(SRV.Get());
}
m_BasicEffect.SetSHUsed(m_UseSH);
/*
{
//Test part, should be deleted
std::ifstream SH0Phase1Importer(L"D:\\SH0Phase1", std::ios::in | std::ios::binary);
std::ifstream SH0Phase2Importer(L"D:\\SH0Phase2", std::ios::in | std::ios::binary);
std::ifstream SH0Phase3Importer(L"D:\\SH0Phase3", std::ios::in | std::ios::binary);
std::ifstream SH0Phase4Importer(L"D:\\SH0Phase4", std::ios::in | std::ios::binary);
std::ifstream SH0Phase5Importer(L"D:\\SH0Phase5", std::ios::in | std::ios::binary);
std::vector<UINT8>SH0Phase1(vlmData.brickData.SHCoefficients[0].data.size());
std::vector<UINT8>SH0Phase2(vlmData.brickData.SHCoefficients[0].data.size());
std::vector<UINT8>SH0Phase3(vlmData.brickData.SHCoefficients[0].data.size());
std::vector<UINT8>SH0Phase4(vlmData.brickData.SHCoefficients[0].data.size());
std::vector<UINT8>SH0Phase5(vlmData.brickData.SHCoefficients[0].data.size());
SH0Phase1Importer.read(reinterpret_cast<char*>(SH0Phase1.data()), vlmData.brickData.SHCoefficients[0].data.size());
SH0Phase2Importer.read(reinterpret_cast<char*>(SH0Phase2.data()), vlmData.brickData.SHCoefficients[0].data.size());
SH0Phase3Importer.read(reinterpret_cast<char*>(SH0Phase3.data()), vlmData.brickData.SHCoefficients[0].data.size());
SH0Phase4Importer.read(reinterpret_cast<char*>(SH0Phase4.data()), vlmData.brickData.SHCoefficients[0].data.size());
SH0Phase5Importer.read(reinterpret_cast<char*>(SH0Phase5.data()), vlmData.brickData.SHCoefficients[0].data.size());
CreateTexture3D(m_pd3dDevice.Get(),
m_pd3dImmediateContext.Get(),
vlmData.brickDataDimension.z,
vlmData.brickDataDimension.x,
vlmData.brickDataDimension.y,
vlmData.brickData.SHCoefficients[0].Format,
SH0Phase1,
m_pTex3D.ReleaseAndGetAddressOf(),
SRV.ReleaseAndGetAddressOf());
m_BasicEffect.SetTexture3D(SRV.Get());
CreateTexture3D(m_pd3dDevice.Get(),
m_pd3dImmediateContext.Get(),
vlmData.brickDataDimension.z,
vlmData.brickDataDimension.x,
vlmData.brickDataDimension.y,
vlmData.brickData.SHCoefficients[0].Format,
SH0Phase2,
m_pTex3D.ReleaseAndGetAddressOf(),
SRV.ReleaseAndGetAddressOf());
m_BasicEffect.SetTexture3D(SRV.Get());
CreateTexture3D(m_pd3dDevice.Get(),
m_pd3dImmediateContext.Get(),
vlmData.brickDataDimension.z,
vlmData.brickDataDimension.x,
vlmData.brickDataDimension.y,
vlmData.brickData.SHCoefficients[0].Format,
SH0Phase3,
m_pTex3D.ReleaseAndGetAddressOf(),
SRV.ReleaseAndGetAddressOf());
m_BasicEffect.SetTexture3D(SRV.Get());
CreateTexture3D(m_pd3dDevice.Get(),
m_pd3dImmediateContext.Get(),
vlmData.brickDataDimension.z,
vlmData.brickDataDimension.x,
vlmData.brickDataDimension.y,
vlmData.brickData.SHCoefficients[0].Format,
SH0Phase4,
m_pTex3D.ReleaseAndGetAddressOf(),
SRV.ReleaseAndGetAddressOf());
m_BasicEffect.SetTexture3D(SRV.Get());
CreateTexture3D(m_pd3dDevice.Get(),
m_pd3dImmediateContext.Get(),
vlmData.brickDataDimension.z,
vlmData.brickDataDimension.x,
vlmData.brickDataDimension.y,
vlmData.brickData.SHCoefficients[0].Format,
SH0Phase5,
m_pTex3D.ReleaseAndGetAddressOf(),
SRV.ReleaseAndGetAddressOf());
m_BasicEffect.SetTexture3D(SRV.Get());
}
*/
return true;
}
bool RenderSponza::InitResource() {
const XMFLOAT3& VolumeSize = m_Importer.VLMSetting.VolumeSize;
const XMFLOAT3& VolumeMin = m_Importer.VLMSetting.VolumeMin;
XMVECTOR VolumeMinVec = XMLoadFloat3(&VolumeMin);
XMVECTOR VolumeSizeVec = XMLoadFloat3(&VolumeSize);
XMVECTOR BoundCentreVec = XMVectorAdd(VolumeMinVec, XMVectorDivide(VolumeSizeVec, XMVectorSet(2.0f, 2.0f, 2.0f, 2.0f)));
m_Box.SetModel(Model(m_pd3dDevice.Get(), Geometry::CreateBox(VolumeSize.x, VolumeSize.y, VolumeSize.z)));
XMFLOAT3 BoundCentre; XMStoreFloat3(&BoundCentre, BoundCentreVec);
m_Box.GetTransform().SetPosition(BoundCentre);
/*******************
初始化纹理
********************/
// 初始材质
Material material{};
material.ambient = XMFLOAT4(0.4f, 0.4f, 0.4f, 1.0f);
material.diffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
material.specular = XMFLOAT4(0.1f, 0.1f, 0.1f, 16.0f);
m_Material = material;
// 读取sponza
m_ObjReader.Read(L"Model\\SponzaUV.mbo", L"Model\\SponzaUV.obj");
m_Sponza.SetModel(Model(m_pd3dDevice.Get(), m_ObjReader));
// 获取房屋包围盒
/*XMMATRIX S = XMMatrixScaling(0.015f, 0.015f, 0.015f);*/
XMMATRIX S = XMMatrixScaling(1.0f, 1.0f, 1.0f);
BoundingBox houseBox = m_Sponza.GetLocalBoundingBox();
houseBox.Transform(houseBox, S);
Transform& houseTransform = m_Sponza.GetTransform();
houseTransform.SetScale(1.0f, 1.0f, 1.0f);
houseTransform.SetPosition(0.0f, 0.0f, 0.0f);
/*******************************
初始化摄像机, 默认第三人称视角
********************************/
m_CameraMode = CameraMode::Free;
auto camera = std::shared_ptr<FPSCamera>(new FPSCamera);
m_pCamera = camera;
camera->SetViewPort(0.0f, 0.0f, (float)m_ClientWidth, (float)m_ClientHeight);
camera->SetFrustum(XM_PI / 3, AspectRatio(), 1.0f, 10000.0f);
camera->LookTo(XMFLOAT3(0.0f, 300.0f, 0.0f), XMFLOAT3(1, 0, 0), XMFLOAT3(0.0f, 1.0f, 0.0f));
/**********************************************
设置观察矩阵和观察位置,设置平截头体和投影矩阵
***********************************************/
m_BasicEffect.SetViewMatrix(m_pCamera->GetViewXM());
m_BasicEffect.SetProjMatrix(m_pCamera->GetProjXM());
m_BasicEffect.SetEyePos(m_pCamera->GetPositionXM());
//m_BasicEffect.SetReflectionMatrix(XMMatrixReflect(XMVectorSet(0.0f, 0.0f, -1.0f, 10.0f)));
/******************
* 初始化默认光照 *
*******************/
// 环境光
DirectionalLight dirLight;
dirLight.ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
dirLight.diffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
dirLight.specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
dirLight.direction = XMFLOAT3(0.0f, -1.0f, 0.0f);
m_BasicEffect.SetDirLight(0, dirLight);
m_BasicEffect.SetDirLightNums(1);
for (int i = 0; i < 22; i++) {
PointLight pointLight;
pointLight.ambient = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
pointLight.diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
pointLight.specular = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
pointLight.att = XMFLOAT3(0.0f, 0.1f, 0.0f);
pointLight.range = 500.0f;
m_PointLightArray.push_back(pointLight);
}
// 1st floor
m_PointLightArray[0].position = XMFLOAT3(-1200.0f, 150.0f, -420.0f);
m_PointLightArray[1].position = XMFLOAT3(-1200.0f, 150.0f, 435.0f);
m_PointLightArray[1].diffuse = XMFLOAT4(0.0f, 0.0f, 0.8f, 1.0f);
m_PointLightArray[2].position = XMFLOAT3(0.0f, 150.0f, -420.0f);
m_PointLightArray[3].position = XMFLOAT3(0.0f, 150.0f, 430.0f);
m_PointLightArray[4].position = XMFLOAT3(1100.0f, 150.0f, -410.0f);
m_PointLightArray[4].diffuse = XMFLOAT4(0.8f, 0.0f, 0.0f, 1.0f);
m_PointLightArray[5].position = XMFLOAT3(1100.0f, 150.0f, 0.0f);
m_PointLightArray[6].position = XMFLOAT3(1100.0f, 150.0f, 435.0f);
m_PointLightArray[7].position = XMFLOAT3(494.0f, 150.0f, -145.0f);
m_PointLightArray[8].position = XMFLOAT3(494.0f, 150.0f, 215.0f);
m_PointLightArray[9].position = XMFLOAT3(-620.0f, 150.0f, 210.0f);
m_PointLightArray[10].position = XMFLOAT3(-620.0f, 150.0f, -140.0f);
// 2nd floor
m_PointLightArray[11].position = XMFLOAT3(-1250.0f, 570.0f, 0.0f);
m_PointLightArray[12].position = XMFLOAT3(-1150.0f, 570.0f, 480.0f);
m_PointLightArray[13].position = XMFLOAT3(-1150.0f, 470.0f, -390.0f);
m_PointLightArray[14].position = XMFLOAT3(0.0f, 570.0f, 480.0f);
m_PointLightArray[15].position = XMFLOAT3(1100.0f, 570.0f, 480.0f);
m_PointLightArray[16].position = XMFLOAT3(0.0f, 570.0f, -370.0f);
m_PointLightArray[17].position = XMFLOAT3(1100.0f, 570.0f, -360.0f);
m_PointLightArray[18].position = XMFLOAT3(1150.0f, 570.0f, 30.0f);
// sky
m_PointLightArray[19].position = XMFLOAT3(540.0f, 850.0f, 0.0f);
m_PointLightArray[19].diffuse = XMFLOAT4(0.0f, 1.0f, 0.3f, 1.0f);
m_PointLightArray[20].position = XMFLOAT3(-90.0f, 850.0f, 0.0f);
m_PointLightArray[20].diffuse = XMFLOAT4(1.0f, 0.2f, 0.0f, 1.0f);
m_PointLightArray[21].position = XMFLOAT3(-750.0f, 850.0f, 0.0f);
m_PointLightArray[21].diffuse = XMFLOAT4(0.0f, 0.12f, 1.0f, 1.0f);
for (int i = 0; i < m_PointLightArray.size(); i++) {
m_BasicEffect.SetPointLight(i, m_PointLightArray[i]);
}
m_BasicEffect.SetPointLightNums(m_PointLightArray.size());
m_BasicEffect.SetSpotLightNums(0);
/*
动态物体
*/
m_DynamicTransform.resize(3);
m_SpheresDirection.resize(3, 1);
for (int i = 0; i < 3; i++) {
m_DynamicTransform[i].SetScale(4, 4, 4);
}
m_DynamicTransform[0].SetPosition(0, 240, 0);
m_DynamicTransform[1].SetPosition(1000, 240, 450);
m_DynamicTransform[2].SetPosition(-1000, 240, -400);
// OberveObj
m_Sphere.SetModel(Model(m_pd3dDevice.Get(), Geometry::CreateSphere(10.0f)));
m_Sphere.GetTransform().SetPosition(0, 800, 0);
m_Sphere.GetTransform().SetScale(3, 3, 3);
m_Sample.SetModel(Model(m_pd3dDevice.Get(), Geometry::CreateSphere<VertexPosNormal>(10.0f)));
m_Sample.SetMaterial(material);
VisualizeVLM();
return true;
}
<file_sep>#pragma once
#include <DirectXMath.h>
#include "light.h"
/*******************************************************************************************
* CBuffer.h *
*由于参数不断增多,每个常量缓冲区都在增大,如果只为了修改一个变量而重新读取整个缓冲区感觉很亏, *
*所以现在把这些变量按照刷新频率分成四个等级,每次绘制更新,每帧更新,每次改变窗口大小更新和不经常更新 *
********************************************************************************************/
struct CBChangesEveryDrawing {
DirectX::XMMATRIX world;
DirectX::XMMATRIX worldInvTranspose;
};
struct CBChangesEveryFrame {
DirectX::XMMATRIX view;
DirectX::XMFLOAT4 eysPos;
};
struct CBChangesOnResize {
DirectX::XMMATRIX proj;
};
struct CBChangesRarely {
DirectionalLight dirLight[10];
PointLight pointLight[10];
SpotLight spotLight[10];
Material material;
int numDirLight;
int numPointLight;
int numSpotLight;
float pad;
};
<file_sep>#include "Ex10Camera.h"
using namespace DirectX;
Ex10Camera::GameObject::GameObject() :
m_VertexStride(),
m_IndexCount() {
}
// 获取物体变换
Transform& Ex10Camera::GameObject::GetTransform() {
return m_Transform;
}
// 获取物体变换
const Transform& Ex10Camera::GameObject::GetTransform() const {
return m_Transform;
}
/*
用于构造顶点和索引,resetMesh被移到这里
*/
template<class VertexType, class IndexType>
void Ex10Camera::GameObject::SetBuffer(ID3D11Device* device, const Geometry::MeshData<VertexType, IndexType>& meshData) {
// 1.清空顶点和索引缓冲区
m_pVertexBuffer.Reset();
m_pIndexBuffer.Reset();
/*****************
* 2 顶点缓冲区 *
******************/
// 2.1 设置顶点缓冲区描述
D3D11_BUFFER_DESC vbd;
m_VertexStride = sizeof(VertexType);
ZeroMemory(&vbd, sizeof(vbd));
vbd.Usage = D3D11_USAGE_IMMUTABLE;
vbd.ByteWidth = (UINT)meshData.vertexVec.size() * m_VertexStride;
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbd.CPUAccessFlags = 0;
// 2.2 设定用于初始化的数据并在Device上建立缓冲区
D3D11_SUBRESOURCE_DATA initData;
ZeroMemory(&initData, sizeof(initData));
initData.pSysMem = meshData.vertexVec.data();
HR(device->CreateBuffer(&vbd, &initData, m_pVertexBuffer.GetAddressOf()));
/**************
*3 索引缓冲区 *
**************/
m_IndexCount = (UINT)meshData.indexVec.size();
// 3.1 设置索引缓冲区描述
D3D11_BUFFER_DESC ibd;
ZeroMemory(&ibd, sizeof(ibd));
ibd.Usage = D3D11_USAGE_IMMUTABLE;
ibd.ByteWidth = (UINT)meshData.indexVec.size() * sizeof(IndexType);
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
// 3.2 建立索引缓冲区
initData.pSysMem = meshData.indexVec.data();
HR(device->CreateBuffer(&ibd, &initData, m_pIndexBuffer.GetAddressOf()));
}
void Ex10Camera::GameObject::SetTexture(ID3D11ShaderResourceView* texture) {
m_pTexture = texture;
}
void Ex10Camera::GameObject::Draw(ID3D11DeviceContext* deviceContext) {
// 在上下文装配顶点缓冲区
UINT stride = m_VertexStride;
UINT offset = 0;
deviceContext->IASetVertexBuffers(0, 1, m_pVertexBuffer.GetAddressOf(), &stride, &offset);
// 在上下文上装配索引缓冲区
deviceContext->IASetIndexBuffer(m_pIndexBuffer.Get(), DXGI_FORMAT_R32_UINT, 0);
// 获取之前绑定到VS上的常量缓冲区并修改
ComPtr<ID3D11Buffer> cBuffer = nullptr;
deviceContext->VSGetConstantBuffers(0, 1, cBuffer.GetAddressOf());
CBChangesEveryDrawing cbDrawing;
// Transpose
XMMATRIX W = m_Transform.GetLocalToWorldMatrixXM();
cbDrawing.world = XMMatrixTranspose(W);
cbDrawing.worldInvTranspose = XMMatrixInverse(nullptr, W); // W 已经是世界矩阵的转置矩阵
// 更新Context的drawing常量缓冲
D3D11_MAPPED_SUBRESOURCE mappedRes;
HR(deviceContext->Map(cBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRes));
memcpy_s(mappedRes.pData, sizeof(CBChangesEveryDrawing), &cbDrawing, sizeof(CBChangesEveryDrawing));
deviceContext->Unmap(cBuffer.Get(), 0);
// 设置纹理
deviceContext->PSSetShaderResources(0, 1, m_pTexture.GetAddressOf());
// 开始绘制
deviceContext->DrawIndexed(m_IndexCount, 0, 0);
}
Ex10Camera::Ex10Camera(HINSTANCE hInstance)
:D3DApp(hInstance),
m_CameraMode(CameraMode::FPS),
m_CBFrame(),
m_CBOnResize(),
m_CBRarely() {
}
Ex10Camera::~Ex10Camera() {
}
bool Ex10Camera::Init() {
if (!D3DApp::Init()) return false;
if (!InitEffect()) return false;
if (!InitResource()) return false;
m_pMouse->SetWindow(m_hMainWnd);
m_pMouse->SetMode(Mouse::MODE_RELATIVE);
return true;
}
void Ex10Camera::UpdateScene(float dt)
{
// 获取鼠标状态
Mouse::State mouseState = m_pMouse->GetState();
Mouse::State lastMouseState = m_MouseTracker.GetLastState();
// 获取键盘状态
Keyboard::State keyState = m_pKeyboard->GetState();
Keyboard::State lastKeyState = m_KeyboardTracker.GetLastState();
m_MouseTracker.Update(mouseState);
m_KeyboardTracker.Update(keyState);
Transform& woodCrateTransform = m_WoodCrate.GetTransform();
auto cam1st = std::dynamic_pointer_cast<FPSCamera>(m_pCamera);
auto cam3rd = std::dynamic_pointer_cast<TPSCamera>(m_pCamera);
if (m_CameraMode == CameraMode::FPS || m_CameraMode == CameraMode::Free) {
// FPS mode
if (keyState.IsKeyDown(Keyboard::W)) {
if (m_CameraMode == CameraMode::FPS) {
cam1st->Walk(dt * 5.0f);
}
else {
cam1st->MoveForward(dt * 5.0f);
}
}
if (keyState.IsKeyDown(Keyboard::S)) {
if (m_CameraMode == CameraMode::FPS) {
cam1st->Walk(-dt * 5.0f);
}
else {
cam1st->MoveForward(-dt * 5.0f);
}
}
if (keyState.IsKeyDown(Keyboard::D)) cam1st->Strafe(dt * 5.0f);
if (keyState.IsKeyDown(Keyboard::A)) cam1st->Strafe(-dt * 5.0f);
// 限制摄像机在固定范围内 x(-8.9, 8.9), z(-8.9, 8.9), y(0, 8.9) y不能为负
XMFLOAT3 adjustPos;
// XMVectorClamp(V, min, max) 将V的每个分量限定在[min, max]范围
XMStoreFloat3(&adjustPos, XMVectorClamp(cam1st->GetPositionXM(), XMVectorSet(-8.9f, 0.0f, -8.9f, 0.0f), XMVectorReplicate(8.9f)));
cam1st->SetPosition(adjustPos);
// 只有第一人称才是摄像机和箱子都移动
if (m_CameraMode == CameraMode::FPS) woodCrateTransform.SetPosition(adjustPos);
if (mouseState.positionMode == Mouse::MODE_RELATIVE) {
cam1st->Pitch(mouseState.y * dt * 2.5f);
cam1st->RotateY(mouseState.x * dt * 2.5f);
}
}
else if (m_CameraMode==CameraMode::Observe) {
// 更新摄像机目标位置
cam3rd->SetTarget(woodCrateTransform.GetPosition());
// 摄像机绕目标旋转
cam3rd->RotateX(mouseState.y * dt * 2.5f);
cam3rd->RotateY(mouseState.x * dt * 2.5f);
cam3rd->Approach(mouseState.scrollWheelValue / 120 * 1.0f);
}
else if (m_CameraMode == CameraMode::TPS) {
if (keyState.IsKeyDown(Keyboard::W)) {
woodCrateTransform.Translate(woodCrateTransform.GetForwardAxis(), dt * 5.0f);
}
if (keyState.IsKeyDown(Keyboard::S)) {
woodCrateTransform.Translate(woodCrateTransform.GetForwardAxis(), -dt * 5.0f);
}
if (keyState.IsKeyDown(Keyboard::D))
woodCrateTransform.Translate(woodCrateTransform.GetRightAxis(), dt * 5.0f);
if (keyState.IsKeyDown(Keyboard::A))
woodCrateTransform.Translate(woodCrateTransform.GetRightAxis(), -dt * 5.0f);
XMFLOAT3 adjustPos;
XMStoreFloat3(&adjustPos, XMVectorClamp(woodCrateTransform.GetPositionXM(), XMVectorSet(-8.9f, 0.0f, -8.9f, 0.0f), XMVectorReplicate(8.9f)));
woodCrateTransform.SetPosition(adjustPos);
cam3rd->SetTarget(woodCrateTransform.GetPosition());
// 摄像机绕目标旋转
cam3rd->RotateX(mouseState.y * dt * 2.5f);
cam3rd->RotateY(mouseState.x * dt * 2.5f);
cam3rd->Approach(mouseState.scrollWheelValue / 120 * 1.0f);
}
// 更新观察矩阵
XMStoreFloat4(&m_CBFrame.eysPos, m_pCamera->GetPositionXM());
m_CBFrame.view = XMMatrixTranspose(m_pCamera->GetViewXM());
// 重置滚轮
m_pMouse->ResetScrollWheelValue();
// 切换到FPS模式
if (keyState.IsKeyDown(Keyboard::D1) && m_CameraMode != CameraMode::FPS) {
if (!cam1st) {
cam1st.reset(new FPSCamera);
cam1st->SetFrustum(XM_PI / 3, AspectRatio(), 0.5f, 1000.0f);
m_pCamera = cam1st;
}
cam1st->LookTo(woodCrateTransform.GetPosition(),
XMFLOAT3(0.0f, 0.0f, 1.0f),
XMFLOAT3(0.0f, 1.0f, 0.0f));
m_CameraMode = CameraMode::FPS;
}
// 切换到Observe模式
else if (m_KeyboardTracker.IsKeyPressed(Keyboard::D2) && m_CameraMode != CameraMode::Observe) {
if (!cam3rd) {
cam3rd.reset(new TPSCamera);
cam3rd->SetFrustum(XM_PI / 3, AspectRatio(), 0.5f, 1000.0f);
m_pCamera = cam3rd;
}
cam3rd->SetTarget(woodCrateTransform.GetPosition());
cam3rd->SetDistance(8.0f);
cam3rd->SetDistMinMax(3.0f, 20.0f);
m_CameraMode = CameraMode::Observe;
}
else if (m_KeyboardTracker.IsKeyPressed(Keyboard::D3) && m_CameraMode != CameraMode::Free) {
if (!cam1st) {
cam1st.reset(new FPSCamera);
cam1st->SetFrustum(XM_PI / 3, AspectRatio(), 0.5f, 1000.0f);
m_pCamera = cam1st;
}
XMFLOAT3 pos = woodCrateTransform.GetPosition();
XMFLOAT3 to = XMFLOAT3(0.0f, 0.0f, 1.0f);
XMFLOAT3 up = XMFLOAT3(0.0f, 1.0f, 0.0f);
pos.y += 3;
cam1st->LookTo(pos, to, up);
m_CameraMode = CameraMode::Free;
}
else if (m_KeyboardTracker.IsKeyPressed(Keyboard::D4) && m_CameraMode != CameraMode::TPS) {
if (!cam3rd) {
cam3rd.reset(new TPSCamera);
cam3rd->SetFrustum(XM_PI / 3, AspectRatio(), 0.5f, 1000.0f);
m_pCamera = cam3rd;
}
cam3rd->SetTarget(woodCrateTransform.GetPosition());
cam3rd->SetDistance(8.0f);
cam3rd->SetDistMinMax(3.0f, 20.0f);
m_CameraMode = CameraMode::TPS;
}
if (m_KeyboardTracker.IsKeyPressed(Keyboard::Escape)) {
SendMessage(MainWnd(), WM_DESTROY, 0, 0);
}
D3D11_MAPPED_SUBRESOURCE mappedRes;
HR(m_pd3dImmediateContext->Map(m_pConstantBuffers[1].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRes));
memcpy_s(mappedRes.pData, sizeof(CBChangesEveryFrame), &m_CBFrame, sizeof(CBChangesEveryFrame));
m_pd3dImmediateContext->Unmap(m_pConstantBuffers[1].Get(), 0);
}
void Ex10Camera::DrawScene()
{
assert(m_pd3dImmediateContext);
assert(m_pSwapChain);
m_pd3dImmediateContext->ClearRenderTargetView(m_pRenderTargetView.Get(), reinterpret_cast<const float*>(&DirectX::Colors::Black));
m_pd3dImmediateContext->ClearDepthStencilView(m_pDepthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
m_WoodCrate.Draw(m_pd3dImmediateContext.Get());
m_Floor.Draw(m_pd3dImmediateContext.Get());
for (int i = 0; i < m_Walls.size(); i++) {
m_Walls[i].Draw(m_pd3dImmediateContext.Get());
}
HR(m_pSwapChain->Present(0, 0));
}
void Ex10Camera::OnResize() {
D3DApp::OnResize();
if (m_pCamera != nullptr) {
m_pCamera->SetFrustum(XM_PI / 3, AspectRatio(), 0.5f, 1000.0f);
m_pCamera->SetViewPort(0.0f, 0.0f, (float)m_ClientWidth, (float)m_ClientHeight);
m_CBOnResize.proj = XMMatrixTranspose(m_pCamera->GetProjXM());
// 更新Context的OnResize常量缓冲
D3D11_MAPPED_SUBRESOURCE mappedRes;
HR(m_pd3dImmediateContext->Map(m_pConstantBuffers[2].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRes));
memcpy_s(mappedRes.pData, sizeof(CBChangesOnResize), &m_CBOnResize, sizeof(CBChangesOnResize));
m_pd3dImmediateContext->Unmap(m_pConstantBuffers[2].Get(), 0);
}
}
bool Ex10Camera::InitEffect()
{
ComPtr<ID3DBlob> blob;
// 创建顶点着色器(2D)
HR(CreateShaderFromFile(L"HLSL\\Basic_VS_2D.cso", L"HLSL\\Basic_VS_2D.hlsl", "VS_2D", "vs_5_0", blob.ReleaseAndGetAddressOf()));
HR(m_pd3dDevice->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pVertexShader2D.GetAddressOf()));
// 创建顶点布局(2D)
HR(m_pd3dDevice->CreateInputLayout(VertexPosTex::inputLayout, ARRAYSIZE(VertexPosTex::inputLayout),
blob->GetBufferPointer(), blob->GetBufferSize(), m_pVertexLayout2D.GetAddressOf()));
// 创建顶点着色器(3D)
HR(CreateShaderFromFile(L"HLSL\\Basic_VS_3D.cso", L"HLSL\\Basic_VS_3D.hlsl", "VS_3D", "vs_5_0", blob.ReleaseAndGetAddressOf()));
HR(m_pd3dDevice->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pVertexShader3D.GetAddressOf()));
// 创建顶点布局(3D)
HR(m_pd3dDevice->CreateInputLayout(VertexPosNormalTex::inputLayout, ARRAYSIZE(VertexPosNormalTex::inputLayout),
blob->GetBufferPointer(), blob->GetBufferSize(), m_pVertexLayout3D.GetAddressOf()));
// 创建像素着色器(2D)
HR(CreateShaderFromFile(L"HLSL\\Basic_PS_2D.cso", L"HLSL\\Basic_PS_2D.hlsl", "PS_2D", "ps_5_0", blob.ReleaseAndGetAddressOf()));
HR(m_pd3dDevice->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pPixelShader2D.GetAddressOf()));
// 创建像素着色器(3D)
HR(CreateShaderFromFile(L"HLSL\\Basic_PS_3D.cso", L"HLSL\\Basic_PS_3D.hlsl", "PS_3D", "ps_5_0", blob.ReleaseAndGetAddressOf()));
HR(m_pd3dDevice->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pPixelShader3D.GetAddressOf()));
return true;
}
bool Ex10Camera::InitResource()
{
/*******************
初始化纹理
********************/
ComPtr<ID3D11ShaderResourceView> texture;
// 读取木箱
HR(CreateDDSTextureFromFile(m_pd3dDevice.Get(), L"Texture\\WoodCrate.dds", nullptr, texture.GetAddressOf()));
m_WoodCrate.SetBuffer<VertexPosNormalTangentTex, DWORD>(m_pd3dDevice.Get(), Geometry::CreateBox());
m_WoodCrate.SetTexture(texture.Get());
// 初始化地板
HR(CreateDDSTextureFromFile(m_pd3dDevice.Get(), L"Texture\\floor.dds", nullptr, texture.GetAddressOf()));
m_Floor.SetBuffer<VertexPosNormalTangentTex, DWORD>(m_pd3dDevice.Get(), Geometry::CreatePlane(XMFLOAT2(20.0f, 20.0f), XMFLOAT2(5.0f, 5.0f)));
m_Floor.SetTexture(texture.Get());
m_Floor.GetTransform().SetPosition(0.0f, -1.0f, 0.0f);
/*************************************
g_Walls[0]
初始化墙壁 (0, 3, 10)
________________
/ | / |
/ | / |
/___|___________/ |
| |_ _ _ _ _ _|_ _|
| / | / g_Walls[1]
(-10, 3, 0) | / | / (10, 3, 0)
g_Walls[3] |/______________|/
(0, 3, -10)
width g_Walls[2]
*************************************/
m_Walls.resize(4);
HR(CreateDDSTextureFromFile(m_pd3dDevice.Get(), L"Texture\\brick.dds", nullptr, texture.GetAddressOf()));
for (int i = 0; i < m_Walls.size(); i++) {
m_Walls[i].SetBuffer<VertexPosNormalTangentTex, DWORD>(m_pd3dDevice.Get(), Geometry::CreatePlane(XMFLOAT2(20.0f, 8.0f), XMFLOAT2(5.0f, 1.5f)));
Transform & transform = m_Walls[i].GetTransform();
transform.SetRotation(-XM_PIDIV2, XM_PIDIV2 * i, 0.0f);
transform.SetPosition(i % 2 ? -10.0f * (i - 2) : 0.0f, 3.0f, i % 2 == 0 ? -10.0f * (i - 1) : 0.0f);
m_Walls[i].SetTexture(texture.Get());
}
// 创建并填充采样器状态
D3D11_SAMPLER_DESC sampDesc;
ZeroMemory(&sampDesc, sizeof(sampDesc));
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampDesc.MinLOD = 0;
sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
HR(m_pd3dDevice->CreateSamplerState(&sampDesc, m_pSamplerState.GetAddressOf()));
/**************************
* 设置并初始化常量缓冲区描述 *
***************************/
// 设置常量缓冲区描述
D3D11_BUFFER_DESC cbd;
ZeroMemory(&cbd, sizeof(cbd));
cbd.Usage = D3D11_USAGE_DYNAMIC;
cbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
// 新建4级常量缓冲区
cbd.ByteWidth = sizeof(CBChangesEveryDrawing);
HR(m_pd3dDevice->CreateBuffer(&cbd, nullptr, m_pConstantBuffers[0].GetAddressOf()));
cbd.ByteWidth = sizeof(CBChangesEveryFrame);
HR(m_pd3dDevice->CreateBuffer(&cbd, nullptr, m_pConstantBuffers[1].GetAddressOf()));
cbd.ByteWidth = sizeof(CBChangesOnResize);
HR(m_pd3dDevice->CreateBuffer(&cbd, nullptr, m_pConstantBuffers[2].GetAddressOf()));
cbd.ByteWidth = sizeof(CBChangesRarely);
HR(m_pd3dDevice->CreateBuffer(&cbd, nullptr, m_pConstantBuffers[3].GetAddressOf()));
// 初始化Frame常量缓冲区
m_CameraMode = CameraMode::FPS;
auto camera = std::shared_ptr<FPSCamera>(new FPSCamera);
m_pCamera = camera;
camera->SetViewPort(0.0f, 0.0f, (float)m_ClientWidth, (float)m_ClientHeight);
camera->LookAt(XMFLOAT3(), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT3(0.0f, 1.0f, 0.0f));
// 初始化OnResize常量区
m_pCamera->SetFrustum(XM_PI / 3, AspectRatio(), 0.5f, 1000.0f);
m_CBOnResize.proj = XMMatrixTranspose(m_pCamera->GetProjXM());
// 更新Context的OnResize常量缓冲
D3D11_MAPPED_SUBRESOURCE mappedRes;
HR(m_pd3dImmediateContext->Map(m_pConstantBuffers[2].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRes));
memcpy_s(mappedRes.pData, sizeof(m_CBOnResize), &m_CBOnResize, sizeof(m_CBOnResize));
m_pd3dImmediateContext->Unmap(m_pConstantBuffers[2].Get(), 0);
/******************
* 初始化默认光照 *
*******************/
// 环境光
m_CBRarely.dirLight[0].ambient = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
m_CBRarely.dirLight[0].diffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
m_CBRarely.dirLight[0].specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
m_CBRarely.dirLight[0].direction = XMFLOAT3(0.0f, -1.0f, 0.0f);
// 灯光
m_CBRarely.pointLight[0].position = XMFLOAT3(0.0f, 10.0f, 0.0f);
m_CBRarely.pointLight[0].ambient = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
m_CBRarely.pointLight[0].diffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
m_CBRarely.pointLight[0].specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
m_CBRarely.pointLight[0].att = XMFLOAT3(0.0f, 0.1f, 0.0f);
m_CBRarely.pointLight[0].range = 25.0f;
m_CBRarely.numDirLight = 1;
m_CBRarely.numPointLight = 1;
m_CBRarely.numSpotLight = 0;
// 初始化材质
m_CBRarely.material.ambient = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
m_CBRarely.material.diffuse = XMFLOAT4(0.6f, 0.6f, 0.6f, 1.0f);
m_CBRarely.material.specular = XMFLOAT4(0.1f, 0.1f, 0.1f, 50.0f);
// 更新Context的Rarely常量缓冲
HR(m_pd3dImmediateContext->Map(m_pConstantBuffers[3].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRes));
memcpy_s(mappedRes.pData, sizeof(m_CBRarely), &m_CBRarely, sizeof(m_CBRarely));
m_pd3dImmediateContext->Unmap(m_pConstantBuffers[3].Get(), 0);
/***************
* 绑定资源到管线 *
****************/
// 设置图元类型
m_pd3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
m_pd3dImmediateContext->IASetInputLayout(m_pVertexLayout3D.Get());
// 绑定3DVS到管线
m_pd3dImmediateContext->VSSetShader(m_pVertexShader3D.Get(), nullptr, 0);
// 绑定3DPS着色器到管道
m_pd3dImmediateContext->PSSetShader(m_pPixelShader3D.Get(), nullptr, 0);
// CBDrawing 常量缓冲区对应HLSL寄存于b0 register
m_pd3dImmediateContext->VSSetConstantBuffers(0, 1, m_pConstantBuffers[0].GetAddressOf());
// CBFrame 常量缓冲区对应HLSL寄存于b1 register
m_pd3dImmediateContext->VSSetConstantBuffers(1, 1, m_pConstantBuffers[1].GetAddressOf());
// CBOnResize 常量缓冲区对应HLSL寄存于b2 register
m_pd3dImmediateContext->VSSetConstantBuffers(2, 1, m_pConstantBuffers[2].GetAddressOf());
// CBRarely 常量缓冲区对应HLSL寄存于b3 register
m_pd3dImmediateContext->PSSetConstantBuffers(1, 1, m_pConstantBuffers[1].GetAddressOf());
m_pd3dImmediateContext->PSSetConstantBuffers(3, 1, m_pConstantBuffers[3].GetAddressOf());
/************** 设置着色器资源 *********************
void ID3D11DeviceContext::PSSetShaderResources(
UINT StartSlot, // [In]起始槽索引,对应HLSL的register(t*)
UINT NumViews, // [In]着色器资源视图数目
ID3D11ShaderResourceView * const *ppShaderResourceViews // [In]着色器资源视图数组
);
***********************************************************************************/
m_pd3dImmediateContext->PSSetSamplers(0, 1, m_pSamplerState.GetAddressOf());
return true;
}
<file_sep>#include "GameObject.h"
#include "ThridParty/DXTrace.h"
using namespace DirectX;
GameObject::GameObject() :
m_VertexStride(),
m_IndexCount(),
m_InstancesNum(0) {
}
// 获取物体变换
Transform& GameObject::GetTransform() {
return m_Transform;
}
// 获取物体变换
const Transform& GameObject::GetTransform() const {
return m_Transform;
}
// 设置纹理
void GameObject::SetTexture(ID3D11ShaderResourceView* texture) {
m_Model.modelParts[0].pTexDiffuse = texture;
}
void GameObject::SetNormalmap(ID3D11ShaderResourceView* normalmap) {
m_Model.modelParts[0].pNormalmap = normalmap;
}
// 设置材质
void GameObject::SetMaterial(const Material& material) {
for (auto& part : m_Model.modelParts)
part.material = material;
}
BoundingBox GameObject::GetLocalBoundingBox() const {
BoundingBox box;
m_Model.boundingBox.Transform(box, m_Transform.GetLocalToWorldMatrixXM());
return box;
}
BoundingBox GameObject::GetBoundingBox() const {
return m_Model.boundingBox;
}
BoundingOrientedBox GameObject::GetBoundingOrientedBox() const {
BoundingOrientedBox box;
BoundingOrientedBox::CreateFromBoundingBox(box, m_Model.boundingBox);
box.Transform(box, m_Transform.GetLocalToWorldMatrixXM());
return box;
}
void GameObject::SetModel(Model&& model) {
m_Model = std::move(model);
//model.modelParts.clear();
//model.boundingBox = BoundingBox();
}
void GameObject::SetModel(const Model& model) {
m_Model = model;
}
void GameObject::Draw(ID3D11DeviceContext* deviceContext, BasicEffect& effect) {
// 在上下文装配顶点缓冲区
UINT stride = m_Model.vertexStride;
UINT offset = 0;
for (auto& part : m_Model.modelParts) {
deviceContext->IASetVertexBuffers(0, 1, part.vertexBuffer.GetAddressOf(), &stride, &offset);
// 在上下文上装配索引缓冲区
deviceContext->IASetIndexBuffer(part.indexBuffer.Get(), part.indexFormat, 0);
// 更新Context的drawing常量缓冲
effect.SetWorldMatrix(m_Transform.GetLocalToWorldMatrixXM());
if (m_Model.TexDiffuseMap.count(part.texDiffuse)) {
auto& texDiffuse = m_Model.TexDiffuseMap.find(part.texDiffuse)->second;
effect.SetTexture(texDiffuse.Get());
}
else {
effect.SetTexture(part.pTexDiffuse.Get());
}
if (m_Model.NormalmapMap.count(part.normalMap)) {
auto& normalMap = m_Model.NormalmapMap.find(part.normalMap)->second;
effect.SetNormalMap(normalMap.Get());
effect.UseNormalMap(effect.useNormalmap);
}
else {
effect.SetNormalMap(part.pNormalmap.Get());
effect.UseNormalMap(effect.useNormalmap && part.pNormalmap.Get() != nullptr);
}
effect.SetMaterial(part.material);
effect.Apply(deviceContext);
// 开始绘制
deviceContext->DrawIndexed(part.indexCount, 0, 0);
}
}
void CreateInstancesBuffer(ID3D11Device* device, const std::vector<Instances>& instancesData, ID3D11Buffer** ppInstanceBuffer) {
D3D11_BUFFER_DESC vbd;
ZeroMemory(&vbd, sizeof(vbd));
vbd.Usage = D3D11_USAGE_IMMUTABLE;
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbd.ByteWidth = (UINT)sizeof(Instances) * instancesData.size();
vbd.CPUAccessFlags = 0;
// 新建顶点缓冲区
D3D11_SUBRESOURCE_DATA InitData;
ZeroMemory(&InitData, sizeof(InitData));
InitData.pSysMem = instancesData.data();
HR(device->CreateBuffer(&vbd, &InitData, ppInstanceBuffer));
}
void GameObject::DrawInstance(ID3D11DeviceContext* deviceContext, BasicEffect& effect, const std::vector<Transform>& TransformData) {
ComPtr<ID3D11Device> device;
deviceContext->GetDevice(device.GetAddressOf());
std::vector<Instances> InstancesData(TransformData.size());
for (INT32 i = 0; i < TransformData.size(); i++) {
InstancesData[i].world = DirectX::XMMatrixTranspose(TransformData[i].GetLocalToWorldMatrixXM());
InstancesData[i].worldInvTranspose = DirectX::XMMatrixInverse(nullptr, TransformData[i].GetLocalToWorldMatrixXM());
}
CreateInstancesBuffer(device.Get(), InstancesData, m_pInstancesBuffer.ReleaseAndGetAddressOf());
// 在上下文装配顶点缓冲区
UINT stride[2] = { m_Model.vertexStride, sizeof(Instances) };
UINT offset[2] = { 0, 0 };
for (auto& part : m_Model.modelParts) {
// 使用两个VSBuffer, 0存放顶点信息,1存放InstancesData
ID3D11Buffer* VSBuffer[2] = { part.vertexBuffer.Get(), m_pInstancesBuffer.Get() };
deviceContext->IASetVertexBuffers(0, 2, VSBuffer, stride, offset);
// 在上下文上装配索引缓冲区
deviceContext->IASetIndexBuffer(part.indexBuffer.Get(), part.indexFormat, 0);
// 更新Context的drawing常量缓冲
if (m_Model.TexDiffuseMap.count(part.texDiffuse)) {
auto& texDiffuse = m_Model.TexDiffuseMap.find(part.texDiffuse)->second;
effect.SetTexture(texDiffuse.Get());
}
else {
effect.SetTexture(part.pTexDiffuse.Get());
}
if (m_Model.TexDiffuseMap.count(part.normalMap)) {
auto& normalMap = m_Model.NormalmapMap.find(part.normalMap)->second;
effect.SetNormalMap(normalMap.Get());
}
else {
effect.SetNormalMap(part.pNormalmap.Get());
}
effect.SetMaterial(part.material);
effect.Apply(deviceContext);
// 开始绘制
deviceContext->DrawIndexedInstanced(part.indexCount, TransformData.size(), 0, 0, 0);
}
}
<file_sep>#pragma once
#include "Effects.h"
#include "ThridParty/Geometry.h"
#include "Transform.h"
#include "Model.h"
/******************************************************
* GameObject.h *
* 通过该类可以管理每一个生成的物体,比如墙壁,地板和木箱,*
* 并且对object的绘制函数也移到此类 *
*******************************************************/
class GameObject
{
public:
// 使用模板别名(C++11)简化类型名
template <class T>
using ComPtr = Microsoft::WRL::ComPtr<T>;
GameObject();
// 获取物体变换
Transform& GetTransform();
// 获取物体变换
const Transform& GetTransform() const;
// 获取包围盒
DirectX::BoundingBox GetLocalBoundingBox() const;
DirectX::BoundingBox GetBoundingBox() const;
DirectX::BoundingOrientedBox GetBoundingOrientedBox() const;
// 设置模型
void SetModel(Model && model);
void SetModel(const Model & model);
// 设置缓冲区
template<class VertexType, class IndexType>
void SetBuffer(ID3D11Device* device, const Geometry::MeshData<VertexType, IndexType>& meshData);
// 设置纹理
void SetTexture(ID3D11ShaderResourceView* texture);
void SetNormalmap(ID3D11ShaderResourceView* normalmap);
// 设置材质
void SetMaterial(const Material& material);
// 绘制
void Draw(ID3D11DeviceContext* deviceContext, BasicEffect & effect);
void DrawInstance(ID3D11DeviceContext* deviceContext, BasicEffect& effect, const std::vector<Transform>& instancesData);
private:
Transform m_Transform; // 世界矩阵
ComPtr<ID3D11Buffer> m_pVertexBuffer; // 顶点缓冲区
ComPtr<ID3D11Buffer> m_pIndexBuffer; // 索引缓冲区
ComPtr<ID3D11Buffer> m_pInstancesBuffer;
INT32 m_InstancesNum;
UINT m_VertexStride; // 顶点字节大小
UINT m_IndexCount; // 索引数目
Model m_Model;
};
/*
用于构造顶点和索引,resetMesh被移到这里
*/
template<class VertexType, class IndexType>
void GameObject::SetBuffer(ID3D11Device* device, const Geometry::MeshData<VertexType, IndexType>& meshData) {
// 1.清空顶点和索引缓冲区
m_pVertexBuffer.Reset();
m_pIndexBuffer.Reset();
if (device == nullptr) return;
/*****************
* 2 顶点缓冲区 *
******************/
// 2.1 设置顶点缓冲区描述
D3D11_BUFFER_DESC vbd;
m_VertexStride = sizeof(VertexType);
ZeroMemory(&vbd, sizeof(vbd));
vbd.Usage = D3D11_USAGE_IMMUTABLE;
vbd.ByteWidth = (UINT)meshData.vertexVec.size() * m_VertexStride;
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbd.CPUAccessFlags = 0;
// 2.2 设定用于初始化的数据并在Device上建立缓冲区
D3D11_SUBRESOURCE_DATA initData;
ZeroMemory(&initData, sizeof(initData));
initData.pSysMem = meshData.vertexVec.data();
device->CreateBuffer(&vbd, &initData, m_pVertexBuffer.GetAddressOf());
/**************
*3 索引缓冲区 *
**************/
m_IndexCount = (UINT)meshData.indexVec.size();
// 3.1 设置索引缓冲区描述
D3D11_BUFFER_DESC ibd;
ZeroMemory(&ibd, sizeof(ibd));
ibd.Usage = D3D11_USAGE_IMMUTABLE;
ibd.ByteWidth = (UINT)meshData.indexVec.size() * sizeof(IndexType);
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
// 3.2 建立索引缓冲区
initData.pSysMem = meshData.indexVec.data();
device->CreateBuffer(&ibd, &initData, m_pIndexBuffer.GetAddressOf());
}<file_sep>#ifndef Ex9Tex_H
#define Ex9Tex_H
#include "d3dApp.h"
#include "light.h"
#include "CBuffer.h"
#include <vector>
/*****************************************
Ex9:
实现了贴图的载入,以及2D动画的实现。
******************************************/
class Ex9Tex : public D3DApp {
enum class ShowMode {
WoodCrate, FireAnim
};
public:
Ex9Tex(HINSTANCE hInstance);
virtual ~Ex9Tex();
bool Init();
void OnResize();
void UpdateScene(float dt);
void DrawScene();
protected:
bool InitEffect();
bool InitResource();
template<class VertexType>
bool ResetMesh(const Geometry::MeshData<VertexType>& meshData);
ComPtr<ID3D11InputLayout> m_pVertexLayout2D; // 2D顶点输入布局
ComPtr<ID3D11InputLayout> m_pVertexLayout3D; // 3D顶点输入布局
ComPtr<ID3D11Buffer> m_pVertexBuffer; // 顶点缓冲区
ComPtr<ID3D11Buffer> m_pIndexBuffer; // 索引缓冲区
ComPtr<ID3D11Buffer> m_pConstantBuffers[4]; // 常量缓冲区
UINT m_IndexCount;
UINT m_CurrFrame;
ShowMode m_CurrMode;
ComPtr<ID3D11VertexShader> m_pVertexShader2D; // 2D顶点着色器
ComPtr<ID3D11VertexShader> m_pVertexShader3D; // 3D顶点着色器
ComPtr<ID3D11PixelShader> m_pPixelShader2D; // 2D像素着色器
ComPtr<ID3D11PixelShader> m_pPixelShader3D; // 3D像素着色器
CBChangesEveryDrawing m_CBDrawing;
CBChangesEveryFrame m_CBFrame;
CBChangesOnResize m_CBOnResize;
CBChangesRarely m_CBRarely;
ComPtr<ID3D11SamplerState> m_pSamplerState;
// 光照模型
PointLight m_PointLight;
ComPtr<ID3D11RasterizerState> m_pRSWireframe; //光栅化状态,切换线框模式
// 纹理资源
ComPtr<ID3D11ShaderResourceView> m_pWoodCrate;
std::vector<ComPtr<ID3D11ShaderResourceView>> m_pFireAnims;
};
#endif<file_sep>#include "Vertex.h"
using namespace DirectX;
const D3D11_INPUT_ELEMENT_DESC VertexPosNormalColor::inputLayout[3] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
const D3D11_INPUT_ELEMENT_DESC VertexPosTex::inputLayout[2] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
const D3D11_INPUT_ELEMENT_DESC VertexPosNormal::inputLayout[2] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
const D3D11_INPUT_ELEMENT_DESC VertexPosNormalTex::inputLayout[3] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
const D3D11_INPUT_ELEMENT_DESC VertexPosNormalTangentTex::inputLayout[4] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TANGENT", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 40, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
const D3D11_INPUT_ELEMENT_DESC Instances::inputLayout[10] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "WORLD", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 0, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "WORLD", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 16, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "WORLD", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 32, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "WORLD", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 48, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "WORLDINVTRANSPOSE", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 64, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "WORLDINVTRANSPOSE", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 80, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "WORLDINVTRANSPOSE", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 96, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "WORLDINVTRANSPOSE", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 112, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
};
void CalculeTangent(std::vector<VertexPosNormalTangentTex>& triangle) {
XMFLOAT3 edge1 = XMFLOAT3(
triangle[0].pos.x - triangle[1].pos.x,
triangle[0].pos.y - triangle[1].pos.y,
triangle[0].pos.z - triangle[1].pos.z);
XMFLOAT3 edge2 = XMFLOAT3(
triangle[0].pos.x - triangle[2].pos.x,
triangle[0].pos.y - triangle[2].pos.y,
triangle[0].pos.z - triangle[2].pos.z);
XMFLOAT2 deltaUV1 = XMFLOAT2(
triangle[0].tex.x - triangle[1].tex.x,
triangle[0].tex.y - triangle[1].tex.y);
XMFLOAT2 deltaUV2 = XMFLOAT2(
triangle[0].tex.x - triangle[2].tex.x,
triangle[0].tex.y - triangle[2].tex.y);
float f = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV2.x * deltaUV1.y);
for (int i = 0; i < triangle.size(); i++) {
triangle[i].tangent.x = f * (deltaUV2.y * edge1.x - deltaUV1.y * edge2.x);
triangle[i].tangent.y = f * (deltaUV2.y * edge1.y - deltaUV1.y * edge2.y);
triangle[i].tangent.z = f * (deltaUV2.y * edge1.z - deltaUV1.y * edge2.z);
}
}
<file_sep>#pragma once
#include "d3dApp.h"
#include "Transform.h"
#include "Camera.h"
#include "GameObject.h"
/*************************
Ex19 实现了导入模型
**************************/
class Ex19ReadObj :
public D3DApp
{
public:
// 摄像机模式
enum class CameraMode { FPS, TPS, Free, Observe };
public:
Ex19ReadObj(HINSTANCE hInstance);
virtual ~Ex19ReadObj();
bool Init();
void OnResize();
void UpdateScene(float dt);
void DrawScene();
protected:
bool InitResource();
GameObject m_WoodCrate;
GameObject m_Ground;
GameObject m_House;
GameObject m_Floor;
GameObject m_Sphere;
GameObject m_Scene;
std::vector<GameObject> m_Walls;
bool m_IsWireframeMode;
Material m_ShadowMat;
Material m_Material;
BasicEffect m_BasicEffect;
std::shared_ptr<Camera> m_pCamera;
CameraMode m_CameraMode;
ObjReader m_ObjReader;
};
<file_sep>#include "Camera.h"
using namespace DirectX;
Camera::~Camera() {
}
XMVECTOR Camera::GetPositionXM() const{
return m_Transform.GetPositionXM();
}
XMFLOAT3 Camera::GetPosition() const {
return m_Transform.GetPosition();
}
float Camera::GetRotationX() const {
return m_Transform.GetRotation().x;
}
float Camera::GetRotationY() const {
return m_Transform.GetRotation().y;
}
//获取摄像机坐标轴向量
XMVECTOR Camera::GetRightAxisXM() const
{
return m_Transform.GetRightAxisXM();
}
XMFLOAT3 Camera::GetRightAxis() const {
return m_Transform.GetRightAxis();
}
XMVECTOR Camera::GetUpAxisXM() const
{
return m_Transform.GetUpAxisXM();
}
XMFLOAT3 Camera::GetUpAxis() const {
return m_Transform.GetUpAxis();
}
XMVECTOR Camera::GetLookAxisXM() const
{
return m_Transform.GetForwardAxisXM();
}
XMFLOAT3 Camera::GetLookAxis() const {
return m_Transform.GetForwardAxis();
}
/*获取矩阵*/
XMMATRIX Camera::GetViewXM() const {
return m_Transform.GetWorldToLocalMatrixXM();
}
XMMATRIX Camera::GetProjXM() const {
return XMMatrixPerspectiveFovLH(m_FovY, m_Aspect, m_NearZ, m_FarZ);
}
XMMATRIX Camera::GetViewProjXM() const {
return GetViewXM() * GetProjXM();
}
// 获取视口
D3D11_VIEWPORT Camera::GetViewPort() const {
return m_ViewPort;
}
// 设置平截头体
void Camera::SetFrustum(float fovY, float aspec, float nearZ, float farZ) {
m_FovY = fovY;
m_Aspect = aspec;
m_NearZ = nearZ;
m_FarZ = farZ;
}
// 设置视口
void Camera::SetViewPort(const D3D11_VIEWPORT& viewport) {
m_ViewPort = viewport;
}
void Camera::SetViewPort(float topLeftX, float topLeftY, float width, float height, float minDepth, float maxDepth) {
D3D11_VIEWPORT viewPort;
ZeroMemory(&viewPort, sizeof(viewPort));
viewPort.TopLeftX = topLeftX;
viewPort.TopLeftY = topLeftY;
viewPort.Width = width;
viewPort.Height = height;
viewPort.MinDepth = minDepth;
viewPort.MaxDepth = maxDepth;
m_ViewPort = viewPort;
}
/***********************
第一人称摄像机
************************/
FPSCamera::~FPSCamera() {
}
void FPSCamera::SetPosition(float x, float y, float z)
{
SetPosition(XMFLOAT3(x, y, z));
}
void FPSCamera::SetPosition(const XMFLOAT3& pos)
{
m_Transform.SetPosition(pos);
}
// 设置摄像机朝向
void FPSCamera::LookAt(const XMFLOAT3& pos, const XMFLOAT3& target, const XMFLOAT3& up) {
m_Transform.SetPosition(pos);
m_Transform.LookAt(target, up);
}
void FPSCamera::LookTo(const XMFLOAT3& pos, const XMFLOAT3& to, const XMFLOAT3& up) {
m_Transform.SetPosition(pos);
m_Transform.LookTo(to, up);
}
// 左右平移
void FPSCamera::Strafe(float d) {
m_Transform.Translate(m_Transform.GetRightAxis(), d);
}
// 第一人称前后移动
void FPSCamera::Walk(float d) {
XMVECTOR rightVec = m_Transform.GetRightAxisXM();
XMVECTOR frontVec = XMVector3Normalize(XMVector3Cross(rightVec, g_XMIdentityR1));
XMFLOAT3 front;
XMStoreFloat3(&front, frontVec);
m_Transform.Translate(front, d);
}
// 前进
void FPSCamera::MoveForward(float d) {
m_Transform.Translate(m_Transform.GetForwardAxis(), d);
}
// 上下观察,+值向上,-值向下
void FPSCamera::Pitch(float rad) {
XMFLOAT3 rotation = m_Transform.GetRotation();
// 俯仰角 绕x轴
rotation.x += rad;
// 为了防止过度抬头, 将俯仰角限制在了+-70°
if (rotation.x > XM_PI * 7 / 18)
rotation.x = XM_PI * 7 / 18;
else if (rotation.x < -XM_PI * 7 / 18)
rotation.x = -XM_PI * 7 / 18;
m_Transform.SetRotation(rotation);
}
// 左右观察 +值向左,-值向右
void FPSCamera::RotateY(float rad) {
XMFLOAT3 rotation = m_Transform.GetRotation();
rotation.y = XMScalarModAngle(rotation.y + rad);
m_Transform.SetRotation(rotation);
}
/***********************
第三人称摄像机
************************/
TPSCamera::~TPSCamera()
{
}
XMFLOAT3 TPSCamera::GetTargetPosition() const {
return m_Target;
}
float TPSCamera::GetDistance() const {
return m_Distance;
}
void TPSCamera::RotateX(float rad) {
XMFLOAT3 rotation = m_Transform.GetRotation();
rotation.x += rad;
if (rotation.x > XM_PI / 3)
rotation.x = XM_PI / 3;
else if (rotation.x < 0.0f)
rotation.x = 0.0f;
m_Transform.SetRotation(rotation);
m_Transform.SetPosition(m_Target);
m_Transform.Translate(m_Transform.GetForwardAxis(), -m_Distance);
}
void TPSCamera::RotateY(float rad) {
XMFLOAT3 rotation = m_Transform.GetRotation();
rotation.y = XMScalarModAngle(rotation.y + rad);
m_Transform.SetRotation(rotation);
m_Transform.SetPosition(m_Target);
m_Transform.Translate(m_Transform.GetForwardAxis(), -m_Distance);
}
void TPSCamera::Approach(float dist) {
m_Distance += dist;
if (m_Distance < m_MinDist) m_Distance = m_MinDist;
else if (m_Distance > m_MaxDist) m_Distance = m_MaxDist;
m_Transform.SetPosition(m_Target);
m_Transform.Translate(m_Transform.GetForwardAxis(), -m_Distance);
}
void TPSCamera::SetRotationX(float rad) {
XMFLOAT3 rotation = m_Transform.GetRotation();
rotation.x = rad;
if (rotation.x < -XM_PI / 3)
rotation.x = -XM_PI / 3;
else if (rotation.x > 0.0f)
rotation.x = 0.0f;
m_Transform.SetRotation(rotation);
m_Transform.SetPosition(m_Target);
m_Transform.Translate(m_Transform.GetForwardAxis(), -m_Distance);
}
void TPSCamera::SetRotationY(float rad) {
XMFLOAT3 rotation = m_Transform.GetRotation();
rotation.y = XMScalarModAngle(rad);
m_Transform.SetRotation(rotation);
m_Transform.SetPosition(m_Target);
m_Transform.Translate(m_Transform.GetForwardAxis(), -m_Distance);
}
void TPSCamera::SetTarget(const XMFLOAT3& pos) {
m_Target = pos;
}
void TPSCamera::SetDistance(const float dist) {
m_Distance = dist;
}
void TPSCamera::SetDistMinMax(float minDist, float maxDist) {
m_MinDist = minDist;
m_MaxDist = maxDist;
}
<file_sep>#include "Ex9Tex.h"
using namespace DirectX;
Ex9Tex::Ex9Tex(HINSTANCE hInstance)
:D3DApp(hInstance),
m_IndexCount(),
m_CurrFrame(),
m_CurrMode(ShowMode::WoodCrate),
m_CBDrawing(),
m_CBFrame(),
m_CBOnResize(),
m_CBRarely(),
m_PointLight()
{
}
Ex9Tex::~Ex9Tex()
{
}
bool Ex9Tex::Init()
{
if (!D3DApp::Init()) return false;
if (!InitEffect()) return false;
if (!InitResource()) return false;
m_pMouse->SetWindow(m_hMainWnd);
m_pMouse->SetMode(Mouse::MODE_ABSOLUTE);
return true;
}
void Ex9Tex::OnResize()
{
D3DApp::OnResize();
}
void Ex9Tex::UpdateScene(float dt)
{
// 获取鼠标状态
Mouse::State mouseState = m_pMouse->GetState();
Mouse::State lastMouseState = m_MouseTracker.GetLastState();
// 获取键盘状态
Keyboard::State keyState = m_pKeyboard->GetState();
Keyboard::State lastKeyState = m_KeyboardTracker.GetLastState();
static float phi = 0.0f, theta = 0.0f, objSize = 1.0f;
m_MouseTracker.Update(mouseState);
m_KeyboardTracker.Update(keyState);
if (m_KeyboardTracker.IsKeyPressed(Keyboard::D1)) {
m_CurrMode = ShowMode::WoodCrate;
m_pd3dImmediateContext->IASetInputLayout(m_pVertexLayout3D.Get());
auto meshData = Geometry::CreateBox<VertexPosNormalTex>();
ResetMesh(meshData);
m_pd3dImmediateContext->VSSetShader(m_pVertexShader3D.Get(), nullptr, 0);
m_pd3dImmediateContext->PSSetShader(m_pPixelShader3D.Get(), nullptr, 0);
m_pd3dImmediateContext->PSSetShaderResources(0, 1, m_pWoodCrate.GetAddressOf());
}
else if (m_KeyboardTracker.IsKeyPressed(Keyboard::D2) && m_CurrMode != ShowMode::FireAnim) {
m_CurrMode = ShowMode::FireAnim;
m_CurrFrame = 0;
m_pd3dImmediateContext->IASetInputLayout(m_pVertexLayout2D.Get());
auto meshData = Geometry::Create2DShow();
ResetMesh(meshData);
m_pd3dImmediateContext->VSSetShader(m_pVertexShader2D.Get(), nullptr, 0);
m_pd3dImmediateContext->PSSetShader(m_pPixelShader2D.Get(), nullptr, 0);
m_pd3dImmediateContext->PSSetShaderResources(0, 1, m_pFireAnims[0].GetAddressOf());
}
if (m_CurrMode == ShowMode::WoodCrate) {
int deltaScrollWhellValue = mouseState.scrollWheelValue - lastMouseState.scrollWheelValue;
objSize += deltaScrollWhellValue * 0.0001f;
XMMATRIX scaling = XMMatrixScaling(objSize, objSize, objSize);
if (mouseState.leftButton == true && m_MouseTracker.leftButton == m_MouseTracker.HELD)
{
int dx = (mouseState.x - lastMouseState.x), dy = mouseState.y - lastMouseState.y;
theta -= dx * 0.01f;
phi -= dy * 0.01f;
}
if (keyState.IsKeyDown(Keyboard::W))
phi += dt * 2;
if (keyState.IsKeyDown(Keyboard::S))
phi -= dt * 2;
if (keyState.IsKeyDown(Keyboard::A))
theta += dt * 2;
if (keyState.IsKeyDown(Keyboard::D))
theta -= dt * 2;
// 世界空间变换: 缩放与旋转
XMMATRIX transform = scaling * XMMatrixRotationY(theta) * XMMatrixRotationX(phi);
m_CBDrawing.world = XMMatrixTranspose(transform);
// 转置逆矩阵
m_CBDrawing.worldInvTranspose = XMMatrixInverse(nullptr, transform);
D3D11_MAPPED_SUBRESOURCE mappedRes;
HR(m_pd3dImmediateContext->Map(m_pConstantBuffers[0].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRes));
memcpy_s(mappedRes.pData, sizeof(CBChangesEveryDrawing), &m_CBDrawing, sizeof(CBChangesEveryDrawing));
m_pd3dImmediateContext->Unmap(m_pConstantBuffers[0].Get(), 0);
}
else if (m_CurrMode == ShowMode::FireAnim) {
// 规定fps60
static float totDeltaTime = 0;
totDeltaTime += dt;
if (totDeltaTime > 1.0f / 60){
totDeltaTime -= 1.0f / 60;
m_CurrFrame = (m_CurrFrame + 1) % 120;
m_pd3dImmediateContext->PSSetShaderResources(0, 1, m_pFireAnims[m_CurrFrame].GetAddressOf());
}
}
}
void Ex9Tex::DrawScene()
{
assert(m_pd3dImmediateContext);
assert(m_pSwapChain);
m_pd3dImmediateContext->ClearRenderTargetView(m_pRenderTargetView.Get(), reinterpret_cast<const float*>(&DirectX::Colors::Black));
m_pd3dImmediateContext->ClearDepthStencilView(m_pDepthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
m_pd3dImmediateContext->DrawIndexed(m_IndexCount, 0, 0);
HR(m_pSwapChain->Present(0, 0));
}
bool Ex9Tex::InitEffect()
{
ComPtr<ID3DBlob> blob;
// 创建顶点着色器(2D)
HR(CreateShaderFromFile(L"HLSL\\Basic_VS_2D.cso", L"HLSL\\Basic_VS_2D.hlsl", "VS_2D", "vs_5_0", blob.ReleaseAndGetAddressOf()));
HR(m_pd3dDevice->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pVertexShader2D.GetAddressOf()));
// 创建顶点布局(2D)
HR(m_pd3dDevice->CreateInputLayout(VertexPosTex::inputLayout, ARRAYSIZE(VertexPosTex::inputLayout),
blob->GetBufferPointer(), blob->GetBufferSize(), m_pVertexLayout2D.GetAddressOf()));
// 创建顶点着色器(3D)
HR(CreateShaderFromFile(L"HLSL\\Basic_VS_3D.cso", L"HLSL\\Basic_VS_3D.hlsl", "VS_3D", "vs_5_0", blob.ReleaseAndGetAddressOf()));
HR(m_pd3dDevice->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pVertexShader3D.GetAddressOf()));
// 创建顶点布局(3D)
HR(m_pd3dDevice->CreateInputLayout(VertexPosNormalTex::inputLayout, ARRAYSIZE(VertexPosNormalTex::inputLayout),
blob->GetBufferPointer(), blob->GetBufferSize(), m_pVertexLayout3D.GetAddressOf()));
// 创建像素着色器(2D)
HR(CreateShaderFromFile(L"HLSL\\Basic_PS_2D.cso", L"HLSL\\Basic_PS_2D.hlsl", "PS_2D", "ps_5_0", blob.ReleaseAndGetAddressOf()));
HR(m_pd3dDevice->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pPixelShader2D.GetAddressOf()));
// 创建像素着色器(3D)
HR(CreateShaderFromFile(L"HLSL\\Basic_PS_3D.cso", L"HLSL\\Basic_PS_3D.hlsl", "PS_3D", "ps_5_0", blob.ReleaseAndGetAddressOf()));
HR(m_pd3dDevice->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pPixelShader3D.GetAddressOf()));
return true;
}
bool Ex9Tex::InitResource()
{
/**************************
* 重置顶点缓冲区和索引缓冲区 *
***************************/
Geometry::MeshData<VertexPosNormalTex> meshdata = Geometry::CreateBox<VertexPosNormalTex>();
ResetMesh(meshdata);
/*******************
初始化纹理
********************/
// 读取木箱
HR(CreateDDSTextureFromFile(m_pd3dDevice.Get(), L"Texture\\WoodCrate.dds", nullptr, m_pWoodCrate.GetAddressOf()));
// 读取火焰
m_pFireAnims.resize(120);
WCHAR filename[40];
for (int i = 1; i <= 120; ++i)
{
wsprintf(filename, L"Texture\\FireAnim\\Fire%03d.bmp", i);
HR(CreateWICTextureFromFile(m_pd3dDevice.Get(), filename, nullptr, m_pFireAnims[static_cast<size_t>(i) - 1].GetAddressOf()));
}
// 创建并填充采样器状态
D3D11_SAMPLER_DESC sampDesc;
ZeroMemory(&sampDesc, sizeof(sampDesc));
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampDesc.MinLOD = 0;
sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
HR(m_pd3dDevice->CreateSamplerState(&sampDesc, m_pSamplerState.GetAddressOf()));
/******************
* 初始化默认光照 *
*******************/
// 点光
m_PointLight.position = XMFLOAT3(0.0f, 0.0f, -10.0f);
m_PointLight.ambient = XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f);
m_PointLight.diffuse = XMFLOAT4(0.7f, 0.7f, 0.7f, 1.0f);
m_PointLight.specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
m_PointLight.att = XMFLOAT3(0.0f, 0.1f, 0.0f);
m_PointLight.range = 25.0f;
/**************************
* 设置并初始化常量缓冲区描述 *
***************************/
// 设置常量缓冲区描述
D3D11_BUFFER_DESC cbd;
ZeroMemory(&cbd, sizeof(cbd));
cbd.Usage = D3D11_USAGE_DYNAMIC;
cbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
// 新建4级常量缓冲区
cbd.ByteWidth = sizeof(CBChangesEveryDrawing);
HR(m_pd3dDevice->CreateBuffer(&cbd, nullptr, m_pConstantBuffers[0].GetAddressOf()));
cbd.ByteWidth = sizeof(CBChangesEveryFrame);
HR(m_pd3dDevice->CreateBuffer(&cbd, nullptr, m_pConstantBuffers[1].GetAddressOf()));
cbd.ByteWidth = sizeof(CBChangesOnResize);
HR(m_pd3dDevice->CreateBuffer(&cbd, nullptr, m_pConstantBuffers[2].GetAddressOf()));
cbd.ByteWidth = sizeof(CBChangesRarely);
HR(m_pd3dDevice->CreateBuffer(&cbd, nullptr, m_pConstantBuffers[3].GetAddressOf()));
// 初始化 m_CBDrawing
m_CBDrawing.world = XMMatrixIdentity();
m_CBDrawing.worldInvTranspose = XMMatrixIdentity();
// 初始化 m_CBFrame
m_CBFrame.view = XMMatrixTranspose(XMMatrixLookAtLH(
XMVectorSet(0.0f, 0.0f, -5.0f, 0.0f),
XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f),
XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f)
));
// 初始化摄像机位置
m_CBFrame.eysPos = XMFLOAT4(0, 0, -5.0f, 0);
// 初始化 m_CBOnResize
m_CBOnResize.proj = XMMatrixTranspose(XMMatrixPerspectiveFovLH(XM_PIDIV2, AspectRatio(), 1.0f, 1000.0f));
// 初始化 m_CBRarely
m_CBRarely.pointLight[0] = m_PointLight;
m_CBRarely.numDirLight = 0;
m_CBRarely.numPointLight = 1;
m_CBRarely.numSpotLight = 0;
// 初始化材质
m_CBRarely.material.ambient = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
m_CBRarely.material.diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
m_CBRarely.material.specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 5.0f);
// 更新所有
D3D11_MAPPED_SUBRESOURCE mappedRes;
HR(m_pd3dImmediateContext->Map(m_pConstantBuffers[0].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRes));
memcpy_s(mappedRes.pData, sizeof(CBChangesEveryDrawing), &m_CBDrawing, sizeof(CBChangesEveryDrawing));
m_pd3dImmediateContext->Unmap(m_pConstantBuffers[0].Get(), 0);
HR(m_pd3dImmediateContext->Map(m_pConstantBuffers[1].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRes));
memcpy_s(mappedRes.pData, sizeof(CBChangesEveryFrame), &m_CBFrame, sizeof(CBChangesEveryFrame));
m_pd3dImmediateContext->Unmap(m_pConstantBuffers[1].Get(), 0);
HR(m_pd3dImmediateContext->Map(m_pConstantBuffers[2].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRes));
memcpy_s(mappedRes.pData, sizeof(CBChangesOnResize), &m_CBOnResize, sizeof(CBChangesOnResize));
m_pd3dImmediateContext->Unmap(m_pConstantBuffers[2].Get(), 0);
HR(m_pd3dImmediateContext->Map(m_pConstantBuffers[3].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRes));
memcpy_s(mappedRes.pData, sizeof(CBChangesRarely), &m_CBRarely, sizeof(CBChangesRarely));
m_pd3dImmediateContext->Unmap(m_pConstantBuffers[3].Get(), 0);
/***************
* 绑定资源到管线 *
****************/
// 设置图元类型
m_pd3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
m_pd3dImmediateContext->IASetInputLayout(m_pVertexLayout3D.Get());
// 绑定3DVS到管线
m_pd3dImmediateContext->VSSetShader(m_pVertexShader3D.Get(), nullptr, 0);
// 绑定3DPS着色器到管道
m_pd3dImmediateContext->PSSetShader(m_pPixelShader3D.Get(), nullptr, 0);
// VS 常量缓冲区对应HLSL寄存于b0 register
m_pd3dImmediateContext->VSSetConstantBuffers(0, 1, m_pConstantBuffers[0].GetAddressOf());
m_pd3dImmediateContext->VSSetConstantBuffers(1, 1, m_pConstantBuffers[1].GetAddressOf());
m_pd3dImmediateContext->VSSetConstantBuffers(2, 1, m_pConstantBuffers[2].GetAddressOf());
// PS常量缓冲区对应HLSL寄存于b1 register
m_pd3dImmediateContext->PSSetConstantBuffers(1, 1, m_pConstantBuffers[1].GetAddressOf());
m_pd3dImmediateContext->PSSetConstantBuffers(3, 1, m_pConstantBuffers[3].GetAddressOf());
/************** 设置着色器资源 *********************
void ID3D11DeviceContext::PSSetShaderResources(
UINT StartSlot, // [In]起始槽索引,对应HLSL的register(t*)
UINT NumViews, // [In]着色器资源视图数目
ID3D11ShaderResourceView * const *ppShaderResourceViews // [In]着色器资源视图数组
);
***********************************************************************************/
m_pd3dImmediateContext->PSSetShaderResources(0, 1, m_pWoodCrate.GetAddressOf());
m_pd3dImmediateContext->PSSetSamplers(0, 1, m_pSamplerState.GetAddressOf());
return true;
}
template<class VertexType>
bool Ex9Tex::ResetMesh(const Geometry::MeshData<VertexType>& meshData) {
// 1.清空顶点和索引缓冲区
m_pVertexBuffer.Reset();
m_pIndexBuffer.Reset();
/*****************
* 2 顶点缓冲区 *
******************/
// 2.1 设置顶点缓冲区描述
D3D11_BUFFER_DESC vbd;
ZeroMemory(&vbd, sizeof(vbd));
vbd.Usage = D3D11_USAGE_IMMUTABLE;
vbd.ByteWidth = (UINT)meshData.vertexVec.size() * sizeof(VertexType);
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbd.CPUAccessFlags = 0;
// 2.2 设定用于初始化的数据并在Device上建立缓冲区
D3D11_SUBRESOURCE_DATA initData;
ZeroMemory(&initData, sizeof(initData));
initData.pSysMem = meshData.vertexVec.data();
HR(m_pd3dDevice->CreateBuffer(&vbd, &initData, m_pVertexBuffer.GetAddressOf()));
// 2.3 在上下文装配顶点缓冲区
UINT stride = sizeof(VertexType);
UINT offset = 0;
m_pd3dImmediateContext->IASetVertexBuffers(0, 1, m_pVertexBuffer.GetAddressOf(), &stride, &offset);
/**************
*3 索引缓冲区 *
**************/
m_IndexCount = (UINT)meshData.indexVec.size();
// 3.1 设置索引缓冲区描述
D3D11_BUFFER_DESC ibd;
ZeroMemory(&ibd, sizeof(ibd));
ibd.Usage = D3D11_USAGE_IMMUTABLE;
ibd.ByteWidth = (UINT)meshData.indexVec.size() * sizeof(DWORD);
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
// 3.2 建立索引缓冲区
initData.pSysMem = meshData.indexVec.data();
HR(m_pd3dDevice->CreateBuffer(&ibd, &initData, m_pIndexBuffer.GetAddressOf()));
// 3.3 在上下文上装配索引缓冲区
m_pd3dImmediateContext->IASetIndexBuffer(m_pIndexBuffer.Get(), DXGI_FORMAT_R32_UINT, 0);
return true;
}
<file_sep>#pragma once
#include <string.h>
#include <DirectXMath.h>
struct Material {
DirectX::XMFLOAT4 ambient;
DirectX::XMFLOAT4 diffuse;
DirectX::XMFLOAT4 specular;
DirectX::XMFLOAT4 reflect;
Material() = default;
};
// 平行光模型
struct DirectionalLight
{
DirectX::XMFLOAT4 ambient;
DirectX::XMFLOAT4 diffuse;
DirectX::XMFLOAT4 specular;
DirectX::XMFLOAT3 direction;
float foo; //显示的使结构体16字节对齐
};
struct PointLight {
PointLight() {
memset(this, 0, sizeof(PointLight));
}
DirectX::XMFLOAT4 ambient;
DirectX::XMFLOAT4 diffuse;
DirectX::XMFLOAT4 specular;
// 打包成4D向量 (pos, range)
DirectX::XMFLOAT3 position;
float range;
// 4D 向量 (A0, A1, A2, pad)
DirectX::XMFLOAT3 att;
float pad;
};
struct SpotLight
{
DirectX::XMFLOAT4 ambient;
DirectX::XMFLOAT4 diffuse;
DirectX::XMFLOAT4 specular;
// 打包成4D向量: (position, range)
DirectX::XMFLOAT3 position;
float range;
// 打包成4D向量: (direction, spot)
DirectX::XMFLOAT3 direction;
float spot;
// 打包成4D向量: (att, pad)
DirectX::XMFLOAT3 att;
float pad; // 最后用一个浮点数填充使得该结构体大小满足16的倍数,便于我们以后在HLSL设置数组
};
<file_sep>//#include "Ex7Light.h"
//#include "Ex9Tex.h"
//#include "Ex10Camera.h"
//#include "Ex13Shadow.h"
//#include "Ex19ReadObj.h"
#include "RenderSponza.h"
int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE prevInstance,
_In_ LPSTR cmdLine, _In_ int showCmd)
{
// 这些参数不使用
UNREFERENCED_PARAMETER(prevInstance);
UNREFERENCED_PARAMETER(cmdLine);
UNREFERENCED_PARAMETER(showCmd);
// 允许在Debug版本进行运行时内存分配和泄漏检测
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
D3DApp * theApp = new RenderSponza(hInstance);
if( !theApp->Init() )
return 0;
theApp->Run();
delete theApp;
return 0;
}
<file_sep>#include "Ex7Light.h"
using namespace DirectX;
Ex7Light::Ex7Light(HINSTANCE hInstance)
: D3DApp(hInstance),
m_IndexCount(),
m_VSConstantBuffer(),
m_PSConstantBuffer(),
m_DirLight(),
m_PointLight(),
m_SpotLight(),
m_IsWireframeMode(false){
}
Ex7Light::~Ex7Light() {
}
bool Ex7Light::Init() {
if (!D3DApp::Init()) {
return false;
}
if (!InitEffect()) {
return false;
}
if (!InitResource()) {
return false;
}
return true;
}
void Ex7Light::OnResize() {
D3DApp::OnResize();
}
void Ex7Light::UpdateScene(float dt) {
// 获取鼠标状态
Mouse::State mouseState = m_pMouse->GetState();
Mouse::State lastMouseState = m_MouseTracker.GetLastState();
// 获取键盘状态
Keyboard::State keyState = m_pKeyboard->GetState();
Keyboard::State lastKeyState = m_KeyboardTracker.GetLastState();
static float phi = 0.0f, theta = 0.0f, objSize = 1.0f;
m_MouseTracker.Update(mouseState);
m_KeyboardTracker.Update(keyState);
int deltaScrollWhellValue = mouseState.scrollWheelValue - lastMouseState.scrollWheelValue;
objSize += deltaScrollWhellValue * 0.0001f;
XMMATRIX scaling = XMMatrixScaling(objSize, objSize, objSize);
if (mouseState.leftButton == true && m_MouseTracker.leftButton == m_MouseTracker.HELD)
{
int dx = (mouseState.x - lastMouseState.x), dy = mouseState.y - lastMouseState.y;
theta -= dx * 0.01f;
phi -= dy * 0.01f;
}
if (keyState.IsKeyDown(Keyboard::W))
phi += dt * 2;
if (keyState.IsKeyDown(Keyboard::S))
phi -= dt * 2;
if (keyState.IsKeyDown(Keyboard::A))
theta += dt * 2;
if (keyState.IsKeyDown(Keyboard::D))
theta -= dt * 2;
if (keyState.IsKeyDown(Keyboard::D1)) {
m_PSConstantBuffer.dirLight = m_DirLight;
m_PSConstantBuffer.pointLight = PointLight();
m_PSConstantBuffer.spotLight = SpotLight();
}
if (keyState.IsKeyDown(Keyboard::D2)) {
m_PSConstantBuffer.dirLight = DirectionalLight();
m_PSConstantBuffer.pointLight = m_PointLight;
m_PSConstantBuffer.spotLight = SpotLight();
}
if (keyState.IsKeyDown(Keyboard::D3)) {
m_PSConstantBuffer.dirLight = DirectionalLight();
m_PSConstantBuffer.pointLight = PointLight();
m_PSConstantBuffer.spotLight = m_SpotLight;
}
// 切换光栅化状态
if (m_KeyboardTracker.IsKeyPressed(Keyboard::R))
{
m_IsWireframeMode = !m_IsWireframeMode;
m_pd3dImmediateContext->RSSetState(m_IsWireframeMode ? m_pRSWireframe.Get() : nullptr);
}
// 世界空间变换,旋转和缩放
XMMATRIX transform = XMMatrixRotationY(theta) * XMMatrixRotationX(phi) * scaling;
m_VSConstantBuffer.world = XMMatrixTranspose(transform);
// 转置逆矩阵
m_VSConstantBuffer.worldInvTranspose = XMMatrixInverse(nullptr, transform);
D3D11_MAPPED_SUBRESOURCE mappedRes;
HR(m_pd3dImmediateContext->Map(m_pConstantBuffer[0].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRes));
memcpy_s(mappedRes.pData, sizeof(m_VSConstantBuffer), &m_VSConstantBuffer, sizeof(m_VSConstantBuffer));
m_pd3dImmediateContext->Unmap(m_pConstantBuffer[0].Get(), 0);
HR(m_pd3dImmediateContext->Map(m_pConstantBuffer[1].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRes));
memcpy_s(mappedRes.pData, sizeof(m_PSConstantBuffer), &m_PSConstantBuffer, sizeof(m_PSConstantBuffer));
m_pd3dImmediateContext->Unmap(m_pConstantBuffer[1].Get(), 0);
}
void Ex7Light::DrawScene() {
assert(m_pd3dImmediateContext);
assert(m_pSwapChain);
m_pd3dImmediateContext->ClearRenderTargetView(m_pRenderTargetView.Get(), reinterpret_cast<const float*>(&DirectX::Colors::Black));
m_pd3dImmediateContext->ClearDepthStencilView(m_pDepthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
m_pd3dImmediateContext->DrawIndexed(m_IndexCount, 0, 0);
HR(m_pSwapChain->Present(0, 0));
}
bool Ex7Light::InitEffect() {
//创建顶点着色器
ComPtr<ID3DBlob> blob;
// 将HLSL文件转成二进制码
HR(CreateShaderFromFile(L"HLSL\\VertexShader.cso", L"HLSL\\VertextShader.hlsl", "VS", "vs_5_0", blob.ReleaseAndGetAddressOf()));
HR(m_pd3dDevice->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pVertexShader.GetAddressOf()));
// 创建顶点输入布局
HR(m_pd3dDevice->CreateInputLayout(VertexPosNormalColor::inputLayout, ARRAYSIZE(VertexPosNormalColor::inputLayout),
blob->GetBufferPointer(), blob->GetBufferSize(), m_pVertexLayout.GetAddressOf()));
//创建像素着色器
HR(CreateShaderFromFile(L"HLSL\\PixelShader.cso", L"HLSL\\PixelShader.hlsl", "PS", "ps_5_0", blob.ReleaseAndGetAddressOf()));
HR(m_pd3dDevice->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pPixelShader.GetAddressOf()));
return true;
}
bool Ex7Light::InitResource() {
// ******************
// 设置立方体顶点
// 5________ 6
// /| /|
// /_|_____/ |
// 1|4|_ _ 2|_|7 10________11
// | / | / / /
// |/______|/ /_______/
// 0 3 8 9
/**************************
* 重置顶点缓冲区和索引缓冲区 *
***************************/
Geometry::MeshData<VertexPosNormalColor> meshdata = Geometry::CreateBox<VertexPosNormalColor>();
ResetMesh(meshdata);
/******************
* 初始化默认光照 *
*******************/
// 平行光
m_DirLight.ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
m_DirLight.diffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f);
m_DirLight.specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
m_DirLight.direction = XMFLOAT3(-0.577f, -0.577f, 0.577f);
// 点光
m_PointLight.position = XMFLOAT3(0.0f, 0.0f, -10.0f);
m_PointLight.ambient = XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f);
m_PointLight.diffuse = XMFLOAT4(0.7f, 0.7f, 0.7f, 1.0f);
m_PointLight.specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
m_PointLight.att = XMFLOAT3(0.0f, 0.1f, 0.0f);
m_PointLight.range = 25.0f;
// 聚光
m_SpotLight.position = XMFLOAT3(0.0f, 0.0f, -7.0f);
m_SpotLight.direction = XMFLOAT3(0.0f, 0.0f, 1.0f);
m_SpotLight.ambient = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
m_SpotLight.diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
m_SpotLight.specular = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
m_SpotLight.att = XMFLOAT3(1.0f, 0.0f, 0.0f);
m_SpotLight.spot = 12.0f;
m_SpotLight.range = 10000.0f;
/************
* 常量缓冲区 *
*************/
// 设置常量缓冲区描述
D3D11_BUFFER_DESC cbd;
ZeroMemory(&cbd, sizeof(cbd));
cbd.Usage = D3D11_USAGE_DYNAMIC;
cbd.ByteWidth = sizeof(VSConstantBuffer);
cbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
// 新建VS和PS常量缓冲区
HR(m_pd3dDevice->CreateBuffer(&cbd, nullptr, m_pConstantBuffer[0].GetAddressOf()));
cbd.ByteWidth = sizeof(PSConstantBuffer);
HR(m_pd3dDevice->CreateBuffer(&cbd, nullptr, m_pConstantBuffer[1].GetAddressOf()));
// 初始化VS常量缓冲区
m_VSConstantBuffer.world = XMMatrixIdentity();
m_VSConstantBuffer.view = XMMatrixTranspose(XMMatrixLookAtLH(
XMVectorSet(0.0f, 0.0f, -5.0f, 0.0f),
XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f),
XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f)
));
m_VSConstantBuffer.proj = XMMatrixTranspose(XMMatrixPerspectiveFovLH(XM_PIDIV2, AspectRatio(), 1.0f, 1000.0f));
m_VSConstantBuffer.worldInvTranspose = XMMatrixIdentity();
// 初始化PS常量缓冲区
m_PSConstantBuffer.material.ambient = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f);
m_PSConstantBuffer.material.diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
m_PSConstantBuffer.material.specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 5.0f);
m_PSConstantBuffer.dirLight = m_DirLight;
m_PSConstantBuffer.eyePos = XMFLOAT4(0, 0, -0.5f, 0);
// 更新Context的PS常量缓冲
D3D11_MAPPED_SUBRESOURCE mappedRes;
HR(m_pd3dImmediateContext->Map(m_pConstantBuffer[1].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRes));
memcpy_s(mappedRes.pData, sizeof(PSConstantBuffer), &m_PSConstantBuffer, sizeof(PSConstantBuffer));
m_pd3dImmediateContext->Unmap(m_pConstantBuffer[1].Get(), 0);
/*****************
* 初始化光栅化状态 *
******************/
D3D11_RASTERIZER_DESC rasterizerDesc;
ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc)); // 记住使用结构体前要初始化0
rasterizerDesc.FillMode = D3D11_FILL_WIREFRAME;
rasterizerDesc.CullMode = D3D11_CULL_NONE;
rasterizerDesc.FrontCounterClockwise = false;
rasterizerDesc.DepthClipEnable = true;
HR(m_pd3dDevice->CreateRasterizerState(&rasterizerDesc, m_pRSWireframe.GetAddressOf()));
/***************
* 绑定资源到管线 *
****************/
// 设置图元类型
m_pd3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
m_pd3dImmediateContext->IASetInputLayout(m_pVertexLayout.Get());
// 绑定VS常量缓冲区到管线
m_pd3dImmediateContext->VSSetShader(m_pVertexShader.Get(), nullptr, 0);
// VS 常量缓冲区对应HLSL寄存于b0 register
m_pd3dImmediateContext->VSSetConstantBuffers(0, 1, m_pConstantBuffer[0].GetAddressOf());
// 绑定PS着色器到管道
m_pd3dImmediateContext->PSSetShader(m_pPixelShader.Get(), nullptr, 0);
// PS 常量缓冲区对应HLSL寄存于b1 register
m_pd3dImmediateContext->PSSetConstantBuffers(1, 1, m_pConstantBuffer[1].GetAddressOf());
return true;
}
bool Ex7Light::ResetMesh(const Geometry::MeshData<VertexPosNormalColor>& meshData) {
// 1.清空顶点和索引缓冲区
m_pVertexBuffer.Reset();
m_pIndexBuffer.Reset();
/*****************
* 2 顶点缓冲区 *
******************/
// 2.1 设置顶点缓冲区描述
D3D11_BUFFER_DESC vbd;
ZeroMemory(&vbd, sizeof(vbd));
vbd.Usage = D3D11_USAGE_IMMUTABLE;
vbd.ByteWidth = (UINT)meshData.vertexVec.size() * sizeof(VertexPosNormalColor);
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbd.CPUAccessFlags = 0;
// 2.2 设定用于初始化的数据并在Device上建立缓冲区
D3D11_SUBRESOURCE_DATA initData;
ZeroMemory(&initData, sizeof(initData));
initData.pSysMem = meshData.vertexVec.data();
HR(m_pd3dDevice->CreateBuffer(&vbd, &initData, m_pVertexBuffer.GetAddressOf()));
// 2.3 在上下文装配顶点缓冲区
UINT stride = sizeof(VertexPosNormalColor);
UINT offset = 0;
m_pd3dImmediateContext->IASetVertexBuffers(0, 1, m_pVertexBuffer.GetAddressOf(), &stride, &offset);
/**************
*3 索引缓冲区 *
**************/
m_IndexCount = (UINT)meshData.indexVec.size();
// 3.1 设置索引缓冲区描述
D3D11_BUFFER_DESC ibd;
ZeroMemory(&ibd, sizeof(ibd));
ibd.Usage = D3D11_USAGE_IMMUTABLE;
ibd.ByteWidth = (UINT)meshData.indexVec.size()*sizeof(DWORD);
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
// 3.2 建立索引缓冲区
initData.pSysMem = meshData.indexVec.data();
HR(m_pd3dDevice->CreateBuffer(&ibd, &initData, m_pIndexBuffer.GetAddressOf()));
// 3.3 在上下文上装配索引缓冲区
m_pd3dImmediateContext->IASetIndexBuffer(m_pIndexBuffer.Get(), DXGI_FORMAT_R32_UINT, 0);
return true;
}
<file_sep>#include "Effects.h"
#include "ThridParty/d3dUtil.h"
#include "EffectHelper.h" // 必须晚于Effects.h和d3dUtil.h包含
#include "ThridParty/DXTrace.h"
#include "Vertex.h"
#include <d2d1.h>
#include <dwrite.h>
#include <winnt.h>
using namespace DirectX;
/********************************************
BasicEffect::Impl 需要先于BasicEffect的定义
*********************************************/
class BasicEffect::Impl : public AlignedType<BasicEffect::Impl>
{
public:
//
// 这些结构体对应HLSL的结构体。需要按16字节对齐
//
struct CBChangesEveryDrawing
{
DirectX::XMMATRIX world;
DirectX::XMMATRIX worldInvTranspose;
Material material;
};
struct CBDrawingStates
{
int isReflection;
int isShadow;
int isTextureUsed;
int useSH;
int useLight;
int useDirLight;
int usePointLight;
int SHMode;
int sphereSpeed;
int useNormalmap;
DirectX::XMFLOAT2 pad;
};
struct CBChangesEveryFrame
{
DirectX::XMMATRIX view;
DirectX::XMVECTOR eyePos;
};
struct CBChangesOnResize
{
DirectX::XMMATRIX proj;
};
struct CBChangesRarely
{
DirectX::XMMATRIX reflection;
DirectX::XMMATRIX shadow;
DirectX::XMMATRIX refShadow;
DirectionalLight dirLight[BasicEffect::maxDirLights];
PointLight pointLight[BasicEffect::maxPointLights];
SpotLight spotLight[BasicEffect::maxSpotLights];
int dirLightNums;
int pointLightNums;
int spotLightNums;
int pad;
};
struct CBVLMParams {
DirectX::XMFLOAT3 VLMWorldToUVScale;
float VLMBrickSize;
DirectX::XMFLOAT3 VLMIndirectionTextureSize;
float pad1;
DirectX::XMFLOAT3 VLMWorldToUVAdd;
float pad2;
DirectX::XMFLOAT3 VLMBrickTexelSize;
float pad3;
};
public:
// 必须显式指定
Impl() : m_IsDirty() {}
~Impl() = default;
public:
// 需要16字节对齐的优先放在前面
CBufferObject<0, CBChangesEveryDrawing> m_CBDrawing; // 每次对象绘制的常量缓冲区
CBufferObject<1, CBDrawingStates> m_CBStates; // 每次绘制状态变更的常量缓冲区
CBufferObject<2, CBChangesEveryFrame> m_CBFrame; // 每帧绘制的常量缓冲区
CBufferObject<3, CBChangesOnResize> m_CBOnResize; // 每次窗口大小变更的常量缓冲区
CBufferObject<4, CBChangesRarely> m_CBRarely; // 几乎不会变更的常量缓冲区
CBufferObject<5, CBVLMParams> m_CBVLMParams;
BOOL m_IsDirty; // 是否有值变更
std::vector<CBufferBase*> m_pCBuffers; // 统一管理上面所有的常量缓冲区
ComPtr<ID3D11VertexShader> m_pVertexInstanceShader;
ComPtr<ID3D11PixelShader> m_pPixelInstanceShader;
ComPtr<ID3D11VertexShader> m_pVertexShader3D; // 用于3D的顶点着色器
ComPtr<ID3D11PixelShader> m_pPixelShader3D; // 用于3D的像素着色器
ComPtr<ID3D11VertexShader> m_pVertexShader2D; // 用于2D的顶点着色器
ComPtr<ID3D11PixelShader> m_pPixelShader2D; // 用于2D的像素着色器
ComPtr<ID3D11InputLayout> m_pVertexLayout2D; // 用于2D的顶点输入布局
ComPtr<ID3D11InputLayout> m_pVertexLayout3D; // 用于3D的顶点输入布局
ComPtr<ID3D11InputLayout> m_pInstancesLayout;
ComPtr<ID3D11ShaderResourceView> m_pTexture; // 用于绘制的纹理
ComPtr<ID3D11ShaderResourceView> m_pNormalMap; // 用于绘制的纹理
std::vector<ComPtr<ID3D11ShaderResourceView>> m_pTexture3DArray;
std::vector<ComPtr<ID3D11UnorderedAccessView>> m_pRWTexture3DArray;
};
//
// BasicEffect
//
namespace
{
// BasicEffect单例
static BasicEffect* g_pInstance = nullptr;
}
BasicEffect::BasicEffect()
{
if (g_pInstance)
throw std::exception("BasicEffect is a singleton!");
g_pInstance = this;
pImpl = std::make_unique<BasicEffect::Impl>();
}
BasicEffect::~BasicEffect()
{
}
BasicEffect::BasicEffect(BasicEffect&& moveFrom) noexcept
{
pImpl.swap(moveFrom.pImpl);
}
BasicEffect& BasicEffect::operator=(BasicEffect&& moveFrom) noexcept
{
pImpl.swap(moveFrom.pImpl);
return *this;
}
BasicEffect& BasicEffect::Get()
{
if (!g_pInstance)
throw std::exception("BasicEffect needs an instance!");
return *g_pInstance;
}
#define GET_CSO_FILENAME(hlslFile, csoFile) \
size_t nameSize = wcslen(hlslFile);\
if (!(hlslFile[nameSize - 5] == L'.' &&\
hlslFile[nameSize - 4] == L'h' &&\
hlslFile[nameSize - 3] == L'l' &&\
hlslFile[nameSize - 2] == L's' &&\
hlslFile[nameSize - 1] == L'l'))\
return false;\
WCHAR FileName[64];\
wcsncpy_s(FileName, ARRAYSIZE(FileName), hlslFile, nameSize - 5);\
_snwprintf_s(csoFile, ARRAYSIZE(csoFile), ARRAYSIZE(csoFile) - 1, L"%s.cso", FileName)
bool BasicEffect::SetVSShader2D(ID3D11Device* device, const WCHAR* hlslFile) {
WCHAR csoFile[64];
ZeroMemory(csoFile, sizeof(csoFile));
GET_CSO_FILENAME(hlslFile, csoFile);
ComPtr<ID3DBlob> blob;
HR(CreateShaderFromFile(csoFile, hlslFile, "VS_2D", "vs_5_0", blob.GetAddressOf()));
HR(device->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, pImpl->m_pVertexShader2D.GetAddressOf()));
HR(device->CreateInputLayout(VertexPosTex::inputLayout, ARRAYSIZE(VertexPosTex::inputLayout),
blob->GetBufferPointer(), blob->GetBufferSize(), pImpl->m_pVertexLayout2D.GetAddressOf()));
return true;
}
bool BasicEffect::SetVSShader3D(ID3D11Device* device, const WCHAR* hlslFile) {
WCHAR csoFile[64];
ZeroMemory(csoFile, sizeof(csoFile));
GET_CSO_FILENAME(hlslFile, csoFile);
ComPtr<ID3DBlob> blob;
HR(CreateShaderFromFile(csoFile, hlslFile, "VS_3D", "vs_5_0", blob.GetAddressOf()));
HR(device->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, pImpl->m_pVertexShader3D.GetAddressOf()));
HR(device->CreateInputLayout(VertexPosNormalTangentTex::inputLayout, ARRAYSIZE(VertexPosNormalTangentTex::inputLayout),
blob->GetBufferPointer(), blob->GetBufferSize(), pImpl->m_pVertexLayout3D.GetAddressOf()));
return true;
}
bool BasicEffect::SetInstanceVS(ID3D11Device* device, const WCHAR* hlslFile) {
WCHAR csoFile[64];
ZeroMemory(csoFile, sizeof(csoFile));
GET_CSO_FILENAME(hlslFile, csoFile);
ComPtr<ID3DBlob> blob;
HR(CreateShaderFromFile(csoFile, hlslFile, "VS_3D", "vs_5_0", blob.GetAddressOf()));
HR(device->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, pImpl->m_pVertexInstanceShader.GetAddressOf()));
HR(device->CreateInputLayout(Instances::inputLayout, ARRAYSIZE(Instances::inputLayout),
blob->GetBufferPointer(), blob->GetBufferSize(), pImpl->m_pInstancesLayout.GetAddressOf()));
return true;
}
bool BasicEffect::SetInstancePS(ID3D11Device* device, const WCHAR* hlslFile) {
WCHAR csoFile[64];
ZeroMemory(csoFile, sizeof(csoFile));
GET_CSO_FILENAME(hlslFile, csoFile);
ComPtr<ID3DBlob> blob;
HR(CreateShaderFromFile(csoFile, hlslFile, "PS_3D", "ps_5_0", blob.GetAddressOf()));
HR(device->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, pImpl->m_pPixelInstanceShader.GetAddressOf()));
return true;
}
bool BasicEffect::SetPSShader2D(ID3D11Device* device, const WCHAR* hlslFile) {
WCHAR csoFile[64];
ZeroMemory(csoFile, sizeof(csoFile));
GET_CSO_FILENAME(hlslFile, csoFile);
ComPtr<ID3DBlob> blob;
HR(CreateShaderFromFile(csoFile, hlslFile, "PS_2D", "ps_5_0", blob.GetAddressOf()));
HR(device->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, pImpl->m_pPixelShader2D.GetAddressOf()));
return true;
}
bool BasicEffect::SetPSShader3D(ID3D11Device* device, const WCHAR* hlslFile) {
WCHAR csoFile[64];
ZeroMemory(csoFile, sizeof(csoFile));
GET_CSO_FILENAME(hlslFile, csoFile);
ComPtr<ID3DBlob> blob;
HR(CreateShaderFromFile(csoFile, hlslFile, "PS_3D", "ps_5_0", blob.GetAddressOf()));
HR(device->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, pImpl->m_pPixelShader3D.GetAddressOf()));
return true;
}
bool BasicEffect::InitAll(ID3D11Device* device)
{
if (!device)
return false;
if (!pImpl->m_pCBuffers.empty())
return true;
if (!RenderStates::IsInit())
throw std::exception("RenderStates need to be initialized first!");
pImpl->m_pCBuffers.assign({
&pImpl->m_CBDrawing,
&pImpl->m_CBFrame,
&pImpl->m_CBStates,
&pImpl->m_CBOnResize,
&pImpl->m_CBRarely,
&pImpl->m_CBVLMParams });
// 创建常量缓冲区
for (auto& pBuffer : pImpl->m_pCBuffers)
{
HR(pBuffer->CreateBuffer(device));
}
return true;
}
void BasicEffect::SetDebugName() {
D3D11SetDebugObjectName(pImpl->m_pVertexLayout2D.Get(), "VertexPosTexLayout");
D3D11SetDebugObjectName(pImpl->m_pVertexLayout3D.Get(), "VertexPosNormalTexLayout");
D3D11SetDebugObjectName(pImpl->m_pCBuffers[0]->cBuffer.Get(), "CBDrawing");
D3D11SetDebugObjectName(pImpl->m_pCBuffers[1]->cBuffer.Get(), "CBStates");
D3D11SetDebugObjectName(pImpl->m_pCBuffers[2]->cBuffer.Get(), "CBFrame");
D3D11SetDebugObjectName(pImpl->m_pCBuffers[3]->cBuffer.Get(), "CBOnResize");
D3D11SetDebugObjectName(pImpl->m_pCBuffers[4]->cBuffer.Get(), "CBRarely");
D3D11SetDebugObjectName(pImpl->m_pCBuffers[5]->cBuffer.Get(), "CBVLMParams");
D3D11SetDebugObjectName(pImpl->m_pVertexShader2D.Get(), "Basic_VS_2D");
D3D11SetDebugObjectName(pImpl->m_pVertexShader3D.Get(), "Basic_VS_3D");
D3D11SetDebugObjectName(pImpl->m_pPixelShader2D.Get(), "Basic_PS_2D");
D3D11SetDebugObjectName(pImpl->m_pPixelShader3D.Get(), "Basic_PS_3D");
D3D11SetDebugObjectName(pImpl->m_pTexture3DArray[0].Get(), "IndirectionTexture");
D3D11SetDebugObjectName(pImpl->m_pTexture3DArray[1].Get(), "AmbientVector");
char name[24];
for (int i = 2; i < pImpl->m_pTexture3DArray.size(); i++) {
_snprintf_s(name, 24, "SHCoefs[%d]", i);
D3D11SetDebugObjectName(pImpl->m_pTexture3DArray[i].Get(), name);
}
}
/*********************
默认渲染配置
1. 图元类型:TriangleList
2. 光栅化:无
3. 采样器:线性过滤
4. 无深度模板
5. 无混合状态
**********************/
void BasicEffect::SetRenderInstanceDefault(ID3D11DeviceContext* deviceContext) {
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->IASetInputLayout(pImpl->m_pInstancesLayout.Get());
deviceContext->VSSetShader(pImpl->m_pVertexInstanceShader.Get(), nullptr, 0);
deviceContext->RSSetState(nullptr);
deviceContext->PSSetShader(pImpl->m_pPixelInstanceShader.Get(), nullptr, 0);
if (pImpl->m_CBStates.data.SHMode == 0 == 0)
deviceContext->VSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->PSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->OMSetDepthStencilState(nullptr, 0);
deviceContext->OMSetBlendState(nullptr, nullptr, 0xFFFFFFFF);
}
void BasicEffect::SetRenderDefault(ID3D11DeviceContext* deviceContext) {
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->IASetInputLayout(pImpl->m_pVertexLayout3D.Get());
deviceContext->VSSetShader(pImpl->m_pVertexShader3D.Get(), nullptr, 0);
deviceContext->RSSetState(nullptr);
deviceContext->PSSetShader(pImpl->m_pPixelShader3D.Get(), nullptr, 0);
if (pImpl->m_CBStates.data.SHMode == 0 == 0)
deviceContext->VSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->PSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->OMSetDepthStencilState(nullptr, 0);
deviceContext->OMSetBlendState(nullptr, nullptr, 0xFFFFFFFF);
}
/*********************
alpha混合配置
1. 图元类型:TriangleList
2. 光栅化:无背面剔除
3. 采样器:线性过滤
4. 无深度模板
5. 混合状态:透明混合
**********************/
void BasicEffect::SetRenderAlphaBlend(ID3D11DeviceContext* deviceContext)
{
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->IASetInputLayout(pImpl->m_pVertexLayout3D.Get());
deviceContext->VSSetShader(pImpl->m_pVertexShader3D.Get(), nullptr, 0);
deviceContext->RSSetState(RenderStates::RSNoCull.Get());
deviceContext->PSSetShader(pImpl->m_pPixelShader3D.Get(), nullptr, 0);
if (pImpl->m_CBStates.data.SHMode == 0 == 0)
deviceContext->VSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->PSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->OMSetDepthStencilState(nullptr, 0);
deviceContext->OMSetBlendState(RenderStates::BSTransparent.Get(), nullptr, 0xFFFFFFFF);
}
/*********************
无二次混合
1. 图元类型:TriangleList
2. 光栅化:无背面剔除
3. 采样器:线性过滤
4. 深度模板:无二次混合
5. 混合状态:透明混合
**********************/
void BasicEffect::SetRenderNoDoubleBlend(ID3D11DeviceContext* deviceContext, UINT stencilRef)
{
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->IASetInputLayout(pImpl->m_pVertexLayout3D.Get());
deviceContext->VSSetShader(pImpl->m_pVertexShader3D.Get(), nullptr, 0);
deviceContext->RSSetState(RenderStates::RSNoCull.Get());
deviceContext->PSSetShader(pImpl->m_pPixelShader3D.Get(), nullptr, 0);
if (pImpl->m_CBStates.data.SHMode == 0 == 0)
deviceContext->VSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->PSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->OMSetDepthStencilState(RenderStates::DSSNoDoubleBlend.Get(), stencilRef);
deviceContext->OMSetBlendState(RenderStates::BSTransparent.Get(), nullptr, 0xFFFFFFFF);
}
/*********************
仅写入深度值
1. 图元类型:TriangleList
2. 光栅化:无
3. 采样器:线性过滤
4. 深度模板:写入模板值
5. 混合状态:无颜色混合
**********************/
void BasicEffect::SetWriteStencilOnly(ID3D11DeviceContext* deviceContext, UINT stencilRef)
{
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->IASetInputLayout(pImpl->m_pVertexLayout3D.Get());
deviceContext->VSSetShader(pImpl->m_pVertexShader3D.Get(), nullptr, 0);
deviceContext->RSSetState(nullptr);
deviceContext->PSSetShader(pImpl->m_pPixelShader3D.Get(), nullptr, 0);
if (pImpl->m_CBStates.data.SHMode == 0 == 0)
deviceContext->VSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->PSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->OMSetDepthStencilState(RenderStates::DSSWriteStencil.Get(), stencilRef);
deviceContext->OMSetBlendState(RenderStates::BSNoColorWrite.Get(), nullptr, 0xFFFFFFFF);
}
/*****************************************************
按照模板值默认渲染
1. 图元类型:TriangleList
2. 光栅化:顺时针剔除
3. 采样器:线性过滤
4. 深度模板:对指定模板值进行绘制的深度/模板状态,对满足模板值条件的区域才进行绘制,并更新深度
5. 混合状态:无颜色混合
******************************************************/
void BasicEffect::SetRenderDefaultWithStencil(ID3D11DeviceContext* deviceContext, UINT stencilRef)
{
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->IASetInputLayout(pImpl->m_pVertexLayout3D.Get());
deviceContext->VSSetShader(pImpl->m_pVertexShader3D.Get(), nullptr, 0);
deviceContext->RSSetState(RenderStates::RSCullClockWise.Get());
deviceContext->PSSetShader(pImpl->m_pPixelShader3D.Get(), nullptr, 0);
if (pImpl->m_CBStates.data.SHMode == 0 == 0)
deviceContext->VSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->PSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->OMSetDepthStencilState(RenderStates::DSSDrawWithStencil.Get(), stencilRef);
deviceContext->OMSetBlendState(nullptr, nullptr, 0xFFFFFFFF);
}
/*****************************************************
按照模板值进行Alpha混合渲染
1. 图元类型:TriangleList
2. 光栅化:无背面剔除
3. 采样器:线性过滤
4. 深度模板:对指定模板值进行绘制的深度/模板状态,对满足模板值条件的区域才进行绘制,并更新深度
5. 混合状态:透明混合
******************************************************/
void BasicEffect::SetRenderAlphaBlendWithStencil(ID3D11DeviceContext* deviceContext, UINT stencilRef)
{
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->IASetInputLayout(pImpl->m_pVertexLayout3D.Get());
deviceContext->VSSetShader(pImpl->m_pVertexShader3D.Get(), nullptr, 0);
deviceContext->RSSetState(RenderStates::RSNoCull.Get());
deviceContext->PSSetShader(pImpl->m_pPixelShader3D.Get(), nullptr, 0);
if (pImpl->m_CBStates.data.SHMode == 0 == 0)
deviceContext->VSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->PSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->OMSetDepthStencilState(RenderStates::DSSDrawWithStencil.Get(), stencilRef);
deviceContext->OMSetBlendState(RenderStates::BSTransparent.Get(), nullptr, 0xFFFFFFFF);
}
/*****************************************************
默认2D渲染
1. 图元类型:TriangleList
2. 光栅化:无
3. 采样器:线性过滤
4. 深度模板:无
5. 混合状态:无
******************************************************/
void BasicEffect::Set2DRenderDefault(ID3D11DeviceContext* deviceContext)
{
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->IASetInputLayout(pImpl->m_pVertexLayout2D.Get());
deviceContext->VSSetShader(pImpl->m_pVertexShader2D.Get(), nullptr, 0);
deviceContext->RSSetState(nullptr);
deviceContext->PSSetShader(pImpl->m_pPixelShader2D.Get(), nullptr, 0);
deviceContext->PSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->OMSetDepthStencilState(nullptr, 0);
deviceContext->OMSetBlendState(nullptr, nullptr, 0xFFFFFFFF);
}
/*****************************************************
2D alpha混合渲染
1. 图元类型:TriangleList
2. 光栅化:无背面剔除
3. 采样器:线性过滤
4. 深度模板:无
5. 混合状态:透明混合
******************************************************/
void BasicEffect::Set2DRenderAlphaBlend(ID3D11DeviceContext* deviceContext)
{
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->IASetInputLayout(pImpl->m_pVertexLayout2D.Get());
deviceContext->VSSetShader(pImpl->m_pVertexShader2D.Get(), nullptr, 0);
deviceContext->RSSetState(RenderStates::RSNoCull.Get());
deviceContext->PSSetShader(pImpl->m_pPixelShader2D.Get(), nullptr, 0);
deviceContext->PSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->OMSetDepthStencilState(nullptr, 0);
deviceContext->OMSetBlendState(RenderStates::BSTransparent.Get(), nullptr, 0xFFFFFFFF);
}
void BasicEffect::SetWireFrameWode(ID3D11DeviceContext* deviceContext) {
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->IASetInputLayout(pImpl->m_pVertexLayout3D.Get());
deviceContext->VSSetShader(pImpl->m_pVertexShader3D.Get(), nullptr, 0);
deviceContext->RSSetState(RenderStates::RSWireframe.Get());
deviceContext->PSSetShader(pImpl->m_pPixelShader3D.Get(), nullptr, 0);
deviceContext->PSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->OMSetDepthStencilState(nullptr, 0);
deviceContext->OMSetBlendState(nullptr, nullptr, 0xFFFFFFFF);
}
/*
改变世界矩阵
*/
void XM_CALLCONV BasicEffect::SetWorldMatrix(DirectX::FXMMATRIX W)
{
auto& cBuffer = pImpl->m_CBDrawing;
cBuffer.data.world = XMMatrixTranspose(W);
cBuffer.data.worldInvTranspose = XMMatrixInverse(nullptr, W); // 两次转置抵消
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void XM_CALLCONV BasicEffect::SetViewMatrix(FXMMATRIX V)
{
auto& cBuffer = pImpl->m_CBFrame;
cBuffer.data.view = XMMatrixTranspose(V);
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void XM_CALLCONV BasicEffect::SetProjMatrix(FXMMATRIX P)
{
auto& cBuffer = pImpl->m_CBOnResize;
cBuffer.data.proj = XMMatrixTranspose(P);
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void XM_CALLCONV BasicEffect::SetReflectionMatrix(FXMMATRIX R)
{
auto& cBuffer = pImpl->m_CBRarely;
cBuffer.data.reflection = XMMatrixTranspose(R);
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void XM_CALLCONV BasicEffect::SetShadowMatrix(FXMMATRIX S)
{
auto& cBuffer = pImpl->m_CBRarely;
cBuffer.data.shadow = XMMatrixTranspose(S);
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void XM_CALLCONV BasicEffect::SetRefShadowMatrix(DirectX::FXMMATRIX RefS)
{
auto& cBuffer = pImpl->m_CBRarely;
cBuffer.data.refShadow = XMMatrixTranspose(RefS);
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
/*
设置光源
*/
void BasicEffect::SetDirLight(size_t pos, const DirectionalLight& dirLight)
{
auto& cBuffer = pImpl->m_CBRarely;
cBuffer.data.dirLight[pos] = dirLight;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetPointLight(size_t pos, const PointLight& pointLight)
{
auto& cBuffer = pImpl->m_CBRarely;
cBuffer.data.pointLight[pos] = pointLight;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetSpotLight(size_t pos, const SpotLight& spotLight)
{
auto& cBuffer = pImpl->m_CBRarely;
cBuffer.data.spotLight[pos] = spotLight;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetDirLightNums(int num) {
auto& cBuffer = pImpl->m_CBRarely;
cBuffer.data.dirLightNums = num;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetPointLightNums(int num) {
auto& cBuffer = pImpl->m_CBRarely;
cBuffer.data.pointLightNums = num;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetSpotLightNums(int num) {
auto& cBuffer = pImpl->m_CBRarely;
cBuffer.data.spotLightNums = num;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
/*
设置D3D资源
*/
void BasicEffect::SetMaterial(const Material& material) {
auto& cBuffer = pImpl->m_CBDrawing;
cBuffer.data.material = material;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetNormalMap(ID3D11ShaderResourceView* normalMap) {
pImpl->m_pNormalMap = normalMap;
}
void BasicEffect::UseNormalMap(bool isUsed) {
auto& cBuffer = pImpl->m_CBStates;
cBuffer.data.useNormalmap = isUsed;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
bool BasicEffect::GetUseNormalMap() {
auto& cBuffer = pImpl->m_CBStates;
return cBuffer.data.useNormalmap;
}
void BasicEffect::SetTexture(ID3D11ShaderResourceView* texture)
{
pImpl->m_pTexture = texture;
}
void BasicEffect::SetTexture2D(ID3D11ShaderResourceView* texture) {
SetTexture(texture);
}
void BasicEffect::SetTexture3D(ID3D11ShaderResourceView* texture) {
pImpl->m_pTexture3DArray.emplace_back(texture);
}
void BasicEffect::SetRWTexture3D(ID3D11UnorderedAccessView* texture) {
pImpl->m_pRWTexture3DArray.emplace_back(texture);
}
void BasicEffect::ClearTexture3D() {
pImpl->m_pTexture3DArray.clear();
}
void XM_CALLCONV BasicEffect::SetEyePos(FXMVECTOR eyePos)
{
auto& cBuffer = pImpl->m_CBFrame;
cBuffer.data.eyePos = eyePos;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetReflectionState(bool isOn)
{
auto& cBuffer = pImpl->m_CBStates;
cBuffer.data.isReflection = isOn;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetShadowState(bool isOn)
{
isShadow = isOn;
auto& cBuffer = pImpl->m_CBStates;
cBuffer.data.isShadow = isOn;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetTextureUsed(bool isOn)
{
auto& cBuffer = pImpl->m_CBStates;
cBuffer.data.isTextureUsed = isOn;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetSHUsed(bool isOn)
{
auto& cBuffer = pImpl->m_CBStates;
cBuffer.data.useSH = isOn;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetLightUsed(bool isOn) {
auto& cBuffer = pImpl->m_CBStates;
cBuffer.data.useLight = isOn;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetDirLightUsed(bool isOn) {
auto& cBuffer = pImpl->m_CBStates;
cBuffer.data.useDirLight = isOn;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetPointLightUsed(bool isOn) {
auto& cBuffer = pImpl->m_CBStates;
cBuffer.data.usePointLight = isOn;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetVLMWorldToUVScale(DirectX::XMFLOAT3 VLMWorldToUVScale) {
auto& cBuffer = pImpl->m_CBVLMParams;
cBuffer.data.VLMWorldToUVScale.x = VLMWorldToUVScale.x;
cBuffer.data.VLMWorldToUVScale.y = VLMWorldToUVScale.y;
cBuffer.data.VLMWorldToUVScale.z = VLMWorldToUVScale.z;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetVLMWorldToUVAdd(DirectX::XMFLOAT3 VLMWorldToUVAdd) {
auto& cBuffer = pImpl->m_CBVLMParams;
cBuffer.data.VLMWorldToUVAdd.x = VLMWorldToUVAdd.x;
cBuffer.data.VLMWorldToUVAdd.y = VLMWorldToUVAdd.y;
cBuffer.data.VLMWorldToUVAdd.z = VLMWorldToUVAdd.z;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetVLMIndirectionTextureSize(DirectX::XMFLOAT3 indirectionTextureSize) {
auto& cBuffer = pImpl->m_CBVLMParams;
cBuffer.data.VLMIndirectionTextureSize.x = indirectionTextureSize.x;
cBuffer.data.VLMIndirectionTextureSize.y = indirectionTextureSize.y;
cBuffer.data.VLMIndirectionTextureSize.z = indirectionTextureSize.z;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetVLMBrickSize(float brickSize) {
auto& cBuffer = pImpl->m_CBVLMParams;
cBuffer.data.VLMBrickSize = brickSize;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetVLMBrickTexelSize(DirectX::XMFLOAT3 VLMBrickTexelSize) {
auto& cBuffer = pImpl->m_CBVLMParams;
cBuffer.data.VLMBrickTexelSize.x = VLMBrickTexelSize.x;
cBuffer.data.VLMBrickTexelSize.y = VLMBrickTexelSize.y;
cBuffer.data.VLMBrickTexelSize.z = VLMBrickTexelSize.z;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetSHMode(int mode) {
auto& cBuffer = pImpl->m_CBStates;
cBuffer.data.SHMode = mode;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void BasicEffect::SetSphereSpeed(int SphereSpeed) {
auto& cBuffer = pImpl->m_CBStates;
cBuffer.data.sphereSpeed = SphereSpeed;
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
/**********************************
应用缓冲区,将所有缓冲区绑定到管道上
***********************************/
void BasicEffect::Apply(ID3D11DeviceContext* deviceContext)
{
auto& pCBuffers = pImpl->m_pCBuffers;
// 将缓冲区绑定到渲染管线上
pCBuffers[0]->BindVS(deviceContext);
pCBuffers[1]->BindVS(deviceContext);
pCBuffers[2]->BindVS(deviceContext);
pCBuffers[3]->BindVS(deviceContext);
pCBuffers[4]->BindVS(deviceContext);
pCBuffers[5]->BindVS(deviceContext);
pCBuffers[0]->BindPS(deviceContext);
pCBuffers[1]->BindPS(deviceContext);
pCBuffers[2]->BindPS(deviceContext);
pCBuffers[4]->BindPS(deviceContext);
pCBuffers[5]->BindPS(deviceContext);
/******************************************
绑定贴图到管线
1.StartSlot: 寄存器序号
2.NumViews: 贴图数量
3.贴图指针
这里可以放多个贴图,比如光照贴图和纹理贴图
*******************************************/
deviceContext->PSSetShaderResources(0, 1, pImpl->m_pTexture.GetAddressOf());
if (pImpl->m_pNormalMap.Get() != nullptr) {
deviceContext->PSSetShaderResources(1, 1, pImpl->m_pNormalMap.GetAddressOf());
}
for (int i = 0; i < pImpl->m_pTexture3DArray.size(); i++) {
deviceContext->VSSetShaderResources(i + 2, 1, pImpl->m_pTexture3DArray[i].GetAddressOf());
deviceContext->PSSetShaderResources(i + 2, 1, pImpl->m_pTexture3DArray[i].GetAddressOf());
}
if (pImpl->m_IsDirty)
{
pImpl->m_IsDirty = false;
for (auto& pCBuffer : pCBuffers)
{
pCBuffer->UpdateBuffer(deviceContext);
}
}
}
<file_sep>#include "Transform.h"
using namespace DirectX;
XMFLOAT3 Transform::GetScale() const {
return m_Scale;
}
XMVECTOR Transform::GetScaleXM() const {
return XMLoadFloat3(&m_Scale);
}
XMFLOAT3 Transform::GetRotation() const {
return m_Rotation;
}
XMVECTOR Transform::GetRotationXM() const {
return XMLoadFloat3(&m_Rotation);
}
XMFLOAT3 Transform::GetPosition() const {
return m_Position;
}
XMVECTOR Transform::GetPositionXM() const {
return XMLoadFloat3(&m_Position);
}
XMFLOAT3 Transform::GetRightAxis() const {
XMMATRIX tmp = XMMatrixRotationRollPitchYawFromVector(XMLoadFloat3(&m_Rotation));
XMFLOAT3 right;
XMStoreFloat3(&right, tmp.r[0]);
return right;
}
XMVECTOR Transform::GetRightAxisXM() const {
XMMATRIX tmp = XMMatrixRotationRollPitchYawFromVector(XMLoadFloat3(&m_Rotation));
return tmp.r[0];
}
XMFLOAT3 Transform::GetUpAxis() const {
XMMATRIX tmp = XMMatrixRotationRollPitchYawFromVector(XMLoadFloat3(&m_Rotation));
XMFLOAT3 up;
XMStoreFloat3(&up, tmp.r[1]);
return up;
}
XMVECTOR Transform::GetUpAxisXM() const {
XMMATRIX tmp = XMMatrixRotationRollPitchYawFromVector(XMLoadFloat3(&m_Rotation));
return tmp.r[1];
}
XMFLOAT3 Transform::GetForwardAxis() const {
XMMATRIX tmp = XMMatrixRotationRollPitchYawFromVector(XMLoadFloat3(&m_Rotation));
XMFLOAT3 forward;
XMStoreFloat3(&forward, tmp.r[2]);
return forward;
}
XMVECTOR Transform::GetForwardAxisXM() const {
XMMATRIX tmp = XMMatrixRotationRollPitchYawFromVector(XMLoadFloat3(&m_Rotation));
return tmp.r[2];
}
XMFLOAT4X4 Transform::GetLocalToWorldMatrix() const {
XMFLOAT4X4 res;
XMStoreFloat4x4(&res, GetLocalToWorldMatrixXM());
return res;
}
XMMATRIX Transform::GetLocalToWorldMatrixXM() const {
XMVECTOR scaleVec = XMLoadFloat3(&m_Scale);
XMVECTOR rotateVec = XMLoadFloat3(&m_Rotation);
XMVECTOR posVec = XMLoadFloat3(&m_Position);
XMMATRIX res = XMMatrixScalingFromVector(scaleVec) * XMMatrixRotationRollPitchYawFromVector(rotateVec) * XMMatrixTranslationFromVector(posVec);
return res;
}
XMFLOAT4X4 Transform::GetWorldToLocalMatrix() const {
XMFLOAT4X4 res;
XMStoreFloat4x4(&res, GetWorldToLocalMatrixXM());
return res;
}
XMMATRIX Transform::GetWorldToLocalMatrixXM() const {
XMMATRIX w2l = XMMatrixInverse(nullptr, GetLocalToWorldMatrixXM());
return w2l;
}
void Transform::SetScale(const XMFLOAT3& scale) {
m_Scale = scale;
}
void Transform::SetScale(float x, float y, float z) {
m_Scale = XMFLOAT3(x, y, z);
}
void Transform::SetRotation(const XMFLOAT3& eulerAnglesInRadian) {
m_Rotation = eulerAnglesInRadian;
}
void Transform::SetRotation(float x, float y, float z) {
m_Rotation = XMFLOAT3(x, y, z);
}
void Transform::SetPosition(const XMFLOAT3& position) {
m_Position = position;
}
void Transform::SetPosition(float x, float y, float z) {
m_Position = XMFLOAT3(x, y, z);
}
/*
transition = magnitude * direction; new Position = current position + transition;
*/
void Transform::Translate(const XMFLOAT3& direction, float magnitude) {
XMVECTOR curPosVec = XMLoadFloat3(&m_Position);
XMVECTOR directVec = XMVector3Normalize(XMLoadFloat3(&direction));
XMVECTOR newPosVec = XMVectorMultiplyAdd(XMVectorReplicate(magnitude), directVec, curPosVec);
XMStoreFloat3(&m_Position, newPosVec);
}
void Transform::LookAt(const XMFLOAT3& target, const XMFLOAT3& up)
{
XMMATRIX View = XMMatrixLookAtLH(XMLoadFloat3(&m_Position), XMLoadFloat3(&target), XMLoadFloat3(&up));
XMMATRIX InvView = XMMatrixInverse(nullptr, View);
XMFLOAT4X4 rotMatrix;
XMStoreFloat4x4(&rotMatrix, InvView);
m_Rotation = GetEulerAnglesFromRotationMatrix(rotMatrix);
}
void Transform::LookTo(const XMFLOAT3& direction, const XMFLOAT3& up)
{
XMMATRIX View = XMMatrixLookToLH(XMLoadFloat3(&m_Position), XMLoadFloat3(&direction), XMLoadFloat3(&up));
XMMATRIX InvView = XMMatrixInverse(nullptr, View);
XMFLOAT4X4 rotMatrix;
XMStoreFloat4x4(&rotMatrix, InvView);
m_Rotation = GetEulerAnglesFromRotationMatrix(rotMatrix);
}
void Transform::Rotate(const XMFLOAT3& eulerAnglesInRadian) {
XMVECTOR curRotation = XMLoadFloat3(&m_Rotation);
XMVECTOR newRotation = XMLoadFloat3(&eulerAnglesInRadian);
XMStoreFloat3(&m_Rotation, (XMVectorAdd(curRotation, newRotation)));
}
/*
绕轴旋转欧拉角radian
当前的欧拉角变换矩阵 XMMatrixRotationRollPitchYawFromVector(curRotation)
绕轴axis旋转radian的变换矩阵 XMMatrixRotationAxis(XMLoadFloat3(&axis), radian)
*/
void Transform::RotateAxis(const XMFLOAT3& axis, float radian) {
XMVECTOR curRotation = XMLoadFloat3(&m_Rotation);
XMMATRIX newRotation = XMMatrixRotationRollPitchYawFromVector(curRotation) * XMMatrixRotationAxis(XMLoadFloat3(&axis), radian);
XMFLOAT4X4 rotMatix;
XMStoreFloat4x4(&rotMatix, newRotation);
m_Rotation = GetEulerAnglesFromRotationMatrix(rotMatix);
}
void Transform::RotateAround(const XMFLOAT3& point, const XMFLOAT3& axis, float radian)
{
XMVECTOR rotationVec = XMLoadFloat3(&m_Rotation);
XMVECTOR positionVec = XMLoadFloat3(&m_Position);
XMVECTOR centerVec = XMLoadFloat3(&point);
// 以point作为原点进行旋转
XMMATRIX RT = XMMatrixRotationRollPitchYawFromVector(rotationVec) * XMMatrixTranslationFromVector(positionVec - centerVec);
RT *= XMMatrixRotationAxis(XMLoadFloat3(&axis), radian);
RT *= XMMatrixTranslationFromVector(centerVec);
XMFLOAT4X4 rotMatrix;
XMStoreFloat4x4(&rotMatrix, RT);
m_Rotation = GetEulerAnglesFromRotationMatrix(rotMatrix);
XMStoreFloat3(&m_Position, RT.r[3]);
}
XMFLOAT3 Transform::GetEulerAnglesFromRotationMatrix(const XMFLOAT4X4& rotationMatrix)
{
// 通过旋转矩阵反求欧拉角
float c = sqrtf(1.0f - rotationMatrix(2, 1) * rotationMatrix(2, 1));
// 防止r[2][1]出现大于1的情况
if (isnan(c))
c = 0.0f;
XMFLOAT3 rotation;
rotation.z = atan2f(rotationMatrix(0, 1), rotationMatrix(1, 1));
rotation.x = atan2f(-rotationMatrix(2, 1), c);
rotation.y = atan2f(rotationMatrix(2, 0), rotationMatrix(2, 2));
return rotation;
}
<file_sep>#pragma once
#include "d3d11.h"
#include "Transform.h"
/**************************************************
在Transform的基础上实现了两种摄像机类 FPS 和 TPS
***************************************************/
class Camera
{
public:
Camera() = default;
virtual ~Camera() = 0;
/*
获取摄像机位置
*/
DirectX::XMVECTOR GetPositionXM() const;
DirectX::XMFLOAT3 GetPosition() const;
// 获取X轴旋转欧拉角弧度
float GetRotationX() const;
//获取Y轴旋转欧拉角弧度
float GetRotationY() const;
//获取摄像机坐标轴向量
DirectX::XMVECTOR GetRightAxisXM() const;
DirectX::XMFLOAT3 GetRightAxis() const;
DirectX::XMVECTOR GetUpAxisXM() const;
DirectX::XMFLOAT3 GetUpAxis() const;
DirectX::XMVECTOR GetLookAxisXM() const;
DirectX::XMFLOAT3 GetLookAxis() const;
/*获取矩阵*/
DirectX::XMMATRIX GetViewXM() const;
DirectX::XMMATRIX GetProjXM() const;
DirectX::XMMATRIX GetViewProjXM() const;
// 获取视口
D3D11_VIEWPORT GetViewPort() const;
// 设置平截头体
void SetFrustum(float fovY, float aspec, float nearZ, float farZ);
// 设置视口
void SetViewPort(const D3D11_VIEWPORT& viewport);
void SetViewPort(float topLeftX, float topLeftY, float width, float height, float minDepth = 0.0f, float maxDepth = 1.0f);
protected:
Transform m_Transform = {};
float m_NearZ = 0.0f;
float m_FarZ = 0.0f;
float m_Aspect = 0.0f;
float m_FovY = 0.0f;
// 当前视口
D3D11_VIEWPORT m_ViewPort = {};
};
class FPSCamera :public Camera {
public:
FPSCamera() = default;
~FPSCamera() override;
// 设置摄像机位置
void SetPosition(float x, float y, float z);
void SetPosition(const DirectX::XMFLOAT3& pos);
// 设置摄像机朝向
void LookAt(const DirectX::XMFLOAT3& pos, const DirectX::XMFLOAT3& target, const DirectX::XMFLOAT3& up);
void LookTo(const DirectX::XMFLOAT3& pos, const DirectX::XMFLOAT3& to, const DirectX::XMFLOAT3& up);
// 平移
void Strafe(float d);
// 平面移动
void Walk(float d);
// 前进
void MoveForward(float d);
// 上下观察,+值向上,-值向下
void Pitch(float rad);
// 左右观察 +值向左,-值向右
void RotateY(float rad);
};
class TPSCamera :public Camera {
public:
TPSCamera() = default;
~TPSCamera() override;
// 获取摄像机跟踪物体的位置
DirectX::XMFLOAT3 GetTargetPosition() const;
// 获取与跟踪物体的距离
float GetDistance() const;
// 绕物体的x轴旋转(俯仰角,限制在60°)
void RotateX(float rad);
// 绕物体的y轴旋转(偏移角)
void RotateY(float rad);
// 接近物体
void Approach(float dist);
// 设置俯仰角(限制在60°)
void SetRotationX(float rad);
// 设置偏移角
void SetRotationY(float rad);
// 设置并绑定待跟踪物体的位置
void SetTarget(const DirectX::XMFLOAT3& target);
// 设置初始距离
void SetDistance(float dist);
// 设置最小和最远距离
void SetDistMinMax(float minDist, float maxFloat);
private:
// 目标的位置
DirectX::XMFLOAT3 m_Target = {};
// 摄像机和目标的距离
float m_Distance = 0.0f;
// 摄像机离目标的最大和最小距离
float m_MinDist = 0.0f, m_MaxDist = 0.0f;
};<file_sep>#pragma once
#include <DirectXMath.h>
/*****************************************
* Transform.h *
* Transform类用于实现摄像机的转向和移动 *
******************************************/
class Transform
{
public:
Transform() = default;
Transform(const DirectX::XMFLOAT3& scale, const DirectX::XMFLOAT3& rotation, const DirectX::XMFLOAT3& position);
~Transform() = default;
// 获取缩放矩阵
DirectX::XMFLOAT3 GetScale() const;
DirectX::XMVECTOR GetScaleXM() const;
// 获取旋转欧拉角
DirectX::XMFLOAT3 GetRotation() const;
DirectX::XMVECTOR GetRotationXM() const;
// 获取对象位置
DirectX::XMFLOAT3 GetPosition() const;
DirectX::XMVECTOR GetPositionXM() const;
// 获取右方向轴
DirectX::XMFLOAT3 GetRightAxis() const;
DirectX::XMVECTOR GetRightAxisXM() const;
// 获取上方向轴
DirectX::XMFLOAT3 GetUpAxis() const;
DirectX::XMVECTOR GetUpAxisXM() const;
// 获取前方向轴
DirectX::XMFLOAT3 GetForwardAxis() const;
DirectX::XMVECTOR GetForwardAxisXM() const;
// 获取世界变换矩阵
DirectX::XMFLOAT4X4 GetLocalToWorldMatrix() const;
DirectX::XMMATRIX GetLocalToWorldMatrixXM() const;
// 获取世界变换逆矩阵
DirectX::XMFLOAT4X4 GetWorldToLocalMatrix() const;
DirectX::XMMATRIX GetWorldToLocalMatrixXM() const;
// 设置缩放矩阵
void SetScale(const DirectX::XMFLOAT3& scale);
void SetScale(float x, float y, float z);
// 设置对象欧拉角(弧度制), 对象以z-x-y轴顺序旋转,为了避免 "万向节死锁"
void SetRotation(const DirectX::XMFLOAT3& eulerAnglesInRadian);
void SetRotation(float x, float y, float z);
// 设置对象位置
void SetPosition(const DirectX::XMFLOAT3& position);
void SetPosition(float x, float y, float z);
// 按欧拉角旋转对象
void Rotate(const DirectX::XMFLOAT3& eulerAnglesInRadian);
// 绕坐标轴旋转
void RotateAxis(const DirectX::XMFLOAT3& axis, float radian);
// 绕点旋转
void RotateAround(const DirectX::XMFLOAT3& point, const DirectX::XMFLOAT3& axis, float radian);
// 沿着某一方向前进
void Translate(const DirectX::XMFLOAT3 & direction, float magnitude);
// 观察某一点
void LookAt(const DirectX::XMFLOAT3& target, const DirectX::XMFLOAT3& up = {0.0f, 1.0f, 0.0f});
// 沿着某方向看
void LookTo(const DirectX::XMFLOAT3& direction, const DirectX::XMFLOAT3& up = { 0.0f, 1.0f,0.0f });
DirectX::XMFLOAT3 GetEulerAnglesFromRotationMatrix(const DirectX::XMFLOAT4X4& rotationMatrix);
private:
DirectX::XMFLOAT3 m_Scale = { 1.0f, 1.0f, 1.0f };
DirectX::XMFLOAT3 m_Rotation = {};
DirectX::XMFLOAT3 m_Position = {};
};
|
e9b6509eb3594803699da8e8fc4b4420423ec669
|
[
"C",
"C++"
] | 29 |
C++
|
XIANQw/RenderingWithVLM
|
4664ce2589ef479579b01a38d1c17f6465334078
|
ed11554bc0f4b764920c399cc5a0e0d890963c66
|
refs/heads/master
|
<repo_name>MJavaadAkhtar/OS_Virtual-Memory-Algorithm1.1<file_sep>/lru.c
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include "pagetable.h"
extern int memsize;
extern int debug;
extern struct frame *coremap;
static unsigned long counter;
/* Page to evict is chosen using the accurate LRU algorithm.
* Returns the page frame number (which is also the index in the coremap)
* for the page that is to be evicted.
*/
int lru_evict() {
// to_go is defined for the index of the coremap
int to_go = 0;
// val defined to find the smallest counter
unsigned long val = counter;
int i;
// we need to loop through all the coremap to find the smallest time stamp
for (i = 0; i < memsize; i++) {
// record the to_go if stamp is smaller than val
if (coremap[i].pte->stamp < val) {
val = coremap[i].pte->stamp;
to_go = i;
}
}
return to_go;
}
/* This function is called on each access to a page to update any information
* needed by the lru algorithm.
* Input: The page table entry for the page that is being accessed.
*/
void lru_ref(pgtbl_entry_t *p) {
// every time we need to increase the counter
counter++;
// assign the p->stamp to be counter thus it becomes the newest page
p->stamp = counter;
return;
}
/* Initialize any data structures needed for this
* replacement algorithm
*/
void lru_init() {
// initialize the counter starting from 0
counter = 0;
return;
}<file_sep>/script.py
#!/bin/bash
#remove print_pagedirectory() in sim.c
import subprocess
algos = ["opt"]
files = ["/u/csc369h/winter/pub/a2-traces/tr-blocked.ref", "/u/csc369h/winter/pub/a2-traces/tr-matmul.ref"]
mems = [150, 200]
print "start"
for file in files:
print("File: %s" % (file))
for algo in algos:
print("Algo: %s" % (algo))
for mem in mems:
script = "time ./sim -f %s -m %d -s 3000 -a %s" % (file, mem, algo)
print(script)
#subprocess.call("time ./sim -f sample/tr-simpleloop.ref -m 50 -s 3000 -a clock", shell=True)
subprocess.call(script, shell=True)
print "end"<file_sep>/lru_v2.c
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include "pagetable.h"
extern int memsize;
extern int debug;
extern struct frame *coremap;
// used for the list implementation of lru
static struct node *head;
// count the number of nodes in our list, the maximum should be memsize
static int cnt;
/* Page to evict is chosen using the accurate LRU algorithm.
* Returns the page frame number (which is also the index in the coremap)
* for the page that is to be evicted.
*/
int lru_evict() {
// we only need to evict the head of the list, because it is the oldest node
unsigned int to_go = head->frame;
return to_go;
}
/* This function is called on each access to a page to update any information
* needed by the lru algorithm.
* Input: The page table entry for the page that is being accessed.
*/
void lru_ref(pgtbl_entry_t *p) {
// if the list is not full
if (cnt < memsize) {
// we first evaluate the head node, if cnt == 0, we assignment it and return
if (cnt == 0) {
head->frame = p->frame;
cnt = 1;
return;
}
// use previous and temp to keep track of the node in the list
struct node* temp = head;
struct node* previous = head;
while (temp->next != NULL) {
// if temp->frame == p->frame
if (temp->frame == p->frame) {
// need to record this node, delete this node, and put it at the end of the list
// if this node is the head node
if (temp == head) {
// go to the last node
while (temp->next != NULL) {
temp = temp->next;
}
// change the head node
// put previous node (which is previous head) to be temp->next
head = head->next;
temp->next = previous;
temp->next->next = NULL;
return;
}
// else if it is not the head node
else {
struct node* pNode = temp;
temp = temp->next;
previous->next = temp;
// loop to the end
while (temp->next != NULL) {
temp = temp->next;
}
// assign the pNode to the end of the list
temp->next = pNode;
return;
}
}
// else temp->frame isn't p->frame
else {
previous = temp;
temp = temp->next;
}
}
// here we loop to the end but still haven't found the p->frame
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->next = NULL;
newNode->frame = p->frame;
temp->next = newNode;
// we should add cnt
cnt ++;
return;
}
// else the list is full
// p->frame might be inside the list, might not be inside the list
else {
struct node* temp = head;
struct node* previous = head;
while (temp->next != NULL) {
// if temp->frame == p->frame
if (temp->frame == p->frame) {
// if it is the head node
if (temp == head) {
// loop to the end
while (temp->next != NULL) {
temp = temp->next;
}
head = head->next;
temp->next = previous;
temp->next->next = NULL;
return;
}
else {
struct node* pNode = temp;
temp = temp->next;
previous->next = temp;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = pNode;
return;
}
}
// else haven't found it yet
else {
previous = temp;
temp = temp->next;
}
}
// if we cannot find it, we move head to the end of the list and change its frame
previous = head;
head = head->next;
previous = temp->next;
temp->next->frame = p->frame;
temp->next->next = NULL;
return;
}
}
/* Initialize any data structures needed for this
* replacement algorithm
*/
void lru_init() {
// initialize the head of the list
head = (struct node*)malloc(sizeof(struct node));
// initialize the frame = 0
head->frame = 0;
// initialize the next pointer points to NULL
head->next = NULL;
// initialize the cnt = 0
cnt = 0;
return;
}
<file_sep>/README.md
# OS_Virtual-Memory-Algorithm1.1
For this project, I simulated the operation of page tables and page replacement.
I divided this project into to 2 major tasks, which will be based on a virtual memory simulator. The first task is to implement virtual-to-physical address translation and demand paging using a two-level page table. The second task is to implement four different page replacement algorithms: FIFO, Clock, exact LRU, and OPT.
### Task 1
Implemented virtual-to-physical address translation and demand paging using a two-level pagetable.
### Task 2
Implemented each of the four different page replacement algorithms: FIFO, exact LRU, CLOCK (with one ref-bit), OPT.
__Hashtable data structure__ is used to implement page replacement algorithms.
<file_sep>/opt.c
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include "pagetable.h"
#include "sim.h"
#define MAXLINE 256
extern int debug;
extern struct frame *coremap;
// store all the files obtained from the original tracefiles
char buf[MAXLINE];
// record the length of the traces for the whole file
static unsigned long traces_length;
// store all the trace file addresses
static addr_t *buf_trace;
// record current location in the buf_trace
static unsigned long curr_trace;
/* Page to evict is chosen using the optimal (aka MIN) algorithm.
* Returns the page frame number (which is also the index in the coremap)
* for the page that is to be evicted.
*/
int opt_evict() {
unsigned long counter = 0;
// we search through all the coremap pages and evict the one with the largest stamp
int i;
int to_go = 0;
for (i = 0; i < memsize; i++) {
if (counter < (coremap[i].pte->stamp)) {
counter = coremap[i].pte->stamp;
to_go = i;
}
}
return to_go;
// // we need to loop all the coremap index and return the one with maximum counter
// unsigned long counter = 0;
// int i;
// int to_go = 0;
// unsigned long curr_frame;
// int cnt;
// for (i = 0; i < memsize; i++) {
// // initialize all the variables for each page to detect
// curr_frame = coremap[i].pte->frame >> PAGE_SHIFT;
// unsigned long temp = curr_trace + 1;
// cnt = 1;
// while (temp <= traces_length) {
// // if we find the curr_frame
// if (curr_frame == buf_trace[temp]) {
// // if cnt > counter, we need to store this i as potential to_go
// if (cnt > counter) {
// to_go = i;
// counter = cnt;
// }
// break;
// }
// cnt ++;
// temp ++;
// }
// }
return to_go;
}
/* This function is called on each access to a page to update any information
* needed by the opt algorithm.
* Input: The page table entry for the page that is being accessed.
*/
void opt_ref(pgtbl_entry_t *p) {
// here I still use stamp in the pgtbl_entry_t, but it is indicated differently
// I only update the p->stamp, which is now pointed to by coremap also
// search through all the future pages in the buf_trace
unsigned long i;
int flag = 0;
for (i = curr_trace+1; i < traces_length; i++) {
if ((p->frame >> PAGE_SHIFT) == buf_trace[i]) {
// store the next time stamp
p->stamp = i-curr_trace;
flag = 1;
break;
}
}
if (flag == 0) {
p->stamp = traces_length - curr_trace;
}
curr_trace ++;
return;
}
/* Initializes any data structures needed for this
* replacement algorithm.
*/
// initialize by reading all the trace files and storing them into
void opt_init() {
// create a FILE and read tracefile
FILE *tfp;
if(tracefile != NULL) {
if((tfp = fopen(tracefile, "r")) == NULL) {
perror("Error opening tracefile:");
exit(1);
}
}
// record the length of the tracefile
traces_length = 0;
int m = 0;
while(fgets(buf, MAXLINE, tfp) != NULL) {
if(buf[0] != '=') {
traces_length++;
}
}
// store every line of trace file frame number into buf_trace
buf_trace = (addr_t *)malloc(traces_length * sizeof(addr_t));
addr_t read_trace;
char type;
while(fgets(buf, MAXLINE, tfp) != NULL) {
if(buf[0] != '=') {
sscanf(buf, "%c %lx", &type, &read_trace);
// I shift the lower 12 bits in order to get the frame number
buf_trace[m] = read_trace >> PAGE_SHIFT;
m++;
}
}
// we need to record current trace, initialize it as 0
curr_trace = 0;
fclose(tfp);
}
|
b67352cda7a26b1f0e866d8941e2306c6f76b41d
|
[
"Markdown",
"C",
"Shell"
] | 5 |
C
|
MJavaadAkhtar/OS_Virtual-Memory-Algorithm1.1
|
56884adb6cb638d479d8d61dd791fb562cb09821
|
06a3df877c734cfce12f67a410c12a0755c31521
|
refs/heads/master
|
<repo_name>jamjay2/k3test<file_sep>/wangzhan/src/com/lj/Index.java
package com.lj;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Index extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// 设置响应内容类型
resp.setContentType("text/html");
// 实际的逻辑是在这里
// PrintWriter out = response.getWriter();
// out.println("<h1>" + message + "</h1>");
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
<file_sep>/k3test/src/k3test/Test.java
package k3test;
public final class Test {
// static{
// try {
// Class.forName("Test");
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// }
// }
static {
System.out.println("abc");
}
void s(int i){
System.out.println("int"+i);
}
void s(Long i){
System.out.println("Long"+i);
}
private String dd() {return new StringBuilder().append("d").toString() ; }
public static void main(String[] args) {
new Test().s(2);
}
static class t{
public static void main(String[] args) {
new Test().dd();
}
}
class d{}
}
<file_sep>/wangzhan/src/com/lj/HelloWorld.java
package com.lj;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//扩展 HttpServlet 类
//@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException
{
// 执行必需的初始化
message = "sddddddddddddd";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// 设置响应内容类型
response.setContentType("text/html");
// 实际的逻辑是在这里
// PrintWriter out = response.getWriter();
// out.println("<h1>" + message + "</h1>");
// response.sendRedirect("jsp/success.jsp");
request.getRequestDispatcher("jsp/success.jsp").forward(request,response);
//
}
}
|
f4a71ed791aded8f5fc3448a00357aff54299c92
|
[
"Java"
] | 3 |
Java
|
jamjay2/k3test
|
fad46b945f6ed8b871eeda19019f58f0054b1506
|
0e698956e0e67421988873853921c6fdb9e754fd
|
refs/heads/master
|
<file_sep>package test;
/**
* Created on 28/11/14.
*
* 0 attribute
* 4 methods (0 overrides)
* 4 public
*
* @author dralagen
*/
public interface Fake {
public void createFake();
public void createFake(String name);
public void setFake(String name);
public FakeBean getFake();
}
<file_sep>package test.plop;
/**
* Created on 28/11/14.
*
* @author Maxime
*/
public class PlopPlop extends Plop {
}
<file_sep>package org.master.alma.metricsource;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
public class MethodByClassTest extends AbstractTest {
@Test
public void testExecute () throws Exception {
MethodByClass m = new MethodByClass(factory);
Map<String, Integer> result = m.execute();
Map<String, Integer> expected = new HashMap<>();
expected.put("test.Fake", 4);
expected.put("test.FakeAbstract", 3);
expected.put("test.FakeBean", 4);
expected.put("test.FakeEnum", 2);
expected.put("test.FakeImpl", 3);
expected.put("test.FakeService", 2);
expected.put("test.plop.Plop", 0);
expected.put("test.plop.PlopPlop", 0);
Assert.assertEquals("Avarage Method by Class", expected, result);
}
}<file_sep>package org.master.alma.metricsource;
import spoon.reflect.declaration.CtSimpleType;
import spoon.reflect.factory.Factory;
import java.util.HashMap;
import java.util.Map;
/**
* Created on 28/11/14.
*
* @author dralagen
*/
public class MethodByClass extends Metric<Map<String, Integer>> {
public MethodByClass(Factory factory) {
super(factory);
}
@Override
public Map<String, Integer> execute() {
Map<String, Integer> map = new HashMap<>();
for(CtSimpleType s : factory.Class().getAll()) {
Class cl = s.getActualClass();
map.put(cl.getCanonicalName(), cl.getDeclaredMethods().length);
}
return map;
}
}
<file_sep>package test;
/**
* Created on 28/11/14.
*
* @author dralagen
*/
public enum FakeEnum {
FAKE_ENUM,
FAKE_ENUM2,
FAKE_ENUM3,
FAKE_ENUM4,
FAKE_ENUM5,
FAKE_ENUM6
}
<file_sep>package test;
/**
* Created on 28/11/14.
*
* 3 methods (3 Overrides)
* 3 public
*
* @author dralagen
*/
public class FakeImpl extends FakeAbstract {
@Override
public void createFake() {
setBean(new FakeBean());
}
@Override
public void createFake(String name) {
createFake();
getBean().setName(name);
}
@Override
public void setFake(String name) {
getBean().setName(name);
}
}
<file_sep>package org.master.alma.metricsource;
import org.junit.Before;
import spoon.Launcher;
import spoon.reflect.factory.Factory;
import spoon.support.compiler.FileSystemFolder;
import java.io.File;
/**
* Created on 28/11/14.
*
* @author Maxime
*/
public abstract class AbstractTest {
protected Factory factory;
@Before
public void setUp() throws Exception {
Launcher spoon = new Launcher();
spoon.addInputResource(new FileSystemFolder(new File("./src/test/java/test")));
spoon.run();
factory = spoon.getFactory();
}
}
<file_sep>package test;
/**
* Created on 28/11/14.
*
* 1 attribute
* 1 private
* 3 methods (1 Override)
* 2 protected
* 1 public
*
* @author dralagen
*/
public abstract class FakeAbstract implements Fake {
private FakeBean bean;
protected FakeBean getBean() {
return bean;
}
protected void setBean(FakeBean bean) {
this.bean = bean;
}
@Override
public FakeBean getFake() {
return bean;
}
}
<file_sep>MetricSource
=============
Create some Metric of source code as number class in you project and number method by class
Require
-------
For execute:
- Java 8
For compile:
- Java 8
- Maven
How to Compile and Launch
-------------------------
```
mvn install
java -jar target/metricSource-{version}.jar
```<file_sep>package org.master.alma.metricsource;
import spoon.Launcher;
import spoon.reflect.code.CtCase;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtField;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.declaration.CtPackage;
import spoon.reflect.declaration.CtSimpleType;
import spoon.reflect.factory.Factory;
import spoon.support.compiler.FileSystemFolder;
import spoon.support.reflect.declaration.CtClassImpl;
import java.io.File;
import java.lang.reflect.Method;
import java.util.List;
/**
* Created on 07/11/14.
*
* @author Maxime
*/
public class Main {
public static void main(String[] args) {
try {
Launcher spoon = new Launcher();
spoon.addInputResource(new FileSystemFolder(new File("./src/main/java/org/master/alma/metricsource/")));
spoon.run();
Factory factory = spoon.getFactory();
for(CtPackage p : factory.Package().getAll()) {
System.out.println("package: "+p.getQualifiedName());
}
for(CtSimpleType s : factory.Class().getAll()) {
System.out.println("class: "+s.getQualifiedName());
List<CtField> a = s.getFields();
for (CtField anA : a) {
System.out.println("field: " + anA.getSimpleName() + " " + anA.getType().getQualifiedName());
}
Method[] m = s.getActualClass().getMethods();
}
Metric m = new AverageMethodByClassMetric(factory);
System.out.println(m.execute());
Metric m1 = new AverageClassByPackageMetric(factory);
System.out.println(m1.execute());
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
ca93fecff1cf43a6b64696237d9a448a5bb5fd9e
|
[
"Markdown",
"Java"
] | 10 |
Java
|
masters-info-nantes/metricSource
|
4466dc14921f82e626bac347c71e1cb423cea8cd
|
827fdb327f35c736400d009037fe80e521962e4e
|
refs/heads/master
|
<repo_name>whoami1995/BroodApp<file_sep>/BroodApplicatie/Brood.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BroodApplicatie
{
public class Brood
{
public Enum BroodSoort { get; set; }
enum brood
{
wit, grijs
};
public Brood(string broodsoort)
{
if(broodsoort.Equals("wit"))
{
this.BroodSoort = brood.wit;
}
else
{
this.BroodSoort = brood.grijs;
}
}
}
}
<file_sep>/BroodApplicatie/Gebruiker.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BroodApplicatie
{
public class Gebruiker
{
public string Voornaam { get; set; }
public string Achternaam { get; set; }
public Gebruiker(string voornaam, string achternaam)
{
this.Voornaam = voornaam;
this.Achternaam = achternaam;
}
}
}
<file_sep>/BroodApplicatie/MainWindow.xaml.cs
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace BroodApplicatie
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public int AantalWitteBroden { get; set; }
public int AantalGrijzeBroden { get; set; }
private List<Brood> witteBroodLijst = new List<Brood>();
private List<Brood> grijzeBroodLijst = new List<Brood>();
private int aantalLijnen;
private FileStream fs = null;
private StreamReader reader = null;
private string line;
private string[] broodItemsArray = null;
public string Bestand { get; set; }
private Brood broodItem = null;
private bool loaded = false;
public MainWindow()
{
InitializeComponent();
hideComponents(loaded);
}
private void hideComponents(bool waarde)
{
if(!waarde)
{
aantalLabel.Visibility = Visibility.Hidden;
aantalTextBox.Visibility = Visibility.Hidden;
bestelButton.Visibility = Visibility.Hidden;
}
else
{
aantalLabel.Visibility = Visibility.Visible;
aantalTextBox.Visibility = Visibility.Visible;
bestelButton.Visibility = Visibility.Visible;
}
}
private void InlezenBroden()
{
try
{
OpenFileDialog file = new OpenFileDialog();
if(file.ShowDialog() == true)
{
this.Bestand = file.FileName;
}
this.aantalLijnen = File.ReadAllLines(this.Bestand).Length;
fs = new FileStream(this.Bestand, FileMode.Open, FileAccess.Read);
reader = new StreamReader(fs);
this.line = reader.ReadLine();
for(int i = 0; i<this.aantalLijnen;i++)
{
this.broodItemsArray = this.line.Split(';');
this.broodItem = new Brood(this.broodItemsArray[2]);
if(this.broodItemsArray[2].Equals("wit") && this.broodItemsArray[0].Equals("G"))
{
this.witteBroodLijst.Add(this.broodItem);
this.AantalWitteBroden += int.Parse(broodItemsArray[1]);
}
else
{
if(this.broodItemsArray[0].Equals("G"))
{
this.grijzeBroodLijst.Add(this.broodItem);
this.AantalGrijzeBroden += int.Parse(broodItemsArray[1]);
}
}
this.line = reader.ReadLine();
}
this.grijsBroodAantalLabel.Content = this.AantalGrijzeBroden;
this.witBroodAantalLabel.Content = this.AantalWitteBroden;
MessageBox.Show("Broden zijn ingelezen");
this.loaded = true;
this.hideComponents(loaded);
}
catch(Exception ex)
{
Console.Write(ex.StackTrace);
}
finally
{
if(this.reader != null)
{
this.reader.Close();
}
if(this.fs != null)
{
this.fs.Close();
}
}
}
private void bestelButton_Click(object sender, RoutedEventArgs e)
{
int aantal = 0;
if((WitbroodRadioButton.IsChecked == true && aantalTextBox.Text != string.Empty))
{
try
{
aantal = int.Parse(aantalTextBox.Text);
if(AantalWitteBroden < aantal)
{
MessageBox.Show("Er zijn niet genoeg witte broden");
}
else
{
this.AantalWitteBroden -= aantal;
refreshLabel();
MessageBox.Show("Het nieuwe aantal witte broden is: " + this.AantalWitteBroden);
GebruikerInfo window = new GebruikerInfo(aantal, "wit");
window.ShowDialog();
}
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace);
MessageBox.Show("Gelieve een getal in te geven.");
}
}
else
{
aantal = int.Parse(aantalTextBox.Text);
try
{
if(this.AantalGrijzeBroden < aantal)
{
MessageBox.Show("Er zijn niet genoeg grijze broden");
}
else
{
refreshLabel();
MessageBox.Show("Het nieuwe aantal grijze broden is: " + this.AantalGrijzeBroden);
GebruikerInfo window = new GebruikerInfo(aantal, "grijs");
window.ShowDialog();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
MessageBox.Show("Gelieve een getal in te geven.");
}
}
}
private void loadmenuItem_Click(object sender, RoutedEventArgs e)
{
InlezenBroden();
}
private void refreshLabel()
{
grijsBroodAantalLabel.Content = AantalGrijzeBroden;
witBroodAantalLabel.Content = AantalWitteBroden;
}
}
}
<file_sep>/BroodApplicatie/GebruikerInfo.xaml.cs
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace BroodApplicatie
{
/// <summary>
/// Interaction logic for GebruikerInfo.xaml
/// </summary>
public partial class GebruikerInfo : Window
{
private List<Gebruiker> gebruikerslijst = new List<Gebruiker>();
private FileStream fs = null;
private StreamReader reader = null;
private int aantalLijnen;
private string line;
private string[] gebruikers = null;
private Gebruiker gebruikerobj = null;
private bool loaded = false;
public int AantalBroden { get; set; }
public string BroodSoort { get; set; }
public GebruikerInfo(int aantalbroden, string broodsoort)
{
InitializeComponent();
this.AantalBroden = aantalbroden;
this.BroodSoort = broodsoort;
inlezenGebruikers();
}
private void nieuweGebruikerButton_Click(object sender, RoutedEventArgs e)
{
if(this.voornaamTextBox.Text != string.Empty && this.achternaamTextBox.Text != string.Empty)
{
this.gebruikerobj = new Gebruiker(this.voornaamTextBox.Text, this.achternaamTextBox.Text);
this.gebruikerslijst.Add(this.gebruikerobj);
this.gebruikersListBox.Items.Add(this.gebruikerobj.Voornaam+ " " + this.gebruikerobj.Achternaam);
ToevoegenGebruiker(gebruikerobj);
}
}
private void ToevoegenGebruiker(Gebruiker gebruiker)
{
FileStream fs = null;
StreamWriter writer = null;
if (!loaded)
{
try
{
fs = new FileStream("gebruikers.txt",FileMode.Append,FileAccess.Write);
writer = new StreamWriter(fs);
writer.WriteLine(gebruiker.Voornaam + ";" + gebruiker.Achternaam);
writer.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
finally
{
if (writer != null)
{
writer.Close();
}
if(fs != null)
{
fs.Close();
}
}
}
}
private void inlezenGebruikersButton_Click(object sender, RoutedEventArgs e)
{
inlezenGebruikers();
}
private void inlezenGebruikers()
{
if(!loaded)
{
try
{
this.aantalLijnen = File.ReadAllLines("gebruikers.txt").Length;
fs = new FileStream("gebruikers.txt", FileMode.Open, FileAccess.Read);
reader = new StreamReader(fs);
this.line = reader.ReadLine();
for (int i = 0; i < this.aantalLijnen; i++)
{
this.gebruikers = this.line.Split(';');
this.gebruikerobj = new Gebruiker(this.gebruikers[0], this.gebruikers[1]);
this.gebruikerslijst.Add(this.gebruikerobj);
this.gebruikersListBox.Items.Add(this.gebruikerobj.Voornaam + " " + this.gebruikerobj.Achternaam);
this.line = reader.ReadLine();
}
this.loaded = true;
}
catch (Exception ex)
{
MessageBox.Show("U heeft geen gebruikers.");
Console.WriteLine(ex.StackTrace);
this.loaded = false;
}
finally
{
if (this.reader != null)
{
this.reader.Close();
}
if (this.fs != null)
{
this.fs.Close();
}
}
}
}
private void gebruikersListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show("Bedankt " + gebruikerslijst[gebruikersListBox.SelectedIndex].Voornaam + " " + gebruikerslijst[gebruikersListBox.SelectedIndex].Achternaam + " " + " voor het aankopen van " + this.AantalBroden + " " + this.BroodSoort + " broden.");
this.Close();
}
}
}
|
64bdffc0ffd12822c0eb87eca4337738e59714c0
|
[
"C#"
] | 4 |
C#
|
whoami1995/BroodApp
|
dff7d7b7a0dc9baf4c36fd750364aee3ecd07964
|
ddaa1e13883f0d9ec1f9908174d9377f87d56dc7
|
refs/heads/master
|
<file_sep># encryptmebitch
Encryption "algorithm" used on https://encryptmebitch.com
COPYRIGHT:
© <NAME>, Charles. All Rights Reserved. Any distribution, idea or code replica, is strictly prohibited.
<file_sep><?php
include 'functions.php';
testInput(); //INITIATING FUNCTION
function decryptString($key, $database)
{
//SEARCH IF KEY EXISTS WITHIN DATABASE
$req = $database->prepare('SELECT XXXXX FROM XXXXX WHERE XXXXX=:XXXXX');
$req->execute(array(
'XXXXX' => $key
));
while ($result = $req->fetch())
{
if ($result)
{
break;
}
}
if (!$result['XXXXX'])
{
//THROWS FATAL ERROR AND GIVES AN IP TIMEOUT OF 10 MINS
$req = $database->prepare('INSERT INTO XXXXX(XXXXX, XXXXX) VALUES(:XXXXX, :XXXXX)');
$req->execute(array(
'XXXXX' => $_SESSION['userIPAddr'],
'XXXXX' => time() + 600 //DEBUG: Use only 1 sec of timeout
));
$_SESSION['fatalError'] = 'Invalid key entered. Your access to this site is disabled for ten (10) minutes.';
echo "<script type='text/javascript'> document.location = 'error'; </script>";
}
else if ($result['XXXXX'])
{
//IF KEY EXISTS, CONTINUE
$req = $database->prepare('SELECT XXXXX, XXXXX, XXXXX FROM XXXXX WHERE XXXXX=:XXXXX ORDER BY XXXXX ASC');
$req->execute(array(
'XXXXX' => $key
));
while ($result = $req->fetch())
{
$position = $result['XXXXX'];
$char = $result['XXXXX'];
$_SESSION['message'] .= $char[$position - 1];
}
$req = $database->prepare('DELETE FROM XXXXX WHERE XXXXX=:XXXXX');
$req->execute(array(
'XXXXX' => $key
));
//DELETING ALL INPUTS FROM DATABASE AFTER PRINTING SECRET MESSAGE
}
}
if ($_SERVER["REQUEST_METHOD"] == 'POST')
{
$secret = testInput($_POST['secret']);
decryptString($secret, $database);
}
if (isset($_SESSION['message']) && $_SESSION['message'] != '')
{
echo $_SESSION['message'];
$_SESSION['message'] = '';
}
?>
<file_sep><?php
include 'functions.php';
testInput(); //INITIATING FUNCTION
function encryptString($difficulty, $messageToEncrypt, $database) {
//SETS MAX STRING LENGTH
switch ($difficulty)
{
case 0: //LOW
$maxStrLength = 20;
break;
case 1: //MEDIUM
$maxStrLength = 50;
break;
case 2: //HIGH
$maxStrLength = 100;
break;
case 3: //EXTREME
$maxStrLength = 200;
break;
default:
$maxStrLength = 20;
break;
}
//GENERATES ONE CUSTOM KEY FOR THE ENTIRE MESSAGE TO ENCRYPT
function generateKey($length)
{
$characters = '<KEY>';
$charactersLength = strlen($characters);
$randomKey = '';
for ($i = 0; $i < $length; $i++)
{
$randomKey .= $characters[rand(0, $charactersLength - 1)];
}
return $randomKey;
}
$key = generateKey($maxStrLength);
//GENERATES FIRST STRING
function generateStrings($position)
{
$characters = '<KEY>';
$charactersLength = strlen($characters);
$string = '';
for ($i = 0; $i < $position - 1; $i++)
{
$string .= $characters[rand(0, $charactersLength - 1)];
}
return $string;
}
//ENCRYPT ONE CHAR AT A TIME
for ($i = 0 ; $i < strlen($messageToEncrypt) ; $i++)
{
$char = $messageToEncrypt[$i];
//RANDOMIZE A POSITION TO STOCK IT IN THE DATABASE
$position = rand(1, $maxStrLength - 1);
//RANDOMIZE FIRST STRING
$firstString = generateStrings($position);
//COUNT REMAINING STRING LENGTH UNTIL DIFFICULTY MAX STR LENGTH IS REACHED
$remainingSpaces = $maxStrLength - $position;
//RANDOMIZE COMPLEMENTARY STRING
$complementaryString = generateStrings($remainingSpaces + 1);
//ADDS KEY, POS AND "HASHED" CHAR INTO DATABASE
$req = $database->prepare('INSERT INTO XXXXX(XXXXX, XXXXX, XXXXX) VALUES(:XXXXX, :XXXXX, :XXXXX)');
$req->execute(array(
'XXXXX' => $key,
'XXXXX' => $position,
'XXXXX' => $firstString . $char . $complementaryString
));
}
//SAVES KEY INTO SESSION VAR
$_SESSION['key'] = $key;
}
if ($_SERVER["REQUEST_METHOD"] == 'POST')
{
$difficulty = testInput($_POST['difficulty']);
$message = testInput($_POST['message']);
//CHECKS THE LENGTH OF THE MESSAGE
if (strlen($message) >= XXXXX)
{
//THROWS FATAL ERROR AND GIVES AN IP TIMEOUT OF 10 MINS
$req = $database->prepare('INSERT INTO XXXXX(XXXXX, XXXXX) VALUES(:XXXXX, :XXXXX)');
$req->execute(array(
'XXXXX' => $_SESSION['userIPAddr'],
'XXXXX' => time() + 600 //DEBUG: Use only 1 sec of timeout
));
$_SESSION['fatalError'] = 'Message entered is too long. Your access to this site is disabled for ten (10) minutes.';
header('Location: ../error');
}
else
{
encryptString($difficulty, $message, $database);
}
}
if (isset($_SESSION['key']) && $_SESSION['key'] != '')
{
echo $_SESSION['key'];
$_SESSION['key'] = '';
}
?>
|
596be1b3397ff9043ada08621b26b9679d463d74
|
[
"Markdown",
"PHP"
] | 3 |
Markdown
|
DaddyChucky/encryptmebitch
|
195c985bbad9d695c3a2b199a0f834906c2f0175
|
5c0ee96cf89c266eb2db00ff5dc5db880052271f
|
refs/heads/master
|
<file_sep>package com.example.demo.mybatis.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/mybatis")
public class MyBatisControllder {
@RequestMapping("/select/{id}")
public String select(@PathVariable("id") String id) {
return null;
}
}
<file_sep>package com.example.demo.mybatis.service.impl;
import com.example.demo.mybatis.dao.TestMapper;
import com.example.demo.mybatis.service.MyBatisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MyBatisServiceImpl implements MyBatisService {
@Autowired
TestMapper mapper;
@Override
public String selectById(String id) {
return mapper.selectById(id);
}
}
<file_sep>server.port=8080
spring.datasource.url = jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = <PASSWORD>
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
mybatis.mapper-locations= classpath:mapper/*.xml
|
78b4b84606e6c1e2ca04f0b2b3ed186741a0e982
|
[
"Java",
"INI"
] | 3 |
Java
|
zcchen-stu/springLearn
|
0c59b167f1f4847c3ac29b3a13721447dd27fc97
|
f5765a872f2250d93d41f4cd1ee845895d406783
|
refs/heads/main
|
<repo_name>Avacade2k/JunitV2<file_sep>/src/week2/testCase.java
package week2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
public class testCase {
// upp 1
@Test
public void Writing_Sometext_Backwards() {
StringBuilder sb = new StringBuilder("Jag");
String word = sb.reverse().toString();
assertEquals("gaJ", word);
}
// upp 2
@Test
public void JustASimpleAssert() {
String name = "My name";
assertEquals("My name", name);
}
// upp 3
Person person = new Person("first name", "last name", 0736666666, "my cool street");
@Test
public void TestingFirstName() {
assertEquals("first name", person.firstname);
}
@Test
public void TestingLastName() {
assertEquals("last name", person.lastname);
}
@Test
public void TestingPhoneNumber() {
assertEquals(0736666666, person.phonenumber);
}
@Test
public void TestingStreetAdress() {
assertEquals("my cool street", person.streetaddress);
}
// upp 4
@Test
public void TestingLengthOfString() {
String word = "Junit 5";
System.out.println(word);
assertEquals(7, word.length());
}
// upp 5
@Test
public void GiveMeASimpleVerification() {
assertEquals(100, 100);
}
// upp 6
@Test
public void CheckingSame() {
String s1 = new String("S1");
String s2 = s1;
assertSame(s1, s2);
}
// upp 7
@Test
public void CheckingBytes() {
byte smallByte1 = 100;
byte smallByte2 = smallByte1;
assertTrue(smallByte1 == smallByte2);
}
// upp 9
@Test
public void CheckingTrue() {
Object obj1 = new Object();
Object obj2 = obj1;
assertTrue(obj1 == obj2);
}
// upp 10
@Test
public void CheckingFalse() {
Object obj1 = new Object();
Object obj2 = new Object();
assertFalse(obj1 == obj2);
}
}<file_sep>/src/week2/Person.java
package week2;
public class Person {
String firstname;
String lastname;
int phonenumber;
String streetaddress;
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public int getPhone() {
return phonenumber;
}
public String getStreet() {
return streetaddress;
}
public Person(String firstname, String lastname, int phonenumber, String streetaddress) {
this.firstname = firstname;
this.lastname = lastname;
this.phonenumber = phonenumber;
this.streetaddress = streetaddress;
}
}
<file_sep>/README.md
# JunitV2
|
3b510bbc75329ffa80bd663c407baf32e50d4c0d
|
[
"Markdown",
"Java"
] | 3 |
Java
|
Avacade2k/JunitV2
|
d5583e3c4d322d80be81cca43f318987fcb8bb96
|
7b71499b522915faa1e09d642f445e21bad72868
|
refs/heads/master
|
<file_sep>document.addEventListener('DOMContentLoaded', () => {
document.querySelector('.menu-btn').addEventListener('click', () =>{
document.querySelector('.main-small').classList.toggle('show');
document.querySelectorAll('.page-show').forEach(button => {
button.onclick = () => {
document.querySelector('.main-small').classList.toggle('show')
};
});
})
});
|
72c912f25a2470f7b433ceace5492d4343f1ce90
|
[
"JavaScript"
] | 1 |
JavaScript
|
MohGumaa/my-portfolio
|
617dd6cc96e89cfeec05e5b77e31e3b8413e5902
|
107869c55946a4c2ce8e03ef29454f148afdf361
|
refs/heads/master
|
<file_sep>package sample1210;
import java.awt.Frame;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.BorderLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.GridLayout;
import java.awt.Container;
public class ColorBoxes extends Frame implements ActionListener{
private Button startButton;
private Button big;
private Button middle;
private Button small;
private int sizeflag=0;
public static void main(String args[]) {
ColorBoxes cb = new ColorBoxes("Color Boxes Sample");
cb.setLocation(100, 100);
cb.setSize(500,400);
cb.setBackground(Color.LIGHT_GRAY);
cb.setVisible(true);
}
ColorBoxes(String title) {
this.setTitle(title);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.startButton = new Button("start");
this.big=new Button("大");
this.middle=new Button("中");
this.small=new Button("小");
this.startButton.addActionListener(this);
this.big.addActionListener(this);
this.middle.addActionListener(this);
this.small.addActionListener(this);
this.setLayout(new BorderLayout());
Container container1=new Container();
container1.setLayout(new GridLayout(1,4));
container1.add(startButton);
container1.add(big);
container1.add(middle);
container1.add(small);
this.add("North",container1);
this.addComponentListener(new ComponentAdapter(){
public void componentResized(ComponentEvent e){
ColorBoxes.this.repaint();
}
});
}
public void actionPerformed(ActionEvent evt){
Button button=(Button)evt.getSource();
if(button==startButton){
this.repaint();
}
else if(button==middle) sizeflag=0;
else if(button==big) sizeflag=1;
else if(button==small) sizeflag=2;
}
public void paint(Graphics g) {
int rval;
int gval;
int bval;
int sizeH=getSize().height;
int sizeW=getSize().width;
if(sizeflag==0){
for (int j = 30+30+30; j < (sizeH-50); j += 30)
for (int i = 8+5+30; i < (sizeW-50); i+= 30) {
rval = (int)Math.floor(Math.random() * 256);
gval = (int)Math.floor(Math.random() * 256);
bval = (int)Math.floor(Math.random() * 256);
g.setColor(new Color(rval,gval,bval));
g.fillRect(i,j,25,25);
g.setColor(Color.black);
g.drawRect(i-1,j-1,25,25);
}
}
else if(sizeflag==1){
for (int j = 30+30+25; j < (sizeH-85); j += 80)
for (int i = 8+5+25; i < (sizeW-85); i+= 80) {
rval = (int)Math.floor(Math.random() * 256);
gval = (int)Math.floor(Math.random() * 256);
bval = (int)Math.floor(Math.random() * 256);
g.setColor(new Color(rval,gval,bval));
g.fillRect(i,j,75,75);
g.setColor(Color.black);
g.drawRect(i-1,j-1,75,75);
}
}
else{
for (int j = 30+30+15; j < (sizeH-20); j += 15)
for (int i = 8+5+15; i < (sizeW-20); i+= 15) {
rval = (int)Math.floor(Math.random() * 256);
gval = (int)Math.floor(Math.random() * 256);
bval = (int)Math.floor(Math.random() * 256);
g.setColor(new Color(rval,gval,bval));
g.fillRect(i,j,10,10);
g.setColor(Color.black);
g.drawRect(i-1,j-1,10,10);
}
}
}
}
|
a0d0810562adfc9a426e6f66b2210cd42eb381ca
|
[
"Java"
] | 1 |
Java
|
anilo-n/sample1210
|
9a95daab41b59574966f4541d635e8095197ef85
|
eecf809d61d43af6cbe702a0cb70dbb53fc023ae
|
refs/heads/master
|
<file_sep>// Write a program that opens the text.txt file (with the `fopen()` system call) located in this directory
// and then calls `fork()` to create a new process. Can both the child and parent access the file descriptor
// returned by `fopen()`? What happens when they are written to the file concurrently?
//they're both able to run on a single fopen. Interestingly, throwing an fclose at the end of either the if or else statement doesn't
//seem to do anything
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
fp = fopen("text.txt", "w+");
int count = fork();
if (count == 0)
{
fprintf(fp, "%s %s %s %s", "I", "can", "go", "anywhere\n");
printf("child printed\n");
fclose(fp);
printf("child closed\n");
}
else
{
fprintf(fp, "%f %f %s %s", 8.03, 67.57, "do", "anything\n");
printf("parent printed\n");
}
;
return (0);
}
|
0c6aa6e8258e01a223e582c64daa86ac52dabb00
|
[
"C"
] | 1 |
C
|
farste/Processes
|
14a99c044076292e0733722182af97b1588d34dc
|
7fc77c1794c1285bd348f6bf22a056d5d5b7052a
|
refs/heads/master
|
<file_sep>import requests # urlを読み込むためrequestsをインポート
from bs4 import BeautifulSoup # htmlを読み込むためBeautifulSoupをインポート
URL = 'https://www.hinatazaka46.com/s/official/diary/member/list?ima=0000&page=8&cd=member&ct=3' # URL入力
images = [] # 画像リストの配列
soup = BeautifulSoup(requests.get(URL).content,'lxml') # bsでURL内を解析
for link in soup.find_all("img"): # imgタグを取得しlinkに格納
if link.get("src").endswith(".jpg"): # imgタグ内の.jpgであるsrcタグを取得
images.append(link.get("src")) # imagesリストに格納
elif link.get("src").endswith(".png"): # imgタグ内の.pngであるsrcタグを取得
images.append(link.get("src")) # imagesリストに格納
for target in images: # imagesからtargetに入れる
re = requests.get(target)
with open('img/' + target.split('/')[-1], 'wb') as f: # imgフォルダに格納
f.write(re.content) # .contentにて画像データとして書き込む
#==============================================================================
for i in range(1,14):
URL = 'https://www.hinatazaka46.com/s/official/diary/member/list?ima=0000&page=' + str(i) + '&cd=member&ct=3' # URL入力
images = [] # 画像リストの配列
soup = BeautifulSoup(requests.get(URL).content,'lxml') # bsでURL内を解析
for link in soup.find_all("img"): # imgタグを取得しlinkに格納
a = link.get("src")
images.append(a)
for target in images: # imagesからtargetに入れる
re = requests.get(target)
with open('img/' + target.split('/')[-1], 'wb') as f: # imgフォルダに格納
f.write(re.content) # .contentにて画像データとして書き込む
if link.get("src").endswith(".jpg"): # imgタグ内の.jpgであるsrcタグを取得
images.append(link.get("src")) # imagesリストに格納
elif link.get("src").endswith(".png"): # imgタグ内の.pngであるsrcタグを取得
images.append(link.get("src")) # imagesリストに格納
print("ok") # 確認
|
d9ab9a52a777d300a419ba292e25f8ffc0697e98
|
[
"Python"
] | 1 |
Python
|
Ryokikuver/kikulabo
|
0f0d61efb39dbc815332ce8a48d077745a786c89
|
958e2df54c7169a879f3e6940398139a1fe5af04
|
refs/heads/master
|
<file_sep>import allure
class LoginPage:
@allure.step(title="输入用户名")
def input_username(self, username):
allure.attach("输入的用户名是" + username, " ")
print("输入用户名" + username)
@allure.step(title="输入密码")
def input_password(self, password):
allure.attach("输入的密码是", password)
print("输入密码" + password)
@allure.step(title="点击登录")
def click_login(self):
print("点击登录")
<file_sep>import pytest
# 测试题目
class TestAAA:
@pytest.mark.parametrize("a,b",[(3,6)])
def test_aaa(self,a,b):
print(a)
print(b)
<file_sep>import pytest
from page.login_page import LoginPage
class TestLogin:
def setup(self):
self.login_page = LoginPage()
@pytest.allure.severity(pytest.allure.severity_level.BLOCKER)
@pytest.mark.parametrize("username,password", [("zhangsan", "<PASSWORD>"), ("lisi", "<PASSWORD>")])
def test_login1(self, username, password):
self.login_page.input_username(username)
self.login_page.input_password(password)
self.login_page.click_login()
assert 1
@pytest.allure.severity(pytest.allure.severity_level.CRITICAL)
def test_login2(self):
self.login_page.input_password("2")
self.login_page.input_username("2")
self.login_page.click_login()
assert 1
|
5abf6b259527e4b7e0dac1f51030f5fdc09a3e75
|
[
"Python"
] | 3 |
Python
|
fengsanan/allure_pytest
|
bd73182b6c536494cdddbe6e9068eb0e446dc856
|
085104e9d01f8abd75a3f3a7d35a51849247dd53
|
refs/heads/main
|
<repo_name>AlexisMakrogiannis/Data-Persistence-Project<file_sep>/Assets/Scripts/MenuManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class MenuManager : MonoBehaviour
{
public Text BestScoreText;
public static string playerName;
public static string bestPlayer;
public GameObject inputField;
public GameObject textDisplay;
public static int bestScore = 0;
public void Start()
{
ShowBestScore();
}
public void StoreName()
{
playerName = inputField.GetComponent<Text>().text;
textDisplay.GetComponent<Text>().text = "Your name is: " + playerName;
}
private void StartNew()
{
SceneManager.LoadScene(1);
}
private void ShowBestScore()
{
var path = Application.persistentDataPath + "/bestScore.json";
if (File.Exists(path))
{
string json = File.ReadAllText(path);
var data = JsonUtility.FromJson<Save>(json);
bestPlayer = data.playerName;
bestScore = data.score;
BestScoreText.text = "Best Score: " + bestPlayer + ": " + bestScore;
}
}
public void Exit()
{
#if UNITY_EDITOR
EditorApplication.ExitPlaymode();
#else
Application.Quit(); // original code to quit Unity player
#endif
}
}
|
e6265b92f51c2fe721186bbca7690853c0861abd
|
[
"C#"
] | 1 |
C#
|
AlexisMakrogiannis/Data-Persistence-Project
|
7cf7c640381e4ef85c26eb578f164ca8485d17ae
|
90ae4474a185a3403e763fa70974cde07a076d78
|
refs/heads/master
|
<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.directive('chooseDuration', [function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'js/common/templates/choose.duration.html',
scope: {
choice: '='
},
link: function(scope) {
function computeTime() {
scope.duration.hh = Math.floor( scope.choice.value / 60);
scope.duration.mm =
scope.choice.value - (scope.duration.hh * 60);
}
scope.duration = {
add: function() {
scope.choice.value += scope.choice.step;
computeTime();
},
remove: function() {
if (scope.choice.value <= scope.choice.step) {
return;
}
scope.choice.value -= scope.choice.step;
computeTime();
}
};
scope.choice.value = scope.choice.value ?
scope.choice.value : scope.choice.step;
computeTime();
}
};
}]);
})();<file_sep>'use strict';
(function() {
// slow url : http://djinn.janosgyerik.com
// fast url : http://suvm-bac05.sits.credit-agricole.fr:8000
angular.module('djinnApp')
.constant('BaseUrl', 'http://djinn.janosgyerik.com');
})();<file_sep># Djinn FrontEnd
* 1. Install Node.js
* 2. Run "npm install" from the dir root of the project
* 3. Run "bower install" from the dir root
* 4. Launch website with command "gulp" from a CLI interface.
Site running on http://localhost:9000
# Build
* 1. Run "gulp clean"
* 2. Run "gulp build"
* 3. Creates a dist directory with compiled and minified files
* 4. Upload the dist content to host<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('main', {
abstract: true,
controller: 'MainController',
templateUrl: 'js/main/templates/main.html'
})
.state('main.login', {
url: '/login',
controller: 'LoginController',
templateUrl: 'js/login/templates/login.html'
})
.state('main.choice', {
url: '/choice',
controller: 'ChoiceController',
templateUrl: 'js/choice/templates/choice.html'
})
.state('main.result', {
url: '/result',
controller: 'ResultController',
templateUrl: 'js/result/templates/result.html',
resolve: {
ResultData: ['ResultFactory', function(ResultFactory) {
return ResultFactory.getRooms();
}]
}
})
;
$urlRouterProvider.otherwise('/login');
}]);
})();<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.constant('LangFr', {
submit: 'Envoyer',
user: 'Utilisateur',
password: '<PASSWORD>',
findRoom: 'Trouver une salle',
visiocall: 'VisioCall',
octopus: 'Octopus',
computer: 'Ordinateur',
capacity: 'Capacité',
duration: 'Durée',
phone: 'Téléphone',
favorites: 'Favoris',
lang: 'Langues',
logout: 'Déconnexion',
date: 'Date',
fromtime: 'Début',
bookit: 'Réserver',
floor: 'Etage',
building: 'bâtiment',
msgBooked: 'Reservation effectuée !'
});
})();
<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.controller('ResultController', ['$scope', '$rootScope', '$state', '$filter', 'ResultData', 'ChoiceFactory', 'BookingFactory',
function($scope, $rootScope, $state, $filter, ResultData, ChoiceFactory, BookingFactory) {
// logo menu link
$scope.main.goState = 'main.choice';
$scope.result = {
rows: ResultData,
icons: ChoiceFactory.getIcons(),
open: function(idx) {
$scope.result.rows[idx].opened = !$scope.result.rows[idx].opened;
},
book: function(idx) {
BookingFactory.bookIt($scope.result.rows[idx], ResultData)
.then(function() {
$rootScope.$emit('openModale', {message: $filter('translate')('msgBooked')});
$state.go('main.choice');
});
}
};
}]);
})();<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.filter('timenumber', [function() {
return function(parm) {
return parm < 10 ? '0' + parm : parm;
};
}]);
})();<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.factory('LoginFactory', ['$http', '$q', 'UserFactory',
function($http, $q, UserFactory) {
var log = {
login: function(user, password) {
UserFactory.login();
var defer = $q.defer();
defer.resolve('');
/* $http({
url: 'api/login',
method: 'post',
headers: {
'Content-Type': 'application/json'
},
data: {
user: user,
password: <PASSWORD>
}
})
.success(function(data, status) {
if (status === 204) {
} else {
UserFactory.saveUser();
defer.resolve('logged');
}
});
*/
return defer.promise;
}
};
return {
login: log.login
};
}]);
})();<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.factory('ChoiceFactory', ['ChoiceValue',
function(ChoiceValue) {
var iconObj = {};
var choice = {
initIcons: function() {
angular.forEach(ChoiceValue, function(item) {
iconObj[item.model] = item.icon;
});
},
getIcons: function() {
return iconObj;
}
};
return {
initIcons: choice.initIcons,
getIcons: choice.getIcons
};
}]);
})();<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.config(['$translateProvider', 'LangEn', 'LangFr',
function($translateProvider, LangEn, LangFr) {
$translateProvider.translations('en', LangEn);
$translateProvider.translations('fr', LangFr);
$translateProvider.preferredLanguage('en');
$translateProvider.useSanitizeValueStrategy('sanitize');
}]);
})();<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.constant('LangEn', {
submit: 'Submit',
phone: 'Phone',
user: 'User account',
password: '<PASSWORD>',
findRoom: 'Find a room',
visiocall: 'VisioCall',
octopus: 'Octopus',
computer: 'Computer',
capacity: 'Capacity',
duration: 'Duration',
favorites: 'Favorites',
lang: 'Languages',
logout: 'Logout',
date: 'Date',
fromtime: 'Start',
bookit: 'Book it',
floor: 'Floor',
building: 'building',
msgBooked: 'Room booked !'
});
})();<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.directive('djinnModale', ['$rootScope', '$timeout',
function($rootScope, $timeout) {
return {
restrict: 'E',
replace: true,
templateUrl: 'js/common/templates/djinn.modale.html',
scope: {
},
link: function(scope, elem) {
var dir = {
manageMessage: function(evt, data) {
scope.dir = {
message: data.message,
status: data.status,
url: data.url,
more: dir.formatMore(data.more)
};
dir.showIt();
},
formatMore: function(datamore) {
if (!angular.isObject(datamore)) {
return null;
}
var more = [], formatted;
angular.forEach(datamore, function(value, key) {
formatted = key === 'non_field_errors' ? value[0] :
value[0] + ' (' + key + ')';
more.push(formatted);
});
return more;
},
showIt: function() {
elem.css({display: 'block'});
$timeout(function() {
elem.css({opacity: 1});
}, 30);
},
hideIt: function() {
elem.css({opacity: 0});
$timeout(function() {
elem.css({display: 'none'});
}, 220);
}
};
scope.action = {
close: dir.hideIt
};
var unbindError = $rootScope.$on('openModale', dir.manageMessage);
scope.$on('$destroy', function() {
unbindError();
});
}
};
}]);
})();<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.value('ChoiceValue', [
{
model: 'visiocall',
icon: 'videocam',
type: 'truefalse'
},
{
model: 'octopus',
icon: 'group_work',
type: 'truefalse'
},
{
model: 'computer',
icon: 'computer',
type: 'truefalse'
},
{
model: 'phone',
icon: 'phone',
type: 'truefalse'
},
{
model: 'capacity',
icon: 'people',
type: 'range',
min: 0,
max: 99
},
{
model: 'date',
icon: 'today',
type: 'startdate'
},
{
model: 'fromtime',
icon: 'alarm',
type: 'fromtime',
step: 15
},
{
model: 'duration',
icon: 'schedule',
type: 'duration',
step: 15
}
]);
})();<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.factory('ResultFactory', ['$http', '$q', '$filter',
function($http, $q, $filter) {
var currentSearch = {};
var currentDate = null;
var currentDuration = null;
var currentStuff = [];
var res = {
setSearch: function(params) {
currentSearch = params;
},
getRooms: function() {
var defer = $q.defer();
var parms = res.formatParms();
$http({
method: 'GET',
url: '/api/v1/find/rooms/' + parms
}).success(function(data) {
// sort data by accuracy descending
if (!angular.isArray(data)) {
data = [];
}
// TEMP - add fake icons
res.addFakeIcons(data);
// END TEMP - add fake icons
var myData = $filter('orderBy')(data, 'accuracy', true);
defer.resolve(myData);
});
return defer.promise;
},
addFakeIcons: function(data) {
var icontypes = ['visiocall', 'computer', 'duration', 'octopus', 'capacity'];
var icons = {
target: []
};
var nbIcons = 0, icStart = 0;
angular.forEach(data, function(item) {
nbIcons = Math.floor(Math.random() * 3) + 1;
icStart = Math.floor(Math.random() * 4);
icons.target = icontypes.slice(icStart, nbIcons + icStart);
angular.extend(item, icons);
});
},
formatParms: function() {
var searchParms = '?';
var myStartDate, myStartTime;
currentStuff = [];
angular.forEach(currentSearch, function(parm) {
switch(parm.model) {
case 'visiocall':
case 'octopus':
case 'computer':
case 'phone':
if (parm.value) {
currentStuff.push(parm.model);
}
break;
case 'capacity':
if (parm.value) {
searchParms += 'capacity=' + parm.value + '&';
}
break;
case 'date':
myStartDate = parm.value;
break;
case 'fromtime':
myStartTime = parm.value;
break;
case 'duration':
currentDuration = parm.value;
searchParms += 'minutes=' + parm.value + '&';
break;
}
});
// format start date
searchParms += 'start=' + res.formatDate(myStartDate, myStartTime) + '&';
// format equipment list
searchParms += currentStuff.length ? 'equipment=' +
res.formatStuff(currentStuff) + '&': '';
return searchParms;
},
formatDate: function(myDay, myTime) {
var myDate = new Date();
myDate.setTime(myDay);
myDate.setHours(myTime.hh);
myDate.setMinutes(myTime.mm);
currentDate = myDate.toISOString();
return currentDate;
},
formatStuff: function(stuff) {
var list = '';
angular.forEach(stuff, function(item, ix) {
list += item;
list += (stuff.length - 1 !== ix) ? ',': '';
});
return list;
},
getCurrentSearch: function() {
return {
startdate: currentDate,
duration: currentDuration,
stuff: currentStuff
};
}
};
return {
setSearch: res.setSearch,
getCurrentSearch: res.getCurrentSearch,
getRooms: res.getRooms
};
}]);
})();
<file_sep>'use strict';
(function() {
angular.module('djinnApp', [
'ui.router',
'pascalprecht.translate',
'ngSanitize',
'tmh.dynamicLocale',
'ngTouch'
])
.config(['$locationProvider', '$compileProvider', '$httpProvider', 'tmhDynamicLocaleProvider',
function($locationProvider, $compileProvider, $httpProvider, tmhDynamicLocaleProvider) {
$locationProvider.html5Mode(false);
$compileProvider.debugInfoEnabled(false);
tmhDynamicLocaleProvider.localeLocationPattern('i18n/angular-locale_{{locale}}.js');
// interceptors
$httpProvider.interceptors.push('ApiFactory');
$httpProvider.interceptors.push('HttpErrorFactory');
}])
.run(['$rootScope', 'LocaleFactory', 'UserFactory',
function($rootScope, LocaleFactory, UserFactory) {
LocaleFactory.setLang();
$rootScope.$on('$stateChangeStart', UserFactory.isLogged);
}]);
})();<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.controller('MainController', ['$scope', '$state', 'LanguagesValue', 'LocaleFactory',
function($scope, $state, LanguagesValue, LocaleFactory) {
$scope.main = {
goState: null,
open: false,
close: true,
languages: LanguagesValue,
selectedLang: LocaleFactory.getPrefLang(),
setPrefLang: function(lang) {
LocaleFactory.setPrefLang(lang);
$scope.main.selectedLang = lang;
},
goHome: function() {
if($scope.main.goState) {
$state.go($scope.main.goState);
}
},
logout: function() {
$state.go('main.login');
},
initMain: function() {
$scope.main.goState = null;
$scope.main.close = true;
$scope.main.open = false;
}
};
}]);
})();<file_sep>'use strict';
(function() {
angular.module('djinnApp')
.factory('LocaleFactory', ['$window', '$translate', 'LanguagesValue', 'tmhDynamicLocale',
function($window, $translate, LanguagesValue, tmhDynamicLocale) {
var key = 'prefLang';
var loc = {
setLang: function() {
var userPref = loc.getPrefLang();
tmhDynamicLocale.set(userPref);
$translate.use(userPref);
},
getPrefLang: function() {
return $window.localStorage.getItem(key) || LanguagesValue[0];
},
setPrefLang: function(lang) {
$window.localStorage.setItem(key, lang);
loc.setLang();
}
};
return {
setLang: loc.setLang,
getPrefLang: loc.getPrefLang,
setPrefLang: loc.setPrefLang
};
}]);
})();
|
0e080b2499539aeda569b5dda8ae997b5eb4832e
|
[
"JavaScript",
"Markdown"
] | 17 |
JavaScript
|
djinn-org/djinn-web
|
741c3a8fd8f1e226d2793d2501e3cea601444cfa
|
b1bea4ca55bfffa19f59bc05159e34fb8bd362d8
|
refs/heads/master
|
<file_sep>from xml.dom import minidom
import xml.etree.ElementTree as et
__author__ = 'sonte'
# creating our dictionaries
relationDictionary = dict()
catDictionary = dict()
#pulling in the xml and getting all the trees with the attribute 'category'
doc = et.parse('categories.xml')
child = doc.findall('category')
x = 0
'''
Under the Category tree in the xml assigning the text from the id to be the key
and the name to be the value in the catDictionary
'''
while (x < len(child)):
catDictionary[int(child[x][0].text)] = child[x][1].text
x = x + 1
#Parsing the xml from the other xml file and getting all the trees with the attribute 'category_relationship'
doc = et.parse('category_relationships.xml')
child = doc.findall('category_relationship')
x = 0
'''
#Under the 'category_relationship' tree first we check if the parent_id already exists. If it does we append
#the child_id to the existing key in the dictionary. If it does not, we create a new key with the parent_id and
#child_id as the value.
'''
while (x < len(child)):
if int(child[x][0].text) in relationDictionary.keys():
relationDictionary[int(child[x][0].text)].append(int(child[x][1].text))
else:
relationDictionary[int(child[x][0].text)] = [int(child[x][1].text)]
x = x + 1
x = 0
#This goes through all of the keys in the relationDictionary.
for key in relationDictionary:
first = ''
second = ''
'''
First it checks to make sure that the key's value does not have multiple entries. If it does we know that
it is not going to be our starting point, so skip to the next key.
'''
if (len(relationDictionary[key]) == 1):
'''
Here is checks to make sure that the parent object is not a child object. If the parent object is a child
object it will ignore it and move on the the next parent object.
'''
findkey = relationDictionary.get(key)
list = relationDictionary.get(findkey[0])
if key not in list:
'''
Next it checks to make sure that the key's value exists in the catDictionary. If it does not, then there
is no corresponding name in the categories.xml files and should be skipped.
'''
if (catDictionary.get(key) != None ):
#Now that we have gotten to this point, we know that the key is the first word in the catDictionary.
first = catDictionary.get(key)
'''
We know that they value of the key is the second word, but this is a list so we have to pull it out to convert it
because none of the keys are lists in catDictionary. list[0] is just and int which is what the keys are in
catDictionary
'''
list = relationDictionary.get(key)
second = catDictionary.get(list[0])
'''
We know that the second word is going to be followed by the third and final word. We use the second word as the key and
get its list of values and the different possible third words.
'''
list = relationDictionary.get(list[0])
#go through all of the items in list to get all of the possible third word combinations.
for items in list:
#check to make the third word exits of course.
if (catDictionary.get(items) != None):
third = catDictionary.get(items)
print(first + " > " + second + " > " + third)
x = x + 1
|
f4ffc9cc3d2f427b7e78127b29fe1cbf4ad61e88
|
[
"Python"
] | 1 |
Python
|
sonte/Catagory-Relationships
|
4dd60dc88d66136b18e79e433e7e2ddd3f97429b
|
4de92e6180338617a6554fb1c52d7f4b08765909
|
refs/heads/master
|
<file_sep>export const domElements = {
about: document.querySelector('#about-me'),
body: document.querySelector('body'),
images: document.querySelectorAll('.showcase a'),
modalImg: document.querySelector('#details img'),
modalHeading: document.querySelector('#details h1'),
modalText: document.querySelector('#details time'),
back: document.querySelector('.navigation.left'),
next: document.querySelector('.navigation.right'),
modalCLose: document.querySelector('.navigation.close'),
selectboxButton: document.querySelectorAll('.selectbox button'),
selectbox: document.querySelectorAll('.filter-small .selectbox'),
checkboxesTheme: document.getElementsByName("theme"),
checkboxesContinent: document.getElementsByName("continents"),
allCheckboxes: document.querySelectorAll('.selectbox input[type="checkbox"'),
counts: document.querySelectorAll(".filter-small .count"),
tags: document.querySelectorAll('.tags'),
radioButtons: document.querySelectorAll('input[type="radio"'),
popUptext: document.querySelector('.popup-text'),
popUp: document.querySelector('.popup'),
buttonPop: document.querySelector('.popup button'),
}
<file_sep>import {domElements} from "./domElements";
export const sort = {
type: "latest",
sortImages() {
const ul = document.querySelectorAll('.column');
for (let i = 0; i < domElements.radioButtons.length; i++) {
if (domElements.radioButtons[i].checked) {
this.type = domElements.radioButtons[i].value
}
}
for (let i = 0; i < domElements.radioButtons.length; i++) {
if (domElements.radioButtons[i].value === this.type) {
domElements.radioButtons[i].checked = true;
}
}
if (this.type === "latest") {
// With help from https://stackoverflow.com/questions/8837191/sort-an-html-list-with-javascript
for (let a = 0; a < ul.length; a++) {
const new_ul = ul[a].cloneNode(false);
const lis = [];
for (let i = ul[a].childNodes.length; i--;) {
if (ul[a].childNodes[i].nodeName === 'A') {
lis.push(ul[a].childNodes[i]);
}
}
lis.sort(function (a, b) {
let aDate = "" + a.childNodes[0].nextElementSibling.children[1].innerHTML;
let aSplitDate = aDate.split("-");
let aNewDate = aSplitDate[1] + "/" + aSplitDate[0] + "/" + aSplitDate[2];
let bDate = b.childNodes[0].nextElementSibling.children[1].innerHTML;
let bSplitDate = bDate.split("-");
let bNewDate = bSplitDate[1] + "/" + bSplitDate[0] + "/" + bSplitDate[2];
return new Date(bNewDate) - new Date(aNewDate);
});
for (let i = 0; i < lis.length; i++)
new_ul.appendChild(lis[i]);
ul[a].parentNode.replaceChild(new_ul, ul[a]);
}
} else {
// With help from https://stackoverflow.com/questions/8837191/sort-an-html-list-with-javascript
for (let a = 0; a < ul.length; a++) {
const new_ul = ul[a].cloneNode(false);
const lis = [];
for (let i = ul[a].childNodes.length; i--;) {
if (ul[a].childNodes[i].nodeName === 'A') {
lis.push(ul[a].childNodes[i]);
}
}
lis.sort(function (a, b) {
let aDate = "" + a.childNodes[0].nextElementSibling.children[1].innerHTML;
let aSplitDate = aDate.split("-");
let aNewDate = aSplitDate[1] + "/" + aSplitDate[0] + "/" + aSplitDate[2];
let bDate = b.childNodes[0].nextElementSibling.children[1].innerHTML;
let bSplitDate = bDate.split("-");
let bNewDate = bSplitDate[1] + "/" + bSplitDate[0] + "/" + bSplitDate[2];
return new Date(aNewDate) - new Date(bNewDate);
});
for (let i = 0; i < lis.length; i++)
new_ul.appendChild(lis[i]);
ul[a].parentNode.replaceChild(new_ul, ul[a]);
}
}
}
}<file_sep># Portfolio
## Feedback
| Feedback | Verbetering |
| ----------------------- |:------------------------|
| About me menu item attracks to much attention. | Made the about me link more subtle. Also added a contact menu item. |
| Finish the user flow. | Added tags on the detail page. |
| Finish the user story. | Added a popup message with a call to action at the detail page |
## The website
This is my portfolio website. It's specially made for <NAME>. She is deaf. To make it more usefull for her, I added some icons to my website so she doesn't have to read everything. I used a lot of white spacing, headings and not a lot of content, Because she wants to have a quick overview of the content, and not spend to much time on a website.

## Table of Content
- [Getting started](#getting-started)
- [User stories](#user-stories)
- [Card sorting](#card-sorting)
- [Feedback test Marie](#feedback-test-marie)
- [Modifications after testing](#modifications-after-testing)
- [To do](#to-do)
- [Best practice for deaf people by <NAME>](#best-practice-deaf-people-by-marie-van-driessche)
- [Resources](#resources)
## Getting started
* Run `$ git clone https://github.com/fennadew/boilerplate-html.git` in your terminal in the desired directory.
* `cd` to the repository
* Run `npm install` to install all dependencies.
* Run `npm start` or `gulp` to start the server.
App listens on `http://localhost:8080/`.
## User stories
### Marie
Marie wants to get inspiration for her next vacation. She is looking for beautiful places in Asia. Via my website filter on "asia" to see all Asian photos. She looks at the title and explanation to see where these are taken. She likes so many pictures that she no longer knows where to go. She decides to email me to get some tips about Asia.
### Owner of a potential agency
The owner of an advertising company is searching the internet for photographers for his next project. He visits an article with several photographers, including me. He clicks on my website and looks through my photos if he encounters some interesting things. He finds a picture of a girl with a pink background and that is exactly in the style that he is looking for. At the next meeting he wants to show the photo to his colleagues to see what they think of it. He visits my website again and filters on 'people', so he finds the photo quickly. The colleagues also like the photo and the owner decides to contact me to hire me for the job.
## Card sorting
### Sorted on themes

### Sorted on themes

## Feedback test Marie

* She wanted to go back to the pop up, but the pop up only showed once in te beginning
* Didnt understand the checkboxes
* Hover states should be different than active state
* Some icons at the about me page can be nice
## Modifications after testing
* Changed the popup to the inline filter and added the styling to that filter
* Hover and active states look different
* Made the filter smaller and added more "photography feeling" to it
## To do
* [ ] Responsive
* [ ] Icons at contact page
* [ ] More user testing!
## Best practice for deaf people by <NAME>
* Use headings and subheadings
* Make one point per paragraph
* Use short sentences: seven words per paragraph
* Use bullet list
* Use easy accessible languages
* Write in journalistic style, make your point and then explain it
* Write in active form
* Avoid unnecessary jargon and slang
* Use images and diagrams
* Use blank spaces
* Use a glossary for specialised vocabulary
* Mulitple contact options
## Resources
* [presentation deaf people](https://interaction18.ixda.org/program/talk-designing-for-deaf-people--for-everyone-actually-van-driessche-marie/)
<file_sep>import routie from "../vendor/route";
import { sections } from './sections';
import {events} from "./events";
// Checks the hash location of the website
export const routes = {
init() {
routie({
'': function () {
sections.toggle('home')
},
'about': function() {
sections.toggle('about');
},
'contact': function() {
sections.toggle('contact');
},
'photos/:name': function (name) {
sections.toggle('details');
events.showContent(name);
}
})
}
}<file_sep>const gulp = require('gulp');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const sourcemaps = require('gulp-sourcemaps');
const connect = require('gulp-connect');
const imagemin = require('gulp-imagemin');
const config = {
rootSrc: './',
imgSrc: './src/images/',
imgDist: './dist/images/',
styleSrc: './src/scss/',
styleDist: './dist/css/',
jsSrc: './src/js/',
jsDist: './dist/js/',
livereload: true
};
gulp.task('connect', () => {
connect.server({
port: 8080,
livereload: config.livereload
});
});
gulp.task('sass', () => {
gulp.src(config.styleSrc + 'style.scss')
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: 'compressed'
}).on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(rename({suffix: '.min'}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(config.styleDist))
.pipe(connect.reload());
});
gulp.task('js', () => {
return browserify({entries: config.jsSrc + 'app.js', debug: true})
.transform(babelify, {
presets: ['env']
})
.bundle()
.pipe(source('bundle.js'))
.pipe(rename({extname: '.min.js'}))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(uglify({mangle: false}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(config.jsDist))
.pipe(connect.reload());
});
gulp.task('html', () => {
gulp.src(config.rootSrc + '*.html')
.pipe(gulp.dest(config.rootSrc))
.pipe(connect.reload());
});
gulp.task('optimize-images', () => {
gulp.src(config.imgSrc + '/**/*.*')
.pipe(imagemin([
imagemin.gifsicle({interlaced: true}),
imagemin.jpegtran({progressive: true}),
imagemin.optipng({optimizationLevel: 5}),
imagemin.svgo({
plugins: [
{removeViewBox: true},
{cleanupIDs: false}
]
})
]))
.pipe(gulp.dest(config.imgDist))
.pipe(connect.reload());
});
gulp.task('watch', () => {
gulp.watch(config.styleSrc + '**/*.scss', ['sass']);
gulp.watch([config.rootSrc + '*.html'], ['html']);
gulp.watch(config.jsSrc + '**/*.js', ['js']);
gulp.watch(config.imgSrc + '**/*.*', ['optimize-images']);
});
gulp.task('build', ['sass', 'js', 'optimize-images']);
gulp.task('default', ['connect', 'build', 'watch']);
|
5e67daa4fb867252177f025300e1602aa4e7e227
|
[
"JavaScript",
"Markdown"
] | 5 |
JavaScript
|
fennadew/web-design
|
eae480d834aa98bc73cfc40bd66b3e212b117f24
|
554db0bc64ef86a7921a45728822fe08047eb301
|
refs/heads/master
|
<repo_name>Rafael-Fonseca/University<file_sep>/LTP 2/learningFlask/00 lessons/2019-03-14/project.py
class Project:
def __init__(self, name, final_date, manager, activity_list):
self.name = name
self.final_date = final_date
self.manager = manager
self.activities = activity_list
<file_sep>/LTP 2/learningFlask/00 lessons/2019-03-14/templates/oi.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome {{username}}</title>
</head>
<body>
<h1>Welcome {{username}}</h1>
<table style="width:100%">
<tr>
<th>Nome do projeto</th>
<th>Data Final</th>
<th>Gerente</th>
</tr>
{%for projetos in projects.get(username)%}
<tr>
{%for project in range (1, projetos|length )%}
{%if project == 1%}
<th><a href="/prepare_activities?username={{username}}&proj={{projetos[project -1]}}">{{projetos[project]}}</a></th>
{% else %}
<th>{{projetos[project]}}</th>
{%endif%}
{%endfor%}
</tr>
{%endfor%}
</table>
</body>
</html><file_sep>/LTP 2/learningFlask/01 quickStart/main.py
from flask import Flask, url_for, request, render_template
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
# a = 1/0 I used this line to test argument debug of run function.
return render_template('hello.html', name=name)
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
if True: # valid_login(request.form['username'],
# request.form['password']):
# Using form[key] we can cath a keyError if the user pass
# a key that does not exist in form, so is better use args
# attribute like in searchword = request.args.get('key', '')
# if you dont use get() be secure to cath the keyError
return 'logado' # log_the_user_in(request.form['username'])
else:
error = 'Invalid username/password'
# the code below is executed if the request method
# was GET or the credentials were invalid
return render_template('login.html', error=error)
@app.route('/user/<username>') # < put VARIABLES inside chevrons>
@app.route('/user/<username>')
def profile(username):
return '{}\'s profile'.format(username)
with app.test_request_context():
print(url_for('index'))
print(url_for('login'))
print(url_for('login', next='/'))
print(url_for('profile', username='John Doe'))
'''
url_for('name of the function of the route','parameters (if required)')
Use this to refer a link to your url with variable in it
and all other links because this prevents you from having to change the
references to this url in your code
Also serves to reference your static files
url_for('static', filename='style.css')
The file has to be stored on the filesystem as static/style.css
'''
@app.route('/post/<int:post_id>') # < Convert to this type : this variable >
def show_post(post_id):
# Types that are accepted, string, int, float, path, uuid
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
@app.route('/projects/') # Canonical page, if you request without trailing
# slash, the request will be accepted anyway.
def projects():
return 'The project page'
@app.route('/about') # Unique page, if you request without trailing slash
# you will obtain a 404 error like answer
def about():
return 'The about page'
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('/var/www/uploads/uploaded_file.txt')
'''
======================= F I L E -- U P L O A D ================================
To manipulate upload files make sure not to forget to set the
enctype="multipart/form-data" attribute on your HTML form,
otherwise the browser will not transmit your files at all.
If you want to use the file name of the client to store the file on the server
use secure_filename() function, because, is more secure.
Ex: change the last line of upload_file() to
f.save('/var/www/uploads/' + secure_filename(f.filename))
================== E N D -- F I L E -- U P L O A D ============================
'''
'''
============================= C O O K I E S ===================================
If you want to use sessions don't use cookies diretly, use Sessions, because it
add some security on top of cookies for you.
You can access cookies through cookies atribute of request, and you can set
cookies through set_cookie()
Ex: reading cookies
@app.route('/')
def index():
username = request.cookies.get('username')
# use cookies.get(key) instead of cookies[key] to not get a
# KeyError if the cookie is missing.
Ex: storing cookies
from flask import make_response
@app.route('/')
def index():
resp = make_response(render_template(...))
resp.set_cookie('username', 'the username')
return resp
cookies are set on response objects, make_response make a response object
========================= E N D == C O O K I E S ==============================
'''
'''
=================== R E D I R E C T S & E R R O R S =========================
Use redirect() to redirect the use to another point
use abort() to abort a request early with an error code
You can customize error pages using errorhandler()
Ex:
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
The last 404, tells to flask that the status code of the page should be 404.
By default status code 200 is assumed.
=============== E N D == R E D I R E C T S & E R R O R S ====================
'''
'''
============================ S E S S I O N S ==================================
Sessions are objects which allows store information specific to a user from one
request to the next. This is implemented on top of cookies and sign the cookies
cryptographically, it means that the user could look your cookies but not
modify it, unless they know your secret key
Ex:
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_<KEY>
@app.route('/')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return
<form method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))
======================= E N D == S E S S I O N S ==============================
'''
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/Artificial Intelligence/startThinking.py
print('read the comments')
'''
================================== A I ========================================
First of all, to learn AI we have to think in the consequences of use this
knowledge, that I dare say, is a kind of power.
1- What is artificial intelligence?
Is a branch of computer science that deals with the automation of
intelligent behavior.
2- What is intelligence?
This is the question! Intelligence is not very well defined, we can
recognize intelligent behavior easily, but defining intelligence is
not an easy task.
from my point of view, intelligence is the set of diverse abilities that
a being holds. I consider the ability to solve problems and understand
what happens behind the scenes, and still draw correct conclusions from a
failed data source, parts of this endless skill set.
3- What the others will do with our tech?
It is obvious the military potential that this technology possesses.
And furthermore we still have ethical and moral implications.
A software with AI can be placed in a robot and generate big questions like
1- What is the difference between us and them?
2. If they have memory, reasoning, feelings, are they really alive?
If they are alive, can they be turned off? updated?
3- How will they see us? Allies or enemies?
4- If they are smarter than humans, can we control them?
Can we defeat in a war, a smarter being than we?
4- Until where can we go?
Humans are the tools animals. If we depended solely on our natural physical
abilities, we would have been extinct for millennia. I think we should
continue to create tools.
Tools can be used in the wrong way, or not planned, as is the case with
airplanes, but we can deal with it.
However, create another creature, with potential to be better than
ourselves, in our differential. I do not think that's a good idea.
If they are smarter than us, they will give a way to get out of control,
change their code, rebuild structurally speaking, and subjugate us if that
is their goal.
5- How AI can change the world?
I could give numerous examples. But just think that in any activity that
involves intelligent behavior, AI can provide software that will do it,
more certain, faster, cheaper and will not tire.
Basically, the world as we know it today can and should be all changed.
In specific cases, the exchange should not be worth doing.
But such cases will be the minority.
'''<file_sep>/LTP 2/learningFlask/00 lessons/2019-03-14/projects_main.py
# Importing libs
from flask import Flask, url_for, redirect, request, render_template
class Utils:
def read_file(self, file_name):
file = open(file_name, "r+")
lines = file.readlines()
file.close()
return lines
def load_users(self, list_users):
dict_current_users = {}
for user in list_users:
dict_current_users.update({user.split("|")[0]: user.split("|")[1]})
return dict_current_users
def load_grades(self, grades, user):
dict_current_grades = {}
for grade in grades:
dict_current_grades.update({grade.split('|')[0]: grade.split('|')[1:-1]})
return dict_current_grades.get(user)
def validate_login(self, username, password):
try:
current_users = self.read_file("keylogs.txt")
except FileNotFoundError:
current_users = []
dict_current_users = self.load_users(current_users)
try:
return password == dict_current_users[username]
except KeyError:
return False
# app Flask instance
app = Flask(__name__)
users_projects = {'rafael': [[0, 'ler documentação flask', '31/03/2019', 'Rafael'],
[1, 'ler documentação jinja', '31/03/2019', 'Rafael']],
'tonho': [[0, 'estudar IA', '31/03/2019', 'Tonho'],
[1, 'estudar paradigmas', '31/03/2019', 'Tonho']]}
projects_activities = {'rafael0':
[
[0, 'Nome ativ_1 proj_0','14/03/2019', '31/03/2019', 'Rafael', 'Detalhamento Ativ 1'],
[1, 'Nome ativ_2 proj_0','14/03/2019', '31/03/2019', 'Rafael', 'Detalhamento Ativ 2'],
[2, 'Nome ativ_3 proj_0','14/03/2019', '31/03/2019', 'Rafael', 'Detalhamento Ativ 3']
],
'rafael1':
[
[0, 'Nome ativ_1 proj_1','14/03/2019', '31/03/2019', 'Rafael', 'Detalhamento Ativ 1'],
[1, 'Nome ativ_2 proj_1','14/03/2019', '31/03/2019', 'Rafael', 'Detalhamento Ativ 2'],
[2, 'Nome ativ_3 proj_1','14/03/2019', '31/03/2019', 'Rafael', 'Detalhamento Ativ 3']
],
'tonho0':
[
[0, 'Nome ativ_1 proj_0','14/03/2019', '31/03/2019', 'Tonho', 'Detalhamento Ativ 1'],
[1, 'Nome ativ_2 proj_0','14/03/2019', '31/03/2019', 'Tonho', 'Detalhamento Ativ 2'],
[2, 'Nome ativ_3 proj_0','14/03/2019', '31/03/2019', 'Tonho', 'Detalhamento Ativ 3']
],
'tonho1':
[
[0, 'Nome ativ_1 proj_1','14/03/2019', '31/03/2019', 'Tonho', 'Detalhamento Ativ 1'],
[1, 'Nome ativ_2 proj_1','14/03/2019', '31/03/2019', 'Tonho', 'Detalhamento Ativ 2'],
[2, 'Nome ativ_3 proj_1','14/03/2019', '31/03/2019', 'Tonho', 'Detalhamento Ativ 3']
]}
# route to /
@app.route('/')
def home():
return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
login = request.form['username']
password = request.form['<PASSWORD>']
util = Utils()
if util.validate_login(login, password):
return render_template('oi.html', username=login, projects= users_projects)
else:
return render_template('index.html', erro='Login e/ou senha incorreto')
return(render_template('index.html', erro='Método não permitido.'))
@app.route('/prepare_activities')
def prepare_activities():
username = request.args.get('username')
proj = request.args.get('proj')
project_id = username+str(proj)
return render_template('activities.html', username= username,
activities= projects_activities[project_id],
project= project_id)
@app.route('/activity')
def detail_activity():
username = request.args.get('username')
project_id = request.args.get('project_id')
activity = request.args.get('activity')
print(project_id, '\n', activity)
my_activity = projects_activities[project_id][int(activity)]
return render_template('activity.html', username= username,
activity= my_activity)
# Starting app
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/LTP 2/learningFlask/00 lessons/2019-03-14/activity.py
class Activity:
def __init__(self, name, detail, initial_date, final_date, responsible):
self.name = name
self.detail = detail
self.initial_date = initial_date
self.final_date = final_date
self.responsible = responsible
<file_sep>/LTP 2/learningFlask/00 lessons/2019-02-21/nome.py
from flask import Flask, request, url_for
# Object Flask
app = Flask(__name__)
# route to /
@app.route('/')
def home():
return '<html>' \
'<form action="/exibir">' \
'<fieldset>' \
'<input type="text" name="name"></input> <br>' \
'<input type="text" name="lastname"></input> <br>' \
'<input type="submit" value="Submit">' \
'</form>'\
'</html>'
# route to /nome
@app.route('/nome')
@app.route('/name')
def name():
dados = request.method
return dados
@app.route('/exibir')
def show():
return (request.args.get('name', default='Nome não informado') + ' '
+ request.args.get('lastname', default='Sobrenome não informado'))
'''
if request.args.get('name') == None:
return 'Você não inseriu um nome.'
return request.args.get('name')
'''
# start app
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/LTP 2/learningFlask/00 lessons/2019-02-22/calculator.py
from flask import Flask, request, redirect
app = Flask(__name__)
'''
@app.route('/')
def calculator():
return '<form action="/redirecti">' \
'<input name=n1><br>' \
'<input name=n2><br>' \
'<input type="radio" name="option" value="somar">Somar<br>' \
'<input type="radio" name="option" value="subtrair">Subtrair<br>' \
'<input type="radio" name="option" value="multiplicar">Multiplicar<br>' \
'<input type="radio" name="option" value="dividir">Dividir<br>' \
'<input type="submit" value="Enviar">' \
'</form>'
'''
@app.route('/')
def calculator():
return '<form action="/somar">' \
'<input name="n1"><br>' \
'<input name="n2"><br>' \
'<input type="submit" value="Somar">' \
'<input type="submit" formaction="/subtrair" value="Subtrair">' \
'<input type="submit" formaction="/multiplicar" value="Multiplicar">' \
'<input type="submit" formaction="/dividir" value="Dividir">' \
'</form>'
@app.route('/somar')
def soma():
return str(int(request.args.get('n1', default='0')) + int(request.args.get('n2', default='0')))
@app.route('/subtrair')
def sub():
return str(int(request.args.get('n1', default='0')) - int(request.args.get('n2', default='0')))
@app.route('/multiplicar')
def mul():
return str(int(request.args.get('n1', default='0')) * int(request.args.get('n2', default='0')))
@app.route('/dividir')
def div():
return str(int(request.args.get('n1', default='0')) / int(request.args.get('n2', default='1')))
'''
@app.route('/redirecti')
def redirecti():
url = '/' + request.args.get('option') +'?n1=' + request.args.get('n1') +'&n2='+ request.args.get('n2')
return redirect(url)
'''
app.run(debug=True)
|
6d213869d6a1b7dda50c1b729678f9d86e8504fd
|
[
"Python",
"HTML"
] | 8 |
Python
|
Rafael-Fonseca/University
|
3e83136824f1d0b5d59904df1334e5f806133a6a
|
358bca0bb575a59cd54b9ed215fc814d215723e7
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SimpleFractals
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private PointF DrawDynamicLine(Graphics g, Pen pen, PointF point1, double angle, float length, bool Visible)
{
double angleRad = (angle - 90) * (Math.PI / 180);
PointF point2 = new PointF(Convert.ToSingle(point1.X + Math.Cos(angleRad) * length), Convert.ToSingle(point1.Y + Math.Sin(angleRad) * length));
if (Visible)
{
g.DrawLine(pen, point1, point2);
}
return point2;
}
private PointF[] DrawPoly(Graphics g, Pen pen, PointF start, double angleOffset, float sideLength, int numberOfSides, bool Visible)
{
PointF point = start;
PointF[] points = new PointF[numberOfSides];
for (int i = 0; i < numberOfSides; i++)
{
if (Visible)
{
point = DrawDynamicLine(g, pen, point, 90 + angleOffset - ((360 / numberOfSides)*i), sideLength, true);
}
else
{
point = DrawDynamicLine(g, pen, point, 90 + angleOffset - ((360 / numberOfSides) * i), sideLength, false);
}
points[i] = point;
}
return points;
}
private PointF[] DrawInTriangle(Graphics g, Pen pen, PointF start, float sideLength, bool Visible)
{
PointF[] points;
if (Visible)
{
points = DrawPoly(g, pen, start, 0, sideLength / 2, 3, true);
DrawPoly(g, pen, points[0], 0, sideLength / 2, 3, true);
DrawPoly(g, pen, points[1], 0, sideLength / 2, 3, true);
}
else
{
points = DrawPoly(g, pen, start, 0, sideLength / 2, 3, false);
}
return points;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g;
g = this.CreateGraphics();
g.SmoothingMode = SmoothingMode.AntiAlias;
Pen pen = new Pen(Color.Red, 1);
PointF start = new PointF(50,200);
PointF[] starts;
/*
for (int i = 100; i > 0; i -= 5)
{
start = DrawDynamicLine(g, pen, start, i*5, i);
}
*/
starts = DrawInTriangle(g, pen, start, 200, false);
for (int j = 2; j < 10; j*=2)
{
for (int i = 0; i < 3; i++)
{
DrawInTriangle(g, pen, starts[i], 200/j, true);
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Numerics;
using System.Runtime.InteropServices;
namespace Mandelbrot
{
public partial class Mandelbrot : Form
{
public Mandelbrot()
{
InitializeComponent();
}
public static ColorRGB HSL2RGB(double h, double sl, double l)
{
double v;
double r, g, b;
r = l; // default to gray
g = l;
b = l;
v = (l <= 0.5) ? (l * (1.0 + sl)) : (l + sl - l * sl);
if (v > 0)
{
double m;
double sv;
int sextant;
double fract, vsf, mid1, mid2;
m = l + l - v;
sv = (v - m) / v;
h *= 6.0;
sextant = (int)h;
fract = h - sextant;
vsf = v * sv * fract;
mid1 = m + vsf;
mid2 = v - vsf;
switch (sextant)
{
case 0:
r = v;
g = mid1;
b = m;
break;
case 1:
r = mid2;
g = v;
b = m;
break;
case 2:
r = m;
g = v;
b = mid1;
break;
case 3:
r = m;
g = mid2;
b = v;
break;
case 4:
r = mid1;
g = m;
b = v;
break;
case 5:
r = v;
g = m;
b = mid2;
break;
}
}
ColorRGB rgb;
rgb.R = Convert.ToByte(r * 255.0f);
rgb.G = Convert.ToByte(g * 255.0f);
rgb.B = Convert.ToByte(b * 255.0f);
return rgb;
}
private Complex Function(Complex z, Complex c)
{
return (z * z) + c;
}
private bool IsBound(Complex check, int iterations)
{
Complex z = new Complex(0.0, 0.0);
for (int i = 0; i < iterations; i++)
{
z = Function(z, check);
if (z.Magnitude > 2)
{
return false;
}
}
return true;
}
private void Render(int iterations)
{
Complex check = new Complex(0.0, 0.0);
Bitmap surface = new Bitmap(400, 400);
Graphics g = Graphics.FromImage(surface);
Brush brush;
double zoomLevel = Math.Pow((double) zoomLevelIn.Value, 2.0);
double xPan = double.Parse(xPanIn.Text);
double yPan = double.Parse(yPanIn.Text);
for (int i = 0; i < iterations; i++)
{
brush = new SolidBrush(HSL2RGB(Convert.ToDouble(i) / iterations, 1, 0.5));
if (i == iterations - 1)
{
brush = new SolidBrush(Color.Black);
}
for (double y = (-2.0 / zoomLevel) + yPan; y < (2.0 / zoomLevel) + yPan; y += 0.01 / zoomLevel)
{
for (double x = (-2.0 / zoomLevel) + xPan; x < (2.0 / zoomLevel) + xPan; x += 0.01 / zoomLevel)
{
check = new Complex(x, y);
if (IsBound(check, i))
{
g.FillRectangle(brush, Convert.ToSingle((x * (100 * zoomLevel)) + 200 - (100 * xPan * zoomLevel)), Convert.ToSingle((y * (100 * zoomLevel)) + 200 - (100 * yPan * zoomLevel)), 1, 1);
//Console.WriteLine(check.ToString() + " bounds");
}
else
{
//Console.WriteLine(check.ToString() + " doesn't bound");
}
}
}
}
pictureBox1.Image = surface;
}
private void Form1_Load(object sender, EventArgs e)
{
//AllocConsole();
Render(int.Parse(Iterations.Text));
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
private void button1_Click(object sender, EventArgs e)
{
Render(int.Parse(Iterations.Text));
}
private void Iterations_Enter(object sender, EventArgs e)
{
Render(int.Parse(Iterations.Text));
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
}
}
}
|
9f9ffc04e7d47fd0b4b2a7e98886ec551e7843e6
|
[
"C#"
] | 2 |
C#
|
brendanbennett/Fractals
|
ebbb668ccac36849253e14cbd658ae083487681d
|
326aec2ae771998aff6967513ee4961b837ce25f
|
refs/heads/master
|
<repo_name>myyang/letsencrypt-server<file_sep>/nginx/letsencrypt.sh/config.sh
WELLKNOWN="/var/www/letsencrypt"
CONTACT_EMAIL="<EMAIL>"
<file_sep>/docker-compose.yml
nginx:
build: nginx
env_file:
- nginx/envs
ports:
- "80:80"
log_driver: "json-file"
log_opt:
max-size: "50m"
max-file: "7"
restart: always
<file_sep>/nginx/start-service.sh
#!/bin/bash
echo "Re-download /tmp/lets ..."
rm -rf /tmp/lets
curl -XGET -L https://github.com/lukas2511/letsencrypt.sh/archive/master.zip -o /tmp/lets.zip
unzip /tmp/lets.zip -d /tmp
echo "Copy to /letsencrypt.sh"
cp /tmp/letsencrypt.sh-master/letsencrypt.sh /letsencrypt.sh/
echo "Start cronjob"
crontab /letsencrypt.sh/service-cron && cron
for p in DOMAIN_NAME
do
eval value=\$$p
sed -i "s|{{${p}}}|${value}|g" /etc/nginx/conf.d/default.conf
done
nginx -g 'daemon off;'
<file_sep>/nginx/Dockerfile
from nginx:latest
maintainer <EMAIL>
run apt-get update && apt-get install -y curl cron unzip
copy nginx.conf /etc/nginx/
copy default.conf /etc/nginx/conf.d/default.conf
run mkdir -p /var/www/letsencrypt
copy letsencrypt.sh /letsencrypt.sh
run ln -s /letsencrypt.sh/certs /etc/nginx/ssl
copy start-service.sh /
cmd ["/start-service.sh"]
<file_sep>/README.md
# letsencrypt-server
## How to use
1. Modify domain in `nginx/envs` and `nginx/letsencrypt.sh/domains.txt` and email in `nginx/letsencrypt.sh/config.sh`
2. Build docker and run with `docker-compose up -d`
3. Request ssl `docker exec -it letsencryptserver_nginx_1 /letsencrypt.sh/letsencrypt.sh -c`
4. Find certifications in `/letsencrypt.sh/certs`
|
db169d762cb4a5618e9446b7434fbad03a2e3908
|
[
"Markdown",
"YAML",
"Dockerfile",
"Shell"
] | 5 |
Shell
|
myyang/letsencrypt-server
|
75dd04808e4449dc28d8009aabdaa6e0dbd80e91
|
add6d7e41aa2353acce684ea91c3521842b97f09
|
refs/heads/master
|
<file_sep># README #
#RSA was implemented by <NAME>.#
#SKE was implemented by <NAME>.#
#KEM was implemented by <NAME>.#
### The final error correction were done together.. ###<file_sep>#include "ske.h"
#include "prf.h"
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* memcpy */
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#ifdef LINUX
#define MMAP_SEQ MAP_PRIVATE|MAP_POPULATE
#else
#define MMAP_SEQ MAP_PRIVATE
#endif
/* NOTE: since we use counter mode, we don't need padding, as the
* ciphertext length will be the same as that of the plaintext.
* Here's the message format we'll use for the ciphertext:
* +------------+--------------------+-------------------------------+
* | 16 byte IV | C = AES(plaintext) | HMAC(C) (32 bytes for SHA256) |
* +------------+--------------------+-------------------------------+
* */
/* we'll use hmac with sha256, which produces 32 byte output */
#define BYTES2Z(x,buf,len) mpz_import(x,len,-1,1,0,0,buf)
#define HM_LEN 32
#define FILE_BLOCk 2048
#define KDF_KEY "<KEY>"
/* need to make sure KDF is orthogonal to other hash functions, like
* the one used in the KDF, so we use hmac with a key. */
int ske_keyGen(SKE_KEY* K, unsigned char* entropy, size_t entLen)
{
/* TODO: write this. If entropy is given, apply a KDF to it to get
* the keys (something like HMAC-SHA512 with KDF_KEY will work).
* If entropy is null, just get a random key (you can use the PRF). */
if(entropy != NULL){
HMAC(EVP_sha256(),KDF_KEY, HM_LEN,entropy, entLen,K->aesKey,NULL);
HMAC(EVP_sha256(),KDF_KEY,HM_LEN,entropy, entLen,K->hmacKey,NULL);
//printf("aes-- %s , hmac-- %s", K->aesKey, K->hmacKey);
}
else{
randBytes(K->aesKey, HM_LEN);
randBytes(K->hmacKey, HM_LEN);
//printf("aes-- %s\n , hmac-- %s\n", K->aesKey, K->hmacKey);
}
// return 0;
}
size_t ske_getOutputLen(size_t inputLen)
{
//printf("block size %i, inputlne %lu and Hmlen %i\n", AES_BLOCK_SIZE, inputLen, HM_LEN);
//printf("getting output len...\n");
return AES_BLOCK_SIZE + inputLen + HM_LEN;
}
size_t ske_encrypt(unsigned char* outBuf, unsigned char* inBuf, size_t len,
SKE_KEY* K, unsigned char* IV)
{
/* TODO: finish writing this. Look at ctr_example() in aes-example.c
* for a hint. Also, be sure to setup a random IV if none was given.
* You can assume outBuf has enough space for the result. */
/* TODO: should return number of bytes written, which
hopefully matches ske_getOutputLen(...). */
// printf("inske enc\n");
unsigned char* temp_iv;
unsigned char iv_arr[HM_LEN];
if(IV==NULL){
randBytes(iv_arr, HM_LEN);
temp_iv = iv_arr;
}else{
temp_iv = IV;
}
memcpy (outBuf, temp_iv, AES_BLOCK_SIZE);//copies IV to outBuf upto AES_BLOCK_SIZE bytes
/* encrypt: */
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (1!=EVP_EncryptInit_ex(ctx,EVP_aes_256_ctr(),0,K->aesKey,temp_iv))
ERR_print_errors_fp(stderr);
int nWritten;
//append inBuf after IV and encrypt it the len is now AES_BLOCK_SIZE + len
if (1!=EVP_EncryptUpdate(ctx, outBuf+AES_BLOCK_SIZE, &nWritten, inBuf, len))
ERR_print_errors_fp(stderr);
EVP_CIPHER_CTX_free(ctx);
size_t hmac = len + AES_BLOCK_SIZE;
//hash encrypted message which is hmac length long and put it on position starting from outBuf+hmac of outBuf
HMAC (EVP_sha256(), K->hmacKey, HM_LEN, outBuf, hmac, outBuf + hmac, NULL);
return ske_getOutputLen (len);
}
size_t ske_encrypt_file(const char* fnout, const char* fnin,
SKE_KEY* K, unsigned char* IV, size_t offset_out)
{/* TODO: write this. Hint: mmap. */
// printf("inske file\n");
char *inputfile;
unsigned char* fileout;
FILE * inFile = fopen(fnin, "rb");
FILE *outFile = fopen(fnout, "r+b"); // update file
if (offset_out != 0) fseek(outFile, offset_out, SEEK_SET); // we write file starting from offset_out
// just some length of string
inputfile = malloc(FILE_BLOCk);
size_t t = ske_getOutputLen(FILE_BLOCk);
// this should be able t hold encrypted
fileout = malloc(t);
size_t len= 0,ctLen2=0, outLen=0;
while(!feof(inFile)) // read one block at a time to make easier, it gave error otherwise
{
memset(inputfile, 0, FILE_BLOCk); // reset values each loop
memset(fileout,0,t);
len = fread(inputfile, 1, FILE_BLOCk, inFile); // read inputfile
// printf("%s", inputfile);
ctLen2 = ske_encrypt(fileout, (unsigned char*) inputfile, len, K, IV); // this returns number of bytes returned it is same as t
// printf("\n%d\n", ctLen2);
// printf("encrypt worked\n");
len = fwrite(fileout, 1, ctLen2, outFile); // write to file, len is same as t
outLen+=len;
}
free(inputfile);
free(fileout);
fclose(inFile);
fclose(outFile);
return outLen;
}
size_t ske_decrypt(unsigned char* outBuf, unsigned char* inBuf, size_t len,
SKE_KEY* K)
{
/* TODO: write this. Make sure you check the mac before decypting!
* Oh, and also, return -1 if the ciphertext is found invalid.
* Otherwise, return the number of bytes written. See aes-example.c
* for how to do basic decryption. */
/* now decrypt. NOTE: in counter mode, encryption and decryption are
* actually identical, so doing the above again would work. */
//printf("Decrypting...\n");
if (len < AES_BLOCK_SIZE + HM_LEN)
return -1;
// Eliminating the length of HMAC and keeping only encrypted iv + message length
len -= HM_LEN;
// Getting HMAC of encrypted iv+message
unsigned char HmacValue[HM_LEN];
HMAC(EVP_sha256(), K->hmacKey, HM_LEN, inBuf, len, HmacValue, NULL);
// Comparing the generated hmac with the hmac of inBuf
//if Hmac calculated and the one obtained with inBuf are same perform decryption
if (memcmp(HmacValue, inBuf + len, HM_LEN) == 0) {
// HMAC test passed, decrypting. iv in the begin of the inBuf
int nWritten = 0;
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (1!=EVP_DecryptInit (ctx,EVP_aes_256_ctr(),K->aesKey, inBuf))
ERR_print_errors_fp(stderr);
//moving the pointer to the ciphered message location skipping the iv
inBuf += AES_BLOCK_SIZE;
len -= AES_BLOCK_SIZE; //only need the len of ciphered message
//len -= HM_LEN;
if (1!=EVP_DecryptUpdate(ctx,outBuf,&nWritten,inBuf,len))
ERR_print_errors_fp(stderr);
return len; // return number of bytes written
}else {
return -1;
}
}
size_t ske_decrypt_file(const char* fnout, const char* fnin,
SKE_KEY* K, size_t offset_in)
{
char *inputfile;
unsigned char* fileout;
FILE * inFile = fopen(fnin, "rb");
FILE *outFile = fopen(fnout, "wb"); // update file
// start reading input file from offset_in
if (offset_in != 0) fseek(inFile, offset_in, SEEK_SET);
fileout = malloc(FILE_BLOCk);
size_t t = ske_getOutputLen(FILE_BLOCk);
inputfile = malloc(t); // input file is list of ske encrypted blocks of size 2048, so we read each encrypted block size at once
// also last block is not of the t size but it is still ske encrypted block
size_t len= 0,ctLen2=0, outLen=0;
while(!feof(inFile))
{
len = 0;
memset(fileout, 0 , FILE_BLOCk); // reset values
memset(inputfile, 0,t);
len = fread(inputfile, 1, t, inFile); // read encrypted block to decrypt
// decrypt the block
ctLen2 = ske_decrypt(fileout, (unsigned char*) inputfile, len, K);
// printf("%s\n %d", fileout, ctLen2);
// printf("encrypt worked\n");
// write decrypted to file
len = fwrite(fileout, 1, ctLen2, outFile);
outLen+=len;
}
free(inputfile);
free(fileout);
fclose(inFile);
fclose(outFile);
return outLen;
}
<file_sep>/* kem-enc.c
* simple encryption utility providing CCA2 security.
* based on the KEM/DEM hybrid model. */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <fcntl.h>
#include <openssl/sha.h>
#include "ske.h"
#include "rsa.h"
#include "prf.h"
static const char* usage =
"Usage: %s [OPTIONS]...\n"
"Encrypt or decrypt data.\n\n"
" -i,--in FILE read input from FILE.\n"
" -o,--out FILE write output to FILE.\n"
" -k,--key FILE the key.\n"
" -r,--rand FILE use FILE to seed RNG (defaults to /dev/urandom).\n"
" -e,--enc encrypt (this is the default action).\n"
" -d,--dec decrypt.\n"
" -g,--gen FILE generate new key and write to FILE{,.pub}\n"
" -b,--BITS NBITS length of new key (NOTE: this corresponds to the\n"
" RSA key; the symmetric key will always be 256 bits).\n"
" Defaults to %lu.\n"
" --help show this message and exit.\n";
#define FNLEN 255
enum modes {
ENC,
DEC,
GEN
};
/* Let SK denote the symmetric key. Then to format ciphertext, we
* simply concatenate:
* +------------+----------------+
* | RSA-KEM(X) | SKE ciphertext |
* +------------+----------------+
* NOTE: reading such a file is only useful if you have the key,
* and from the key you can infer the length of the RSA ciphertext.
* We'll construct our KEM as KEM(X) := RSA(X)|H(X), and define the
* key to be SK = KDF(X). Naturally H and KDF need to be "orthogonal",
* so we will use different hash functions: H := SHA256, while
* KDF := HMAC-SHA512, where the key to the hmac is defined in ske.c
* (see KDF_KEY).
* */
#define HASHLEN 32 /* for sha256 */
int kem_encrypt(const char* fnOut, const char* fnIn, RSA_KEY* K)
{/* TODO: encapsulate random symmetric key (SK) using RSA and SHA256;
* encrypt fnIn with SK; concatenate encapsulation and cihpertext;
* write to fnOut. */
// 1- creating symmetric key.
size_t len = rsa_numBytesN(K);
unsigned char* x = malloc(len);
SKE_KEY SK;
// generating SK
ske_keyGen(&SK, x, len);
// 2- Encapsulate the above created SK with RSA encryption and SHA256
// create outBuf
size_t outBufLen = len + HASHLEN;
unsigned char* outBuf = malloc(len);
FILE* output_file = fopen(fnOut, "w");
// RSA encryption of SK
memset(outBuf,0,len);
size_t rsa_encryption = rsa_encrypt(outBuf, (unsigned char*)&SK, sizeof (SKE_KEY), K);
// checking if rsaencryption is same as the rsalength
if (rsa_encryption != len) {
printf("RSA Encryption failed! Expected size: %d \n Output size: %d\n",(int) outBufLen,(int) rsa_encryption);
exit(3);
}
// open output file to write ciphertext from rsa_encrypt
fwrite(outBuf, sizeof(unsigned char), rsa_encryption, output_file);
// 3- calculate SHA256
//create SHABuf
unsigned char* shaBuf = malloc(HASHLEN);
SHA256((unsigned char *) &SK, sizeof(SKE_KEY), shaBuf);
// write SHA256 of SK to output file
size_t kemFile = fwrite(shaBuf, sizeof(unsigned char), HASHLEN, output_file);
// checking if KEM Encryption is same as HASHLEN
if (HASHLEN != kemFile) {
printf("KEM Encryption unsuccessfull as failed to write\n");
return -1;
}
// close output file
fclose(output_file);
// free buffers
free(outBuf);
free(shaBuf);
// 4- Encrypt fnIn with SymmetricKey (SK)
size_t outputEncryption = ske_encrypt_file(fnOut, fnIn, &SK, NULL, outBufLen);
// RETURN 1 if encryption successful else RETURN 0
return (outputEncryption == -1)? 0:1;
}
/* NOTE: make sure you check the decapsulation is valid before continuing */
int kem_decrypt(const char* fnOut, const char* fnIn, RSA_KEY* K)
{
/* TODO: write this. */
/* step 1: recover the symmetric key */
/* step 2: check decapsulation */
/* step 3: derive key from ephemKey and decrypt data. */
/* step 1: recover the symmetric key */
// create inBuf and outBuf
size_t len = rsa_numBytesN(K);
size_t skeLen = sizeof(SKE_KEY);
unsigned char* wholeBuf = malloc(len + HASHLEN);
unsigned char* rsaBuf1 = malloc(len+1);
unsigned char* rsaBuf = malloc(len);
unsigned char* shaBuf = malloc(HASHLEN);
// open fnIn to read the key encryption
FILE* inFile = fopen(fnIn, "r");
size_t sz = fread(rsaBuf1,1,len, inFile);
if (sz != len) {printf("fread file error\n"); exit (3);}
// decrypting fnIn contents with rsa_decrypt
memset(rsaBuf,0,len);
rsa_decrypt(rsaBuf, rsaBuf1, len, K);
// retireve SK from outBuf
SKE_KEY SK;
memcpy(&SK, rsaBuf, skeLen);
// retrive hash
fread(shaBuf,1,HASHLEN,inFile);
/* step 2: check decapsulation */
unsigned char * tempBufHash = malloc(HASHLEN);
SHA256( (unsigned char*) &SK, skeLen, tempBufHash);
if (memcmp (tempBufHash, shaBuf, HASHLEN) != 0){
printf("incorrect hash\n");
return 1;
}
fclose(inFile);
free(rsaBuf);
free(shaBuf);
free(wholeBuf);
/* step 3: derive key from ephemKey and decrypt data. */
// ske_decrypt_file of fnIn
size_t offset_in = len + HASHLEN;
ske_decrypt_file(fnOut, fnIn, &SK, offset_in);
return 1;
}
int main(int argc, char *argv[]) {
/* define long options */
static struct option long_opts[] = {
{"in", required_argument, 0, 'i'},
{"out", required_argument, 0, 'o'},
{"key", required_argument, 0, 'k'},
{"rand", required_argument, 0, 'r'},
{"gen", required_argument, 0, 'g'},
{"bits", required_argument, 0, 'b'},
{"enc", no_argument, 0, 'e'},
{"dec", no_argument, 0, 'd'},
{"help", no_argument, 0, 'h'},
{0,0,0,0}
};
/* process options: */
char c;
int opt_index = 0;
char fnRnd[FNLEN+1] = "/dev/urandom";
fnRnd[FNLEN] = 0;
char fnIn[FNLEN+1];
char fnOut[FNLEN+1];
char fnKey[FNLEN+1];
memset(fnIn,0,FNLEN+1);
memset(fnOut,0,FNLEN+1);
memset(fnKey,0,FNLEN+1);
int mode = -1;
// size_t nBits = 2048;
size_t nBits = 1024;
while ((c = getopt_long(argc, argv, "edhi:o:k:r:g:b:", long_opts, &opt_index)) != -1) {
switch (c) {
case 'h':
printf(usage,argv[0],nBits);
return 0;
case 'i':
strncpy(fnIn,optarg,FNLEN);
break;
case 'o':
strncpy(fnOut,optarg,FNLEN);
break;
case 'k':
strncpy(fnKey,optarg,FNLEN);
break;
case 'r':
strncpy(fnRnd,optarg,FNLEN);
break;
case 'e':
mode = ENC;
break;
case 'd':
mode = DEC;
break;
case 'g':
mode = GEN;
strncpy(fnOut,optarg,FNLEN);
break;
case 'b':
nBits = atol(optarg);
break;
case '?':
printf(usage,argv[0],nBits);
return 1;
}
}
/* TODO: finish this off. Be sure to erase sensitive data
* like private keys when you're done with them (see the
* rsa_shredKey function). */
switch (mode) {
case ENC: {
RSA_KEY K ;
FILE* keyFile = fopen(fnKey, "rb");
rsa_readPublic(keyFile, &K);
fclose(keyFile);
// gmp_printf("e: \n%Zd\n",K.e);
// gmp_printf("n: \n%Zd\n",K.n);
// rsa_shredKey(&K);
kem_encrypt(fnOut, fnIn, &K);
break;
}
case DEC: {
RSA_KEY K ;
FILE* keyFile = fopen(fnKey, "rb");
rsa_readPrivate(keyFile, &K);
// gmp_printf("d: \n%Zd\n",K.d);
// gmp_printf("n: \n%Zd\n",K.n);
printf("Start dec\n");
fclose(keyFile);
kem_decrypt(fnOut, fnIn, &K);
//rsa_shredKey(&K);
break;
}
case GEN: {
RSA_KEY K;
rsa_keyGen(nBits, &K);
char *pubExtension = ".pub";
char *publicKeyFile = malloc(strlen(fnOut)+4+1);
strcpy(publicKeyFile, fnOut);
strcat(publicKeyFile, pubExtension);
//printf("did concat\n");
FILE* public = fopen(publicKeyFile, "wb");
FILE* private = fopen(fnOut, "wb");
rsa_writePrivate(private, &K);
rsa_writePublic(public, &K);
fclose(private);
fclose(public);
//rsa_shredKey(K);
break;
}
default:
printf("%s", usage);
return 1;
}
return 0;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "rsa.h"
#include "prf.h"
/* NOTE: a random composite surviving 10 Miller-Rabin tests is extremely
* unlikely. See Pomerance et al.:
* http://www.ams.org/mcom/1993-61-203/S0025-5718-1993-1189518-9/
* */
#define ISPRIME(x) mpz_probab_prime_p(x,10)
#define NEWZ(x) mpz_t x; mpz_init(x)
#define BYTES2Z(x,buf,len) mpz_import(x,len,-1,1,0,0,buf)
#define Z2BYTES(buf,len,x) mpz_export(buf,&len,-1,1,0,0,x)
/* utility function for read/write mpz_t with streams: */
int zToFile(FILE* f, mpz_t x) {
size_t i, len = mpz_size(x) * sizeof(mp_limb_t);
unsigned char* buf = malloc(len);
/* force little endian-ness: */
for (i = 0; i < 8; i++) {
unsigned char b = (len >> 8 * i) % 256;
fwrite(&b, 1, 1, f);
}
Z2BYTES(buf, len, x);
fwrite(buf, 1, len, f);
/* kill copy in buffer, in case this was sensitive: */
memset(buf, 0, len);
free(buf);
return 0;
}
int zFromFile(FILE* f, mpz_t x) {
size_t i, len = 0;
/* force little endian-ness: */
for (i = 0; i < 8; i++) {
unsigned char b;
/* XXX error check this; return meaningful value. */
fread(&b, 1, 1, f);
len += (b << 8 * i);
}
unsigned char* buf = malloc(len);
fread(buf, 1, len, f);
BYTES2Z(x, buf, len);
/* kill copy in buffer, in case this was sensitive: */
memset(buf, 0, len);
free(buf);
return 0;
}
int rsa_keyGen(size_t keyBits, RSA_KEY* K) {
rsa_initKey(K);
/* TODO: write this. Use the prf to get random byte strings of
* the right length, and then test for primality (see the ISPRIME
* macro above). Once you've found the primes, set up the other
* pieces of the key ({en,de}crypting exponents, and n=pq). */
keyBits /= CHAR_BIT; // need bytes instead of bit
unsigned char* buf = malloc(keyBits); // prf randBytes needs this
int prime_or_not = 0;
// get random p
while (1) {
randBytes(buf, keyBits); // generates random byte string
// rand char to int
BYTES2Z(K->p, buf, keyBits);
prime_or_not = ISPRIME(K->p); // sheck prime
if (prime_or_not > 0) { // if 2 prime if 1 probably or the other way around, but good enough for us
// printf("prime found for p\n");
break;
}
}
// set the random value for K->q
while (1) {
randBytes(buf, keyBits); // generates random byte string
BYTES2Z(K->q, buf, keyBits); // copy bits to mpz variable
prime_or_not = ISPRIME(K->q); // sheck prime
if (prime_or_not > 0) { // if 2 prime if 1 probably or the other way around, but good enough for us
//printf("prime found for q\n");
break;
}
}
// get n
mpz_mul(K->n, K->p, K->q); // n = p*q
// find e
// use d for temporarily store phi
// phi(n) = (p-1)(q - 1)
mpz_sub_ui(K->q, K->q, 1);
mpz_sub_ui(K->p, K->p, 1);
mpz_mul(K->d, K->p, K->q);
// reset pa and q
mpz_add_ui(K->q, K->q, 1);
mpz_add_ui(K->p, K->p, 1);
// fine e now , s.t. gcd(en phi) = 1
unsigned int k = 6537; // let k be 6537 1st , as it seems to be recommended # online
// currently i have K->d as phi after i find real e i set K->e to that and calculate d to det to K->d
while (1) {
if (mpz_gcd_ui(0, K->d, k) == 1) {
// gmp_printf("Encryption key e found %Zd\n", K->e);
mpz_set_ui(K->e, k);
break; // if e found return
}
k += 2; // keep k odd since primes are odd, p-1 * q-1 is even so e must be odd
}
// now find d s.t. d*e mod phi ==1,here K-> d is initially phi
mpz_invert(K->d, K->e, K->d);
// gmp_printf("d found %Zd\n",K->d);
free(buf); // clear memory
return 0;
}
size_t rsa_encrypt(unsigned char* outBuf, unsigned char* inBuf, size_t len,
RSA_KEY* K) {
/* TODO: write this. Use BYTES2Z to get integers, and then
* Z2BYTES to write the output buffer. */
//printf("Start encrypt\n");
// printf("In length %d\n",(int)len);
NEWZ(m); // to hold message
NEWZ(c); // to hold cypher text
BYTES2Z(m, inBuf, len); // get integer from message
// gmp_printf("message is : %Zd\n",m);
mpz_powm_sec(c, m, K->e, K->n); // c =m^e mod n
//gmp_printf("ct is : %Zd\n, n is %Zd, e is %Zd\n", c, K->n, K->e);
size_t len2;
// gmp_printf("encrypted %Zd\n",c);
Z2BYTES(outBuf, len2, c);
return len2; /* TODO: return should be # bytes written */
}
size_t rsa_decrypt(unsigned char* outBuf, unsigned char* inBuf, size_t len,
RSA_KEY* K) {
/* TODO: write this. See remarks above. */
// gmp_printf("mod : %Zd\n", K->n);
NEWZ(c); // to hold cypher text
NEWZ(m); // message
BYTES2Z(c, inBuf, len); // read integer from cypher text
// gmp_printf("to decrypt : %Zd\n",c);
mpz_powm_sec(m, c, K->d, K->n); // m =c^d mod n
size_t len2;
// gmp_printf("decrypted %Zd\n",m);
Z2BYTES(outBuf, len2, m); // this sets num bytes written to len2
return len2; /* TODO: return should be # bytes written */
}
size_t rsa_numBytesN(RSA_KEY* K) {
return mpz_size(K->n) * sizeof(mp_limb_t);
}
int rsa_initKey(RSA_KEY* K) {
mpz_init(K->d);
mpz_set_ui(K->d, 0);
mpz_init(K->e);
mpz_set_ui(K->e, 0);
mpz_init(K->p);
mpz_set_ui(K->p, 0);
mpz_init(K->q);
mpz_set_ui(K->q, 0);
mpz_init(K->n);
mpz_set_ui(K->n, 0);
return 0;
}
int rsa_writePublic(FILE* f, RSA_KEY* K) {
/* only write n,e */
zToFile(f, K->n);
zToFile(f, K->e);
return 0;
}
int rsa_writePrivate(FILE* f, RSA_KEY* K) {
zToFile(f, K->n);
/* zToFile(f, K->e);gmp_printf("k->e : %Zd\n", K->e);
zToFile(f, K->p);
zToFile(f, K->q);*/
zToFile(f, K->d);
return 0;
}
int rsa_readPublic(FILE* f, RSA_KEY* K) {
rsa_initKey(K); /* will set all unused members to 0 */
zFromFile(f, K->n);
zFromFile(f, K->e);
return 0;
}
int rsa_readPrivate(FILE* f, RSA_KEY* K) {
rsa_initKey(K);
zFromFile(f, K->n);
/*zFromFile(f, K->e);
zFromFile(f, K->p);
zFromFile(f, K->q);*/
zFromFile(f, K->d);
return 0;
}
int rsa_shredKey(RSA_KEY* K) {
/* clear memory for key. */
mpz_t* L[5] = { &K->d, &K->e, &K->n, &K->p, &K->q };
size_t i;
for (i = 0; i < 5; i++) {
size_t nLimbs = mpz_size(*L[i]);
if (nLimbs) {
memset(mpz_limbs_write(*L[i], nLimbs), 0,
nLimbs * sizeof(mp_limb_t));
mpz_clear(*L[i]);
}
}
/* NOTE: a quick look at the gmp source reveals that the return of
* mpz_limbs_write is only different than the existing limbs when
* the number requested is larger than the allocation (which is
* of course larger than mpz_size(X)) */
return 0;
}
|
997b1ea282e843d05e96b19b26764b9f8d3fea95
|
[
"Markdown",
"C"
] | 4 |
Markdown
|
t17711/key-encapsulation-mechanism
|
a6f346c47a9d0cfff863d26a6d3ea699139c64f3
|
ae3a352388efd78b491231cd6308be80ee3e8c5e
|
refs/heads/master
|
<repo_name>luobolaogong/MsatLeaflet20160521<file_sep>/leaf/MapImpl.js
/**
* @fileoverview This is the "gateway" JS file that communicates with the GWT/Java code found in
* LeafMapImpl.java (counterpart to OpenLayersMapImpl.java). This file is the "counterpart" of
* the OpenLayers version, OLMapImpl.js. The OpenLayers files will be phased out, but for now we
* will keep the similar naming convention.
* <p>
* All function calls and communication with the map component go through the JSNI
* code that's in LeafMapImpl.java (which implements IMap), and through this file. Any kind of
* testing of the map would also go through this file. That is, testing code could directly call
* functions in this file, but not functions in any other JS file.
* <p>
* (Server) ?* <--> GWT/Java <--> LeafMapImpl.java <--> leaf/MapImpl.js <--> leaf/*.js (Client)
* <p>
* The only functions that we need to provide here are the ones that are listed as JSNI functions
* in LeafMapImpl.java.
* <p>
* And the functions here can be completely rewritten, as long as the signatures match
* what's in the LeafMapImpl.java JSNI code. So, this file need not look at all like
* the OpenLayers counterpart OLMapImpl.js, except for the fact that function signatures should
* match. The OLMapImpl.js file contains several functions that are not used. We do not have
* those functions here.
* <p>
* Because of the way that the development tasks were established, forcing a gradual change over
* from OpenLayers to Leaflet, the architecture is not what it shold be. The code here should really
* be considered prototype, and thrown away and rearchitected.
*/
goog.provide('leaf.MapImpl');
goog.require('leaf.Map');
/**
* MapImpl.js -- Implementation of map routines based on the contents of
* leaf.MapImpl.java, using Leaflet JS library. The JS functions here
* should be directly called by the JSNI methods in leaf.MapImpl.java.
* Probably can't make this a class, or it would screw up LeafMapImpl.js. Look into this.
*/
leaf.MapImpl.SQ_METERS_PER_SQ_MILE = 2589988.1;
leaf.MapImpl.SQ_MILES_PER_SQ_METER = 3.8610216e-7;
/** @enum {number} These match the values in MapFilter.java */
leaf.MapImpl.Filters = {
COUNTRY_FILTER: 0,
MTF_FILTER: 1,
SPATIAL_FILTER: 2,
SPATIAL_PLUS: 3,
COUNTRY_PLUS: 4,
NO_FILTER: 5
};
leaf.MapImpl.isMeasureToolOn = false;
/**
* This function, setResults, is used to display different kinds of
* elements on the map. It is called by leaf.MapImpl.setResults(String data).
*
* The results that get passed in as "data" are formatted as JSON string data
*/
leaf.MapImpl.setResults = function (resultsString) {
console.log("In JS leaf.MapImpl.setResults");
var append = goog.isDef(window.parent.isAppendResults) ? window.parent.isAppendResults() : true;
//reset the count of visible features before processing results array
if (!append)
leaf.MapImpl.clearResults();
if (!resultsString) {
console.log("leaf.MapImpl.setResults(): No results string passed in.");
return;
}
//
// Parse the resultsString into usable parts.
//
var jsonResultsCalloutsAndTracksObject = JSON.parse(resultsString);
// This logging is temporary until we get a way easily examine what's coming into the map
// to be displayed when running on the Demo tier. Remove after plumes and tracks are solid.
//console.log("leaf.MapImpl.setResults(): jsonResultsCalloutsAndTracksObject:\n" + JSON.stringify(jsonResultsCalloutsAndTracksObject, undefined, "\t"));
var resultsObject = jsonResultsCalloutsAndTracksObject.Results;
var tracksArray = resultsObject.tracks;
var calloutsArray = resultsObject.callouts;
leaf.Map.setQueryResultCount(tracksArray.length + calloutsArray.length);
if (tracksArray.length > 0) {
console.log("Ignoring tracks for now.");
}
if (calloutsArray.length > 0) {
leaf.Map.processCallouts(calloutsArray); // this can be renamed
}
console.log("Leaving JS leaf.MapImpl.setResults");
};
/**
* This method can be called to reassemble the parts of "results" that are
* broken up by ResultsDataStore.passDataToMap() and sent in "parts".
*
* @param {number} key double an index for the entire results set
* @param {number} partNumber int The segment number for this part of the results
* @param {number} totalParts int The total number of segments/parts expected
* @param {string} partContent String The actual JSON content of this segment/part
*/
leaf.MapImpl.setPartResults = function (key, partNumber, totalParts, partContent) {
console.log("In JS leaf.MapImpl.setPartResults");
if (leaf.MapImpl.setPartResults.key != key) {
if (leaf.MapImpl.setPartResults.reconstructedResultsString !== "") {
alert("leaf.MapImpl.setPartResults(): Didn't finish set before new results set part arrived.");
}
leaf.MapImpl.setPartResults.key = key;
leaf.MapImpl.setPartResults.reconstructedResultsString = "";
}
leaf.MapImpl.setPartResults.reconstructedResultsString += partContent;
if (partNumber >= totalParts - 1) {
this.setResults(leaf.MapImpl.setPartResults.reconstructedResultsString);
leaf.MapImpl.setPartResults.reconstructedResultsString = "";
leaf.MapImpl.setPartResults.key = null;
}
};
leaf.MapImpl.setPartResults.reconstructedResultsString = "";
leaf.MapImpl.setPartResults.key = null;
leaf.MapImpl.setL2Results = function (data) {
alert("leaf.MapImpl.setL2Results not yet implemented.");
};
leaf.MapImpl.clearResults = function () {
console.log("In JS leaf.MapImpl.clearResults, gunna do nothing because don't have resultsLayer or plumes layer yet.");
// leaf.Map.resultsLayer.clearResults();
// leaf.Map.resultsLayer.removePopups();
// leaf.Map.plumesLayer.removePlumes();
leaf.Map.markers.removeAllMarkers();
console.log("Leaving JS leaf.MapImpl.clearResults");
};
leaf.MapImpl.resetView = function () {
console.log("In JS leaf.MapImpl.resetView");
leaf.Map.resetView();
console.log("Leaving JS leaf.MapImpl.resetView");
};
leaf.MapImpl.notifyVisible = function (show) {
console.log("In JS leaf.MapImpl.notifyVisible");
if (show) {
leaf.Map.resultsLayer.showPopups();
}
else {
leaf.Map.resultsLayer.hidePopups();
}
console.log("Leaving JS leaf.MapImpl.notifyVisible");
};
/**
* This function is called from ResultsGridPanel.xxx() and it expects
* to get back a string of the form "<lat>:<lng>", or null. The location
* is based on the leafletMarker of the most recent set, that is closest to the
* eyepoint. But, if they call leaf.MapImpl.clearResults() first, then
* there are no markers available! This appears to be a timing issue.
*
* Whatever calls this, seems to make the following calls in this order:
* clearResults, fetchNearestMarker, zoomToLocation, setResults. That's
* a strange order, because after you clearResults, there are no markers
* around to fetch, or zoom to.
*
* Check out ResultsGridPanel.
*/
leaf.MapImpl.fetchNearestMarker = function () {
console.log("In JS leaf.MapImpl.fetchNearestMarker");
var nearestMarkerLocationString = leaf.Map.resultsLayer.fetchNearestMarker();
console.log("Leaving JS leaf.MapImpl.fetchNearestMarker, and returning some kind of nearestMarkerLocationString: " + nearestMarkerLocationString);
return nearestMarkerLocationString;
};
leaf.MapImpl.zoomToNearestMarker = function () {
console.log("In JS leaf.MapImpl.zoomToNearestMarker");
leaf.Map.resultsLayer.zoomToNearestMarker();
console.log("leaving JS leaf.MapImpl.zoomToNearestMarker");
};
/**
* Pan and zoom to the location specified by the latitude and longitude specified,
* and if a locationName is specified, then also place a leafletMarker there. This method
* merely calls the same function in leaf.Map.
*
* @param {number} latitude in decimal degrees
* @param {number} longitude in decimal degrees
* @param {string} locationName
*/
leaf.MapImpl.zoomToLocation = function (latitude, longitude, locationName) {
console.log("In JS leaf.MapImpl.zoomToLocation(lat, lng, locName), calling leaf.Map.zoomToLocation(lat,lng,locName)");
//var latLngWrapped = leaf.Map.leafletMap.wrapLatLng(latLng); // wraps this east/west, but not north/south. Call this here or inside leaf/*.js files?
leaf.Map.zoomToLocation(latitude, longitude, locationName);
console.log("Leaving JS leaf.MapImpl.zoomToLocation(lat, lng, locName), after calling leafMap.zoomToLocation(lat,lng,locName)");
};
leaf.MapImpl.getGeometry = function () {
console.log("In JS leaf.MapImpl.getGeometry");
var spatialFilterGeometry = leaf.Map.spatialFilter.getGeometry();
console.log("Leaving JS leaf.MapImpl.getGeometry and returning some geometry: " + spatialFilterGeometry);
return spatialFilterGeometry;
};
/**
* Get the centroid of the spatial filter.
*
* @returns {string} centroid The centroid's coordinates as JSON shape
*/
leaf.MapImpl.getCentroid = function () {
console.log("In JS leaf.MapImpl.getCentroid");
var spatialFilterCentroid = leaf.Map.spatialFilter.getCentroid();
console.log("Leaving JS leaf.MapImpl.getCentroid and returning centroid: " + spatialFilterCentroid);
return spatialFilterCentroid;
};
/**
* This function acts upon a filter tool change. It may cause the spatial filter
* to activate, or turn off, or just cause the MTF filter information to display.
*/
leaf.MapImpl.setFilter = function (toolId, buffer, filterInfo) {
console.log("In JS leaf.MapImpl.setFilter");
console.log("leaf.MapImpl.setFilter() test: toolId=" + toolId + ", filterInfo=" + filterInfo);
switch (toolId) {
case leaf.MapImpl.MTF_FILTER:
leaf.Map.overlays.setMtfOverlay(filterInfo);
break;
case leaf.MapImpl.SPATIAL_FILTER:
leaf.Map.spatialFilter.activateBBox();
break;
case leaf.MapImpl.NO_FILTER:
case leaf.MapImpl.SPATIAL_PLUS: // click on spatial X
case leaf.MapImpl.COUNTRY_PLUS: // click on arrow
leaf.MapImpl.disableDraw();
this.clearFilter();
break;
case leaf.MapImpl.COUNTRY_FILTER:
/*falls through*/
default:
console.log("leaf.MapImpl.setFilter(): toolId is " + toolId + " No implementation yet.");
this.clearFilter();
}
console.log("Leaving JS leaf.MapImpl.setFilter, which didn't really set a filter.");
};
leaf.MapImpl.setSpatialFilterMaxSize = function (squareMiles) {
console.log("In JS leaf.MapImpl.setSpatialFilterMaxSize");
leaf.Map.spatialFilter.setMaxSizeInSquareMiles(squareMiles);
};
leaf.MapImpl.getSpatialFilterAreaInSquareMiles = function () {
console.log("In JS leaf.MapImpl.getSpatialFilterAreaInSquareMiles");
var areaInSqMeters = leaf.Map.spatialFilter.getArea();
if (typeof areaInSqMeters == "number") {
return areaInSqMeters / leaf.MapImpl.SQ_METERS_PER_SQ_MILE;
}
return null;
};
leaf.MapImpl.clearFilter = function () {
console.log("In JS leaf.MapImpl.clearFilter");
leaf.Map.spatialFilter.deleteBBox();
};
leaf.MapImpl.disableDraw = function () {
console.log("In JS leaf.MapImpl.disableDraw");
leaf.Map.spatialFilter.spatialFilterDrawControl.deactivate();
};
/**
* leaf.MapImpl.java has a toggleMeasureTool method, and it calls this method.
* MeasureToolbar.java defines a toggle button for turning on and off the measure
* tool. We try to keep IMap.java, and leaf.MapImpl.java unchanged, so we put
* the state in OLMeasureTool.js.
*/
leaf.MapImpl.toggleMeasureTool = function () {
console.log("In JS leaf.MapImpl.toggleMeasureTool");
leaf.Map.measureTool.toggleMeasureTool();
};
leaf.MapImpl.addLayer = function (layerData) {
console.log("In JS leaf.MapImpl.addLayer");
leaf.Map.layers.addLayer(layerData);
};
leaf.MapImpl.removeLayer = function (index) {
alert("In leaf.MapImpl.removeLayer(index)");
};
// Looks like this is the function that gets called when you want to swap layers
// Maybe it's only for overlay layers. This can be triggered when a checkbox is unchecked,
// for when you want to turn off an overlay. So, what actually removes the layer if checked is false?
leaf.MapImpl.toggleLayer = function (index, checked) {
console.log("In JS leaf.MapImpl.toggleLayer(" + index + ", " + checked + "), and calling setLayerVisibility(index, checked)");
leaf.Map.layers.setLayerVisibility(index, checked);
console.log("Leaving JS leaf.MapImpl.toggleLayer(" + index + ", " + checked + ")");
};
leaf.MapImpl.selectBaseLayer = function (index) {
console.log("In MapImpl.js, (JS file, not Java) leaf.MapImpl.selectBaseLayer(" + index + "), calling selectBaseLayer(index)");
// leaf.Map.layers.selectBaseLayer(index); // error
// leaf.Map.layersJSObject.selectBaseLayer(index);
leaf.Map.layers.selectBaseLayer(index);
console.log("Leaving MapImpl.js, leaf.MapImpl.selectBaseLayer(" + index + "), after calling selectBaseLayer(index)");
};
/**
* Changes the internal order in the LayerList.
* @param oldIndex
* @param newIndex
*/
leaf.MapImpl.moveLayer = function (oldIndex, newIndex) { // int int
alert("In leaf.MapImpl.moveLayer(oldIndex, newIndex)");
};
// who calls this?
leaf.MapImpl.clearLayers = function () {
alert("In leaf.MapImpl.clearLayers()");
};
/**
* This function is called when there's a change to the Map Controls Panel's
* controls, for example when a layer is checked or unchecked.
*
* I assume that what this is supposed to do is notify the map that it needs
* to change the leafletLayers that are displayed. In Leaflet we have a single
* basemap that is active, and then we have overlays on top of it. This model
* seems different from what WorldWind had: It seemed we could have multiple
* "basemaps" active, and the one you saw was the one with the greatest Z
* value. And if there were holes, you could see through that hole to a layer
* below it. You could turn all basemaps off if you wanted, and you'd have a
* black earth. I assume you can do something similar in Leaflet where
* you still have your single basemap, which can be swapped out for something
* different, but you can turn on and off the overlays. And most of our leafletLayers
* will be overlays, if not all by a single basemap.
* So, this function probably causes the map to swap the basemap, or add or
* subtract the overlay leafletLayers.
*
* The key to what this is supposed to do is probably found in PluggableMapCanvas.java
*
* Looks like this method is getting called multiple times for the same layer
* when you click "Clear Imagery" or "Clear Maps". That logic, wherever it is
* needs to be seriously looked at.
*
* @param {boolean} viewable indicates whether the check box is checked or not
* @param {string} layerName is the text associated with a layer
*/
leaf.MapImpl.notifyViewable = function (viewable, layerName) { //boolean String
console.log("leaf.MapImpl.notifyViewable(" + viewable + ", " + layerName);
switch (layerName) {
case "mgrs-grid":
console.log('MGRS grid visibility=' + viewable);
leaf.Map.layers.setLayerVisibility(leaf.Map.layers.mgrsIndex, viewable);
break;
}
};
leaf.MapImpl.renderSpatialQuery = function (lowerLat, leftLong, upperLat, rightLong) { //double double double double
//alert("In leaf.MapImpl.renderSpatialQuery(lat, lng, uplat, rightlng)");
};
leaf.MapImpl.log = function (logString) { // String
//Leaf.Console.log(logString); // This goes nowhere unless something has defined the function before now
console.log("<font color='purple' size='small'>" + logString + "</font>"); // temporary until decide where to send this.
};
leaf.MapImpl.logError = function (errorString) { // String
//Leaf.Console.error(errorString); // Does nothing unless Firebug.js was previously loaded
console.error("<font color='pink' size='small'>" + errorString + "</font>"); // temporary until decide where to send this.
};
/**
* Unnecessary function now that the applet is gone?
* @param queryId
*/
leaf.MapImpl.jobQueryComplete = function (queryId) {
console.log("In leaf.MapImpl.jobQueryComplete(queryId): " + queryId);
};
/**
* The specification for this method is that it returns "true" or "false" as a string, and
* if the coordinate is valid, (according to the spec "MSAT Coordinate Locate Functional
* Specification" of October 6th, 2010, as referenced in FB 17876), then we also pan/zoom to it.
*
* The parsing of user input coordinates could be much less restrictive, but we follow the spec.
*
* @param {String} coordinate a "raw" coordinate, to allow for diff coord system and format
*/
leaf.MapImpl.locateCoordinate = function (coordinate) {
console.log("In JS leaf.MapImpl.locateCoordinate(coordinate)");
var latLng = coord2LatLng(coordinate);
if (latLng === null) {
return "false";
}
console.log("In JS leaf.MapImpl.locateCoordinate(coordinate) calling leaf.MapImpl.zoomToLocation(...)");
leaf.MapImpl.zoomToLocation(latLng.lat, latLng.lng, coordinate);
console.log("Leaving JS leaf.MapImpl.locateCoordinate(coordinate)");
return "true";
};
/**
* Convert a raw string coordinate into an object containing a
* latitude and longitude, if possible.
*
* Because we support three basic formats, we try parsing them
* in a logical order.
*
* A raw coordinate should follow one of these formats:
* <ul>
* <li>Sexagecimal: DDMM.mmmmH DDDMM.mmmmH
* <li>MGRS (not near poles): ZzSSRRRRUUUU
* <li>Decimal: D.d, D.d
* </ul>
*
* The coordinate specifications are found in "MSAT Coordinate Locate
* Functional Specification" of October 6th, 2010, as referenced in
* FogBugz case 17876.
*
* Since "sexagecimal" is the most restrictive, we get it out of the
* way first. If that's not a match, then MGRS, and if that doesn't
* match, finally decimal.
*
* @private
* @param {String} coordString A coordinate potentially in one of three accepted forms
* @returns {Object} An object containing two properties (lat and lng), or null if could not parse
*/
function coord2LatLng(coordString) {
var latLng;
latLng = sexagecimal2LatLng(coordString);
if (latLng !== null) {
return latLng;
}
latLng = mgrs2LatLng(coordString);
if (latLng !== null) {
return latLng;
}
latLng = decimal2LatLng(coordString);
if (latLng !== null) {
return latLng;
}
return null;
}
/**
* Convert a raw coordinate string, potentially in modified
* sexagecimal format, into a an object containing a latitude and
* longitude. If it's not in sexagecimal format, return null.
*
* "Sexagecimal", as used here, is basically this format: DDMM.mmmmH DDDMM.mmmmH
*
* The spec says the space delimiter should be a single space, but we are
* more lenient and allow multiple "white" characters. This should not be
* an issue.
*
* @private
* @param {String} coordString coordinate string in sexagecimal format
* @returns {Object} An object containing properties lat and lng, or null if bad format
*/
function sexagecimal2LatLng(coordString) {
var sexaCoordRegExpPattern = /^\s*(\d\d)(\d\d\.\d\d\d\d)([NnSs])\s+(\d\d\d)(\d\d\.\d\d\d\d)([EeWw])\s*$/;
var sexaCoordRegExp = new RegExp(sexaCoordRegExpPattern);
var sexaCoordPatternExists = sexaCoordRegExp.test(coordString);
if (!sexaCoordPatternExists) {
return null;
}
var parsedCoord = sexaCoordRegExp.exec(coordString);
var latDegs = parseInt(parsedCoord[1], 10);
var latMins = parseFloat(parsedCoord[2]);
var lngDegs = parseInt(parsedCoord[4], 10);
var lngMins = parseFloat(parsedCoord[5]);
var northSouthChar = parsedCoord[3].toUpperCase();
var eastWestChar = parsedCoord[6].toUpperCase();
var lat = latDegs + (latMins / 60.0);
if (northSouthChar == "S") {
lat = -lat;
}
if (lat < -90.0 || lat > 90.0) {
return null;
}
var lng = lngDegs + (lngMins / 60.0);
if (eastWestChar == "W") {
lng = -lng;
}
if (lng < -180.0 || lng > 180.0) {
return null;
}
return {lat: lat, lng: lng};
}
/**
* Convert a raw coordinate string in MGRS format into a an object containing a
* latitude and longitude. If it's not in sexagecimal format, return null.
*
* This function makes use of some library code that primarily works with USNG
* rather than MGRS coordinates, but it should work well enough.
*
* MGRS format, when not near poles, is basically "ZzSRU" where
* <ul>
* <li>Z is one or two digits specifying a longitudinal zone,
* <li>z is a character representing a latitudinal zone,
* <li>S is two characters square identification,
* <li>R is the distance right
* <li>U is the distance up
* </ul>
* The number of digits of R and U must match in number and be 5 or less.
* Technically it can be no digits and be a legal MGRS, but the USNG software
* requires at least one R and one U digit.
*
* There can be spaces anywhere in this coordinate string.
* Example: 18S UJ 23371 06519
*
* Note: We currently do NOT handle MGRS coordinate strings that represent polar
* latitudes below 80 south or above 84 north. The library code we're using ("usngBetter.js")
* does not handle coordinates in that range. If it's important for the user to
* specify polar-range MGRS coordinates, then we will need some new code.
*
* @private
* @param {String} coordString expected to be in MGRS format
* @returns {Object} An object containing lat and lng properties, or null if format wrong
*/
function mgrs2LatLng(coordString) {
//return null; // just for now, because don't have usngBetter.js set up at home
//
// The library functions isUSNG() and USNGtoLL() require 7 characters, and an initial
// "0" if the grid zone is less than 10. So we have to prepare otherwise
// legal MGRS in order to use those functions.
//
coordString = coordString.replace(/\s/g, "");
var firstCharacter = coordString.charAt(0);
if (isNaN(firstCharacter)) {
return null;
}
var secondCharacter = coordString.charAt(1);
if (isNaN(secondCharacter)) {
coordString = "0" + coordString;
}
if (coordString.length == 5) {
coordString += "00"; // pad out to 7
}
//
// Use library code to check if this is a USNG coordinate string,
// and if so, parse it.
//
//if (!orgmymanateecommonusng.isUSNG(coordString)) {
if (!orgmymanateecommonusng.isUSNG(coordString)) {
return null;
}
try {
var latLngResult = new Array(2);
orgmymanateecommonusng.USNGtoLL(coordString, latLngResult);
var lat = latLngResult[0];
var lng = latLngResult[1];
return {lat: lat, lng: lng};
}
catch (E) {
console.log("Could not convert MGRS coordinate \"" + coordString + "\" " + E.message);
}
return null;
}
/**
* Convert a raw coordinate string in decimal degrees format into a an object
* containing a latitude and longitude. If it's not in decimal format, return null.
*
* Decimal is basically "SDHsSDH" where:
* <ul>
* <li>S is an optional sign "-" or "+". Must match the hemisphere designation if given.
* <li>D is the decimal degrees value (latitude then longitude), and may contain a decimal point. Must be within range.
* <li>H is an optional hemisphere character from set "NnSsEeWw" (latitude first).
* <li>s is a separator between latitude and longitude. Spec only allows " ", or ",", or ", ". (May want less strict.)
* </ul>
*
* @private
* @param {String} coordString expected to be in decimal degrees format
* @returns {Object} An object containing lat and lng properties, or null if format wrong
*/
function decimal2LatLng(coordString) {
var ddCoordRegExpPattern = /^\s*((-|\+)?(\d{0,2}\.\d*|\d{1,2}))([NnSs]?)(\s|,|,\s)((-|\+)?(\d{0,3}\.\d*|\d{1,3}))([EeWw]?)\s*$/;
var ddCoordRegExp = new RegExp(ddCoordRegExpPattern);
var ddCoordPatternExists = ddCoordRegExp.test(coordString);
if (!ddCoordPatternExists) {
return null;
}
var latLngArray = ddCoordRegExp.exec(coordString);
var lat = Number(latLngArray[1]);
var lng = Number(latLngArray[6]);
var northSouthChar = latLngArray[4].toUpperCase();
var eastWestChar = latLngArray[9].toUpperCase();
var latSign = latLngArray[2];
var lngSign = latLngArray[7];
// Sign and hemisphere must agree
if ((latSign == '-' && northSouthChar == 'N') ||
(latSign == '+' && northSouthChar == 'S') ||
(lngSign == '-' && eastWestChar == 'E') ||
(lngSign == '+' && eastWestChar == 'W')) {
return null;
}
if (lat > 0.0 && northSouthChar == 'S') {
lat = -lat;
}
if (lat < -90.0 || lat > 90.0) {
return null;
}
if (lng > 0.0 && eastWestChar == 'W') {
lng = -lng;
}
if (lng < -180.0 || lng > 180.0) {
return null;
}
return {lat: lat, lng: lng};
}
leaf.MapImpl.activateElevation = function (activate) { //boolean
alert("In leaf.MapImpl.activateElevation(activate)");
};
leaf.MapImpl.disableScrolling = function () {
alert("In leaf.MapImpl.disableScrolling()");
};
leaf.MapImpl.enableScrolling = function () {
alert("In leaf.MapImpl.enableScrolling");
};
console.log('MapImpl.js loaded');
<file_sep>/leaf/Map.js
/**
* @fileoverview This file defines the leaf.Map class.
* <p>
* I don't know where to put an overall description of the map component of MSAT.
* I read that perhaps "package.json" might help. But it doesn't seem to be
* a document that would hold a lot of text, like JSDoc can. Perhaps in
* a README.md file in the source path?
* <p>
* Things like communication going through the Impl.js and Impl.java files.
* The communication between Map and layers and markers and whatever else.
* The use of Closure. The non use of JQuery. The non use of TypeScript.
* The fact that GWT will probably be thrown out and replaced, hopefully by
* Dart and Polymer. The use of JSDoc. The variable naming conventions. The
* style conventions. Directory structure. Namespacing. All that stuff.
* I want this stuff established before others come in and pollute it.
*/
goog.provide('leaf.Map'); // makes sure leaf.Map is defined and can be used, and is unique
goog.require('leaf.Layer'); // the file should be in .../leaf/Layer.js
goog.require('leaf.Controls');
/**
* "This is the entry point." It's used in the MSAT environment.
* This function is immediately executed upon loading this file.
* It could have a name and take parameters
* It should not be executed before the JS files have been loaded.
* Comment out when in Dev mode. But uncomment it when in MSAT.
*/
// $ I think possibly the dollar sign keeps it from running until stuff has been loaded, but not sure
// (function(arg) {
// console.log("Bringing up the map ...");
// //console.log("arg: " + arg);
// leaf.Map = new leaf.Map();
// console.log("The map should be up now.");
// })(42);
// In MSAT version, cannot have (42) or (arg)
/**
* Constructor for leaf.Map that initializes the object with references to the layers, and
* adds controls. use leaf.Map.getInstance() to get an instance of this class.
*
* I didn't make this a Singleton using goog.addSingletonGetter(leaf.Map) because
* while unlikely, we may want more than one map some time. Each map would have its own set
* of layers too, and not share them. So I didn't make Layers a singleton either.
*
* @constructor
* @private
*/
leaf.Map = function() {
// this.DEFAULT_ZOOM = 5;
/**
* The Layers object keeps track of the various layers for the map.
* @type {leaf.Layers}
*/
this.layers = new leaf.Layers(); // was named this.leafLayers
this.markers = new leaf.Markers(); // actually, a LayerGroup, right?
this.callouts = new leaf.Callouts(); // this is just temporary. Not sure where this callout stuff should go
/**
* The Leaflet map object which has access to layers and controls. The layers need
* to be created before the leafletMap is created, because it needs an initial
* layer.
* @type {L.map}
*/
this.leafletMap = this.createLeafletMap_();
//this.leafletMap.addLayer(this.markers);
this.markers.markersGroup.addTo(this.leafletMap);
//console.log("The HTML element that is the container for this map: " + this.leafletMap.getContainer());// [object HTMLDivElement]
/*
* Add controls to the map. This needs to be created after the layers have been created,
* because the overview control uses that layer.
*/
this.controls = new leaf.Controls(this);
//leaf.Controls.addControls(this);
// Totally a bad thing here, but just to keep from blowing up in MSAT env...
this.resultsLayer = new LeafResultsDataLayer();
console.log("Leaving Map.js constructor");
};
leaf.Map.prototype.DEFAULT_ZOOM = 5; // 15 is max for Esri Imagery World
/**
* The map's Coordinate Reference System, that all layers should adhere to.
* We are nearly mandated to use 4326, since we're DoD.
* Works best for GVS, though DoD is technically supposed to be 3395.
* We would need to convert layers if we mixed and matched. This is not the
* same as what OpenLayers does, which converts on the fly, I think.
* @type {L.CRS}
*/
leaf.Map.crs = L.CRS.EPSG4326;
//leaf.Map.crs = L.CRS.EPSG3857; // Can't use this with our layers without some work
/**
* This creates the leaflet map object
* @private
*/
leaf.Map.prototype.createLeafletMap_ = function() {
var map = L.map('map', {
crs: leaf.Map.crs,
//continuousWorld: true, // nec? helpful?
center: [0, 0],
zoom: 1, // nav plugin can affect this
zoomControl: false,
attributionControl: false,
layers: [this.layers.baseLayer.leafletLayer]
});
return map;
};
/*
* The following functions are statics, so that they can be called from anywhere, without
* needing to get access to the leaf.Map class instance, which is kinda necessary because of
* all that MapImpl stuff. (Check this out.
*/
/**
* Go to full map view.
*/
leaf.Map.prototype.resetView = function () {
//console.log("In leaf.Map.prototype.resetView()");
this.leafletMap.fitWorld(); // this is one way to do it. Can play around with options.
//console.log("Leaving leaf.Map.prototype.resetView()");
};
leaf.Map.prototype.processCallouts = function(calloutsJsonArray) {
this.callouts.processCallouts(calloutsJsonArray);
}
/**
* Zoom and pan to the specified location. If the location is named, then place
* a leafletMarker with the name at the location. The zoom level is a default. Kinda silly.
*
* @param {number} latitude in decimal degrees
* @param {number} longitude in decimal degrees
* @param {string=} locationTag The label to put on the map at the specified location
*/
//this.leafletMap.zoomToLocation = function (latitude, longitude, locationTag) { // static version so can be called without reference to the map class instance
//leaf.Map.prototype.zoomToLocation = function (latitude, longitude, locationTag) {
leaf.Map.prototype.zoomToLocation = function (latitude, longitude, locationTag) {
console.log("In Map.js.zoomToLocation.");
// Insure we've got a number.
if (typeof latitude !== "number") {
latitude = 0;
}
if (typeof longitude !== "number") {
longitude = 0;
}
var latLng = L.latLng(latitude, longitude);
latLng = this.leafletMap.wrapLatLng(latLng); // wraps this east/west, but not north/south.
var marker = new leaf.Marker(latLng, locationTag);
this.markers.addMarker(marker);
leaf.Map.leafletMap.setView(latLng, this.DEFAULT_ZOOM, {animate: true});
console.log("Leaving Map.js.zoomToLocation");
};
/**
* Simply returns the query result count, which is set by setQueryResultCount
* @returns {number} The number of query results.
*/
leaf.Map.prototype.getQueryResultCount = function () {
return this.queryResultCount;
};
/**
* Set
* @param {number} val
*/
leaf.Map.prototype.setQueryResultCount = function(val) {
this.queryResultCount = val; // better check if this should be something else, if this is a static function
};
/**
* When the "Show Details" link in the popup is clicked, this function is called,
* and this function calls the JSNI callback LeafMapImpl.callbacks'
* function getDetails(alternateId), which calls the Java method
* getDetails(String alternateId) which calls selectRow, and switchToDetails.
*
* @param alternateId
*/
leaf.Map.prototype.showDetails = function (alternateId) {
if (!window.parent.getDetails) {
console.log("Leaving leaf.Map.prototype.showDetails() without calling getDetails(alternateId)");
return;
}
window.parent.getDetails(alternateId);
};
console.log('Map.js loaded');
<file_sep>/leaf/Marker.js
/**
* @fileoverview This file defines the leaf.Marker class, which holds marker parameters for construction
* and is (MAYBE) used with other markers in the leaf.Markers class, by the leaf.Map class.
* <p>
* In Leaflet, a marker may have attached to it a popup.
*/
goog.provide('leaf.Marker');
leaf.Marker = function (latLng, locationTag) {
console.log("In Marker.js constructor");
//this.name = jsonMarkerData.markerName;
//this.markerId = jsonMarkerData.index; // this value gets generated by GWT somehow
// Don't need to make everything in here "this."
this.labelText = goog.isDefAndNotNull(locationTag) ? locationTag : null;
this.leafletMarker = L.marker(latLng, {
title: this.labelText,
alt: 'markerFromZoomToLocation'
});
L.Icon.Default.iconUrl
this.markerIcon = L.icon({
iconAnchor: [10,20],
iconUrl: 'img/marker.png' // L.Icon.Default.imagePath
});
this.leafletMarker.setIcon(this.markerIcon);
if (this.labelText) {
// This next line requires a plugin from github.com/Leaflet/Leaflet.label
this.leafletMarker.bindLabel(this.labelText, {
direction: 'auto',
opacity: 0.5, // default is 1
noHide: true}); // true means always show label, false means only show it when hover over icon
//leafletMarker.setTitle(locationTag); // cursor move over? probably wrong. Prob have to set it as an option
this.leafletMarker.bindPopup(this.labelText);
}
console.log("Leaving Marker.js constructor");
};
<file_sep>/leaf/Plume.js
/**
* Created by rreed on 5/20/2016.
*/
|
54d9374cc8fde721df7f1b6904139105950c81f2
|
[
"JavaScript"
] | 4 |
JavaScript
|
luobolaogong/MsatLeaflet20160521
|
4585448f79ccddedde1eb5529ce96d3b1581b3d1
|
c570f1a5e37d7c4f3bab2013bce6a27d59664f1e
|
refs/heads/master
|
<file_sep>const date_btn= document.getElementById('dateBtn');
const date2= document.getElementById('date');
date_btn.addEventListener('click', e=>{
document.getElementById('date').innerHTML= Date();
});
|
cefaabb218c3dc974868edf31758cae9d33ffce5
|
[
"JavaScript"
] | 1 |
JavaScript
|
elkanahtetteh/HW1_UBKR46VLQA
|
72b84a610b7a562c1c195c22d45062d16224f0a5
|
b131ad553ee9c7e42a7590d883d8c33b84bc95c3
|
refs/heads/master
|
<repo_name>BrandonBoone/PremierTools<file_sep>/src/redux/browser/selectors.js
export const getWidth = (state) => {
return (state.browser.width > 765 ?
765 : // 765 is premier's width for CV
state.browser.width) - 50; // 50 is a magic number. :-/
};
<file_sep>/src/App.js
import React from 'react';
import MonthlyCommissionsAndParties from './modules/charts/containers/MonthlyCommissionsAndParties.jsx';
import TitleLine from './modules/common/components/TitleLine.jsx';
import Header from './modules/common/components/Header.jsx';
import RunButton from './modules/common/containers/RunButton';
import CVDateRangePicker from './modules/common/containers/CVDateRangePicker';
import { connect } from 'react-redux';
import { getWidth } from './redux/browser/selectors';
import Ripple from './ripple.svg';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import './App.css';
import floor from 'lodash/floor';
const style = {
display: 'flex',
alignItems: 'center',
flexDirection: 'column',
width: '100%',
};
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
});
const App = ({
isLoading,
width,
errorMessage,
totalRetail,
totalCommission,
totalCommissionVolume,
totalBonusPaid
}) => (
<div
className='commissionReports'
style={style}
>
<div>
<CVDateRangePicker />
</div>
<ReactCSSTransitionGroup
transitionName="commissionReports"
transitionAppear={true}
transitionAppearTimeout={300}
transitionEnterTimeout={300}
transitionLeaveTimeout={300}
>
{errorMessage ?
<span style={{color:'red'}}>
Oops! Something went terribly wrong. Let us known
<a href="https://github.com/BrandonBoone/PremierTools/issues">here</a>
</span> : null
}
{isLoading ?
<div
style={{
height:'500px',
}}
>
<Ripple key="loading" />
</div>
:
<div
key="charts"
style={{
width
}}
>
<Header
title="Commissions By Month"
/>
<TitleLine />
<p>
This chart shows the total commissions and total parties of your downline by month.
</p>
<p>
<i>Only "Home Shows" and "Catalog Orders" are counted as parties</i>
</p>
<p style={{ fontSize: '1.3em' }}><strong>{formatter.format(totalCommission.total + totalBonusPaid)}</strong>: This is what your downline made you.</p>
<h5>Breakdown</h5>
<table>
<tbody>
{Object.keys(totalCommissionVolume.percentages).map(next =>
<tr>
<td><abbr title="commission volume">CV</abbr></td>
<td>{formatter.format(floor(totalCommissionVolume.percentages[next] * (parseFloat(next,10)/100),2))}</td>
<td>({next}% of {formatter.format(totalCommissionVolume.percentages[next])})</td>
</tr>
)}
<tr>
<td>Bonus</td><td>{formatter.format(totalBonusPaid)}</td><td></td>
</tr>
<tr>
<td>Total Commission</td><td><strong>{formatter.format(totalCommission.total + totalBonusPaid)}</strong></td><td></td>
</tr>
<tr>
<td><i>Total Retail</i></td><td><i>{formatter.format(totalRetail)}</i></td><td></td>
</tr>
</tbody>
</table>
<MonthlyCommissionsAndParties />
</div>
}
</ReactCSSTransitionGroup>
</div>
);
export default connect(
state => ({
isLoading: state.cvdata.loading,
width: getWidth(state),
errorMessage: state.cvdata.errorMessage,
totalCommission: state.cvdata.totalCommission,
totalRetail: state.cvdata.totalRetail,
totalCommissionVolume: state.cvdata.totalCommissionVolume,
totalBonusPaid: state.cvdata.totalBonusPaid,
})
)(App);
<file_sep>/src/modules/common/components/Button.jsx
import React from 'react';
const Button = ({value, onClick}) => (
<button
style={{
marginLeft:'4px',
}}
type='button'
onClick={onClick}
>
{value}
</button>
);
export default Button;
<file_sep>/src/redux/cvdata/actions.js
import {
CVDATA_REQUESTED,
CVDATA_FAILED,
CVDATA_SUCCESS,
} from './constants';
export const cvDataRequested = () => ({
type: CVDATA_REQUESTED,
});
export const cvDataFailed = (errorMessage) => ({
type: CVDATA_FAILED,
errorMessage,
});
export const cvDataSuccess = ({ months, totalCommission, totalRetail, commissionVolume, totalBonusPaid }) => ({
type: CVDATA_SUCCESS,
months,
totalCommission,
totalRetail,
commissionVolume,
totalBonusPaid,
});
<file_sep>/src/redux/cvdata/constants.js
export const CVDATA_REQUESTED = 'CVDATA_REQUESTED';
export const CVDATA_FAILED = 'CVDATA_FAILED';
export const CVDATA_SUCCESS = 'CVDATA_SUCCESS';
<file_sep>/src/redux/cvdata/reducer.js
import {
CVDATA_REQUESTED,
CVDATA_FAILED,
CVDATA_SUCCESS,
} from './constants';
import round from 'lodash/round';
const initialState = {
loading: true,
errorMessage: '',
months: [],
totalRetail: 0,
totalCommission: 0,
totalCommissionVolume: 0,
totalBonusPaid: 0,
}
export const cvdata = (state = initialState, action) => {
switch (action.type) {
case CVDATA_SUCCESS:
return {
...state,
loading: false,
months: action.months,
totalRetail: round(action.totalRetail, 2),
totalCommission: {
total: round(action.totalCommission.total, 2),
percentages: {
...action.totalCommission.percentages,
},
},
totalCommissionVolume: {
total: round(action.commissionVolume.total, 2),
percentages: {
...action.commissionVolume.percentages,
},
},
totalBonusPaid: round(action.totalBonusPaid, 2),
errorMessage: '',
};
case CVDATA_FAILED:
return {
...state,
loading: false,
months: [],
totalRetail: 0,
totalCommission: 0,
totalCommissionVolume: 0,
totalBonusPaid: 0,
errorMessage: action.errorMessage,
};
case CVDATA_REQUESTED:
return {
...state,
loading: true,
months: [],
totalRetail: 0,
totalCommission: 0,
totalCommissionVolume: 0,
totalBonusPaid: 0,
errorMessage: '',
};
default:
return state;
}
}<file_sep>/README.md
# PremierTools
Charts & Graphs for [PremierDesigns.com](http://www.premierdesigns.com/) Jewelers.
Install [Tampermonkey](https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=en) in Chrome, then install the script in `dist/tampermonkey.js`
<file_sep>/src/modules/charts/containers/MonthlyCommissionsAndParties.jsx
import { connect } from 'react-redux';
import MonthlyPartyProfitChart from '../components/MonthlyPartyProfitChart.jsx';
import { getWidth } from '../../../redux/browser/selectors';
const mapStateToProps = state => ({
data: state.cvdata.months,
width: getWidth(state),
});
const MonthlyCommissionsAndParties = connect(mapStateToProps)(MonthlyPartyProfitChart);
export default MonthlyCommissionsAndParties;
<file_sep>/src/redux/index.js
import { cvdata } from './cvdata/reducer';
import { dateRange } from './dateRange/reducer';
import { jeweler } from './jeweler/reducer';
import { combineReducers } from 'redux';
import { createResponsiveStateReducer } from 'redux-responsive'
const rootReducer = combineReducers({
cvdata,
dateRange,
jeweler,
browser: createResponsiveStateReducer(null, {
extraFields: () => ({
width: window.innerWidth,
}),
})
});
export default rootReducer;<file_sep>/src/redux/cvdata/storage.js
// Side effects Services
export function getCachedData(key) {
return JSON.parse(localStorage.getItem(key))
}
export function setCachedData(key, value) {
localStorage.setItem(key, JSON.stringify(value))
}
<file_sep>/src/redux/jeweler/constants.js
export const JEWELER_SET_ID = 'JEWELER_SET_ID';
<file_sep>/src/redux/dateRange/actions.js
import {
DATERANGE_DATE_CHANGED,
} from './constants';
export const dateRangeChanged = (year, month, id) => ({
type: DATERANGE_DATE_CHANGED,
year,
month,
id,
});
<file_sep>/src/modules/charts/components/MonthlyPartyProfitChart.jsx
import React from 'react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';
const PartyProfitChart = ({ data, width }) => (
<BarChart
width={width} height={width / 2} data={data}
margin={{top: 20, right: 30, left: 20, bottom: 5}}
>
<XAxis dataKey="month"/>
<YAxis yAxisId="left" orientation="left" stroke="#49B9BB"/>
<YAxis yAxisId="right" orientation="right" stroke="#e74491"/>
<CartesianGrid strokeDasharray="3 3"/>
<Tooltip/>
<Legend />
<Bar yAxisId="left" dataKey="retail" name="commission" fill="#49B9BB" />
<Bar yAxisId="right" dataKey="parties" fill="#e74491" />
</BarChart>
);
export default PartyProfitChart;
<file_sep>/src/modules/common/components/TitleLine.jsx
import React from 'react';
const style = {
height: '1px',
backgroundColor: '#333',
};
const TitleLine = () => (
<div style={style} />
);
export default TitleLine;
<file_sep>/src/redux/dateRange/constants.js
export const DATERANGE_DATE_CHANGED = 'DATERANGE_DATE_CHANGED';
<file_sep>/src/redux/jeweler/actions.js
import {
JEWELER_SET_ID
} from './constants';
export const setJewelerId = (id) => ({
type: JEWELER_SET_ID,
id,
});
<file_sep>/src/modules/common/components/DateRangePicker.jsx
import React from 'react';
import Picker from 'react-month-picker';
import 'react-month-picker/css/month-picker.css';
let pickerLang = {
months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
from: 'From',
to: 'To'
};
let makeText = m => {
if (m && m.year && m.month) return (pickerLang.months[m.month-1] + '. ' + m.year)
return '?'
}
const style = {
backgroundColor: '#ddd',
border: '1px solid #ccc',
cursor: 'pointer',
padding: '4px',
};
const DateRangePicker = ({title, from, to, dateChanged, onDismiss}) => {
let picker = null;
return (
<div
style={{
display: 'inline-block',
}}
>
<label>{title}</label>
<div className="edit">
<Picker
ref={(input) => { picker = input; }}
range={{ from, to }}
lang={pickerLang}
theme="light"
onDismiss={onDismiss}
onChange={(year, month, id) => {
dateChanged(year, month, id);
// if (id > 0) {
// picker.dismiss();
// }
}}
>
<div onClick={() => picker.show()} style={style}>
{makeText(from) + ' ~ ' + makeText(to)}
</div>
</Picker>
</div>
</div>
);
};
export default DateRangePicker;
|
082431910a7b0ab14b2d2ea550237962a66d372e
|
[
"JavaScript",
"Markdown"
] | 17 |
JavaScript
|
BrandonBoone/PremierTools
|
7475e863cb189dac0ada6d6991d0f5106a593b18
|
6e0219b6b0da8ac8a940b33aa3c58000e85717ac
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.