branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>mumium/mumium.github.io<file_sep>/1-resources.html
---
layout: page
title: Resources
description: "独乐乐不如众乐乐"
header-img: "img/home-bg.jpg"
---
<div class="zh post-container">
<!--copied from markdown -->
<blockquote><p>电影、电视剧、动漫的资源分享,点击超链接即可下载种子(持续更新中~)<br>
这里有什么基于我想看什么<br>字幕文件相信大家都能找到,这里就不分享了(如果实在找不到也可以给我发邮件嗷~🙈)</p></blockquote>
<h3 id="toc_0">电影</h3>
<ul>
<li><a href="{{site.baseurl}}/files/千与千寻.Spirited.Away.2001.BD1080P.X264.AC3.Mandarin.torrent">【千与千寻-Spirited.Away-1080p-国语日语双音轨】</a></li>
<li><a href="{{site.baseurl}}/files/Frozen.II.2019.2160p.BluRay.x265.10bit.SDR.DTS-HD.MA.TrueHD.7.1.Atmos-SWTYBLZ.torrent">【冰雪奇缘2-Frozen.II-4k】</a></li>
<li><a href="{{site.baseurl}}/files/[LoliHouse] Tenki No Ko [BDRip 1920x1080 HEVC-10bit FLAC PGS(chs,eng,jpn)].torrent">【天气之子-Tenki No Ko-1080p】</a></li>
<li><a href="{{site.baseurl}}/files/Godzilla.King.of.the.Monsters.2019.BD1080P.X264.AAC.English.CHS-ENG.Mp4Ba.torrent">【哥斯拉2:怪兽之王-Godzilla.King.of.the.Monsters-1080p】</a></li>
<li><a href="{{site.baseurl}}/files/Leon.The.Professional.1994.REMASTERED.EXTENDED.1080p.BluRay.H264.AAC-RARBG.torrent">【这个杀手不太冷-Leon.The.Professional-1080p】</a></li>
<li><a href="{{site.baseurl}}/files/Birds.of.Prey.And.the.Fantabulous.Emancipation.of.One.Harley.Quinn.2020.HD1080P.X264.AAC.English.CHS-ENG.torrent">【猛禽小队和哈莉·奎茵-1080p】</a></li>
</ul>
<h3 id="toc_1">电视剧</h3>
<ul>
<li><a href="{{site.baseurl}}/files/民初奇人传.EP13-14.2020.1080p.国语中字.WEBrip.H265.mp4.torrent">【民初奇人传-EP13-14-1080p】</a></li>
<li><a href="{{site.baseurl}}/files/The.Eight.EP11-12.2020.1080p.WEB-DL.x264.AAC-HQC.torrent">【民初奇人传-EP11-12-1080p】</a></li>
<li><a href="{{site.baseurl}}/files/The.Eight.EP01-10.2020.1080p.WEB-DL.x264.AAC-HQC.torrent">【民初奇人传-EP01-10-1080p】</a></li>
<li><a href="{{site.baseurl}}/files/神盾局特工.第七季.S07E04.1080p.中英字幕.WEBrip.H265.mp4.torrent">【神盾局特工第七季4-Marvels.Agents.of.S.H.I.E.L.D.S07E04-1080p】</a></li>
<li><a href="{{site.baseurl}}/files/西部世界.Westworld.S1-3季全.无删减.中英双语.BD1080p.torrent">【西部世界S1-3季无删减-Westworld.S1-3-1080p】</a></li>
<li><a href="{{site.baseurl}}/files/The.Witcher.S01.1080p.NF.WEB.DDP5.1.x264-NTb[rartv].torrent">【巫师第一季-The.Witcher.S01-1080p】</a></li>
<li><a href="{{site.baseurl}}/files/Titans.S01.1080p.BluRay.x264-TURMOiL[rartv].torrent">【泰坦第一季-Titans.S01-1080p】</a></li>
<li><a href="{{site.baseurl}}/files/Space.Force.S01.1080p.NF.WEBRip.DDP5.1.Atmos.x264-MIXED[rartv].torrent">【太空部队第一季-Space.Force.S01-1080p】</a></li>
</ul>
<h3 id="toc_2">动漫</h3>
<ul>
<li><a href="{{site.baseurl}}/files/[GM-Team][国漫][一人之下 第3季][The Outcast 3rd Season][2020][01-08 Fin][AVC][GB][1080P].torrent">【一人之下第三季-The Outcast 3rd Season-1080p】</a></li>
</ul>
<hr>
<small> <font color="a0a9a9">
<b>特别说明:</b>
<li>资源从互联网上获取,请勿二次传播,侵权删除。</li>
<li>需要什么资源可以邮箱联系我,我尽力寻找🐶。</li>
</font>
<small>
</div><file_sep>/_posts/2020-06-19-尝试建立图床.md
---
layout: post
title: 尝试建立图床
subtitle: 图床建立的关键点总结
date: 2020-06-19
author: Unique_缪缪
header-img: img/post-bg-map.jpg
catalog: true
tags:
- 设计心得
---
# 要点
* GitHub可以用作图床的建立,拥有免费、开源的优点,且GitHub被微软收购后颇具稳定(不会删库跑路)
* 需要遵守官方条例,上传流量不可过大,不可滥用
* 图床依托于开源工具picgo,需要在GitHub个人设置中生成访问令牌密钥,地址为:https://github.com/settings/tokens,**注意保存,密钥只会显示一次!**
* picgo不能上传png文件,服务器会报错(晚上试了试,貌似可以上传了,但直接粘贴不会粘贴URL,而是本地链接,需要手动复制URL!)
# 过程
首先下载[picgo](https://github.com/Molunerfinn/PicGo/releases)(选择exe文件,win平台),安装后配置Github图床
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/qq%E6%88%AA%E5%9B%BE20200619113426.jpg" style="zoom:67%;" />
* 仓库名格式为 *username/repositoryname* ,注意repositoryname中不能有空格,系统会自动将空格用“-”代替。
* 分支名默认为 *master*
* Token中填入在GitHub个人设置中申请的访问令牌密钥,注意保存,密钥只会显示一次!
* 存储路径可以填 *img/*,系统会自动在仓库中生成img文件夹
* 自定义域名用于自定义图片链接
点击确定,设置为默认图床,即可上传图片。
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200619110423.jpg" style="zoom:67%;" />
可将图片直接拖入框中即可上传至仓库,上传后自动复制图片的URL,直接粘贴至文章中即可,可以选择多种格式,markdown格式如此篇文章所示。
注意图片不能为PNG格式,否则不能上传,服务器会报错

# 总结
picgo+GitHub建立图床的方式较为简单,且使用免费,但系统中还存在许多漏洞与不足。目前已知问题如下:
* 上传图片在相册中不显示缩略图
* 文件名中有大写字母的文件显示上传失败,但在仓库中仍能找到
* URL复制到文章中不显示图片(也许是Typora的问题)
* 在picgo相册中删除图片后,仓库中没有删除<file_sep>/_posts/2020-07-20-Markdown基本语法.md
---
layout: post
title: Markdown基本语法
subtitle: 转载简书高鸿祥的MD语法总结
date: 2020-07-20
author: 高鸿祥
header-img: img/post-bg-recitewords.jpg
catalog: true
tags:
- 转载
---
Markdown是一种纯文本格式的标记语言。通过简单的标记语法,它可以使普通文本内容具有一定的格式。
相比WYSIWYG编辑器
**优点:**
1、因为是纯文本,所以只要支持Markdown的地方都能获得一样的编辑效果,可以让作者摆脱排版的困扰,专心写作。
2、操作简单。比如:WYSIWYG编辑时标记个标题,先选中内容,再点击导航栏的标题按钮,选择几级标题。要三个步骤。而Markdown只需要在标题内容前加#即可
**缺点:**
1、需要记一些语法(当然,是很简单。五分钟学会)。
2、有些平台不支持Markdown编辑模式。
还好,简书是支持Markdown编辑模式的。
```
开启方式:设置->默认编辑器->Markdown编辑器
```
# 一、标题
在想要设置为标题的文字前面加#来表示
一个#是一级标题,二个#是二级标题,以此类推。支持六级标题。
注:标准语法一般在#后跟个空格再写文字,貌似简书不加空格也行。
示例:
```
# 这是一级标题
## 这是二级标题
### 这是三级标题
#### 这是四级标题
##### 这是五级标题
###### 这是六级标题
```
效果如下:
# 这是一级标题
## 这是二级标题
### 这是三级标题
#### 这是四级标题
##### 这是五级标题
###### 这是六级标题
------
# 二、字体
- ##### 加粗
要加粗的文字左右分别用两个*号包起来
- ##### 斜体
要倾斜的文字左右分别用一个*号包起来
- ##### 斜体加粗
要倾斜和加粗的文字左右分别用三个*号包起来
- ##### 删除线
要加删除线的文字左右分别用两个~~号包起来
示例:
```
**这是加粗的文字**
*这是倾斜的文字*`
***这是斜体加粗的文字***
~~这是加删除线的文字~~
```
效果如下:
**这是加粗的文字**
*这是倾斜的文字*
***这是斜体加粗的文字\***
~~这是加删除线的文字~~
------
# 三、引用
在引用的文字前加>即可。引用也可以嵌套,如加两个>>三个>>>
n个...
貌似可以一直加下去,但没神马卵用
示例:
```
>这是引用的内容
>>这是引用的内容
>>>>>>>>>>这是引用的内容
```
效果如下:
> 这是引用的内容
>
> > 这是引用的内容
> >
> > > > > > > > > > 这是引用的内容
# 四、分割线
三个或者三个以上的 - 或者 * 都可以。
示例:
```
---
----
***
*****
```
效果如下:
可以看到,显示效果是一样的。
------
------
------
------
# 五、图片
语法:
```

图片alt就是显示在图片下面的文字,相当于对图片内容的解释。
图片title是图片的标题,当鼠标移到图片上时显示的内容。title可加可不加
```
示例:
```

```
效果如下:

blockchain
**上传本地图片直接点击导航栏的图片标志,选择图片即可**
markdown格式追求的是简单、多平台统一。那么图片的存储就是一个问题,需要用图床,提供统一的外链,这样就不用在不同的平台去处理图片的问题了。才能做到书写一次,各处使用。
关于图床的选择我写了一篇文章,对网上存在的各种方法做了总结,需要的朋友可以看看。[markdown图床](https://www.jianshu.com/p/ea1eb11db63f)
# 六、超链接
语法:
```
[超链接名](超链接地址 "超链接title")
title可加可不加
```
示例:
```
[简书](http://jianshu.com)
[百度](http://baidu.com)
```
效果如下:
[简书](https://www.jianshu.com/u/1f5ac0cf6a8b)
[百度](https://links.jianshu.com/go?to=http%3A%2F%2Fbaidu.com)
注:Markdown本身语法不支持链接在新页面中打开,貌似简书做了处理,是可以的。别的平台可能就不行了,如果想要在新页面中打开的话可以用html语言的a标签代替。
```
<a href="超链接地址" target="_blank">超链接名</a>
示例
<a href="https://www.jianshu.com/u/1f5ac0cf6a8b" target="_blank">简书</a>
```
------
# 七、列表
##### 无序列表
语法:
无序列表用 - + * 任何一种都可以
```
- 列表内容
+ 列表内容
* 列表内容
注意:- + * 跟内容之间都要有一个空格
```
效果如下:
- 列表内容
- 列表内容
- 列表内容
##### 有序列表
语法:
数字加点
```
1. 列表内容
2. 列表内容
3. 列表内容
注意:序号跟内容之间要有空格
```
效果如下:
1. 列表内容
2. 列表内容
3. 列表内容
##### 列表嵌套
**上一级和下一级之间敲三个空格即可**
- 一级无序列表内容
- 二级无序列表内容
- 二级无序列表内容
- 二级无序列表内容
- 一级无序列表内容
1. 二级有序列表内容
2. 二级有序列表内容
3. 二级有序列表内容
1. 一级有序列表内容
- 二级无序列表内容
- 二级无序列表内容
- 二级无序列表内容
2. 一级有序列表内容
1. 二级有序列表内容
2. 二级有序列表内容
3. 二级有序列表内容
------
# 八、表格
语法:
```
表头|表头|表头
---|:--:|---:
内容|内容|内容
内容|内容|内容
第二行分割表头和内容。
- 有一个就行,为了对齐,多加了几个
文字默认居左
-两边加:表示文字居中
-右边加:表示文字居右
注:原生的语法两边都要用 | 包起来。此处省略
```
示例:
```
姓名|技能|排行
--|:--:|--:
刘备|哭|大哥
关羽|打|二哥
张飞|骂|三弟
```
效果如下:
| 姓名 | 技能 | 排行 |
| ---- | :--: | ---: |
| 刘备 | 哭 | 大哥 |
| 关羽 | 打 | 二哥 |
| 张飞 | 骂 | 三弟 |
# 九、代码
语法:
单行代码:代码之间分别用一个反引号包起来
```
`代码内容`
```
代码块:代码之间分别用三个反引号包起来,且两边的反引号单独占一行
```
(```)
代码...
代码...
代码...
(```)
```
> 注:为了防止转译,前后三个反引号处加了小括号,实际是没有的。这里只是用来演示,实际中去掉两边小括号即可。
示例:
单行代码
```
`create database hero;`
```
代码块
```
(```)
function fun(){
echo "这是一句非常牛逼的代码";
}
fun();
(```)
```
效果如下:
单行代码
```
create database hero;
```
代码块
```
function fun(){
echo "这是一句非常牛逼的代码";
}
fun();
```
# 十、流程图
```
```flow
st=>start: 开始
op=>operation: My Operation
cond=>condition: Yes or No?
e=>end
st->op->cond
cond(yes)->e
cond(no)->op
&```
```
效果如下:
简书不支持流程图,所以截了个图

流程图.png
作者:高鸿祥
链接:https://www.jianshu.com/p/191d1e21f7ed/
来源:简书
<file_sep>/_posts/2020-07-20-一行代码复制百度文库文章.md
---
layout: post
title: 一行代码复制百度文库文章
subtitle: 用审查元素提取百度文库网页中的文字
date: 2020-07-20
author: Unique_缪缪
header-img: img/post-bg-hacker.jpg
catalog: false
tags:
- 求学旅程
---
最近有些人问我百度文库中的文章怎么免费复制,因为本人确实不喜欢百度的吃相,所以百度旗下的产品我从没给过一分钱= =
> 注:代码2020/7/20测试可用,对PDF等其他格式的文章无效,其他网站的文库内容不敢保证成功,有兴趣可以尝试
---
这里尝试破解下百度文库doc文档的复制限制,步骤如下:
1. 我们以一篇精品文章为例,首先打开你要复制的文章页面,右键选择“审查元素”(Chrome最新版中为“检查”,或按快捷键F12)

2. 在Console选项卡中输入以下代码:
`$('div.ie-fix').text()`
按下回车

可以看到输出结果中显示出了整篇文章,且文章中的段落格式完全保留,可以随意复制
---
此方法肯定不能永久使用,有更多需求的同学可以看看**冰点文库**,不仅doc,pdf、xlsx格式的文件都可以下载下来,但文本段落格式的保留非常感人,需要手动调整许久。<file_sep>/_posts/2020-06-15-博客建立总结.md
---
layout: post
title: 博客建立总结
subtitle: 关于博客建立的关键点总结
date: 2020-06-15
author: Unique_缪缪
header-img: img/post-bg-android.jpg
catalog: true
tags:
- 设计心得
---
# 要点
* Github Pages依托于repository name的内容,Settings中username.github.io的格式要严格,否则网页会404
* 根目录中不能放其他文件夹,会影响到导航的显示(cankao文件夹中的内容显示到了标题中,bug原因不明,目前修改为.cankao暂时解决)
* _config.yml中的description不知为何无法修改(修改后网页内容不更新),还需要向作者请教
* 文章中末尾有一个超链接按钮不知如何删除,且按钮不知为何消失了(此文章发布后发现按钮只是下一篇文章的超链。。我傻了)
* 首页中的Featured tags内容不见了,不知是不是因为目前文章只有一个标签的原因(看来是的,我是傻子。。。)
# 总结
总之,对于吾等小白来说,GitHub Pages建立简单的静态网页不需要太过深入的知识,以此博客为例,网页框架用BY大神现有的模板(从人造国际语处Fork而来,特此感谢!),只需要在文件中稍加修饰即可达到修改网页的目的。但学习途中对Github Desktop的使用也是非常关键的一环,如何从远程库同步到本地,或是从本地上传内容更新到网页上,都是比较基本的操作。熟练地使用Github Desktop后,就不需要在网页端GitHub上修改文件了,只需要掌握Push和Pull即可,这极大地提高了网页的建设效率。
<file_sep>/_posts/2020-06-19-毕业论文撰写技巧.md
---
layout: post
title: 毕业论文撰写技巧
subtitle: 关于我的本科毕业论文整理过程的总结
date: 2020-06-19
author: Unique_缪缪
header-img: img/post-bg-desk.jpg
catalog: true
tags:
- 求学旅程
---
本文主要梳理了我在撰写论文中遇到的、包括同学们向我请教的常见问题,以及一些应对学校学院要求的处理技巧。由于只是我个人的想法,在很多地方的叙述都不全面,化学院的论文细则每年又有所不同,具体实施方案仍需参考**《XXXX届郑州大学化学学院的本科毕业论文实施细则》**(细则有时候也不一定准= =)
**由于我的论文采用Word撰写,以下说明描述都以office2019版本为准。**(WPS我也不会用🙈)
本文将对论文中每一部分的要点进行说明,如有遗漏,希望大家能够联系我进行补充😁
----
### 要点
* 原则上论文装订顺序如下:封面、目录、中英文摘要、正文(包含绪论、总结)、参考文献、致谢、论文翻译原文、论文翻译、表1-8(如申请优秀论文还有其他表)、简洁版论文查重报告。文章中的字体段落、页边距等格式要求以当年细则为准,这里不再赘述。
#### 页码
页码添加本身十分简单,但我们的细则要求页码从正文(绪论)开始计数,且目录部分要单独加入**罗马数字**的页码。到今天为止,已经有大概10个人向我询问如何分开加页码的问题,这里详细说明一下。
在分区加页码前,我们需要对论文进行**“分节“**。不同节之间在**不**选择”链接到上一节“的情况下页眉、页脚、页码互相独立。在”布局“选项卡中,选择”分隔符“按钮,可以看到不同类型的分节符,他们起到的作用相同,但适用于不同的场景,我习惯使用“下一页”,点击后,即可在当前光标位置加入一个分节符。
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200619184951.png" style="zoom:67%;" />
如图,”分节符(下一页)“表达的意思是:从下一页开始分节,如果你看不到分节符,在”开始“选项卡中点击这个符号:
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200619185747.png" style="zoom:67%;" />
或使用快捷键:Ctrl+*,来显示隐藏的标记符号。不只是分节符,空格符、和我们在文章中常用的分页符(添加分页符快捷键:Ctrl+Enter),都会显示出来,虽然有些凌乱,但这个按钮我基本一直开着,方便删除和修改分页符、分节符(分页符可以按退格键删除,分节符需要在首部按Delete删除)。
加入分节符后,符前符后分为两节,我们就可以分别设置页码了。但在添加页码后,你会发现两节的页码仍然是链接在一起的,这是因为”链接到前一节“这个按钮是默认开启的,我们需要手动关闭。
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200619190611.png" style="zoom:67%;" />
之后,即可在不同节下设置不同的页眉、页码。页码格式的设置,包括起始数字,设置为罗马计数等,都在”页码“按钮下的”设置页码格式“中调整。
#### 论文封面
学校有标准的模板,需要注意的是题目如果不长,不需要占用第二行的话需要将第二行下划线删除。同理,如果指导老师只有一位,需要将第二部分的内容删掉。原则上封面内容不许留有空白,且不加页码。但是否加页眉、日期填写等问题以学院通知为准。
#### 目录
Word中有比较方便的生成目录的工具,我发现有不少同学都没有用过,都在手动码目录🙈。。。这个功能在Word2019上方的“引用”选项卡中,点击一下即可生成。
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200619202603.png" style="zoom:67%;" />
不过在此之前需要让Word识别出哪些文字是标题,哪些不是。我们需要给各个标题**分配样式**,在“开始”选项卡中右键各个样式可以设置字体,段落等。
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200619191854.png" style="zoom:67%;" />
我们需要设置好标题(副标题)、章标题、节标题的样式,然后选中标题文字,点击相应的样式即可设置成相应级别的标题。需要注意的是,包括标题在内,我们学校要求数字和字母要用Times New Roman字体,在这些样式的英文格式中可以提前设置好字体,此后就不用费心修改了。
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200619192005.png" style="zoom:67%;" />
标题分配好后,即可生成目录。在后期的大量论文修改工作中,如无特殊需求,我们只需要点击“更新目录”中的“只更新页码”,即可不动标题,只对目录中的页码进行更新,而不需要再一个一个手动删除输入了🙊。
#### 摘要
中文、英文摘要包括论文标题、“摘 要:”字样(注意中间有两个空格)、摘要原文、关键词。这里主要注意原文和关键词之间要空出一行,中英文摘要分别在两页上,可用分页符分成两页。
#### 正文
这个就真帮不了你了,拼命水10000+字完事🙈
不过细则要求每章另起一页,我们可以通过加入分页符实现,和上文提到的那样,每一章末尾加入一个分页符(添加分页符快捷键:Ctrl+Enter),这样不管前面篇幅怎么变,下面的新章节永远是新起一页的。
#### 参考文献
知网、Endnote,都可以自动导出国标格式,各显神通吧!
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200619193037.png" style="zoom:67%;" />
在知网文献界面点击导出即可导出引用标准格式
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200619193330.png" style="zoom:67%;" />
在Word的Endnote插件中点击Insert Citation即可导出参考文献格式
#### 英文文献原文
这里的英文原文我建议以图片的形式插入,直接粘贴原文会出现各种各样的格式和排版问题,将PDF导出jpg图片解千愁,这里我用的是Adobe acrobat,PDF编辑、分页、合并、转Word等功能比WPS好用不知多少倍,就是正版挺贵的,盗版也挺好找的🤪
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200619195223.png" style="zoom:67%;" />
#### 英文文献翻译
翻译工具我用的是copytranslator,这是Github上的一个开源项目,有能力的话可以去支持一下作者😁
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200619194758.png" style="zoom:67%;" />
这个工具集成了谷歌、百度、搜狗、有道、Bing等翻译引擎,选择拖拽复制、自动粘贴翻译是真的很好用!
#### 附表
各种附表需要扫描电子版,这里推荐两款APP,安卓推荐扫描全能王,iPhone推荐office lens,office lens对苹果镜头的优化貌似比安卓要好。。。
如果不放心扫描效果那就还是选择打印机,但这两款软件足够对付论文了。
### 总结
本文主要介绍了一些论文撰写的技巧,以及对各种工具的运用
技巧都是一些计算机使用的基本常识,工具都是一些我使用过后觉得不错的工具
大神可以无视,但希望能给小白提供一些帮助,在毕业的道路上少走一些弯路😁
之后我会考虑在本站的资源区内放一些好用的小工具,如果有什么想要的资源或有什么难题都可以联系我,我会随缘解答🙈
<file_sep>/js/time.js
// 利用时间对象获得 当前 时间
// var now = new Date();
var yearText = ['']
var monthText = ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"];
var dayText = ["一号", "二号", "三号", "四号", "五号", "六号", "七号", "八号", "九号", "十号", "十一号", "十二号", "十三号", "十四号", "十五号", "十六号", "十七号", "十八号", "十九号", "二十号", "二十一号", "二十二号", "二十三号", "二十四号", "二十五号", "二十六号", "二十七号", "二十八号", "二十九号", "三十号", "三十一号"];
var weekText = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
var hourText = ["零点", "一点", "两点", "三点", "四点", "五点", "六点", "七点", "八点", "九点", "十点", "十一点", "十二点", "十三点", "十四点", "十五点", "十六点", "十七点", "十八点", "十九点", "二十点", "二十一点", "二十二点", "二十三点"];
var minuteText = ["零分", "一分", "二分", "三分", "四分", "五分", "六分", "七分", "八分", "九分", "十分",
"十一分", "十二分", "十三分", "十四分", "十五分", "十六分", "十七分", "十八分", "十九分", "二十分",
"二十一分", "二十二分", "二十三分", "二十四分", "二十五分", "二十六分", "二十七分", "二十八分", "二十九分", "三十分",
"三十一分", "三十二分", "三十三分", "三十四分", "三十五分", "三十六分", "三十七分", "三十八分", "三十九分", "四十分",
"四十一分", "四十二分", "四十三分", "四十四分", "四十五分", "四十六分", "四十七分", "四十八分", "四十九分", "五十分",
"五十一分", "五十二分", "五十三分", "五十四分", "五十五分", "五十六分", "五十七分", "五十八分", "五十九分"];
var secondsText = ["一秒", "二秒", "三秒", "四秒", "五秒", "六秒", "七秒", "八秒", "九秒", "十秒",
"十一秒", "十二秒", "十三秒", "十四秒", "十五秒", "十六秒", "十七秒", "十八秒", "十九秒", "二十秒",
"二十一秒", "二十二秒", "二十三秒", "二十四秒", "二十五秒", "二十六秒", "二十七秒", "二十八秒", "二十九秒", "三十秒",
"三十一秒", "三十二秒", "三十三秒", "三十四秒", "三十五秒", "三十六秒", "三十七秒", "三十八秒", "三十九秒", "四十秒",
"四十一秒", "四十二秒", "四十三秒", "四十四秒", "四十五秒", "四十六秒", "四十七秒", "四十八秒", "四十九秒", "五十秒",
"五十一秒", "五十二秒", "五十三秒", "五十四秒", "五十五秒", "五十六秒", "五十七秒", "五十八秒", "五十九秒", "六十秒"];
var clock;
var yearList = [];
var monthList = [];
var dayList = [];
var weekList = [];
var hourList = [];
var minuteList = [];
var secondsList = [];
/**
* 分析,完成效果:
* 1. 实现时钟排列
*
* 步骤:
* 1. 初始化,渲染dom
* 2. 实现随着时间高亮
* 3. 添加动画,使之移动
*/
var textList = [
[yearText, yearList],
[monthText, monthList],
[dayText, dayList],
[weekText, weekList],
[hourText, hourList],
[minuteText, minuteList],
[secondsText, secondsList],
]
window.onload = function () {
init();
setTimeout(function () {
initTransition();
}, 0)
setTimeout(function () {
var timeArr = [0, 0, 0, 0, 0, 0, 0]
rotateTransition(timeArr)
setInterval(function () {
runtime()
}, 1000)
}, 1000)
// setInterval(function () {
// runtime()
// }, 100)
};
// 初始化函数
// function init() {
// clock = document.getElementById('clock');
// // 生成标签 存放文字展示
// for (var i = 0; i < textList.length; i++) {
// for (var j = 0; j < textList[i][0].length; j++) {
// var temp = createLabel(textList[i][0][j]);
// clock.appendChild(temp);
// // 将生成的标签存放在数组list中
// textList[i][1].push(temp);
// }
// }
// }
function init() {
clock = document.querySelector('#clock');
for (var i in textList) {
for (var j in textList[i][0]) {
var temp = createLabel(textList[i][0][j]);
// 将生成的标签存放在数组list中
clock.appendChild(temp);
textList[i][1].push(temp);
}
}
console.log(textList);
}
// 创建标签并将文字填充标签内 接收参数为文字内容
function createLabel(text) {
var div = document.createElement('div');
div.classList.add('label');
div.innerText = text;
return div;
}
// 获得时间
function runtime() {
var now = new Date();
// 获得月 日期 小时 分钟 秒钟
var month = now.getMonth();
var day = now.getDate();
var week = now.getDay();
var hour = now.getHours();
var minute = now.getMinutes();
var seconds = now.getSeconds();
var timeArr = [0, month, day-1, week, hour, minute, seconds]
console.log(timeArr)
clearColor();
rotateTransition(timeArr);
addColor(timeArr);
}
// 为时间添加样式
function addColor(timeArr) {
// var label = document.querySelectorAll('.label')
// for (var i in timeArr) {
// var len = i > 1 ? textList[i - 1][0].length : 0;
// var num = timeArr[i];
// var index = len + num;
// label[index].classList.add('now')
// // console.log(label[index])
// }
for (var i = 1; i < timeArr.length; i++) {
var index = timeArr[i];
// for (var j = 0; j < timeArr.length; j++) {
// var temp = textList[i][1][j];
// // var deg = 360 / textList[i][0].length * j;
// var deg = 360 / textList[i][0].length * (j - timeArr[i]);
// temp.style.transform = temp.style.transform.replace(/-?\d+deg/, deg + 'deg');
// // console.log(temp)
// }
textList[i][1][index].classList.add('now')
}
}
// 清除现在时间颜色
function clearColor() {
var now = document.querySelectorAll('.now');
now.forEach(function (item) {
item.classList.remove('now');
})
}
// 初始展开
function initTransition() {
for (var i in textList) {
for (var item of textList[i][1]) {
item.style.transform = 'translate(' + i * 80 + 'px,-50%)'
item.style.transformOrigin = -(i * 80) + 'px 50%';
}
}
}
// 扇形展开
function rotateTransition(timeArr) {
for (var i in textList) {
for (var j in textList[i][1]) {
var temp = textList[i][1][j];
var deg = 360 / textList[i][0].length * (j - timeArr[i]);
temp.style.transform = 'translate(' + i * 80 + 'px,-50%)' + ' rotate(' + deg + 'deg)';
}
}
}<file_sep>/_posts/2020-06-25-JavaScript的调用.md
---
layout: post
title: JavaScript的调用
subtitle: 在静态网页中调用JavaScript脚本
date: 2020-06-25
author: Unique_缪缪
header-img: img/post-bg-keybord.jpg
catalog: false
tags:
- 设计心得
---
偶尔在知乎上看到了[3D-元素周期表](https://mumium.github.io/3d-periodic-table.html),效果十分酷炫。
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200625121659.png" style="zoom:67%;" />
可以选择4种元素排列形式,过渡动画十分细腻流畅,于是玩了好久🙈,我已经将其放在我的博客下,想玩的同学可以点击上方的超链接进入,而且手机端也可以玩。
---
然后简单研究了一下,里面的特效依托于4个JavaScript脚本:
*three.min.js*
*tween.min.js*
*TrackballControls.js*
*CSS3DRenderer.js*
[three.js](https://github.com/mrdoob/three.js/) 是JavaScript编写的WebGL第三方库,是HTML中的3D引擎,可以实现在浏览器中运行三维场景,也是GitHub中的开源项目,作者为mrdoob。
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200625121108.png" style="zoom:67%;" />
于是尝试把这个周期表放到博客主页上,本以为找到4个js文件,添加代码就能完成的简单工作,没想到遇到了许多麻烦= =
### 工作流程
首先寻找源代码和4个js文件,辗转了许久后发现有不少人已经把源码挂在了GitHub上,且都是中文索引的。
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/20200625121217.png" style="zoom:67%;" />
于是随便找了一个fork,得到想要的东西后,将4个js文件放到博客js文件夹下,将源码稍加修改放到根目录下。我最初的想法是在博客首页专门添加一个菜单,将周期表放在菜单链接的新网页中,但随后碰到了数个问题:
* html文件放在根目录下无法生成菜单
解:需要符合菜单的格式,加上模板代码后成功生成
* 进入页面后,发现页面保留了头部背景图、大标题和底部版权文字,无法显示3D模块
解:目测是模板代码的样式问题,新建立了一个nulldefault的页面样式,将背景图、底部文字的部分代码去除后,用此样式替换原样式,提交后查看效果,果然除了页面标题,其余只剩下了黑乎乎一片,但还是不能显示3D模块
* 3D模块不能显示,推测是代码中相对路径书写错误,或博客页面默认不能加载JavaScript两种情况。
解:GitHub中其他人的代码路径也是同样的书写方式,可以加载模块,所以不是相对路径的问题。
那问题的关键应该是博客模板不能加载JavaScript。于是放弃在首页增加菜单的方式,改用超链接在本地链接静态网页。
尝试之后JavaScript加载成功,点击首页这里就可以进入:
<img src="https://raw.githubusercontent.com/mumium/picture-bed/master/img/QQ%E6%88%AA%E5%9B%BE20200625162713.png" style="zoom:67%;" />
<file_sep>/_posts/2020-06-19-markdown标题分级.md
---
layout: post
title: markdown标题分级
subtitle: 关于markdown语法在标题中的分级问题
date: 2020-06-19
author: Unique_缪缪
header-img: img/post-bg-hacker.jpg
catalog: true
tags:
- 设计心得
---
在写“毕业论文撰写技巧”的过程中,发现网页右侧生成的catalog中,主标题和副标题之间没有主次缩进的分别,排查好久后确定了我没有弄错标题的级别,#的数量是正确的。这时突然想到word中有“标题”、“副标题”、“标题1”、“标题2”…… 这样的级别逻辑中,标题和副标题不参与分级,之后的标题才有主次之分。同理,在markdown的语法中,#对应标题,##对应副标题,###对应标题1。那么从###开始以后,标题才参与分级。于是采用###和####设置标题,果然catalog里出现了主次缩进,这个类比应该是合理的。
标题分级如下:
# 一级标题
## 二级标题
### 三级标题
#### 四级标题
##### 五级标题
###### 六级标题
如上所示,一级和二级标题下有分割线,且在Typora中,光标移动到三、四、五、六级标题处时,句首会出现h3、h4、h5、h6的字样,而在一级、二级标题中没有出现,由此得知一级、二级标题与其他分级标题有所不同。
由右侧的catalog所示,一二三级标题同一缩进,四五六级同一缩进,这应该是博客模板默认设置。
可见,在以后写文章时,如要使用缩进catalog,只能用三级四级标题进行区分。
| 2d21f00b9e4035924a06ca75182e4083b35f5dc2 | [
"Markdown",
"JavaScript",
"HTML"
] | 9 | HTML | mumium/mumium.github.io | 9d1f239da10e873ce73e261f56340a3d4dd78f27 | 30d190bb8dd2f833a1b07ec4a4337620e3ff6a55 | |
refs/heads/main | <file_sep>import sys
sys.meta_path
print(sys.path)<file_sep>---
instructor: <NAME>
email: <EMAIL>
location: Online, Room WEB
time: Thursday 06:00PM - 09:25PM
office hour: By Appointment
---
# DS-620 - Data Visualization
## Course Description
Visualization concerns the graphical depiction of data and information in order to communicate its contents and reveal patterns inherent in the data. It is sometimes referred to as visual data mining, or visual analytics.
Data visualization has become a rapidly evolving science. This course explores the underlying theory and practical concepts in creating visual representations of large amounts of data. Topics covered include
- data representation
- information visualization
- real-time visualization
- visualization toolkits including Tableau and their applications to diverse data rich contexts.
At the end of the course, the student will be able to present meaningful information in the most compelling and consumable fashion.
## Prerequisites
This course requires following courses to be taken before this course.
- Introduction to Data Science (DS-510)
- Data Analysis and Decision Modeling (DS-520)
## Learning Outcomes
This course aims to teach you the following concepts.
- Understanding basics of data visualization, including data visualization abstractions, data types,
- Ability to make decision on which data charts are best on different data types
- Data visualization with python using well-known packages, matplotlib, seaborn, etc
- Comprehensive overview of data visualization softwares
- Ability to use Tableau to create dynamic, user-friendly dashboards
## Textbooks & Tools
[Visualization Analysis and Design](https://www.routledge.com/Visualization-Analysis-and-Design/Munzner/p/book/9781466508910) by <NAME>.
``` yml
Title: Visualization Analysis and Design
Author(s): <NAME>
Release date: December 1, 2014
Publisher(s): A K Peters/CRC Press
ISBN: 9781466508910
```
The website by Tamara Munzner also has great content about the book, check it out from [https://www.cs.ubc.ca/~tmm/vadbook/](https://www.cs.ubc.ca/~tmm/vadbook/).
[Handbook of Data Visualization](https://www.springer.com/gp/book/9783540330363) by <NAME>, <NAME>, <NAME>.
``` yml
Title: Handbook of Data Visualization
Author(s):
- <NAME>
- <NAME>
- <NAME>
Release date: 2008
Publisher(s): Springer-Verlag Berlin Heidelberg
ISBN: 978-3-540-33037-0
```
## Course Outline
Below are the distribution of content and assignments for the semester.
| Week | Tasks | Description |
| ------- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| Week 01 | Assignment0 | VAD Chapter 1. What's Vis, and Why Do It? |
| Week 02 | Assignment1 | Theoretical Intro (Types of Charts, etc.) and Viz with Python 1 (matplotlib, pandas, seaborn) |
| Week 03 | Assignment2 | VAD Chapter 2. What: Data Abstraction, Chapter 3. Why: Task Abstraction and Viz with Python 2 (plotly, bokeh, networkx) |
| Week 04 | | VAD Chapter 4. Validation, Chapter 5. Marks and Channels, Chapter 6. Rules of Thumb, Visualization Tools (Tableau, Qlik, Lookup, etc.) |
| Week 05 | Assignment3 | VAD Chapter 7. Arrange Tables, Chapter 10. Map Color and Other Channels, Tableau 1 |
| Week 06 | Final Project Start | VAD Chapter 8. Arrange Spatial Data, Chapter 9. Arrange Networks, Tableau 2 |
| Week 07 | Midterm | Midterm (VAD Chapters), FP Session 1 |
| Week 08 | | Solving all assignments in class, FP Session 2 |
| Week 09 | | Tableau 3, FP Session 3 |
| Week 10 | | Tableau 4, FP Session 4 |
| Week 11 | Final Project End | Final Project Presentations, What's Next |
## Grade Determination
The items that student is responsible for this class is the following. Students will be graded according to this chart.
| Item | Percentage |
| ------------- | ---------- |
| Assignments | 30 % |
| Projects | 30 % |
| Exam | 30 % |
| Participation | 10 % |
| Bonus (Maybe) | 10 % |
Partication means attending to discussions in Blackboard, class sessions, etc.
<sub> Above list is subject to change. </sub>
## Grade Scale
Based on the [Grade Determination](#grade-determination), a final letter grade will be assigned to student based on the following scale.
| Min | Max | Grade |
| --- | --- | ----- |
| 94 | 100 | A |
| 87 | 92 | A- |
| 83 | 86 | B+ |
| 80 | 82 | B |
| 77 | 79 | B- |
| 73 | 76 | C+ |
| 60 | 72 | C |
| 0 | 59 | F |
## Attendence Policy
Due to COVID-19, there is no restriction on attending the lecture, however, attending the classes will benefit on your learning curve a lot more instead of watching lectures online. As said, here are the guides:
- We record the classes and you can always revisit or watch previous classes. Links will be shared.
- When attending to class, please keep your **camera on** and your **microphone off**.
## Academic Honesty and Student Conduct
Students need to submit **only their own original work** (e.g. Code, PPT, figures, visualizations…). Student need to familiarize themselves with the academic rules of the University. In case a student is found guilty under the act of plagiarism, his/her test or assignment will be graded zero.
If plagiarism occurs twice, student will receive ‘F’ grade with immediate effect. It is expected that everybody turns off/mute all devices that emit sounds and noises that may interrupt the class (e.g. mobile phones, pagers, watch alarms). If an occasion arises, in which a student may need to leave the class to receive a phone call (important call), use rest room or get drinking water, he or she should silently walk out without disturbing rest of the class.
Working on assignments and project work, that belongs to another course is **STRICTLY NOT ALLOWED**.
Copying your colleagues code is **STRICTLY NOT ALLOWED**. All submissions will be submitted to autodetection plagiarism tool that our university provides!
## Agreement between You and the Instructor
I certify that in this course, my contribution and assignments will be my own work, based on my personal study and/or research and that I am acknowledging all material and sources will be used in its preparation, whether they be books, articles, reports, lecture notes, and any other kind of document, electronic or personal communication.
I also certify that that in this course, the assignments I will be submitting will not previously been submitted for assessment in any other unit, except where specific permission has been granted from all unit coordinators involved, or at any other time in this unit, and that I have not copied in part or whole or otherwise plagiarized the work of other students and/or persons.
| Student | | Instructor | |
| -------------- | ----------------------------------------- | ----------------- | ----------------------------------------- |
| Student's Name | ......................................... | Instructor's Name | ......................................... |
| Signature | ......................................... | Signature | ......................................... |
## References
Useful links regarding university.
- Check out more information about the prerequisites on [curriculum of the SPU's data science](https://www.saintpeters.edu/academics/graduate-programs/master-of-science-in-data-science/curriculum/).
- Additional information about this class can be found on [SPU's website](https://spiritonline.saintpeters.edu/), which requires student's login.
- Blackboard Classroom [DS-620-DLSO-21SPTR: Data Visualization](https://saintpeters.blackboard.com/).
| 4ed09bbed46441d9554c6d5e3f43bcee4bb4b78a | [
"Markdown",
"Python"
] | 2 | Python | cestrada15/https-github.com-spu-dataviz-211-assignment-0-cestrada15 | 87f0824960bc42a5e6a84d96acc45a0343b7d223 | 6a46a20e626cfc9497e4295ab0d2b5bc870f06d9 | |
refs/heads/master | <file_sep>package com.ajulay;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
public class Server {
ServerSocket serverSocket = null;
private Vector<ClientHandler> clients;
public Server() {
try {
SQLHandler.connect();
serverSocket = new ServerSocket(8189);
clients = new Vector<ClientHandler>();
System.out.println("Server starting...");
while(true){
Socket socket = serverSocket.accept();
System.out.println("connect...");
new ClientHandler(this, socket);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
SQLHandler.disconnect();
}
}
public void broadcastMsg(String str){
for (ClientHandler cl: clients) {
cl.sendMsg(str);
}
}
public void unsubscribe(ClientHandler clientHandler){
clients.remove(clientHandler);
broadcastMsg(clientHandler.getNick() + " is off-line...");
}
public void subscribe(ClientHandler clientHandler){
broadcastMsg(clientHandler.getNick() + " is on-line...");
clients.add(clientHandler);
}
public boolean isNickIsBusy(String nick){
for (ClientHandler ch: clients) {
if (ch.getNick().equals(nick)) {
return true;
}
}
return false;}
public Vector<ClientHandler> getClients() {
return clients;
}
}
| 0a95cd4e270094a2abda7200e84dfb7b020e9c37 | [
"Java"
] | 1 | Java | Ajulay/JavaFXChat | 3ed19211bc39c02ce7934995d71661ab4cc1a37d | a54a6dc9e64ae32797a80a05973b147012b59cf5 | |
refs/heads/master | <repo_name>KevinDTran/js-deli-counter-cb-000<file_sep>/index.js
var katzDeli = [];
function takeANumber(line, name){
line.push(name)
return ("Welcome, " + name+ ". You are number " + line.length + " in line.")
}
function nowServing(line){
if (line.length > 0 ){
var first = line.shift()
return ("Currently serving " + first+ ".")
}
else{
return ("There is nobody waiting to be served!")
}
}
//takes a an array(line) and returns a message displaying the members of the line
//such as: "The line is currently: 1. Grace, 2. Kent, 3. Matz"
function currentLine (line){
var return_line = [],
new_line,
line_start = ("The line is currently:");
if (line.length > 0){
line.forEach(function(name){
return_line.push(" " +(line.indexOf(name)+1) + ". " + name)
})
new_line = line_start.concat(return_line)
return new_line
}
else {
return "The line is currently empty."
}
}
| 79dcc2446b1d0949607891137c314ff39d3aa1a1 | [
"JavaScript"
] | 1 | JavaScript | KevinDTran/js-deli-counter-cb-000 | 587126883145dada759f5001e56e9bf001412522 | 3d2215f97c93c65193eb9613c7987234fcc8ba36 | |
refs/heads/master | <file_sep>//
// message_extend.c
// mycoin
//
// Created by lx on 14-1-8.
// Copyright (c) 2014年 lx. All rights reserved.
//
#include "message_extend.h"
extern int read_raw_varint32(unsigned long *tag, void *_buffer, int offset);
enum message_type_t identify_message(void *_buffer, int start_offset){
unsigned long size;
unsigned long offset = read_raw_varint32(&size, _buffer, start_offset);
unsigned long tag = 0;
if(offset < size + offset) {
offset = read_raw_varint32(&tag, _buffer, offset);
tag = tag>>3;
if(tag == 1){
offset = read_raw_varint32(&tag, _buffer, offset);
return tag;
}
}
return UNKOWN_MESSAGE;
}
enum message_type_t message_convert( char *buf, size_t len, message_t * msg){
unsigned long Message_get_delimited_size(void *_buffer, int offset);
/*
* Tests whether a message can be completely read from the given buffer at
* the offset. The bytes [offset..offset+length-1] are interpreted.
*,
* Returns 1 (true) if buffer[offset..offset+length-1] contains a complete
* message or 0 (false) otherwise.
*/
enum message_type_t msg_type = UNKOWN_MESSAGE;
do{
msg_type = identify_message(buf,0);
switch (msg_type) {
case SECURITY_QUOTE:
break;
case WITHDRAW_QUOTE:
break;
case CONTRACT_NOTE:
ContractNote_read_delimited_from(buf, "e, 0)
break;
case ACCOUNT_EXCHANGE_NOTE:
break;
default:
break;
}
}while (0);
return msg_type;
}<file_sep>//
// QuoteQueueTest.cpp
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "QuoteQueueTest.h"
#include <typeinfo>
namespace {
TEST(QuoteQueueTest, getQuoteQueue) {
int code = random();
QuoteQueue& quoteQueue = QuoteQueue::getInstance();
SellQuoteMultiMap * sellQueue = quoteQueue.getSellQuoteQueue(code);
ASSERT_EQ(typeid(*sellQueue), typeid(SellQuoteMultiMap));
BuyQuoteMultiMap * buyQueue = quoteQueue.getBuyQuoteQueue(code);
ASSERT_EQ(typeid(*buyQueue), typeid(BuyQuoteMultiMap));
ASSERT_NE(buyQueue, sellQueue);
code = random();
SellQuoteMultiMap * sellQueue2 = quoteQueue.getSellQuoteQueue(code);
BuyQuoteMultiMap * buyQueue2 = quoteQueue.getBuyQuoteQueue(code);
ASSERT_NE(buyQueue2, sellQueue2);
ASSERT_EQ(buyQueue, buyQueue2);
ASSERT_EQ(sellQueue, sellQueue2);
}
} // namespace<file_sep>//
// account_exchange.cpp
// mycoin
//
// Created by lx on 14-1-9.
// Copyright (c) 2014年 lx. All rights reserved.
//
#include "account_message.h"
static bool record(session &ses, WithdrawQuote "e){
do{
ses << "insert into exchange_bill(bill_id, bill_type, occur_time, security_code, quality, client) values(?, ?, ?, ?, ?, ?)",
use(quote.billId), use(quote.billType), use(quote.occurTime)
, use(quote.code), use(quote.quality), use(quote.client);
}while(false);
return true;
}
int AccountExchangeProcessor::charge(AccountExchangeNote ¬e, EventSwitcher& switcher){
do {
// 借记depoist资产,贷记资金往来
if(RedisVoucher::account(note.client, BizAccount::getDeposit(note.code), BizAccount::getExchange(note.code),note.quality)){
} while (false);
return STATUS_REJECTED;
}
int AccountExchangeProcessor::withdraw(AccountExchangeNote ¬e, EventSwitcher& switcher){
do {
//借记资金往来,贷记deposit
if(RedisVoucher::account(note.client, BizAccount::getExchange(note.code),BizAccount::getDeposit(note.code), note.quality)){
tr.commit();
note.status = STATUS_FINISHED;
}else{
tr.rollback();
}
} while (false);
return STATUS_REJECTED;
}
<file_sep>//
// DatabaseAccount.cpp
// mycoin
//
// Created by lx on 13-12-15.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "DatabaseAccount.h"
bool DatabaseVoucher::account(time_t occurTime, AccountSuite& suit, const string& debitCode, const string& creditCode, money_t money){
/*
//debit
sql << "insert into " << detail_table << "(occur_time, debit, credit, owner) values( ?, ?, 0,?)", use(occurTime), use(money), use(owner);
//balance_type 时间
sql << "update " << table << " set occur_time=:occur_time, balance =banalce + " <<money << " where balance_type=" << 0 <<" and owner=:owner ", use(occurTime, "occur_time"), use(owner, "owner");
//credit
sql << "insert into " << detail_table << "(occur_time, debit, credit, owner) values( ?, 0, ?,?)", use(occurTime), use(money),use(owner);
//balance_type 时间
sql << "update " << table << " set occur_time=:occur_time, balance =banalce - " <<money << " where balance_type=" <<0 <<" and owner=:owner ", use(occurTime, "occur_time"), use(owner, "owner");
*/
return true;
}
/*
Account AccountDAOSqlite::get(int id){
session sql(sqlite3, "mycoin.sqlite");
int count;
sql << "select count(*) from invoices", into(count);
int id = 7;
sql << "select name from person where id = :id", use(id, "id");
ofstream file("my_log.txt");
sql.set_log_stream(&file);
const int BATCH_SIZE = 25;
std::vector<int> ids;
for (int i = 0; i != BATCH_SIZE; ++i)
{
ids.push_back(i);
}
statement st = (sql.prepare <<
"insert into numbers(value) values(:val)",
use(ids));
for (int i = 0; i != 4; ++i)
{
st.execute(true);
}
}
*/
<file_sep>//
// test.h
// mycoin
//
// Created by lx on 13-12-17.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__test__
#define __mycoin__test__
#endif /* defined(__mycoin__test__) */
<file_sep>//
// MatchStrategy.h
// mycoin
//
// Created by lx on 13-12-21.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__MatchStrategy__
#define __mycoin__MatchStrategy__
#include "../quote.h"
#include "LevelOfQuoteQueue.h"
/*
非类型形参
2.1 、非类型模板形参:模板的非类型形参也就是内置类型形参,如template<class T, int a> class B{};其中int a就是非类型的模板形参。
2.2、 非类型形参在模板定义的内部是常量值,也就是说非类型形参在模板的内部是常量。
2.3、 非类型模板的形参只能是整型,指针和引用,像double,String, String **这样的类型是不允许的。但是double &,double *,对象的引用或指针是正确的。
2.4、 调用非类型模板形参的实参必须是一个常量表达式,即他必须能在编译时计算出结果。
2.5 、注意:任何局部对象,局部变量,局部对象的地址,局部变量的地址都不是一个常量表达式,都不能用作非类型模板形参的实参。全局指针类型,全局变量,全局对象也不是一个常量表达式,不能用作非类型模板形参的实参。
2.6、 全局变量的地址或引用,全局对象的地址或引用const类型变量是常量表达式,可以用作非类型模板形参的实参。
2.7 、sizeof表达式的结果是一个常量表达式,也能用作非类型模板形参的实参。
2.8 、当模板的形参是整型时调用该模板时的实参必须是整型的,且在编译期间是常量,比如template <class T, int a> class A{};如果有int b,这时A<int, b> m;将出错,因为b不是常量,如果const int b,这时A<int, b> m;就是正确的,因为这时b是常量。
2.9 、非类型形参一般不应用于函数模板中,比如有函数模板template<class T, int a> void h(T b){},若使用h(2)调用会出现无法为非类型形参a推演出参数的错误,对这种模板函数可以用显示模板实参来解决,如用h<int, 3>(2)这样就把非类型形参a设置为整数3。显示模板实参在后面介绍。
2.10、 非类型模板形参的形参和实参间所允许的转换
1、允许从数组到指针,从函数到指针的转换。如:template <int *a> class A{}; int b[1]; A<b> m;即数组到指针的转换
2、const修饰符的转换。如:template<const int *a> class A{}; int b; A<&b> m; 即从int *到const int *的转换。
3、提升转换。如:template<int a> class A{}; const short b=2; A<b> m; 即从short到int 的提升转换
4、整值转换。如:template<unsigned int a> class A{}; A<3> m; 即从int 到unsigned int的转换。
5、常规转换。
1、可以为类模板的类型形参提供默认值,但不能为函数模板的类型形参提供默认值。函数模板和类模板都可以为模板的非类型形参提供默认值。
2、类模板的类型形参默认值形式为:template<class T1, class T2=int> class A{};为第二个模板类型形参T2提供int型的默认值。
3、类模板类型形参默认值和函数的默认参数一样,如果有多个类型形参则从第一个形参设定了默认值之后的所有模板形参都要设定默认值,比如template<class T1=int, class T2>class A{};就是错误的,因为T1给出了默认值,而T2没有设定。
4、在类模板的外部定义类中的成员时template 后的形参表应省略默认的形参类型。比如template<class T1, class T2=int> class A{public: void h();}; 定义方法为template<class T1,class T2> void A<T1,T2>::h(){}。
*/
inline security_quality_t matchTopDown(SecurityQuote "e, SecurityQuote & peer);
inline security_quality_t matchBottomUp(SecurityQuote "e, SecurityQuote & peer);
inline security_quality_t marketPriceBuyIn(SecurityQuote "e, SecurityQuote & peer);
inline security_quality_t marketPriceSellOut(SecurityQuote "e, SecurityQuote & peer);
#endif /* defined(__mycoin__MatchStrategy__) */
<file_sep>
OBJ=net.o hiredis.o sds.o async.o
TESTS=mycoin-test
# Fallback to gcc when $CC is not in $PATH.
CXX:=$(shell sh -c 'type $(CC) >/dev/null 2>/dev/null && echo $(CC) || echo gcc')
CC:=$(shell sh -c 'type $(CC) >/dev/null 2>/dev/null && echo $(CC) || echo gcc')
OPTIMIZATION?=-O3
WARNINGS=-Wall -W -Wstrict-prototypes -Wwrite-strings
DEBUG?= -g -ggdb
REAL_CFLAGS=$(OPTIMIZATION) -fPIC $(CFLAGS) $(WARNINGS) $(DEBUG) $(ARCH)
REAL_LDFLAGS=$(LDFLAGS) $(ARCH)
STLIB_MAKE_CMD=ar rcs $(STLIBNAME)
LIB_DIR=/usr/local/lib
INCLUDE_DIR=/usr/local/include
VPATH = match:account
objects = message.o MessageProcessor.o QuoteQueue.o LevelOfQuoteQueue.o QuoteMatchProcessor.o QuoteWithdrawProcessor.o Account.o DatabaseAccount.o AccountSuiteFactory.o BizAccount.o QuoteAccount.o ContractNoteProcessor.o AccountExchangeProcessor.o match.o aroundMatch.o RoutineQuotation.o RedisPublisher.o
all: mycoin test
# Deps (use make dep to generate this)
# Binaries:
message.o: message/message.c message/message.h
MessageProcessor.o: MessageProcessor.cpp MessageProcessor.h message/message.h
QuoteQueue.o: match/QuoteQueue.cpp match/QuoteQueue.h quote.h
LevelOfQuoteQueue.o: match/LevelOfQuoteQueue.cpp match/LevelOfQuoteQueue.h quote.h
QuoteMatchProcessor.o: match/QuoteMatchProcessor.cpp match/QuoteMatchProcessor.h match/LimitPriceStrategy.h match/MarketPriceStrategy.h match/QuoteProcessor.h match/QuoteProcessorSet.h quote.h Singleton.h
QuoteWithdrawProcessor.o: match/QuoteWithdrawProcessor.cpp match/QuoteWithdrawProcessor.h quote.h Singleton.h
Account.o: account/Account.cpp account/Account.h
DatabaseAccount.o: account/DatabaseAccount.cpp account/DatabaseAccount.h account/Account.h
AccountSuiteFactory.o: account/AccountSuiteFactory.cpp account/AccountSuiteFactory.h account/DatabaseAccount.h account/Account.h
BizAccount.o: account/BizAccount.cpp account/BizAccount.h
QuoteAccount.o: account/QuoteAccount.cpp account/QuoteAccount.h account/MessageProcessor.h quote.h
ContractNoteProcessor.o: account/ContractNoteProcessor.cpp account/ContractNoteProcessor.h account/MessageProcessor.h quote.h
AccountExchangeProcessor.o: account/AccountExchangeProcessor.cpp account/AccountExchangeProcessor.h account/MessageProcessor.h quote.h
match.o: match.cpp match.h
RoutineQuotation.o: RoutineQuotation.cpp RoutineQuotation.h quote.h
RedisPublisher.o: RedisPublisher.cpp RedisPublisher.h quote.h RoutineQuotation.h
aroundMatch.o: aroundMatch.cpp aroundMatch.h RedisPublisher.h
mycoin: MycoinApplication.cpp MycoinApplication.h $(objects)
clang++ -v -std=c++11 -stdlib=libc++ -DWORK -o $@ $(REAL_CFLAGS) $(REAL_LDFLAGS) -I. -I$(INCLUDE_DIR) $< $(objects) $(LIB_DIR)/libuv.dylib /Users/lx/work/soci-3.2.2/build/lib/libsoci_core.dylib /Users/lx/work/soci-3.2.2/build/lib/libsoci_sqlite3.dylib $(LIB_DIR)/libPocoUtil.dylib $(LIB_DIR)/libPocoFoundation.dylib $(LIB_DIR)/libPocoData.dylib -L$(LIB_DIR) -lpthread -lhiredis
demo: demo.c demo.h quote.h
$(CC) -o $@ $(REAL_LDFLAGS) $< $(LIB_DIR)/libuv.dylib -lpthread
.cpp.o:
clang++ -std=c++11 -stdlib=libc++ -DWORK -c -I. -I$(INCLUDE_DIR) $<
.c.o:
$(CC) -std=c99 -pedantic -c $(REAL_CFLAGS) -I. -I$(INCLUDE_DIR) $<
clean:
-rm -rf $(TESTS) mycoin $(objects) *.gcda *.gcno *.gcov
dep:
$(CC) -MM *.c
32bit:
@echo ""
@echo "WARNING: if this fails under Linux you probably need to install libc6-dev-i386"
@echo ""
$(MAKE) CFLAGS="-m32" LDFLAGS="-m32"
gprof:
$(MAKE) CFLAGS="-pg" LDFLAGS="-pg"
gcov:
$(MAKE) CFLAGS="-fprofile-arcs -ftest-coverage" LDFLAGS="-fprofile-arcs"
coverage: gcov
make check
mkdir -p tmp/lcov
lcov -d . -c -o tmp/lcov/hiredis.info
genhtml --legend -o tmp/lcov/report tmp/lcov/hiredis.info
noopt:
$(MAKE) OPTIMIZATION=""
.PHONY: all test check clean dep install 32bit gprof gcov noopt
<file_sep>//
// CoinExchangeTestEnvironment.h
// mycoin
//
// Created by lx on 13-12-21.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__CoinExchangeTestEnvironment__
#define __mycoin__CoinExchangeTestEnvironment__
#include <iostream>
//全局事件
class CoinExchangeTestEnvironment : public testing::Environment
{
public:
/*
SetUp()方法在所有案例执行前执行
*/
virtual void SetUp();
/*
TearDown()方法在所有案例执行后执行
*/
virtual void TearDown();
};
#endif /* defined(__mycoin__CoinExchangeTestEnvironment__) */
<file_sep>//
// send_quote.c
// mycoin
//
// Created by lx on 14-1-1.
// Copyright (c) 2014年 lx. All rights reserved.
//
#include <stdio.h>
#include <uv.h>
typedef struct _SecurityQuote{
security_billId_t billId;
enum security_bill_t billType;
time_t occurTime;
security_code_t code;
security_price_t price;
security_quality_t quality;
security_price_t guaranty;
security_billId_t refBillId;
bill_status_t status;
char client[21];
} SecurityQuote;
static uv_shutdown_t shutdown_req;
static uv_write_t write_req;
struct sockaddr_in dest;
static uv_loop_t *loop;
static void write_cb(uv_write_t* req, int status) {
}
static void close_cb(uv_handle_t* handle) {
uv_tcp_t socket;
uv_tcp_init(loop, &socket);
uv_connect_t connect;
uv_tcp_connect(&connect, &socket, dest, on_connect);
}
static void shutdown_cb(uv_shutdown_t* req, int status) {
uv_close((uv_handle_t*)req->handle, close_cb);
}
void on_connect(uv_connect_t* req, int status){
SecurityQuote* quote = req->data;
time("e.occurTime);
uv_write(&write_req, req->handle, (char *)"e, 1, write_cb);
uv_shutdown(&shutdown_req, req->handle, shutdown_cb);
}
int send_quote(const char * host, int port, security_code_t code,security_price_t price, security_quality_t quality, security_price_t guaranty, const char *client)
{
uv_loop_t *loop = uv_default_loop();
quote.code = 1;//2
quote.billId = (long)random();//hash
quote.billType = (security_bill_t)random()%4; // BUY_IN_LIMIT_PRICE, SELL_OUT_LIMIT_PRICE,
quote.quality = random() %10;
if(quote.billType == BUY_IN_LIMIT_PRICE || quote.billType == SELL_OUT_LIMIT_PRICE ){
quote.price = 5000 + random()% 2000;
}else{
quote.guaranty = quote.quality * 6000; //BUY_IN_MARKET_PRICE,SELL_OUT_MARKET_PRICE,
}
SecurityQuote quote;
uv_run(loop, UV_RUN_ONCE);
}
return 0;
}
int withdraw_quote(const char * host, int port, security_code_t code, security_billId_t refBillId, const char *client)
{
uv_loop_t *loop = uv_default_loop();
uv_tcp_t socket;
uv_tcp_init(loop, &socket);
uv_connect_t connect;
SecurityQuote quote;
connect.data = "e;
struct sockaddr_in dest = uv_ip4_addr(host, port);
uv_tcp_connect(&connect, &socket, dest, on_connect);
SecurityQuote quote;
uv_run(loop, UV_RUN_ONCE);
return 0;
}<file_sep>//
// Publisher.h
// mycoin
//
// Created by lx on 14-1-8.
// Copyright (c) 2014年 lx. All rights reserved.
//
#ifndef __mycoin__Publisher__
#define __mycoin__Publisher__
#include "quote.h"
class Publisher{
public:
virtual void publish(const security_code_t code, security_price_t price, security_quality_t quality, security_price_t topBuyPrice[], security_quality_t topBuyQty[], int size1, security_price_t topSellPrice[], security_quality_t topSellQty[], int size2 )=0;
virtual void publish(SecurityQuote "e)=0;
void publish(RoutineQuotation &routine){
routine.publish()
}
void publish(message_t* msg){
if(msg.quote.status != STATUS_FINISHED)
return;
switch(msg.quote.msg_type){
case SecurityQuote:
Singleton<RoutineQuation>::instance().update(quote);
Singleton<Publisher>::instance().publish(quote);
case AccountExchange:
Singleton<Publisher>::instance().publish(note);
break;
case WithdrawQuote:
Singleton<Publisher>::instance().publish(quote);
break;
case CONTRACT_NOTE:
Singleton<RoutineQuation>::instance().update(note);
Singleton<Publisher>::instance().publish(note);
break;
default:
break;
}
}
};
#endif /* defined(__mycoin__Publisher__) */
<file_sep>//
// test.h
// mycoin
//
// Created by lx on 13-12-21.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__test__
#define __mycoin__test__
/*
宏中的#的功能是将其后面的宏参数进行字符串化操作(Stringizing operator),简单说就是在它引用的宏变量的左右各加上一个双引号。
#@是加单引号
##是拼接符号(Token-pasting operator)。
例:
#define paster( n ) token##n
paster(9)展开后token##n变成token9。
*/
/*
for (int i = 0; i < x.size(); ++i)
{
EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
}
*/
/*
布尔值检查
Fatal assertion Nonfatal assertion Verifies
ASSERT_TRUE(condition); EXPECT_TRUE(condition); condition is true
ASSERT_FALSE(condition); EXPECT_FALSE(condition); condition is false
数值型数据检查
Fatal assertion Nonfatal assertion Verifies
ASSERT_EQ(expected, actual); EXPECT_EQ(expected, actual); expected == actual
ASSERT_NE(val1, val2); EXPECT_NE(val1, val2); val1 != val2
ASSERT_LT(val1, val2); EXPECT_LT(val1, val2); val1 < val2
ASSERT_LE(val1, val2); EXPECT_LE(val1, val2); val1 <= val2
ASSERT_GT(val1, val2); EXPECT_GT(val1, val2); val1 > val2
ASSERT_GE(val1, val2); EXPECT_GE(val1, val2); val1 >= val2
字符串检查
Fatal assertion Nonfatal assertion Verifies
ASSERT_STREQ(expected_str, actual_str); EXPECT_STREQ(expected_str, actual_str); the two C strings have the same content
ASSERT_STRNE(str1, str2); EXPECT_STRNE(str1, str2); the two C strings have different content
ASSERT_STRCASEEQ(expected_str, actual_str); EXPECT_STRCASEEQ(expected_str, actual_str); the two C strings have the same content, ignoring case
ASSERT_STRCASENE(str1, str2); EXPECT_STRCASENE(str1, str2); the two C strings have different content, ignoring case
*STREQ*和*STRNE*同时支持char*和wchar_t*类型的,*STRCASEEQ*和*STRCASENE*却只接收char*
显示返回成功或失败
直接返回成功:SUCCEED();
返回失败:
Fatal assertion Nonfatal assertion
FAIL(); ADD_FAILURE();
异常检查
Fatal assertion Nonfatal assertion Verifies
ASSERT_THROW(statement, exception_type); EXPECT_THROW(statement, exception_type); statement throws an exception of the given type
ASSERT_ANY_THROW(statement); EXPECT_ANY_THROW(statement); statement throws an exception of any type
ASSERT_NO_THROW(statement); EXPECT_NO_THROW(statement); statement doesn't throw any exception
Predicate Assertions
在使用EXPECT_TRUE或ASSERT_TRUE时,有时希望能够输出更加详细的信息,比如检查一个函数的返回值TRUE还是FALSE时,希望能够输出传入的参数是什么,以便失败后好跟踪。因此提供了如下的断言:
Fatal assertion Nonfatal assertion Verifies
ASSERT_PRED1(pred1, val1); EXPECT_PRED1(pred1, val1); pred1(val1) returns true
ASSERT_PRED2(pred2, val1, val2); EXPECT_PRED2(pred2, val1, val2); pred2(val1, val2) returns true
Google人说了,他们只提供<=5个参数的,如果需要测试更多的参数,直接告诉他们。
bool MutuallyPrime(int m, int n)
{
return Foo(m , n) > 1;
}
TEST(PredicateAssertionTest, Demo)
{
int m = 5, n = 6;
EXPECT_PRED2(MutuallyPrime, m, n);
}
当失败时,返回错误信息:
error: MutuallyPrime(m, n) evaluates to false, where
m evaluates to 5
n evaluates to 6
如果对这样的输出不满意的话,还可以自定义输出格式,通过如下:
Fatal assertion Nonfatal assertion Verifies
ASSERT_PRED_FORMAT1(pred_format1, val1);` EXPECT_PRED_FORMAT1(pred_format1, val1); pred_format1(val1) is successful
ASSERT_PRED_FORMAT2(pred_format2, val1, val2); EXPECT_PRED_FORMAT2(pred_format2, val1, val2); pred_format2(val1, val2) is successful
testing::AssertionResult AssertFoo(const char* m_expr, const char* n_expr, const char* k_expr, int m, int n, int k) {
if (Foo(m, n) == k)
return testing::AssertionSuccess();
testing::Message msg;
msg << m_expr << " 和 " << n_expr << " 的最大公约数应该是:" << Foo(m, n) << " 而不是:" << k_expr;
return testing::AssertionFailure(msg);
}
TEST(AssertFooTest, HandleFail)
{
EXPECT_PRED_FORMAT3(AssertFoo, 3, 6, 2);
}
浮点型检查
Fatal assertion Nonfatal assertion Verifies
ASSERT_FLOAT_EQ(expected, actual); EXPECT_FLOAT_EQ(expected, actual); the two float values are almost equal
ASSERT_DOUBLE_EQ(expected, actual); EXPECT_DOUBLE_EQ(expected, actual); the two double values are almost equal
对相近的两个数比较:
Fatal assertion Nonfatal assertion Verifies
ASSERT_NEAR(val1, val2, abs_error); EXPECT_NEAR(val1, val2, abs_error); the difference between val1 and val2 doesn't exceed the given absolute error
同时,还可以使用:
EXPECT_PRED_FORMAT2(testing::FloatLE, val1, val2);
EXPECT_PRED_FORMAT2(testing::DoubleLE, val1, val2);
类型检查
类型检查失败时,直接导致代码编不过,难得用处就在这?看下面的例子:
复制代码
template <typename T> class FooType {
public:
void Bar() { testing::StaticAssertTypeEq<int, T>(); }
};
TEST(TypeAssertionTest, Demo)
{
FooType<bool> fooType;
fooType.Bar();
}
死亡测试
Fatal assertion Nonfatal assertion Verifies
ASSERT_DEATH(statement, regex`); EXPECT_DEATH(statement, regex`); statement crashes with the given error
ASSERT_EXIT(statement, predicate, regex`); EXPECT_EXIT(statement, predicate, regex`); statement exits with the given error and its exit code matches predicate
由于有些异常只在Debug下抛出,因此还提供了*_DEBUG_DEATH,用来处理Debug和Realease下的不同。
正则表达式
在POSIX系统(Linux, Cygwin, 和 Mac)中,gtest的死亡测试中使用的是POSIX风格的正则表达式
在Windows系统中,gtest的死亡测试中使用的是gtest自己实现的简单的正则表达式语法。 相比POSIX风格,gtest的简单正则表达式少了很多内容,比如 ("x|y"), ("(xy)"), ("[xy]") 和("x{5,7}")都不支持。
下面是简单正则表达式支持的一些内容:
matches any literal character c
\\d matches any decimal digit
\\D matches any character that's not a decimal digit
\\f matches \f
\\n matches \n
\\r matches \r
\\s matches any ASCII whitespace, including \n
\\S matches any character that's not a whitespace
\\t matches \t
\\v matches \v
\\w matches any letter, _, or decimal digit
\\W matches any character that \\w doesn't match
\\c matches any literal character c, which must be a punctuation
. matches any single character except \n
A? matches 0 or 1 occurrences of A
A* matches 0 or many occurrences of A
A+ matches 1 or many occurrences of A
^ matches the beginning of a string (not that of each line)
$ matches the end of a string (not that of each line)
xy matches x followed by y
gtest定义两个宏,用来表示当前系统支持哪套正则表达式风格:
1. POSIX风格:GTEST_USES_POSIX_RE = 1
2. Simple风格:GTEST_USES_SIMPLE_RE=1
七、死亡测试运行方式
1. fast方式(默认的方式)
testing::FLAGS_gtest_death_test_style = "fast";
2. threadsafe方式
testing::FLAGS_gtest_death_test_style = "threadsafe";
你可以在 main() 里为所有的死亡测试设置测试形式,也可以为某次测试单独设置。Google Test会在每次测试之前保存这个标记并在测试完成后恢复。如:
TEST(MyDeathTest, TestOne) {
testing::FLAGS_gtest_death_test_style = "threadsafe";
// This test is run in the "threadsafe" style:
ASSERT_DEATH(ThisShouldDie(), "");
}
TEST(MyDeathTest, TestTwo) {
// This test is run in the "fast" style:
ASSERT_DEATH(ThisShouldDie(), "");
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
testing::FLAGS_gtest_death_test_style = "fast";
return RUN_ALL_TESTS();
}
注意事项
1. 不要在死亡测试里释放内存。
2. 在父进程里再次释放内存。
3. 不要在程序中使用内存堆检查。
*/
/*
value-parameterized tests 参数化测试数据
1. 告诉gtest你的参数类型
添加一个继承自testing::TestWithParam<T>的类,,其中T就是你需要参数化的参数类型,如参数化一个int型的参数
class IsPrimeParamTest : public::testing::TestWithParam<int>
{
};
2. 使用宏TEST_P,在TEST_P宏里,用GetParam()获取当前的参数的具体值
TEST_P(IsPrimeParamTest, HandleTrueReturn)
{
int n = GetParam();
EXPECT_TRUE(IsPrime(n));
}
3. 使用INSTANTIATE_TEST_CASE_P宏获取要测试的参数范围
INSTANTIATE_TEST_CASE_P(TrueReturn, IsPrimeParamTest, testing::Values(3, 5, 11, 23, 17));
第一个参数是测试案例的前缀,可以任意取。
第二个参数是测试案例的名称,需要和之前定义的参数化的类的名称相同,如:IsPrimeParamTest
第三个参数是可以理解为参数生成器,上面的例子使用test::Values表示使用括号内的参数。Google提供了一系列的参数生成的函数:
Range(begin, end[, step]) 范围在begin~end之间,步长为step,不包括end
Values(v1, v2, ..., vN) v1,v2到vN的值
ValuesIn(container) and ValuesIn(begin, end) 从一个C类型的数组或是STL容器,或是迭代器中取值
Bool() 取false 和 true 两个值
Combine(g1, g2, ..., gN) 将g1,g2,...gN进行排列组合,g1,g2,...gN本身是一个参数生成器,每次分别从g1,g2,..gN中各取出一个值,组合成一个元组(Tuple)作为一个参数。
说明:这个功能只在提供了<tr1/tuple>头的系统中有效。gtest会自动去判断是否支持tr/tuple,如果你的系统确实支持,而gtest判断错误的话,你可以重新定义宏GTEST_HAS_TR1_TUPLE=1。
4参数化后的测试案例名
命名规则大概为:
prefix/test_case_name.test.name/index
type-parameterized tests 类型参数化
gtest提供了应付各种不同类型的数据时的方案,以及参数化类型的方案。
首先定义一个继承testing::Test的模版类,:
template <typename T>
class FooTest : public testing::Test {
public:
typedef std::list<T> List;
static T shared_;
T value_;
};
接着定义需要测试到的具体数据类型,比如下面定义了需要测试char,int和unsigned int :
typedef testing::Types<char, int, unsigned int> MyTypes;
TYPED_TEST_CASE(FooTest, MyTypes);
使用TYPED_TEST宏写测试案例,在声明模版的数据类型时,使用TypeParam
TYPED_TEST(FooTest, DoesBlah) {
// Inside a test, refer to the special name TypeParam to get the type
// parameter. Since we are inside a derived class template, C++ requires
// us to visit the members of FooTest via 'this'.
TypeParam n = this->value_;
// To visit static members of the fixture, add the 'TestFixture::'
// prefix.
n += TestFixture::shared_;
// To refer to typedefs in the fixture, add the 'typename TestFixture::'
// prefix. The 'typename' is required to satisfy the compiler.
typename TestFixture::List values;
values.push_back(n);
}
上面的例子看上去也像是类型的参数化,但是还不够灵活,因为需要事先知道类型的列表。gtest还提供一种更加灵活的类型参数化的方式,允许你在完成测试的逻辑代码之后再去考虑需要参数化的类型列表,并且还可以重复的使用这个类型列表。例子:
template <typename T>
class FooTest : public testing::Test {
};
TYPED_TEST_CASE_P(FooTest);
使用宏TYPED_TEST_P写测试案例:
TYPED_TEST_P(FooTest, DoesBlah) {
// Inside a test, refer to TypeParam to get the type parameter.
TypeParam n = 0;
}
TYPED_TEST_P(FooTest, HasPropertyA) { }
使用REGISTER_TYPED_TEST_CASE_P宏注册,第一个参数是testcase的名称,后面的参数是test的名称
REGISTER_TYPED_TEST_CASE_P(FooTest, DoesBlah, HasPropertyA);
接着指定需要的类型列表:
typedef testing::Types<char, int, unsigned int> MyTypes;
INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes);
*/
/*
gtest提供的运行参数(环境变量、命令行参数或代码里指定)
三种设置的途径:
1. 系统环境变量
2. 命令行参数
3. 代码中指定FLAG
三种途径最中后设置的那个会生效。通常情况下,比较理想的优先级为:命令行参数 > 代码中指定FLAG > 系统环境变量
如果需要在代码中指定FLAG,可以使用testing::GTEST_FLAG这个宏来设置。比如相对于命令行参数--gtest_output,可以使用testing::GTEST_FLAG(output) = "xml:";来设置。注意到了,不需要加--gtest前缀了。同时,推荐将这句放置InitGoogleTest之前,这样就可以使得对于同样的参数,命令行参数优先级高于代码中指定。
如果需要gtest的设置系统环境变量,必须注意的是:
1. 系统环境变量全大写,比如对于--gtest_output,响应的系统环境变量为:GTEST_OUTPUT
2. 有一个命令行参数例外,那就是--gtest_list_tests,它是不接受系统环境变量的
参数列表
了解了上面的内容,我这里就直接将所有命令行参数总结和罗列一下。如果想要获得详细的命令行说明,直接运行你的案例,输入命令行参数:/? 或 --help 或 -help
1. 测试案例集合
命令行参数 说明
--gtest_list_tests 使用这个参数时,将不会执行里面的测试案例,而是输出一个案例的列表。
--gtest_filter
对执行的测试案例进行过滤,支持通配符
? 单个字符
* 任意字符
- 排除,如,-a 表示除了a
: 取或,如,a:b 表示a或b
比如下面的例子:
./foo_test 没有指定过滤条件,运行所有案例
./foo_test --gtest_filter=* 使用通配符*,表示运行所有案例
./foo_test --gtest_filter=FooTest.* 运行所有“测试案例名称(testcase_name)”为FooTest的案例
./foo_test --gtest_filter=*Null*:*Constructor* 运行所有“测试案例名称(testcase_name)”或“测试名称(test_name)”包含Null或Constructor的案例。
./foo_test --gtest_filter=-*DeathTest.* 运行所有非死亡测试案例。
./foo_test --gtest_filter=FooTest.*-FooTest.Bar 运行所有“测试案例名称(testcase_name)”为FooTest的案例,但是除了FooTest.Bar这个案例
--gtest_also_run_disabled_tests
执行案例时,同时也执行被置为无效的测试案例。关于设置测试案例无效的方法为:
在测试案例名称或测试名称中添加DISABLED前缀,比如:
复制代码
// Tests that Foo does Abc.
TEST(FooTest, DISABLED_DoesAbc) { }
class DISABLED_BarTest : public testing::Test { };
// Tests that Bar does Xyz.
TEST_F(DISABLED_BarTest, DoesXyz) { }
复制代码
--gtest_repeat=[COUNT]
设置案例重复运行次数,非常棒的功能!比如:
--gtest_repeat=1000 重复执行1000次,即使中途出现错误。
--gtest_repeat=-1 无限次数执行。。。。
--gtest_repeat=1000 --gtest_break_on_failure 重复执行1000次,并且在第一个错误发生时立即停止。这个功能对调试非常有用。
--gtest_repeat=1000 --gtest_filter=FooBar 重复执行1000次测试案例名称为FooBar的案例。
2. 测试案例输出
命令行参数 说明
--gtest_color=(yes|no|auto) 输出命令行时是否使用一些五颜六色的颜色。默认是auto。
--gtest_print_time 输出命令行时是否打印每个测试案例的执行时间。默认是不打印的。
--gtest_output=xml[:DIRECTORY_PATH\|:FILE_PATH]
将测试结果输出到一个xml中。
1.--gtest_output=xml: 不指定输出路径时,默认为案例当前路径。
2.--gtest_output=xml:d:\ 指定输出到某个目录
3.--gtest_output=xml:d:\foo.xml 指定输出到d:\foo.xml
如果不是指定了特定的文件路径,gtest每次输出的报告不会覆盖,而会以数字后缀的方式创建。xml的输出内容后面介绍吧。
3. 对案例的异常处理
命令行参数 说明
--gtest_break_on_failure 调试模式下,当案例失败时停止,方便调试
--gtest_throw_on_failure 当案例失败时以C++异常的方式抛出
--gtest_catch_exceptions
是否捕捉异常。gtest默认是不捕捉异常的,因此假如你的测试案例抛了一个异常,很可能会弹出一个对话框,这非常的不友好,同时也阻碍了测试案例的运行。如果想不弹这个框,可以通过设置这个参数来实现。如将--gtest_catch_exceptions设置为一个非零的数。
注意:这个参数只在Windows下有效。
四、XML报告输出格式
复制代码
<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="3" failures="1" errors="0" time="35" name="AllTests">
<testsuite name="MathTest" tests="2" failures="1"* errors="0" time="15">
<testcase name="Addition" status="run" time="7" classname="">
<failure message="Value of: add(1, 1) Actual: 3 Expected: 2" type=""/>
<failure message="Value of: add(1, -1) Actual: 1 Expected: 0" type=""/>
</testcase>
<testcase name="Subtraction" status="run" time="5" classname="">
</testcase>
</testsuite>
<testsuite name="LogicTest" tests="1" failures="0" errors="0" time="5">
<testcase name="NonContradiction" status="run" time="5" classname="">
</testcase>
</testsuite>
</testsuites>
*/
/*
在C++中,为了支持RTTI提供了两个操作符:dynamic_cast和typeid。
dynamic_cast允许运行时刻进行类型转换,从而使程序能够在一个类层次结构中安全地转化类型,与之相对应的还有一个非安全的转换操作符static_cast,
typeid是C++的关键字之一,等同于sizeof这类的操作符。typeid操作符的返回结果是名为type_info的标准库类型的对象的引用(在头文件typeinfo中定义),它的表达式有两种形式。
typeid(type) 类型ID
typeid(expr) 运行时刻类型ID
如果表达式的类型是类类型且至少包含有一个虚函数,则typeid操作符返回表达式的动态类型,需要在运行时计算;否则,typeid操作符返回表达式的静态类型,在编译时就可以计算。
ISO C++标准并没有确切定义type_info,确切定义与编译器的实现相关,标准规定必需提供如下四种操作:
t1 == t2 如果两个对象t1和t2类型相同,则返回true;否则返回false
t1 != t2 如果两个对象t1和t2类型不同,则返回true;否则返回false
t.name() 返回类型的C-style字符串,类型名字用系统相关的方法产生
t1.before(t2) 返回指出t1是否出现在t2之前的bool值
ASSERT_EQ(typeid(*sellQueue), typeid(SellQuoteMultiMap));
type_info类提供了public虚 析构函数,以使用户能够用其作为基类。它的默认构造函数和拷贝构造函数及赋值操作符都定义为private,不能定义或复制type_info类型的对象。程序中创建type_info对象的唯一方法是使用typeid操作符。type_info的name成员函数返回C-style的字符串,表示相应的类型名,这个返回的类型名与程序中使用的相应类型名并不一定一致,这具体由编译器的实现所决定的,标准只要求实现为每个类型返回唯一的字符串。
当typeid操作符的操作数是不带有虚函数的类类型时,typeid操作符会指出操作数的类型,而不是底层对象的类型。
如果typeid操作符的操作数是至少包含一个虚拟函数的类类型时,并且该表达式是一个基类的引用,则typeid操作符指出底层对象的派生类类型。而指向基类的指针不是类类型,返回基类的类型。
对于多态类实例,想得到实际的类名称,需要使用到RTTI,这需要在编译的时候加上参数"/GR"
*/
#include <iostream>
#endif /* defined(__mycoin__test__) */
<file_sep>//
// MarketPriceStrategyTest.cpp
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "MarketPriceStrategyTest.h"
#include <typeinfo>
namespace {
TEST(BuyInMarketPriceStrategy, match) {
BuyInMarketPriceStrategy<5> strategy;
//测5档以上
SecurityQuote quote,cpmQuote;
SecurityQuote peer,cpmPeer;
security_quality_t qty;
security_code_t code = random();
quote.code = code;
peer.code = code;
quote.quality = random();
peer.quality = random();
quote.guaranty = random();
peer.price = random();
memcpy(&cpmQuote, "e);
memcpy(&cpmpeer, &peer);
qty = strategy.match(quote, peer);
ASSERT_GE(quote.guaranty,0);
ASSERT_EQ(qty, cmpQuote.quality - quote.quality);
ASSERT_EQ(qty, peer.quality - cmpPeer.quality);
ASSSERT_GE(cmpQuote.quality, qty * peer.price);
quote.guaranty = cmpQuote.guaranty;
quote.quality -= qty;
ASSERT_EQ(0, memcpm(&cmpQuote,"e));
peer.quality += qty;
ASSERT_EQ(0, memcpm(&cmpPeer,&peer));
if(cmpQuote.guaranty >= peer.price ){
ASSERT_GT(qty,0);
quote.guaranty = peer.price -1;
ASSERT_EQ(strategy.match(quote, peer),0);
}else{
ASSERT_EQ(qty,0);
quote.quality = peer.price +1;
ASSERT_GT(strategy.match(quote, peer),0);
}
quote.quality = - random();
qty = strategy.match(quote, peer);
ASSERT_EQ(0, qty);
}
TEST(SellOutMarketPriceStrategy, match) {
SellOutMarketPriceStrategy<5> strategy;
SecurityQuote quote,cpmQuote;
SecurityQuote peer,cpmPeer;
security_quality_t qty;
security_code_t code = random();
quote.code = code;
peer.code = code;
quote.quality = random();
peer.quality = random();
quote.guaranty = random();
peer.price = random();
memcpy(&cpmQuote, "e);
memcpy(&cpmpeer, &peer);
qty = strategy.match(quote, peer);
ASSERT_GE(quote.guaranty,0);
ASSERT_EQ(qty, cmpQuote.quality - quote.quality);
ASSERT_EQ(qty, peer.quality - cmpPeer.quality);
quote.guaranty = cmpQuote.guaranty;
quote.quality -= qty;
ASSERT_EQ(0, memcpm(&cmpQuote,"e));
peer.quality += qty;
ASSERT_EQ(0, memcpm(&cmpPeer,&peer));
if(cmpQuote.guaranty >= peer.price ){
ASSERT_GT(qty,0);
quote.guaranty = peer.price -1;
ASSERT_EQ(strategy.match(quote, peer),0);
}else{
ASSERT_EQ(qty,0);
quote.quality = peer.price +1;
ASSERT_GT(strategy.match(quote, peer),0);
}
quote.quality = - random();
qty = strategy.match(quote, peer);
ASSERT_EQ(0, qty);
}
} // namespace<file_sep>//
// message_extend.h
// mycoin
//
// Created by lx on 14-1-8.
// Copyright (c) 2014年 lx. All rights reserved.
//
#ifndef mycoin_message_extend_h
#define mycoin_message_extend_h
#include "message.h"
#ifdef __cplusplus
extern "C" {
#endif
enum message_type_t identify_message(void *_buffer, int start_offset);
typedef union message_u{
SecurityQuote quote;
WithdrawQuote withdraw;
ContractNote note;
AccountExchangeNote note;
}message_t;
// 宏要能把 类型 置换掉 #define message.msg_type message.quote.msg_type
enum message_type_t message_convert( char *buf, size_t len, message_t * msg);
#ifdef __cplusplus
}
#endif
#endif
<file_sep>//
// matchTest.cpp
// mycoin
//
// Created by lx on 13-12-21.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "matchTest.h"
#include "../quote.h"
#include "readerwriterqueue.h"
extern int matchQuote(SecurityQuote * quote, ReaderWriterQueue<ContractNote > *notes);
template<typename QuoteMultiMap1, typename QuoteMultiMap2>
security_price_t matchQueue(SecurityQuote *quote, QuoteMultiMap1* selfQueue, QuoteMultiMap2 *peerQueue,ReaderWriterQueue<ContractNote > *notes, MatchStrategy &strategy, BalanceStrategy<QuoteMultiMap1, QuoteMultiMap2> &balance);
template<typename QuoteMultiMap>
void withdrawQuote(SecurityQuote *quote, QuoteMultiMap *queue,ReaderWriterQueue<ContractNote > *notes);
QuoteProcessor & getQuoteProcessor(SecurityQuote *quote);
void matchQuote(SecurityQuote * quote, ReaderWriterQueue<ContractNote > *notes);
namespace {
// The fixture for testing class .
//class MatchTest :public ::testing::TestWithParam<int>
//测试内容,股价优先,时间优先,不同类型的quote,撤销单,市价,限价
class MatchTest : public ::testing::Test {
protected:
// You can remove any or all of the following functions if its body
// is empty.
MatchTest() {
// You can do set-up work for each test here.
}
virtual ~MatchTest() {
// You can do clean-up work that doesn't throw exceptions here.
}
/*
SetUpTestCase() 方法在第一个TestCase之前执行
*/
static void SetUpTestCase() {
shared_resource_ = new ;
}
/*
TearDownTestCase() 方法在最后一个TestCase之后执行
*/
static void TearDownTestCase() {
delete shared_resource_;
shared_resource_ = NULL;
}
// Some expensive resource shared by all tests.
static T* shared_resource_;
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
//SetUp()方法在每个TestCase之前执行
virtual void SetUp() {
// Code here will be called immediately after the constructor (right
// before each test).
time("e.occurTime);
quote.code = 1;//2
quote.billId = (long)random();//hash
quote.billType = (security_bill_t)random()%4; // BUY_IN_LIMIT_PRICE, SELL_OUT_LIMIT_PRICE,
quote.quality = random() %10;
if(quote.billType == BUY_IN_LIMIT_PRICE || quote.billType == SELL_OUT_LIMIT_PRICE ){
quote.price = 5000 + random()% 2000;
}else{
quote.guaranty = quote.quality * 6000; //BUY_IN_MARKET_PRICE,SELL_OUT_MARKET_PRICE,
}
}
//TearDown()方法在每个TestCase之后执行
virtual void TearDown() {
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests in the test case.
ReaderWriterQueue<ContractNote > notes(1024);
SecurityQuote quote;
};
TEST_F(MatchTest, withdrawQuote) {
//撤销单
//撤销买单,撤销卖单-简单,空单时
// 有单时
// 单已全部成交
// 单成交部分
// 单完全没成交
//限价单
//市价单
}
} // namespace
<file_sep>//
// ContractNoteProcessor.h
// mycoin-account
//
// Created by lx on 13-12-25.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin_account__ContractNoteProcessor__
#define __mycoin_account__ContractNoteProcessor__
#include "MessageProcessor.h"
class ContractNoteProcessor:public EventProcessor{
protected:
public:
ContractNoteProcessor(message_type msg_type, EventSwitcher* processorMap)
:MessageProcessor(msg_type,processorMap){
}
virtual int execute(message_t *msg, EventSwitcher &switcher){
return execute(*((ContractNote*)&msg), switcher);
}
int execute(ContractNote ¬e,EventSwitcher &switcher){
switch (note.status) {
case STATUS_NEW:
account(note, switcher);
return EVS_ACCEPTED;
case STATUS_ACCOUNTED:
notify
default:
return EVS_REJECTED;
}
}
void account(ContractNote ¬e,EventSwitcher &switcher);
void notify(ContractNote ¬e){
event ;
event.data = note;
switcher.push(event);
}
};
#endif /* defined(__mycoin_account__ContractNoteProcessor__) */
<file_sep>//
// LevelOfQuoteTest.h
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__LevelOfQuoteTest__
#define __mycoin__LevelOfQuoteTest__
#include "gtest/gtest.h"
#include "../LevelOfQuoteQueue.h"
#endif /* defined(__mycoin__LevelOfQuoteTest__) */
<file_sep>//
// account_quote.cpp
// mycoin
//
// Created by lx on 14-1-9.
// Copyright (c) 2014年 lx. All rights reserved.
//
#include "account_message.h"
static bool record(session &ses, SecurityQuote "e){
do{
ses << "insert into quote_bill(bill_id, bill_type, occur_time, status, security_code, price, quality, guaranty,client) values(?, ?, ?, ?, ?, ?, ?, ?,?)",
use(quote.billId), use(quote.billType) , use(quote.occurTime), use(quote.status)
,use(quote.code), use(quote.price), use(quote.quality), use(quote.guaranty)
, use(( char*)quote->client);
}while(false);
return true;
}
int QuoteProcessor::match(SecurityQuote "e,EventSwitcher &switcher){
Singleton<Match>::instance().push(quote); //跨线程要明显的表示出来,不好用now
}
int QuoteProcessor::buyInPrepare(session &ses, SecurityQuote "e){
do {
transaction tr(ses);
if(!record(ses, quote))
break;
AccountSuite* suite = AccountSuiteFactory::instance(ses).getSuite(quote.client);
//买方 借记订金,贷记现金
if(AccountingVoucher::account(*suite, ACCOUNT_DEPOSIT, ACCOUNT_SUBSCRIPTION,quote.guaranty))
break;
tr.commit();
quote.status = STATUS_ACCEPTED;
return quote.status;
} while (false);
return STATUS_REJECTED;
}
static int sellOutPrepare(session &ses, SecurityQuote "e){
do{
transaction tr(ses);
if(!record(ses, quote))
break;
//取消 借记deposit,贷记订金subscription
AccountSuite& suite = *AccountSuiteFactory::instance(ses).getSuite(quote.client);
if(AccountingVoucher::account(suite, ACCOUNT_DEPOSIT, ACCOUNT_SUBSCRIPTION, quote.guaranty))
break;
tr.commit();
quote.status = STATUS_FINISHED;
return quote.status;
}while(false);
return STATUS_REJECTED;
}
int prepareQuote(SecurityQuote "e){
switch(quote.billType){
case BUY_IN_LIMIT_PRICE:
case BUY_IN_MARKET_PRICE:
return buyInPrepare(ses, "e);
case SELL_OUT_LIMIT_PRICE:
case SELL_OUT_MARKET_PRICE:
return sellOutPrepare(ses, "e);
default:
return STATUS_REJECTED;
}
}
static int buyInAccount(session &ses, SecurityQuote "e){
do{
transaction tr(ses);
ses << "update quote_bill set status = " << STATUS_FINISHED<<" where id = ?" , use(quote.billId);
AccountSuite& suite = *AccountSuiteFactory::instance(ses).getSuite(quote.client);
//取消 借记金融资产,贷记可供出售金融资产
if(AccountingVoucher::account(suite, BizAccount::getDeposit(quote.code), BizAccount::getForsale(quote.code), quote.quality))
break;
tr.commit();
quote.status = STATUS_FINISHED;
return quote.status;
}while(false);
return STATUS_REJECTED;
}
static int sellOutAccount(session &ses, SecurityQuote "e){
do{
transaction tr(ses);
ses << "update quote_bill set status = ? where id = ?",use((int)STATUS_FINISHED), use(quote.billId);
//取消 借记deposit,贷记订金subscription
AccountSuite& suite = *AccountSuiteFactory::instance(ses).getSuite(quote.client);
if(AccountingVoucher::account(suite, ACCOUNT_DEPOSIT, ACCOUNT_SUBSCRIPTION, quote.guaranty))
break;
tr.commit();
quote.status = STATUS_FINISHED;
return quote.status;
}while(false);
return STATUS_REJECTED;
}
int accountQuote(SecurityQuote "e){
switch(quote.billType){
case BUY_IN_LIMIT_PRICE:
case BUY_IN_MARKET_PRICE:
return buyInAccount(ses, quote);
case SELL_OUT_LIMIT_PRICE:
case SELL_OUT_MARKET_PRICE:
return sellOutAccount(ses, quote);
default:
return STATUS_REJECTED;
}
}<file_sep>//
// RoutineQuotation.h
// mycoin
//
// Created by lx on 13-12-24.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__RoutineQuotation__
#define __mycoin__RoutineQuotation__
/*
routine quotation 日常行情
成交价 时间间隔内的平均价格
成交量 时间间隔内的合计
top行情 实时,因为未成交的top报价也会包含在内,所以包含了历史情况
*/
#include <time.h>
#include "quote.h"
#include <map>
#include "Publisher.h"
using namespace std;
#define MAX_ROUTINE_LEVEL 10
class RoutineQuotation{
private:
typedef map<security_price_t, security_quality_t> SellQuoteRoutine;
typedef map<security_price_t, security_quality_t, greater<int>> BuyQuoteRoutine;
struct InnerRoutine{
security_price_t sum=0;
security_quality_t qty=0;
SellQuoteRoutine topSells;
BuyQuoteRoutine topBuys;
};
typedef map<security_code_t,struct InnerRoutine> InnerRoutineMap;
InnerRoutineMap innerMap;
static inline void fill_zero(InnerRoutine & data){
data.sum = data.qty = 0;
}
private:
template<typename TopQuotes>
inline void updateTopQuote(TopQuotes& tops, security_price_t price, security_quality_t qty ){
typename TopQuotes::iterator iter = tops.find(price);
if(iter != tops.end()){
iter->second += qty;
}else{
tops[price] = qty;
}
}
public:
inline void reset() {
for (InnerRoutineMap::iterator iter=innerMap.begin(); iter!= innerMap.end(); iter++) {
iter->second.sum = iter->second.qty = 0;
}
//for_each(innerMap.begin(), innerMap.end(), fill_zero);
}
void publish(Publisher &publisher);
int update(message_t *msg);
int update(SecurityQuote "e);
int update(ContractNote ¬e);
};
#endif /* defined(__mycoin__RoutineQuotation__) */
<file_sep>//
// aroundMatch.cpp
// mycoin-account
//
// Created by lx on 13-12-25.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include <stdio.h>
#include <unistd.h>
#include <uv.h>
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include "quote.h"
#include "aroundMatch.h"
#include "readerwriterqueue.h"
#include "account/Account.h"
#include "RoutineQuotation.h"
#include <hiredis/hiredis.h>
#include <hiredis/async.h>
#include <hiredis/adapters/libuv.h>
#include "Singleton.h"
#include "RedisPublisher.h"
#include "message/message_extend.h"
#include "WithdrawProcessor.h"
#include "QuoteProcessor.h"
#include "MessageProcessor.h"
#include "AccountExchangeProcessor.h"
#include "ContractNoteProcessor.h"
#include "queue/queue_quote.h"
#include "account/account_message.h"
#include "notify/notify.h"
using namespace std;
using namespace moodycamel;
static uv_loop_t *loop;
uv_buf_t alloc_message_buffer(uv_handle_t* handle, size_t suggested_size) {
size_t len = suggested_size > 0 ? suggested_size : sizeof(message_t);
char* base = (char *)malloc(len);
return uv_buf_init(base, len);
}
void on_client_close(uv_handle_t* handle){
free(handle);
}
void on_message_received(uv_stream_t* stream,ssize_t nread, uv_buf_t buf){
do{
if(nread < 0)
break;
assert(nread == buf.len);
message_t msg;
if(UNKOWN_MESSAGE == message_convert(buf.base, buf.len, &msg){
break;
}
//消息分类, quote类 withdraw,quote,不同用户并行,可用异步。同一用户前一quote,withdraw次序得保证。方法1 withdraw检查refkey,如果不存在,则设定该key,给出status,该key设一个withraw key, 好让后到得quote找到,然后简单抛弃,留待以后处理。quote 检查key,如果存在,则是重复quote 或是withdraw所设。找到该withdraw key,设置该withdraw staus finished。这些动作使用lua做最好。方法2 withdraw插入后到match,先跑一遍,如果没找到,有可能是withdraw quote 跑到了前面,那么插入到一个队列。 每次quote到时,都检查一次。 方法2 在match中检查比较耗时。采用方法1
//异步插入,检查 在callback中出错
//exchange类, 不同用户基本上不会冲突,可在主线程运行,
//在contractnote note可并行,异步
//redis 的集群可按user来设置 ,note 进行记帐时候,会涉及到多个机器,多个机器之间怎么保证同步
//关键是连接mongodb,couchdb等外部资源的客户端,要有好的异步设计。才能在应用上提高吞吐
//node.js js 有好的异步设计,vert.x呢?
//node.js 对外部资源的异步使用封装得怎样?vert.x呢?
//eventbus内部使用无锁队列,使用event bus,回调函数插入event(成功或失败)到event bus,
//应用程序只需要处理event bus
//event switch类要预先定制好多个callback事件,尤其是web应用相关的
//web服务器采用的fastcgi接口如果异步实现,效率能提高多少
ReaderWriterQueue<message_t> * main_msg_queue = (ReaderWriterQueue<message_t> *)stream->data;
main_msg_queue->enqueue(msg);
}while(0);
free((void *)buf.base);
uv_close((uv_handle_t*) stream, on_client_close);
}
void on_client_connection(uv_stream_t *server, int status) {
if (status == -1) {
return;
}
uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
uv_tcp_init(loop, client);
client->data = server->data;
if (uv_accept(server, (uv_stream_t*) client) == 0) {
uv_read_start((uv_stream_t*) client, alloc_message_buffer, on_message_received);
}else {
uv_close((uv_handle_t*) client, on_client_close);
}
}
void routine_quote_cb(uv_timer_t *handle, int){
publisher.publish(Singleton<RoutineQuotation>::instance());
}
template<> MessageProcessorMap * Singleton<MessageProcessorMap, 1>::_instance = NULL;
int mainloop(int timeout, const string & host, int port, int port2
,const string & publish_host, int publish_port
,ReaderWriterQueue<message_t> * main_match_msg_queue
,ReaderWriterQueue<message_t> * main_io_msg_queue
,ReaderWriterQueue<message_t> * match_msg_queue
,ReaderWriterQueue<message_t> * io_msg_quque){
loop = uv_loop_new();
uv_tcp_t server;
uv_tcp_init(loop, &server);
server->data = (void *)main_io_msg_queue;
struct sockaddr_in bind_addr = uv_ip4_addr(host.c_str(), port);
uv_tcp_bind(&server, bind_addr);
int r = uv_listen((uv_stream_t*) &server, 128, on_client_connection);
if (r) {
fprintf(stderr, "Listen error %s\n", uv_err_name(uv_last_error(loop)));
return 1;
}
RedisPublisher publisher;
publisher.connect("localhost", 6379);
redisLibuvAttach(publisher.getContext(),loop);
uv_timer_t timer_req;
uv_timer_init(loop, &timer_req);
uv_timer_start(&timer_req, routine_quote_cb, timeout, timeout);
int len = 2;
ReaderWriterQueue<message_t> * inqueue[len];
inqueue[0] = main_match_msg_queue;
inqueue[1] = main_io_msg_queue;
message_t msg;
list<message_t> out_msg_list;
extern bool g_run;
while(g_run){
for(int i=0; i++; i<len){
if(inqueue[i].try_dequeue(msg)){
switch(msg.quote.status){
case STATUS_NEW:
if(msg.quote.msg_type == ){
}else{
}
io_msg_quque.enqueue(msg);
break;
case STATUS_ACCEPTED:
match_msg_quque.enqueue(msg);
break;
case STATUS_PROCESSED:
io_msg_quque.enqueue(msg);
break;
case STATUS_FINISHED:
Singleton<RoutineQuation>::instance().update(&msg);
publisher.update(&msg);
break;
default:
break;
}
}
uv_run(loop, UV_RUN_NOWAIT);
}
return 0;
}<file_sep>/*******************************************************************
* C file generated by Protoc for Embedded C. *
* Version 1.0M4 (2013-03-31) *
* *
* Copyright (c) 2009-2013 *
* Technische Universitaet Muenchen *
* http://www4.in.tum.de/ *
* *
* Source : message.proto
* *
* Do not edit. *
*******************************************************************/
#include "Message.h"
int _memcmp(const void *p1, const void *p2, unsigned int size) {
unsigned int i;
for(i = 0; i < size; ++ i) {
if(*((char*)p1 + i) > *((char*)p2 + i))
return 1;
if(*((char*)p1 + i) < *((char*)p2 + i))
return -1;
}
return 0;
}
void _memset(void *msg_ptr, char init_val, unsigned int size) {
unsigned int i;
for(i = 0; i < size; ++ i)
*((char*)msg_ptr + i) = init_val;
}
int varint_packed_size(unsigned long value) {
if ((value & (0xffffffff << 7)) == 0) return 1;
if ((value & (0xffffffff << 14)) == 0) return 2;
if ((value & (0xffffffff << 21)) == 0) return 3;
if ((value & (0xffffffff << 28)) == 0) return 4;
return 5;
}
int write_raw_byte(char value, void *_buffer, int offset) {
*((char *)_buffer + offset) = value;
return ++offset;
}
/** Write a little-endian 32-bit integer. */
int write_raw_little_endian32(unsigned long value, void *_buffer, int offset) {
offset = write_raw_byte((char)((value ) & 0xFF), _buffer, offset);
offset = write_raw_byte((char)((value >> 8) & 0xFF), _buffer, offset);
offset = write_raw_byte((char)((value >> 16) & 0xFF), _buffer, offset);
offset = write_raw_byte((char)((value >> 24) & 0xFF), _buffer, offset);
return offset;
}
/** Write a little-endian 64-bit integer. */
int write_raw_little_endian64(unsigned long long value, void *_buffer, int offset) {
offset = write_raw_byte((char)((value ) & 0xFF), _buffer, offset);
offset = write_raw_byte((char)((value >> 8) & 0xFF), _buffer, offset);
offset = write_raw_byte((char)((value >> 16) & 0xFF), _buffer, offset);
offset = write_raw_byte((char)((value >> 24) & 0xFF), _buffer, offset);
offset = write_raw_byte((char)((value >> 32) & 0xFF), _buffer, offset);
offset = write_raw_byte((char)((value >> 40) & 0xFF), _buffer, offset);
offset = write_raw_byte((char)((value >> 48) & 0xFF), _buffer, offset);
offset = write_raw_byte((char)((value >> 56) & 0xFF), _buffer, offset);
return offset;
}
int write_raw_varint32(unsigned long value, void *_buffer, int offset) {
while (1) {
if ((value & ~0x7F) == 0) {
offset = write_raw_byte((char)value, _buffer, offset);
return offset;
} else {
offset = write_raw_byte((char)((value & 0x7F) | 0x80), _buffer, offset);
value = value >> 7;
}
}
return offset;
}
int write_raw_varint64(unsigned long long value, void *_buffer, int offset) {
while (1) {
if ((value & ~0x7FL) == 0) {
offset = write_raw_byte((char)value, _buffer, offset);
return offset;
} else {
offset = write_raw_byte((char)((value & 0x7F) | 0x80), _buffer, offset);
value = value >> 7;
}
}
return offset;
}
int write_raw_bytes(char *bytes, int bytes_size, void *_buffer, int offset) {
int i;
for(i = 0; i < bytes_size; ++ i) {
offset = write_raw_byte((char)*(bytes + i), _buffer, offset);
}
return offset;
}
unsigned long encode_zig_zag32(signed long n) {
/* Note: the right-shift must be arithmetic. */
return (n << 1) ^ (n >> 31);
}
unsigned long long encode_zig_zag64(signed long long n) {
/* Note: the right-shift must be arithmetic. */
return (n << 1) ^ (n >> 63);
}
signed long decode_zig_zag32(unsigned long n) {
return (n >> 1) ^ -(n & 1);
}
signed long long decode_zig_zag64(unsigned long long n) {
return (n >> 1) ^ -(n & 1);
}
int read_raw_byte(char *tag, void *_buffer, int offset) {
*tag = *((char *) _buffer + offset);
return ++offset;
}
/** Read a 32-bit little-endian integer from the stream. */
int read_raw_little_endian32(unsigned long *tag, void *_buffer, int offset) {
offset = read_raw_byte((char *)tag, _buffer, offset);
char b1 = (char) *tag;
offset = read_raw_byte((char *)tag, _buffer, offset);
char b2 = (char) *tag;
offset = read_raw_byte((char *)tag, _buffer, offset);
char b3 = (char) *tag;
offset = read_raw_byte((char *)tag, _buffer, offset);
char b4 = (char) *tag;
*tag = (((unsigned long)b1 & 0xff) ) |
(((unsigned long)b2 & 0xff) << 8) |
(((unsigned long)b3 & 0xff) << 16) |
(((unsigned long)b4 & 0xff) << 24);
return offset;
}
/** Read a 64-bit little-endian integer from the stream. */
int read_raw_little_endian64(unsigned long long *tag, void *_buffer, int offset) {
offset = read_raw_byte((char *)tag, _buffer, offset);
char b1 = (char) *tag;
offset = read_raw_byte((char *)tag, _buffer, offset);
char b2 = (char) *tag;
offset = read_raw_byte((char *)tag, _buffer, offset);
char b3 = (char) *tag;
offset = read_raw_byte((char *)tag, _buffer, offset);
char b4 = (char) *tag;
offset = read_raw_byte((char *)tag, _buffer, offset);
char b5 = (char) *tag;
offset = read_raw_byte((char *)tag, _buffer, offset);
char b6 = (char) *tag;
offset = read_raw_byte((char *)tag, _buffer, offset);
char b7 = (char) *tag;
offset = read_raw_byte((char *)tag, _buffer, offset);
char b8 = (char) *tag;
*tag = (((unsigned long long)b1 & 0xff) ) |
(((unsigned long long)b2 & 0xff) << 8) |
(((unsigned long long)b3 & 0xff) << 16) |
(((unsigned long long)b4 & 0xff) << 24) |
(((unsigned long long)b5 & 0xff) << 32) |
(((unsigned long long)b6 & 0xff) << 40) |
(((unsigned long long)b7 & 0xff) << 48) |
(((unsigned long long)b8 & 0xff) << 56);
return offset;
}
int read_raw_varint32(unsigned long *tag, void *_buffer, int offset) {
signed char result;
offset = read_raw_byte((char *)&result, _buffer, offset);
if (result >= 0) {
*tag = result;
return offset;
}
*tag = result & 0x7f;
offset = read_raw_byte((char *)&result, _buffer, offset);
if (result >= 0) {
*tag |= result << 7;
} else {
*tag |= (result & 0x7f) << 7;
offset = read_raw_byte((char *)&result, _buffer, offset);
if (result >= 0) {
*tag |= result << 14;
} else {
*tag |= (result & 0x7f) << 14;
offset = read_raw_byte((char *)&result, _buffer, offset);
if (result >= 0) {
*tag |= ((unsigned long)result) << 21;
} else {
*tag |= (((unsigned long)result) & 0x7f) << 21;
offset = read_raw_byte((char *)&result, _buffer, offset);
*tag |= ((unsigned long)result) << 28;
if (result < 0) {
/* Discard upper 32 bits. */
int i;
for (i = 0; i < 5; ++ i) {
offset = read_raw_byte((char *)&result, _buffer, offset);
if (result >= 0) {
return offset;
}
}
/* Invalid state. */
}
}
}
}
return offset;
}
int read_raw_varint64(unsigned long long *tag, void *_buffer, int offset) {
short shift = 0;
signed char b;
*tag = 0;
while (shift < 64) {
offset = read_raw_byte((char *)&b, _buffer, offset);
*tag |= (unsigned long long)(b & 0x7F) << shift;
if ((b & 0x80) == 0) {
return offset;
}
shift += 7;
}
/* return error code. */
return -1;
}
int can_read_raw_varint32(void *_buffer, int offset, int length) {
signed char c;
/* Bound length to valid range [0..5]. */
if (length < 0) length = 0; else
if (length > 5) length = 5;
while (length > 0) {
offset = read_raw_byte((char *)&c, _buffer, offset);
if (c >= 0) {
return 1; /* Can read (1 == true). */
}
length--;
}
return 0; /* Cannot read (0 == false). */
}
int can_read_raw_varint64(void *_buffer, int offset, int length) {
signed char c;
/* Bound length to valid range [0..5]. */
if (length < 0) length = 0; else
if (length > 10) length = 10;
while (length > 0) {
offset = read_raw_byte((char *)&c, _buffer, offset);
if (c >= 0) {
return 1; /* Can read (1 == true). */
}
length--;
}
return 0; /* Cannot read (0 == false). */
}
int Message_can_read_delimited_from(void *_buffer, int offset, unsigned int length) {
unsigned long size;
int payload_offset;
if (length <= 0) return 0; /* Cannot read from empty or invalid message. */
if (!can_read_raw_varint32(_buffer, offset, length)) {
return 0; /* Could not even read the preceding size as varint32. */
}
payload_offset = read_raw_varint32(&size, _buffer, offset);
length = length - (payload_offset - offset);
return (length >= size) ? 1 : 0;
}
unsigned long Message_get_delimited_size(void *_buffer, int offset) {
unsigned long size = 0;
int old_offset = offset;
offset = read_raw_varint32(&size, _buffer, offset);
return size + offset - old_offset;
}
/*******************************************************************
* Enumeration: Message.proto, line 26
*******************************************************************/
int message_type_t_write_with_tag(enum message_type_t *_message_type_t, void *_buffer, int offset, int tag) {
/* Write tag.*/
offset = write_raw_varint32((tag<<3)+0, _buffer, offset);
/* Write content.*/
offset = write_raw_varint32(*_message_type_t, _buffer, offset);
return offset;
}
/*******************************************************************
* Enumeration: Message.proto, line 17
*******************************************************************/
int bill_status_t_write_with_tag(enum bill_status_t *_bill_status_t, void *_buffer, int offset, int tag) {
/* Write tag.*/
offset = write_raw_varint32((tag<<3)+0, _buffer, offset);
/* Write content.*/
offset = write_raw_varint32(*_bill_status_t, _buffer, offset);
return offset;
}
/*******************************************************************
* Enumeration: Message.proto, line 5
*******************************************************************/
int security_bill_t_write_with_tag(enum security_bill_t *_security_bill_t, void *_buffer, int offset, int tag) {
/* Write tag.*/
offset = write_raw_varint32((tag<<3)+0, _buffer, offset);
/* Write content.*/
offset = write_raw_varint32(*_security_bill_t, _buffer, offset);
return offset;
}
/*******************************************************************
* Message: Message.proto, line 35
*******************************************************************/
void SecurityQuote_clear(struct SecurityQuote *_SecurityQuote) {
_memset(_SecurityQuote, 0, sizeof(struct SecurityQuote));
}
void SecurityQuote_init_optional_attributes(struct SecurityQuote *_SecurityQuote) {
}
int SecurityQuote_is_default_message(struct SecurityQuote *_SecurityQuote) {
return _SecurityQuote->msg_type == 0
&& _SecurityQuote->billType == 0
&& _SecurityQuote->billId == 0
&& _SecurityQuote->occurTime == 0
&& _SecurityQuote->status == 0
&& _SecurityQuote->code == 0
&& _SecurityQuote->price == 0
&& _SecurityQuote->quality == 0
&& _SecurityQuote->_guaranty == 0
&& _SecurityQuote->_client_len == 0
;
}
int SecurityQuote_write(struct SecurityQuote *_SecurityQuote, void *_buffer, int offset) {
/* Write content of each message element.*/
offset = message_type_t_write_with_tag(&_SecurityQuote->msg_type, _buffer, offset, 1);
offset = security_bill_t_write_with_tag(&_SecurityQuote->billType, _buffer, offset, 2);
offset = write_raw_varint32((3<<3)+0, _buffer, offset);
offset = write_raw_varint32(_SecurityQuote->billId, _buffer, offset);
offset = write_raw_varint32((4<<3)+0, _buffer, offset);
offset = write_raw_varint32(_SecurityQuote->occurTime, _buffer, offset);
offset = bill_status_t_write_with_tag(&_SecurityQuote->status, _buffer, offset, 5);
offset = write_raw_varint32((6<<3)+0, _buffer, offset);
offset = write_raw_varint64(_SecurityQuote->code, _buffer, offset);
offset = write_raw_varint32((7<<3)+0, _buffer, offset);
offset = write_raw_varint32(_SecurityQuote->price, _buffer, offset);
offset = write_raw_varint32((8<<3)+0, _buffer, offset);
offset = write_raw_varint32(_SecurityQuote->quality, _buffer, offset);
offset = write_raw_varint32((9<<3)+0, _buffer, offset);
offset = write_raw_varint32(_SecurityQuote->_guaranty, _buffer, offset);
offset = write_raw_varint32((10<<3)+2, _buffer, offset);
offset = write_raw_varint32(_SecurityQuote->_client_len, _buffer, offset);
offset = write_raw_bytes(_SecurityQuote->client, _SecurityQuote->_client_len, _buffer, offset);
return offset;
}
int SecurityQuote_write_with_tag(struct SecurityQuote *_SecurityQuote, void *_buffer, int offset, int tag) {
/* Write tag.*/
offset = write_raw_varint32((tag<<3)+2, _buffer, offset);
/* Write content.*/
offset = SecurityQuote_write_delimited_to(_SecurityQuote, _buffer, offset);
return offset;
}
int SecurityQuote_write_delimited_to(struct SecurityQuote *_SecurityQuote, void *_buffer, int offset) {
int i, shift, new_offset, size;
new_offset = SecurityQuote_write(_SecurityQuote, _buffer, offset);
size = new_offset - offset;
shift = (size > 127) ? 2 : 1;
for (i = new_offset - 1; i >= offset; -- i)
*((char *)_buffer + i + shift) = *((char *)_buffer + i);
write_raw_varint32((unsigned long) size, _buffer, offset);
return new_offset + shift;
}
int SecurityQuote_read(void *_buffer, struct SecurityQuote *_SecurityQuote, int offset, int limit) {
unsigned int i = 0;
unsigned long long value = i;
unsigned long tag = value;
/* Reset all attributes to 0 in advance. */
SecurityQuote_clear(_SecurityQuote);
/* Assign the optional attributes. */
SecurityQuote_init_optional_attributes(_SecurityQuote);
/* Read/interpret all attributes from buffer offset until upper limit is reached. */
while(offset < limit) {
offset = read_raw_varint32(&tag, _buffer, offset);
tag = tag>>3;
switch(tag){
/* tag of: _SecurityQuote.msg_type */
case 1 :
offset = read_raw_varint32(&tag, _buffer, offset);
_SecurityQuote->msg_type = tag;
break;
/* tag of: _SecurityQuote.billType */
case 2 :
offset = read_raw_varint32(&tag, _buffer, offset);
_SecurityQuote->billType = tag;
break;
/* tag of: _SecurityQuote.billId */
case 3 :
offset = read_raw_varint32(&tag, _buffer, offset);
_SecurityQuote->billId = tag;
break;
/* tag of: _SecurityQuote.occurTime */
case 4 :
offset = read_raw_varint32(&tag, _buffer, offset);
_SecurityQuote->occurTime = tag;
break;
/* tag of: _SecurityQuote._status */
case 5 :
offset = read_raw_varint32(&tag, _buffer, offset);
_SecurityQuote->status = tag;
break;
/* tag of: _SecurityQuote._code */
case 6 :
offset = read_raw_varint64(&value, _buffer, offset);
_SecurityQuote->code = value;
break;
/* tag of: _SecurityQuote._price */
case 7 :
offset = read_raw_varint32(&tag, _buffer, offset);
_SecurityQuote->price = tag;
break;
/* tag of: _SecurityQuote._quality */
case 8 :
offset = read_raw_varint32(&tag, _buffer, offset);
_SecurityQuote->quality = tag;
break;
/* tag of: _SecurityQuote._guaranty */
case 9 :
offset = read_raw_varint32(&tag, _buffer, offset);
_SecurityQuote->_guaranty = tag;
break;
/* tag of: _SecurityQuote._client */
case 10 :
/* Re-use 'tag' to store string length. */
offset = read_raw_varint32(&tag, _buffer, offset);
_SecurityQuote->_client_len = tag;
for(i = 0; i < tag; ++ i)
offset = read_raw_byte((_SecurityQuote->client + i), _buffer, offset);
break;
}
}
return offset;
}
int SecurityQuote_read_delimited_from(void *_buffer, struct SecurityQuote *_SecurityQuote, int offset) {
unsigned long size;
offset = read_raw_varint32(&size, _buffer, offset);
SecurityQuote_read(_buffer, _SecurityQuote, offset, size + offset);
return offset + size;
}
/*******************************************************************
* Message: Message.proto, line 49
*******************************************************************/
void WithdrawQuote_clear(struct WithdrawQuote *_WithdrawQuote) {
_memset(_WithdrawQuote, 0, sizeof(struct WithdrawQuote));
}
void WithdrawQuote_init_optional_attributes(struct WithdrawQuote *_WithdrawQuote) {
}
int WithdrawQuote_is_default_message(struct WithdrawQuote *_WithdrawQuote) {
return _WithdrawQuote->msg_type == 0
&& _WithdrawQuote->billType == 0
&& _WithdrawQuote->billId == 0
&& _WithdrawQuote->occurTime == 0
&& _WithdrawQuote->status == 0
&& _WithdrawQuote->code == 0
&& _WithdrawQuote->refBillId == 0
&& _WithdrawQuote->_client_len == 0
;
}
int WithdrawQuote_write(struct WithdrawQuote *_WithdrawQuote, void *_buffer, int offset) {
/* Write content of each message element.*/
offset = message_type_t_write_with_tag(&_WithdrawQuote->msg_type, _buffer, offset, 1);
offset = security_bill_t_write_with_tag(&_WithdrawQuote->billType, _buffer, offset, 2);
offset = write_raw_varint32((3<<3)+0, _buffer, offset);
offset = write_raw_varint32(_WithdrawQuote->billId, _buffer, offset);
offset = write_raw_varint32((4<<3)+0, _buffer, offset);
offset = write_raw_varint32(_WithdrawQuote->occurTime, _buffer, offset);
offset = bill_status_t_write_with_tag(&_WithdrawQuote->status, _buffer, offset, 5);
offset = write_raw_varint32((6<<3)+0, _buffer, offset);
offset = write_raw_varint64(_WithdrawQuote->code, _buffer, offset);
offset = write_raw_varint32((7<<3)+0, _buffer, offset);
offset = write_raw_varint32(_WithdrawQuote->refBillId, _buffer, offset);
offset = write_raw_varint32((8<<3)+2, _buffer, offset);
offset = write_raw_varint32(_WithdrawQuote->_client_len, _buffer, offset);
offset = write_raw_bytes(_WithdrawQuote->client, _WithdrawQuote->_client_len, _buffer, offset);
return offset;
}
int WithdrawQuote_write_with_tag(struct WithdrawQuote *_WithdrawQuote, void *_buffer, int offset, int tag) {
/* Write tag.*/
offset = write_raw_varint32((tag<<3)+2, _buffer, offset);
/* Write content.*/
offset = WithdrawQuote_write_delimited_to(_WithdrawQuote, _buffer, offset);
return offset;
}
int WithdrawQuote_write_delimited_to(struct WithdrawQuote *_WithdrawQuote, void *_buffer, int offset) {
int i, shift, new_offset, size;
new_offset = WithdrawQuote_write(_WithdrawQuote, _buffer, offset);
size = new_offset - offset;
shift = (size > 127) ? 2 : 1;
for (i = new_offset - 1; i >= offset; -- i)
*((char *)_buffer + i + shift) = *((char *)_buffer + i);
write_raw_varint32((unsigned long) size, _buffer, offset);
return new_offset + shift;
}
int WithdrawQuote_read(void *_buffer, struct WithdrawQuote *_WithdrawQuote, int offset, int limit) {
unsigned int i = 0;
unsigned long long value = i;
unsigned long tag = value;
/* Reset all attributes to 0 in advance. */
WithdrawQuote_clear(_WithdrawQuote);
/* Assign the optional attributes. */
WithdrawQuote_init_optional_attributes(_WithdrawQuote);
/* Read/interpret all attributes from buffer offset until upper limit is reached. */
while(offset < limit) {
offset = read_raw_varint32(&tag, _buffer, offset);
tag = tag>>3;
switch(tag){
/* tag of: _WithdrawQuote.msg_type */
case 1 :
offset = read_raw_varint32(&tag, _buffer, offset);
_WithdrawQuote->msg_type = tag;
break;
/* tag of: _WithdrawQuote.billType */
case 2 :
offset = read_raw_varint32(&tag, _buffer, offset);
_WithdrawQuote->billType = tag;
break;
/* tag of: _WithdrawQuote.billId */
case 3 :
offset = read_raw_varint32(&tag, _buffer, offset);
_WithdrawQuote->billId = tag;
break;
/* tag of: _WithdrawQuote.occurTime */
case 4 :
offset = read_raw_varint32(&tag, _buffer, offset);
_WithdrawQuote->occurTime = tag;
break;
/* tag of: _WithdrawQuote._status */
case 5 :
offset = read_raw_varint32(&tag, _buffer, offset);
_WithdrawQuote->status = tag;
break;
/* tag of: _WithdrawQuote._code */
case 6 :
offset = read_raw_varint64(&value, _buffer, offset);
_WithdrawQuote->code = value;
break;
/* tag of: _WithdrawQuote._refBillId */
case 7 :
offset = read_raw_varint32(&tag, _buffer, offset);
_WithdrawQuote->refBillId = tag;
break;
/* tag of: _WithdrawQuote._client */
case 8 :
/* Re-use 'tag' to store string length. */
offset = read_raw_varint32(&tag, _buffer, offset);
_WithdrawQuote->_client_len = tag;
for(i = 0; i < tag; ++ i)
offset = read_raw_byte((_WithdrawQuote->client + i), _buffer, offset);
break;
}
}
return offset;
}
int WithdrawQuote_read_delimited_from(void *_buffer, struct WithdrawQuote *_WithdrawQuote, int offset) {
unsigned long size;
offset = read_raw_varint32(&size, _buffer, offset);
WithdrawQuote_read(_buffer, _WithdrawQuote, offset, size + offset);
return offset + size;
}
/*******************************************************************
* Message: Message.proto, line 61
*******************************************************************/
void ContractNote_clear(struct ContractNote *_ContractNote) {
_memset(_ContractNote, 0, sizeof(struct ContractNote));
}
void ContractNote_init_optional_attributes(struct ContractNote *_ContractNote) {
}
int ContractNote_is_default_message(struct ContractNote *_ContractNote) {
return _ContractNote->msg_type == 0
&& _ContractNote->billType == 0
&& _ContractNote->billId == 0
&& _ContractNote->occurTime == 0
&& _ContractNote->status == 0
&& _ContractNote->code == 0
&& _ContractNote->price == 0
&& _ContractNote->quality == 0
&& _ContractNote->sourceBillId == 0
&& _ContractNote->peerBillId == 0
&& _ContractNote->_buyer_len == 0
&& _ContractNote->_seller_len == 0
;
}
int ContractNote_write(struct ContractNote *_ContractNote, void *_buffer, int offset) {
/* Write content of each message element.*/
offset = message_type_t_write_with_tag(&_ContractNote->msg_type, _buffer, offset, 1);
offset = security_bill_t_write_with_tag(&_ContractNote->billType, _buffer, offset, 2);
offset = write_raw_varint32((3<<3)+0, _buffer, offset);
offset = write_raw_varint32(_ContractNote->billId, _buffer, offset);
offset = write_raw_varint32((4<<3)+0, _buffer, offset);
offset = write_raw_varint32(_ContractNote->occurTime, _buffer, offset);
offset = bill_status_t_write_with_tag(&_ContractNote->status, _buffer, offset, 5);
offset = write_raw_varint32((6<<3)+0, _buffer, offset);
offset = write_raw_varint64(_ContractNote->code, _buffer, offset);
offset = write_raw_varint32((7<<3)+0, _buffer, offset);
offset = write_raw_varint32(_ContractNote->price, _buffer, offset);
offset = write_raw_varint32((8<<3)+0, _buffer, offset);
offset = write_raw_varint32(_ContractNote->quality, _buffer, offset);
offset = write_raw_varint32((9<<3)+0, _buffer, offset);
offset = write_raw_varint32(_ContractNote->sourceBillId, _buffer, offset);
offset = write_raw_varint32((10<<3)+0, _buffer, offset);
offset = write_raw_varint32(_ContractNote->peerBillId, _buffer, offset);
offset = write_raw_varint32((11<<3)+2, _buffer, offset);
offset = write_raw_varint32(_ContractNote->_buyer_len, _buffer, offset);
offset = write_raw_bytes(_ContractNote->buyer, _ContractNote->_buyer_len, _buffer, offset);
offset = write_raw_varint32((12<<3)+2, _buffer, offset);
offset = write_raw_varint32(_ContractNote->_seller_len, _buffer, offset);
offset = write_raw_bytes(_ContractNote->seller, _ContractNote->_seller_len, _buffer, offset);
return offset;
}
int ContractNote_write_with_tag(struct ContractNote *_ContractNote, void *_buffer, int offset, int tag) {
/* Write tag.*/
offset = write_raw_varint32((tag<<3)+2, _buffer, offset);
/* Write content.*/
offset = ContractNote_write_delimited_to(_ContractNote, _buffer, offset);
return offset;
}
int ContractNote_write_delimited_to(struct ContractNote *_ContractNote, void *_buffer, int offset) {
int i, shift, new_offset, size;
new_offset = ContractNote_write(_ContractNote, _buffer, offset);
size = new_offset - offset;
shift = (size > 127) ? 2 : 1;
for (i = new_offset - 1; i >= offset; -- i)
*((char *)_buffer + i + shift) = *((char *)_buffer + i);
write_raw_varint32((unsigned long) size, _buffer, offset);
return new_offset + shift;
}
int ContractNote_read(void *_buffer, struct ContractNote *_ContractNote, int offset, int limit) {
unsigned int i = 0;
unsigned long long value = i;
unsigned long tag = value;
/* Reset all attributes to 0 in advance. */
ContractNote_clear(_ContractNote);
/* Assign the optional attributes. */
ContractNote_init_optional_attributes(_ContractNote);
/* Read/interpret all attributes from buffer offset until upper limit is reached. */
while(offset < limit) {
offset = read_raw_varint32(&tag, _buffer, offset);
tag = tag>>3;
switch(tag){
/* tag of: _ContractNote.msg_type */
case 1 :
offset = read_raw_varint32(&tag, _buffer, offset);
_ContractNote->msg_type = tag;
break;
/* tag of: _ContractNote.billType */
case 2 :
offset = read_raw_varint32(&tag, _buffer, offset);
_ContractNote->billType = tag;
break;
/* tag of: _ContractNote.billId */
case 3 :
offset = read_raw_varint32(&tag, _buffer, offset);
_ContractNote->billId = tag;
break;
/* tag of: _ContractNote.occurTime */
case 4 :
offset = read_raw_varint32(&tag, _buffer, offset);
_ContractNote->occurTime = tag;
break;
/* tag of: _ContractNote._status */
case 5 :
offset = read_raw_varint32(&tag, _buffer, offset);
_ContractNote->status = tag;
break;
/* tag of: _ContractNote._code */
case 6 :
offset = read_raw_varint64(&value, _buffer, offset);
_ContractNote->code = value;
break;
/* tag of: _ContractNote._price */
case 7 :
offset = read_raw_varint32(&tag, _buffer, offset);
_ContractNote->price = tag;
break;
/* tag of: _ContractNote._quality */
case 8 :
offset = read_raw_varint32(&tag, _buffer, offset);
_ContractNote->quality = tag;
break;
/* tag of: _ContractNote._sourceBillId */
case 9 :
offset = read_raw_varint32(&tag, _buffer, offset);
_ContractNote->sourceBillId = tag;
break;
/* tag of: _ContractNote._peerBillId */
case 10 :
offset = read_raw_varint32(&tag, _buffer, offset);
_ContractNote->peerBillId = tag;
break;
/* tag of: _ContractNote._buyer */
case 11 :
/* Re-use 'tag' to store string length. */
offset = read_raw_varint32(&tag, _buffer, offset);
_ContractNote->_buyer_len = tag;
for(i = 0; i < tag; ++ i)
offset = read_raw_byte((_ContractNote->buyer + i), _buffer, offset);
break;
/* tag of: _ContractNote._seller */
case 12 :
/* Re-use 'tag' to store string length. */
offset = read_raw_varint32(&tag, _buffer, offset);
_ContractNote->_seller_len = tag;
for(i = 0; i < tag; ++ i)
offset = read_raw_byte((_ContractNote->seller + i), _buffer, offset);
break;
}
}
return offset;
}
int ContractNote_read_delimited_from(void *_buffer, struct ContractNote *_ContractNote, int offset) {
unsigned long size;
offset = read_raw_varint32(&size, _buffer, offset);
ContractNote_read(_buffer, _ContractNote, offset, size + offset);
return offset + size;
}
/*******************************************************************
* Message: Message.proto, line 78
*******************************************************************/
void AccountExchangeNote_clear(struct AccountExchangeNote *_AccountExchangeNote) {
_memset(_AccountExchangeNote, 0, sizeof(struct AccountExchangeNote));
}
void AccountExchangeNote_init_optional_attributes(struct AccountExchangeNote *_AccountExchangeNote) {
}
int AccountExchangeNote_is_default_message(struct AccountExchangeNote *_AccountExchangeNote) {
return _AccountExchangeNote->msg_type == 0
&& _AccountExchangeNote->billType == 0
&& _AccountExchangeNote->billId == 0
&& _AccountExchangeNote->occurTime == 0
&& _AccountExchangeNote->status == 0
&& _AccountExchangeNote->code == 0
&& _AccountExchangeNote->quality == 0
&& _AccountExchangeNote->_client_len == 0
;
}
int AccountExchangeNote_write(struct AccountExchangeNote *_AccountExchangeNote, void *_buffer, int offset) {
/* Write content of each message element.*/
offset = message_type_t_write_with_tag(&_AccountExchangeNote->msg_type, _buffer, offset, 1);
offset = security_bill_t_write_with_tag(&_AccountExchangeNote->billType, _buffer, offset, 2);
offset = write_raw_varint32((3<<3)+0, _buffer, offset);
offset = write_raw_varint32(_AccountExchangeNote->billId, _buffer, offset);
offset = write_raw_varint32((4<<3)+0, _buffer, offset);
offset = write_raw_varint32(_AccountExchangeNote->occurTime, _buffer, offset);
offset = bill_status_t_write_with_tag(&_AccountExchangeNote->status, _buffer, offset, 5);
offset = write_raw_varint32((6<<3)+0, _buffer, offset);
offset = write_raw_varint64(_AccountExchangeNote->code, _buffer, offset);
offset = write_raw_varint32((7<<3)+0, _buffer, offset);
offset = write_raw_varint32(_AccountExchangeNote->quality, _buffer, offset);
offset = write_raw_varint32((8<<3)+2, _buffer, offset);
offset = write_raw_varint32(_AccountExchangeNote->_client_len, _buffer, offset);
offset = write_raw_bytes(_AccountExchangeNote->client, _AccountExchangeNote->_client_len, _buffer, offset);
return offset;
}
int AccountExchangeNote_write_with_tag(struct AccountExchangeNote *_AccountExchangeNote, void *_buffer, int offset, int tag) {
/* Write tag.*/
offset = write_raw_varint32((tag<<3)+2, _buffer, offset);
/* Write content.*/
offset = AccountExchangeNote_write_delimited_to(_AccountExchangeNote, _buffer, offset);
return offset;
}
int AccountExchangeNote_write_delimited_to(struct AccountExchangeNote *_AccountExchangeNote, void *_buffer, int offset) {
int i, shift, new_offset, size;
new_offset = AccountExchangeNote_write(_AccountExchangeNote, _buffer, offset);
size = new_offset - offset;
shift = (size > 127) ? 2 : 1;
for (i = new_offset - 1; i >= offset; -- i)
*((char *)_buffer + i + shift) = *((char *)_buffer + i);
write_raw_varint32((unsigned long) size, _buffer, offset);
return new_offset + shift;
}
int AccountExchangeNote_read(void *_buffer, struct AccountExchangeNote *_AccountExchangeNote, int offset, int limit) {
unsigned int i = 0;
unsigned long long value = i;
unsigned long tag = value;
/* Reset all attributes to 0 in advance. */
AccountExchangeNote_clear(_AccountExchangeNote);
/* Assign the optional attributes. */
AccountExchangeNote_init_optional_attributes(_AccountExchangeNote);
/* Read/interpret all attributes from buffer offset until upper limit is reached. */
while(offset < limit) {
offset = read_raw_varint32(&tag, _buffer, offset);
tag = tag>>3;
switch(tag){
/* tag of: _AccountExchangeNote.msg_type */
case 1 :
offset = read_raw_varint32(&tag, _buffer, offset);
_AccountExchangeNote->msg_type = tag;
break;
/* tag of: _AccountExchangeNote.billType */
case 2 :
offset = read_raw_varint32(&tag, _buffer, offset);
_AccountExchangeNote->billType = tag;
break;
/* tag of: _AccountExchangeNote.billId */
case 3 :
offset = read_raw_varint32(&tag, _buffer, offset);
_AccountExchangeNote->billId = tag;
break;
/* tag of: _AccountExchangeNote.occurTime */
case 4 :
offset = read_raw_varint32(&tag, _buffer, offset);
_AccountExchangeNote->occurTime = tag;
break;
/* tag of: _AccountExchangeNote._status */
case 5 :
offset = read_raw_varint32(&tag, _buffer, offset);
_AccountExchangeNote->status = tag;
break;
/* tag of: _AccountExchangeNote._code */
case 6 :
offset = read_raw_varint64(&value, _buffer, offset);
_AccountExchangeNote->code = value;
break;
/* tag of: _AccountExchangeNote._quality */
case 7 :
offset = read_raw_varint32(&tag, _buffer, offset);
_AccountExchangeNote->quality = tag;
break;
/* tag of: _AccountExchangeNote._client */
case 8 :
/* Re-use 'tag' to store string length. */
offset = read_raw_varint32(&tag, _buffer, offset);
_AccountExchangeNote->_client_len = tag;
for(i = 0; i < tag; ++ i)
offset = read_raw_byte((_AccountExchangeNote->client + i), _buffer, offset);
break;
}
}
return offset;
}
int AccountExchangeNote_read_delimited_from(void *_buffer, struct AccountExchangeNote *_AccountExchangeNote, int offset) {
unsigned long size;
offset = read_raw_varint32(&size, _buffer, offset);
AccountExchangeNote_read(_buffer, _AccountExchangeNote, offset, size + offset);
return offset + size;
}
<file_sep>//
// WithdrawProcessor.h
// mycoin
//
// Created by lx on 14-1-8.
// Copyright (c) 2014年 lx. All rights reserved.
//
#ifndef __mycoin__WithdrawProcessor__
#define __mycoin__WithdrawProcessor__
#include "MessageProcessor.h"
class WithdrawProcessor:public MessageProcessor{
protected:
typedef int (*)(WithdrawQuote&) account_func_t;
typedef int (*)(WithdrawQuote&) match_func_t;
account_func_t accout;
match_func_t match;
public:
WithdrawProcessor(message_type msg_type, MessageProcessorMap* processorMap
, match_func_t match
, account_func_t accout
)
:MessageProcessor(msg_type,processorMap){
this.account = accont;
this.match = match;
}
virtual int execute(message_t *msg,list<message_t> &out_msg_list){
return execute(*((WithdrawQuote*)&msg),out_msg_list);
}
int execute(WithdrawQuote "e,list<message_t> &out_msg_list){
switch (quote.status) {
case STATUS_NEW:
return quote.status = STATUS_ACCEPTED;
case STATUS_ACCEPTED:
return match != NULL ? match(quote, out_msg_list) : STATUS_REJECTED;
case STATUS_PROCESSED:
return account != NULL ? account(quote, out_msg_list) : STATUS_REJECTED;
default:
break;
}
return STATUS_REJECTED;
}
};
#endif /* defined(__mycoin__WithdrawAccount__) */
<file_sep>//
// QuoteProcessorSetTest.h
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__MarketPriceStrategyTest__
#define __mycoin__MarketPriceStrategyTest__
#include "gtest/gtest.h"
#include "../MarketPriceStrategy.h"
#endif /* defined(__mycoin__QuoteProcessorSetTest__) */
<file_sep>//
// MycoinApplication.cpp
// mycoin-account
//
// Created by lx on 13-12-25.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <Poco/Util/ServerApplication.h>
#include <uv.h>
#include "MycoinApplication.h"
#include "aroundMatch.h"
#include "thread_fn.h"
using namespace Poco;
using namespace Poco::Util;
using namespace std;
bool g_run = true;
int main(int argc, char** argv)
{
MycoinApplication app;
app.init(argc,argv);
return app.run(argc, argv);
}
int mainloop(int timeout, const string & host, int port, int port2
,const string & publish_host, int publish_port
,ReaderWriterQueue<message_t> *main_msg_queue
,ReaderWriterQueue<message_t> *main_msg_queue2
,ReaderWriterQueue<message_t> * match_msg_queue
,ReaderWriterQueue<message_t> * io_msg_quque);
int MycoinApplication::main( const std::vector < std::string > & args){
//loadConfiguration();
LayeredConfiguration& conf = config();
const string& host = "localhost"; //conf.getString("host");
int port = 5000; //conf.getInt("quote_port");
int port2 = 5001; //conf.getInt("fund_port");
const string& publish_host = "localhost";//conf.getString("publish_host");
int publish_port = 11211; //conf.getInt("publish_port");
int timeout = 2000;//conf.getInt("quote");
int quote_queue_length = 1024; //conf.getInt("quote_queue_length");
int note_queue_length = 1024;//conf.getInt("note_queue_length");
using namespace moodycamel;
#define CONTRANCT_NOTE_QUEUE_LENGTH 1024
ReaderWriterQueue<message_t> main_msg_queue(quote_queue_length);
ReaderWriterQueue<message_t> main_msg_queue2(quote_queue_length);
ReaderWriterQueue<message_t> io_msg_quque(note_queue_length);
ReaderWriterQueue<message_t> match_msg_queue(quote_queue_length);
struct thread_context_t matchContext;
matchContext.msgs = &match_msg_queue;
matchContext.outs = &main_msg_queue;
uv_thread_t match_id;
uv_thread_create(&match_id, match_fn, &matchContext);
uv_thread_join(&match_id);
struct thread_context_t ioContext;
ioContext.msgs = &io_msg_quque;
ioContext.outs = &main_msg_queue2;
uv_thread_t io_id;
uv_thread_create(&io_id, io_fn, io_msg_quque, main_msg_queue);
uv_thread_join(&io_id);
return mainloop(timeout, host, port, port2, publish_host, publish_port, ¬es, &main_msg_queue, &main_msg_queue2, &match_msg_queue, &io_msg_quque);
}
//routine quotation 日常行情
/*
能否应用map reduce概念,可否嵌入lua,lua是否有足够数据结构来支撑
*/
//如果运行中多个事件,发生了关联,那么创建event source的snapshot救困难了。完成的事件之间的联系会生成一个图,
//当第一个事件产生的图不再生长时,也就是产生了相隔离的图之后,才能创建snapshot。恢复时,应把这些事件通通排除。
//但是排除这些事件之后,能否重演事件 CQRS??无法保证的情况下,必须是整个系统snapshot,而不只是eventsource
//整个系统的snapshot必由多部分组成,多部分如何确保同步/同一? 是不是各部分都得模拟一个eventsource
//在一个不是24小时交易的系统中,可以每次启动做snapshot,那么也能做到从snapshot重演
<file_sep>//
// QuoteWithDrawProcessor.cpp
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "QuoteWithDrawProcessorTest.h"
#include <typeinfo>
namespace {
inline security_price_t process(SecurityQuote *quote, BuyQuoteMultiMap* buyQueue, SellQuoteMultiMap *sellQueue){
SelfQuoteQueue *selfQueue = identify.getSelfQueue(buyQueue, sellQueue);
for(typename SelfQuoteQueue::iterator iter = selfQueue->begin(); iter!=selfQueue->end(); iter++){
if(quote->billId == iter->second.billId){
finishQuote(quote);
break;
}
}
return 0;
}
class QuoteProcessorTest : public ::testing::Test {
protected:
// You can remove any or all of the following functions if its body
// is empty.
QuoteProcessorTest() {
// You can do set-up work for each test here.
}
virtual ~QuoteProcessorTest() {
// You can do clean-up work that doesn't throw exceptions here.
}
/*
SetUpTestCase() 方法在第一个TestCase之前执行
*/
static void SetUpTestCase() {
code = random();
QuoteQueue& quoteQueue = QuoteQueue::getInstance();
sellQueue = "eQueue.getSellQuoteQueue(code);
buyQueue = "eQueue.getBuyQuoteQueue(code);
QuoteProcessorFactory& factory = QuoteProcessorFactory::getInstance();
buyInLimitPriceProcessor = &factory.getQuoteProcessor(BUY_IN_LIMIT_PRICE);
sellOutLimitPriceProcessor = &factory.getQuoteProcessor(SELL_OUT_LIMIT_PRICE);
buyInMarketPriceProcessor = factory.getQuoteProcessor(BUY_IN_MARKET_PRICE);
sellOutMarketPriceProcessor = factory.getQuoteProcessor(SELL_OUT_MARKET_PRICE);
buyQuoteWithdrawProcessor = factory.getQuoteProcessor(BUY_WITHDRAW);
sellQuoteWithdrawProcessor = factory.getQuoteProcessor(SELL_WITHDRAW);
}
/*
TearDownTestCase() 方法在最后一个TestCase之后执行
*/
static void TearDownTestCase() {
QuoteQueue& quoteQueue = QuoteQueue::getInstance();
quoteQueue.clearQueue();
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
//SetUp()方法在每个TestCase之前执行
virtual void SetUp() {
// Code here will be called immediately after the constructor (right
// before each test).
}
//TearDown()方法在每个TestCase之后执行
virtual void TearDown() {
// Code here will be called immediately after each test (right
// before the destructor).
buyQueue.clear();
sellQueue.clear();
}
// Objects declared here can be used by all tests in the test case.
SellQuoteMultiMap * sellQueue;
BuyQuoteMultiMap * buyQueue;
security_code_t code;
QuoteProcessor* buyInLimitPriceProcessor;
QuoteProcessor* sellOutLimitPriceProcessor;
QuoteProcessor* buyInMarketPriceProcessor;
QuoteProcessor* sellOutMarketPriceProcessor;
QuoteProcessor* buyQuoteWithdrawProcessor;
QuoteProcessor* sellQuoteWithdrawProcessor;
};
TEST_F(QuoteProcessorTest, withdrawBuy) {
SecurityQuote quote;
quote.billId = random();
quote.code = code;
quote.billType = BUY_IN_LIMIT_PRICE;
buyInLimitPriceProcessor.process("e, buyQueue, sellQueue);
SecurityQuote quote2;
quote2.billId = random();
quote2.code = code;
quote2.refBillId = quote.billId;
quote2.billType = BUY_WITHDRAW;
buyWithdrawProcessor.process("e, buyQueue, sellQueue );
int count = 0;
for (QuoteProcessor::iterator iter =buyWithdrawProcessor.notes_begin(); iter!= buyWithdrawProcessor.notes_end(); iter++) {
if(iter.sourceBillId == quote.billId || iter.sourceBillId == quote2.billId){
count++;
}
}
ASSERT_EQ(count, 2);
//同时判断是否finished单,即其余参数为0
count = 0;
for (BuyQuoteMuiltiMap::iterator iter = buyQueue.begin(); iter!= buyQueue.end(); iter++) {
if(iter.billId == quote2.refBillId){
count = 1;
break;
}
}
ASSERT_EQ(count, 0);
}
TEST_F(QuoteProcessorTest, withdrawSell) {
SecurityQuote quote;
quote.billId = random();
quote.code = code;
quote.billType = SELL_OUT_LIMIT_PRICE;
buyInLimitPriceProcessor.process("e, buyQueue, sellQueue);
SecurityQuote quote2;
quote2.billId = random();
quote2.code = code;
quote2.refBillId = quote.billId;
quote2.billType = BUY_WITHDRAW;
buyWithdrawProcessor.process("e, buyQueue, sellQueue );
int count = 0;
for (QuoteProcessor::iterator iter =buyWithdrawProcessor.notes_begin(); iter!= buyWithdrawProcessor.notes_end(); iter++) {
if(iter.sourceBillId == quote.billId || iter.sourceBillId == quote2.billId){
count++;
}
}
ASSERT_EQ(count, 2);
//同时判断是否finished单,即其余参数为0
count = 0;
for (BuyQuoteMuiltiMap::iterator iter = buyQueue.begin(); iter!= buyQueue.end(); iter++) {
if(iter.billId == quote2.refBillId){
count = 1;
break;
}
}
ASSERT_EQ(count, 0);
}
} // namespace<file_sep>//
// Account.h
// mycoin
//
// Created by lx on 13-12-13.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef mycoin_Account_h
#define mycoin_Account_h
#include <time.h>
#include <string>
#define ACCOUNT_DEPOSIT ""
#define ACCOUNT_EXCHANGE ""
#define ACCOUNT_EXCHANGE ""
#define ACCOUNT_SUBSCRIPTION ""
#define ACCOUNT_BTC_EXCHANGE ""
#define ACCOUNT_BTC_FORSALE ""
#define ACCOUNT_BTC_DEPOSIT ""
#define ACCOUNT_LTC_EXCHANGE ""
#define ACCOUNT_LTC_DEPOSIT ""
#define ACCOUNT_LTC_FORSALE ""
#define ACCOUNT_FEE_TRANSACTION ""
#define ACCOUNT_CASH ""
#define ACCOUNT_INCOME_TRANSACTION ""
#define ACCOUNT_REFUND ""
typedef enum balance_type_t{REAL_TIME, WEEK, MONTH, YEAE} balance_type_t;
typedef int money_t;
using namespace std;
class Account{
protected:
const string& code;
const string& owner;
time_t start_time;
time_t end_time;
money_t balance;
protected:
virtual bool debit(time_t occurTime, money_t money){return false;}
virtual bool credit(time_t occurTime, money_t money){return false;}
friend class AccountSuite;
public:
money_t geBalance() { return balance;}
Account(const string& owner, const string& code):code(code), owner(owner){}
};
//AccountSuite
//owner, create_time, description, start_time, end_time
class AccountSuite{
protected:
const string& owner;
time_t create_time;
string description;
time_t start_time;
time_t end_time;
AccountingVoucher& voucher;
map<string, Account> accountMap;
public:
AccountSuite(AccountingVoucher& voucher):voucher(voucher){};
Account& getAccount(const string& code);
AccountSuite(const string& name):owner(name){}
bool account(const string& debitCode, const string& creditCode, money_t money){
time_t now;
time(&now);
voucher.account( now, this, debitCode, creditCode, money);
}
bool account(Account& debitAccount, Account& creditAccount, money_t money){
return account( debitAccount.code, creditAccount.code, money);
}
};
//记账凭证
class AccountingVoucher{
public:
bool account(time_t now, AccountSuite& suit, const string& debitCode, const string& creditCode, money_t money);
};
#endif
<file_sep>//
// IdentifyQuoteQueueTest.h
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__IdentifyQuoteQueueTest__
#define __mycoin__IdentifyQuoteQueueTestt__
#include "gtest/gtest.h"
#include "../IdentifyQuoteQueue.h"
#endif
<file_sep>//
// MessageConvertor.h
// mycoin
//
// Created by lx on 14-1-8.
// Copyright (c) 2014年 lx. All rights reserved.
//
#ifndef __mycoin__MessageConvertor__
#define __mycoin__MessageConvertor__
#include "message.h"
template <typename Message>
struct message_traits {
typedef bool (* convert_func_type)(char *, Message &) ;
typedef bool (* identify_func_type)(MessageHeader &) ;
};
template<typename message_type>
bool convertMessage( char *buf, size_t len, message_type & msg, typename message_traits<message_type>::identify_func_type identify_func, typename message_traits<message_type>::convert_func_type convert_func){
unsigned long Message_get_delimited_size(void *_buffer, int offset);
MessageHeader header;
/*
* Tests whether a message can be completely read from the given buffer at
* the offset. The bytes [offset..offset+length-1] are interpreted.
*,
* Returns 1 (true) if buffer[offset..offset+length-1] contains a complete
* message or 0 (false) otherwise.
*/
do{
if( Message_can_read_delimited_from(buf, 0, MAX_MessageHeader_SIZE) == 0)
break;
/*
* Serialize a Person-message into the given buffer at offset and return
* new offset for optional next message.
*/
int MessageHeader_write_delimited_to(struct MessageHeader *_MessageHeader, void *_buffer, int offset);
MessageHeader_read_delimited_from(buf, &header, 0);
if(identify_func(header)){
//以后将统一生成message,不再把message分散到各处
return convert_func(buf, msg);
}
}while (false);
return false;
}
#endif /* defined(__mycoin__MessageConvertor__) */
<file_sep>//
// QuoteMatchProcessorTest.h
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__QuoteMatchProcessorTest__
#define __mycoin__QuoteMatchProcessorTest__
#include "gtest/gtest.h"
#include "../QuoteMatchProcessor.h"
#endif /* defined(__mycoin__QuoteProcessorSetTest__) */
<file_sep>//
// ContractNoteAccounter.cpp
// mycoin
//
// Created by lx on 14-1-9.
// Copyright (c) 2014年 lx. All rights reserved.
//
#include "account_message.h"
#include <soci/soci.h>
#include "ContractNoteAccounter.h"
#include "Account.h"
#include "BizAccount.h"
#include "AccountSuiteFactory.h"
void ContractNoteProcessor::account(ContractNote ¬e){
do{
money_t money = note.price*note.quality;
money_t fee = money* 5 /1000;
const string & platform = "platform";
ResiVoucher voucher (switcher);
//买方借记资产,贷记资产往来
if(voucher.account_multi(note.buyer, BizAccount::getDeposit(note.code), BizAccount::getExchange(note.code),note.quality))
break;
//买方借记资金往来,贷记押金
if(voucher.account_multi(note.buyer, ACCOUNT_EXCHANGE, ACCOUNT_SUBSCRIPTION,money))
break;
//买方 借记手续费(成交价*数量*比例) 贷记 deposit,如果没钱了,那么借记手续费,贷记应付费用
if(voucher.account_multi(note.buyer, ACCOUNT_FEE_TRANSACTION, /*deposit_balance >= money or payable*/ACCOUNT_DEPOSIT, fee))
break;
//卖方 借记exchange,贷记forsale
if(voucher.account_multi(note.seller, BizAccount::getExchange(note.code), BizAccount::getForsale(note.code),note.quality))
break;
//卖方成交后 借记deposit,贷记资金往来
if(voucher.account_multi(note.seller, ACCOUNT_DEPOSIT, ACCOUNT_EXCHANGE,money))
break;
//卖方手续费 借记手续费(成交价*数量*比例) 贷记 deposit
if(voucher.account_multi(note.seller, ACCOUNT_FEE_TRANSACTION, /*seller_deposit_balance >= money or payable*/ACCOUNT_DEPOSIT , fee))
break;
//平台 借计cash 贷记收入 描述 交易号
if(voucher.account_multi(platform, ACCOUNT_CASH, ACCOUNT_INCOME_TRANSACTION, fee))
break;
//平台 买方收入 借计cash 贷记收入 描述 交易号
if(voucher.account_multi(platform, ACCOUNT_CASH, ACCOUNT_INCOME_TRANSACTION, fee))
break;
//平台 返还卖方 借记退款 refund,贷记cash
if(voucher.account_multi(platform, ACCOUNT_REFUND,ACCOUNT_CASH, fee))
break;
//卖方手续费 借记deposit,贷记退回费用或手续费
if(voucher.account_multi(note.seller, ACCOUNT_DEPOSIT, ACCOUNT_FEE_TRANSACTION, fee))
break;
//平台 返还买方 借记退款 refund,贷记cash
if(voucher.account_multi(platform, ACCOUNT_REFUND,ACCOUNT_CASH, fee))
break;
//买方 借记deposit,贷记退回费用或手续费
if(voucher.account_multi(note.buyer, ACCOUNT_DEPOSIT, ACCOUNT_FEE_TRANSACTION, fee))
break;
voucher.submit();
}while(false);
}
<file_sep>//
// Account.cpp
// mycoin
//
// Created by lx on 13-12-28.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "Account.h"
/*
private:
multimap<money_t, Account*> m_debitList, m_creditList;
struct Compare
{
bool operator()(const Account& s1, const Account& s2) const
{
return strcmp(s1, s2) < 0;
}
};
public :
void debit(Account* debitAccount, money_t const & money){
m_debitList.insert(pair<money, debitAccount>);
}
void credit(Account* creditAccount, money_t const & money){
m_creditList.insert<money,creditAccount>;
}
bool account(){
//校验两个列表金额时候相等
//事务处理
return true;
}
*/
Account& AccountSuite::getAccount(const string& code){
map<string, Account>::iterator iter = accountMap.find(code);
if(iter == accountMap.end()){
// iter = accountMap.insert(pair<string, Account>(code, DatabaseAccount(owner,code, ses)));
}
return iter->second;
}
<file_sep>//
// DatabaseAccount.h
// mycoin
//
// Created by lx on 13-12-15.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__DatabaseAccount__
#define __mycoin__DatabaseAccount__
#include <string>
#include <map>
#include <soci/soci.h>
#include "Account.h"
using namespace std;
using namespace soci;
class DatabaseVoucher :public AccountingVoucher{
public:
bool account(time_t now, AccountSuite& suit, const string& debitCode, const string& creditCode, money_t money);
};
#endif /* defined(__mycoin__DatabaseAccount__) */
<file_sep>//
// RedisAccount.h
// mycoin
//
// Created by lx on 14-1-11.
// Copyright (c) 2014年 lx. All rights reserved.
//
#ifndef __mycoin__RedisAccount__
#define __mycoin__RedisAccount__
//
// DatabaseAccount.h
// mycoin
//
// Created by lx on 13-12-15.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__DatabaseAccount__
#define __mycoin__DatabaseAccount__
#include <string>
#include "Account.h"
using namespace std;
class RedisVoucher:public AccountVoucher{
private:
EventSwitcher &switcher;
map<string, Account> accountMap;
public:
RedisVoucher(EventSwitcher &switcher):switcher(switcher){}
Account& getAccount(const string& code);
bool account( AccountSuite& suit, const string& debitCode, const string& creditCode, money_t money);
bool account( AccountSuite& suit, const string& debitCode, const string& creditCode, money_t money);
void submit();
};
#endif /* defined(__mycoin__RedisAccount__) */
<file_sep>//
// QuoteProcessorSetTest.h
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__LimitPriceStrategyTest__
#define __mycoin__LimitPriceStrategyTest__
#include "gtest/gtest.h"
#include "../LimitPriceStrategy.h"
#endif
<file_sep>//
// Singleton.h
// mycoin
//
// Created by lx on 14-1-6.
// Copyright (c) 2014年 lx. All rights reserved.
//
#ifndef mycoin_Singleton_h
#define mycoin_Singleton_h
template<typename InnerSingleton, int sub=0 >
class Singleton{
private:
static InnerSingleton *_instance;
Singleton(){}
public:
~Singleton(){
delete _instance;
_instance = 0;
}
static InnerSingleton& instance(){
if(_instance == 0)
_instance = new InnerSingleton();
return *_instance;
}
static void setInstance(InnerSingleton* single){
if(single != NULL){
if(_instance != NULL){
delete _instance;
}
_instance = single;
}
};
#endif
<file_sep>/*******************************************************************
* Header file generated by Protoc for Embedded C. *
* Version 1.0M4 (2013-03-31) *
* *
* Copyright (c) 2009-2013 *
* Technische Universitaet Muenchen *
* http://www4.in.tum.de/ *
* *
* Source : Message.proto
* *
* Do not edit. *
*******************************************************************/
#ifndef _Message_H
#define _Message_H
#ifdef __cplusplus
extern "C" {
#endif
#define MAX_REPEATED_LENGTH 100
#define MAX_STRING_LENGTH 21
/*******************************************************************
* General functions
*******************************************************************/
/*
* returns the size of a length delimited message which also
* contains the first bytes for the length encoding.
*/
unsigned long Message_get_delimited_size(void *_buffer, int offset);
/*
* Tests whether a message can be completely read from the given buffer at
* the offset. The bytes [offset..offset+length-1] are interpreted.
*
* Returns 1 (true) if buffer[offset..offset+length-1] contains a complete
* message or 0 (false) otherwise.
*/
int Message_can_read_delimited_from(void *_buffer, int offset, unsigned int length);
/*******************************************************************
* Enumeration: Message.proto, line 5
*******************************************************************/
enum security_bill_t {
BUY_IN_LIMIT_PRICE = 0,
SELL_OUT_LIMIT_PRICE = 1,
BUY_IN_MARKET_PRICE = 2,
SELL_OUT_MARKET_PRICE = 3,
BUY_WITHDRAW = 4,
SELL_WITHDRAW = 5,
ACCOUNT_CHARGE = 6,
ACCOUNT_WITHDRAW = 7,
CONTRACT_NOTE = 8
};
/*******************************************************************
* Enumeration: Message.proto, line 17
*******************************************************************/
enum bill_status_t {
STATUS_NEW = 0,
STATUS_PROCESSED = 1,
STATUS_ACCEPTED = 2,
STATUS_REJECTED = 3,
STATUS_FINISHED = 4,
STATUS_INVALID = 5
};
/*******************************************************************
* Enumeration: Message.proto, line 26
*******************************************************************/
enum message_type_t {
UNKOWN_MESSAGE = 0,
SECURITY_QUOTE = 1,
WITHDRAW_QUOTE = 2,
CONTRACT_NOTE = 3,
ACCOUNT_EXCHANGE_NOTE = 4
};
/*******************************************************************
* Message: Message.proto, line 35
*******************************************************************/
/* Maximum size of a serialized SecurityQuote-message, useful for buffer allocation. */
#define MAX_SecurityQuote_SIZE 82
/* Structure that holds a deserialized SecurityQuote-message. */
struct SecurityQuote {
enum message_type_t msg_type;
enum security_bill_t billType;
unsigned long billId;
unsigned long occurTime;
enum bill_status_t status;
unsigned long long code;
unsigned long price;
unsigned long quality;
unsigned long guaranty;
int _client_len;
char client[MAX_STRING_LENGTH];
};
/*
* Serialize a Person-message into the given buffer at offset and return
* new offset for optional next message.
*/
int SecurityQuote_write_delimited_to(struct SecurityQuote *_SecurityQuote, void *_buffer, int offset);
/*
* Serialize a Person-message together with its tag into the given buffer
* at offset and return new offset for optional next message.
* Is useful if a Person-message is embedded in another message.
*/
int SecurityQuote_write_with_tag(struct SecurityQuote *_SecurityQuote, void *_buffer, int offset, int tag);
/*
* Deserialize a Person-message from the given buffer at offset and return
* new offset for optional next message.
*
* Note: All fields in _Person will be reset to 0 before _buffer is interpreted.
*/
int SecurityQuote_read_delimited_from(void *_buffer, struct SecurityQuote *_SecurityQuote, int offset);
/*******************************************************************
* Message: Message.proto, line 49
*******************************************************************/
/* Maximum size of a serialized WithdrawQuote-message, useful for buffer allocation. */
#define MAX_WithdrawQuote_SIZE 68
/* Structure that holds a deserialized WithdrawQuote-message. */
struct WithdrawQuote {
enum message_type_t msg_type;
enum security_bill_t billType;
unsigned long billId;
unsigned long occurTime;
enum bill_status_t status;
unsigned long long code;
unsigned long refBillId;
int _client_len;
char client[MAX_STRING_LENGTH];
};
/*
* Serialize a Person-message into the given buffer at offset and return
* new offset for optional next message.
*/
int WithdrawQuote_write_delimited_to(struct WithdrawQuote *_WithdrawQuote, void *_buffer, int offset);
/*
* Serialize a Person-message together with its tag into the given buffer
* at offset and return new offset for optional next message.
* Is useful if a Person-message is embedded in another message.
*/
int WithdrawQuote_write_with_tag(struct WithdrawQuote *_WithdrawQuote, void *_buffer, int offset, int tag);
/*
* Deserialize a Person-message from the given buffer at offset and return
* new offset for optional next message.
*
* Note: All fields in _Person will be reset to 0 before _buffer is interpreted.
*/
int WithdrawQuote_read_delimited_from(void *_buffer, struct WithdrawQuote *_WithdrawQuote, int offset);
/*******************************************************************
* Message: Message.proto, line 61
*******************************************************************/
/* Maximum size of a serialized ContractNote-message, useful for buffer allocation. */
#define MAX_ContractNote_SIZE 113
/* Structure that holds a deserialized ContractNote-message. */
struct ContractNote {
enum message_type_t msg_type;
enum security_bill_t billType;
unsigned long billId;
unsigned long occurTime;
enum bill_status_t status;
unsigned long long code;
unsigned long price;
unsigned long quality;
unsigned long sourceBillId;
unsigned long peerBillId;
int _buyer_len;
char buyer[MAX_STRING_LENGTH];
int _seller_len;
char seller[MAX_STRING_LENGTH];
};
/*
* Serialize a Person-message into the given buffer at offset and return
* new offset for optional next message.
*/
int ContractNote_write_delimited_to(struct ContractNote *_ContractNote, void *_buffer, int offset);
/*
* Serialize a Person-message together with its tag into the given buffer
* at offset and return new offset for optional next message.
* Is useful if a Person-message is embedded in another message.
*/
int ContractNote_write_with_tag(struct ContractNote *_ContractNote, void *_buffer, int offset, int tag);
/*
* Deserialize a Person-message from the given buffer at offset and return
* new offset for optional next message.
*
* Note: All fields in _Person will be reset to 0 before _buffer is interpreted.
*/
int ContractNote_read_delimited_from(void *_buffer, struct ContractNote *_ContractNote, int offset);
/*******************************************************************
* Message: Message.proto, line 78
*******************************************************************/
/* Maximum size of a serialized AccountExchangeNote-message, useful for buffer allocation. */
#define MAX_AccountExchangeNote_SIZE 68
/* Structure that holds a deserialized AccountExchangeNote-message. */
struct AccountExchangeNote {
enum message_type_t msg_type;
enum security_bill_t billType;
unsigned long billId;
unsigned long occurTime;
enum bill_status_t status;
unsigned long long code;
unsigned long quality;
int _client_len;
char client[MAX_STRING_LENGTH];
};
/*
* Serialize a Person-message into the given buffer at offset and return
* new offset for optional next message.
*/
int AccountExchangeNote_write_delimited_to(struct AccountExchangeNote *_AccountExchangeNote, void *_buffer, int offset);
/*
* Serialize a Person-message together with its tag into the given buffer
* at offset and return new offset for optional next message.
* Is useful if a Person-message is embedded in another message.
*/
int AccountExchangeNote_write_with_tag(struct AccountExchangeNote *_AccountExchangeNote, void *_buffer, int offset, int tag);
/*
* Deserialize a Person-message from the given buffer at offset and return
* new offset for optional next message.
*
* Note: All fields in _Person will be reset to 0 before _buffer is interpreted.
*/
int AccountExchangeNote_read_delimited_from(void *_buffer, struct AccountExchangeNote *_AccountExchangeNote, int offset);
#ifdef __cplusplus
}
#endif
#endif
<file_sep>//
// RedisPublisher.cpp
// mycoin
//
// Created by lx on 13-12-31.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "RedisPublisher.h"
#include <string>
using namespace std;
void RedisPublisher::connect(const char *host, int port){
context = redisAsyncConnect(host, port); //6379
if (context->err) {
}
}
void RedisPublisher::publish(const security_code_t code, security_price_t price, security_quality_t quality, security_price_t topBuyPrice[], security_quality_t topBuyQty[], int size1, security_price_t topSellPrice[], security_quality_t topSellQty[], int size2 ){
if(context == NULL)
return;
/*
std::streambuf json;
json << "{price:" << price << ",quality:" << quality << ",topbuys:[";
for(int i=0; i< size1; i++){
json<< "{price:" << topBuyPrice[i] << ", quality:" << topBuyQty[i] << "},";
}
json << "], topsells:[";
for(int i=0; i< size2; i++){
json << "{price:" << topSellPrice[i] <<", quality:" << topSellQty[i] <<"},";
}
json << "]}";
redisAsyncCommand(context, NULL, NULL, "publish /topic/stock/%b/routation %b"
,code, strlen(code)
,json, strlen(json));
*/
}
void RedisPublisher::publish(SecurityQuote "e){
if(context == NULL)
return;
/*
std::streambuf json ;
json << "{price:" << quote.price << ",quality:" << quote.quality
<< ",guanity:" << quote->guanity << ", status:" << quote.header.status +"}";
redisAsyncCommand(context, NULL, NULL, "publish /topic/stock/queue/%b %b"
,quote.header.billId, strlen(code)
,json, strlen(json));
*/
}
int RedisPublisher::publish(ContractNote ¬e){
// 通知买了多少, 价格,数量都在变,原来的单到底是什么单,发布价格还是
/*
std::streambuf json ;
json << "{price:" << quote.price << ",quality:" << quote.quality
<< ",guanity:" << quote->guanity << ", status:" << quote.header.status +"}";
redisAsyncCommand(context, NULL, NULL, "publish /topic/stock/queue/%b %b"
,quote.header.billId, strlen(code)
,json, strlen(json));
*/
}
<file_sep>//
// IdentifyQuoteQueye.h
// mycoin
//
// Created by lx on 13-12-23.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef mycoin_IdentifyQuoteQueue_h
#define mycoin_IdentifyQuoteQueue_h
#include "../quote.h"
typedef multimap<security_price_t, SecurityQuote> SellQuoteMultiMap;
typedef multimap<security_price_t, SecurityQuote, greater<int>> BuyQuoteMultiMap;
template<typename SelfQuoteQueue, typename PeerQuoteQueue>
struct IdentifyQuoteQueue{
};
template<>
struct IdentifyQuoteQueue<BuyQuoteMultiMap,SellQuoteMultiMap>{
BuyQuoteMultiMap &getSelfQueue(BuyQuoteMultiMap& buyQueue, SellQuoteMultiMap &sellQueue){
return buyQueue;
}
SellQuoteMultiMap &getPeerQueue(BuyQuoteMultiMap& buyQueue, SellQuoteMultiMap &sellQueue){
return sellQueue;
}
};
template<>
struct IdentifyQuoteQueue<SellQuoteMultiMap,BuyQuoteMultiMap>{
SellQuoteMultiMap &getSelfQueue(BuyQuoteMultiMap& buyQueue, SellQuoteMultiMap &sellQueue){
return sellQueue;
}
BuyQuoteMultiMap &getPeerQueue(BuyQuoteMultiMap& buyQueue, SellQuoteMultiMap& sellQueue){
return buyQueue;
}
};
#endif
<file_sep>#include <stdio.h>
#include <typeinfo>
#include <list>
template<typename t1,int param>
class TClass{
};
typedef TClass<int, 1> C1;
typedef TClass<int, 2> C2;
int main(){
C1 c1;
C2 c2;
std::list<C1> clist;
clist.push_back(c1);
clist.push_back(c2);
/*
if(typeid(C1) == typeid(C2)){
printf("ok!");
}else{
printf("oh...");
}
*/
}
<file_sep>//
// LevelOfQuote.h
// mycoin
//
// Created by lx on 13-12-21.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__LevelOfQuote__
#define __mycoin__LevelOfQuote__
#include "../quote.h"
class LevelOfQuoteQueue{
private:
int _level=0;
security_billId_t _lastBillId = 0;
security_price_t _lastPrice =0;
public:
int level(security_billId_t billId, security_price_t peerPrice ){
if(billId != _lastBillId){
_level = 0;
_lastPrice = 0;
_lastBillId = billId;
}
if(peerPrice != _lastPrice){
_lastPrice = peerPrice;
++_level;
}
return _level;
}
};
#endif /* defined(__mycoin__LevelOfQuote__) */
<file_sep>//
// AccountExchangeProcessor.h
// mycoin
//
// Created by lx on 13-12-27.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__AccountExchangeProcessor__
#define __mycoin__AccountExchangeProcessor__
#include "MessageProcessor.h"
class AccountExchangeProcessor:public MessageProcessor{
protected:
typedef int (*)(AccountExchangeNote&) account_func_t;
account_func_t account;
public:
AccountExchangeProcessor(message_type msg_type, MessageProcessorMap* processorMap
, account_func_t account
)
: MessageProcessor(msg_type,processorMap){
this.account = account;
}
int execute(Event *msg, EventSwitcher& switcher){
}
int execute(AccountExchangeNote "e, EventSwitcher& switcher){
if(note.status != STATUS_NEW)
return STATUS_REJECTED;
switch(note.billType){
case ACCOUNT_CHARGE:
return charge(note,switcher);
case ACCOUNT_WITHDRAW:
return withdraw(note,switcher);
default:
return STATUS_REJECTED;
}
}
int withdraw(AccountExchangeNote ¬e);
int charge(AccountExchangeNote ¬e);
};
#endif
<file_sep>//
// RoutineQuote.h
// mycoin
//
// Created by lx on 13-12-31.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__RoutineQuote__
#define __mycoin__RoutineQuote__
#include "quote.h"
#include "Publisher.h"
#include <hiredis/hiredis.h>
#include <hiredis/async.h>
class RedisPublisher:public Publisher{
private:
redisAsyncContext *context =NULL;
public:
void connect(const char *host, int port);
redisAsyncContext * getContext(){
return context;
}
void publish(SecurityQuote "e);
virtual void publish(const security_code_t code, security_price_t price, security_quality_t quality, security_price_t topBuyPrice[], security_quality_t topBuyQty[], int size1, security_price_t topSellPrice[], security_quality_t topSellQty[], int size2 );
int publish (ContractNote ¬e);
};
#endif /* defined(__mycoin__RoutineQuote__) */
<file_sep>//
// MessageProcessor.h
// mycoin
//
// Created by lx on 14-1-3.
// Copyright (c) 2014年 lx. All rights reserved.
//
#ifndef __mycoin__MessageProcessor__
#define __mycoin__MessageProcessor__
#include <map>
#include <list>
#include "message/message_extend.h"
using namespace std;
/*
一致回调处理方式
一致同步异步编程模型
一致多线程,单线程模型
沙漠履带车安全不,不致陷落吧
坦克太重,可以搞点耐热陶瓷,又轻
*/
typedef enum {
ES_RUN_DEFAULT = 0,
ES_RUN_ONCE,
ES_RUN_NOWAIT
} es_run_mode;
template <int size>
class EventSwitcher{
protected:
map<event_type, EventProcessor *> processorMap;
typedef ReaderWriterQueue<Event> EventQueue; //vector<Event> EventQueue;
typedef vector<EventQueue&> EventQueues;
EventQueues queue(size);
public:
void connect(EventProcessor);
void push(Event &event, int rank);
void now(Event &event);
void run(es_run_mode run_mode); //once , process all until null, for ever
};
class EventProcessor{
public:
event_type & const ev_type;
EventProcessor(message_type& ev_type):ev_type(ev_type){
}
virtual int execute(Event &msg, EventSwitcher& switcher)=0;
};
class MessageProcessor;
typedef map<message_type, MessageProcessor*> MessageProcessorMap;
class MessageProcessor{
public:
message_type & msg_type;
MessageProcessor(message_type& msg_type, MessageProcessorMap* processorMap):msg_type(msg_type){
if(processorMap != NULL)
processorMap->insert(msg_type, this);
}
virtual int execute(message_t *msg, list<message_t> &)=0;
};
#endif /* defined(__mycoin__Command__) */
<file_sep>//
// thread_fn.h
// mycoin
//
// Created by lx on 14-1-9.
// Copyright (c) 2014年 lx. All rights reserved.
//
#ifndef mycoin_thread_fn_h
#define mycoin_thread_fn_h
/*
#ifdef __cplusplus
extern "C"{
#endif
*/
struct thread_context_t{
ReaderWriterQueue<message_t> * msgs;
ReaderWriterQueue<message_t> * outs;
};
void match_fn(void *);
void io_fn(void *);
/*
#ifdef __cplusplus
}
#endif
*/
#endif
<file_sep>//
// test.cpp
// mycoin
//
// Created by lx on 13-12-21.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "test.h"
#include "gtest/gtest.h"
int main(int argc, char **argv) {
::testing::AddGlobalTestEnvironment(new CoinExchangeTestEnvironment);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<file_sep>//
// QuoteQueue.h
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__QuoteQueue__
#define __mycoin__QuoteQueue__
#include <stdlib.h>
#include <algorithm>
#include <map>
#include <functional>
#include "../quote.h"
using namespace std;
typedef multimap<security_price_t, SecurityQuote> SellQuoteMultiMap;
typedef multimap<security_price_t, SecurityQuote, greater<int>> BuyQuoteMultiMap;
//inline 应该允许调用方设定
class QuoteQueue{
typedef map<security_code_t, SellQuoteMultiMap > SellQueueHash;
typedef map<security_code_t, BuyQuoteMultiMap > BuyQueueHash;
BuyQueueHash buyQueueHash;
SellQueueHash sellQueueHash;
public:
inline SellQuoteMultiMap* getSellQuoteQueue(security_code_t code){
return innerQueue(sellQueueHash,code);
}
inline BuyQuoteMultiMap* getBuyQuoteQueue(security_code_t code){
return innerQueue(buyQueueHash,code);
}
void clearQueue(){
buyQueueHash.clear();
sellQueueHash.clear();
}
private:
template<typename QueueHash>
inline typename QueueHash::mapped_type * innerQueue(QueueHash& queueHash, security_code_t code){
return &queueHash[code];
}
};
#endif /* defined(__mycoin__QuoteQueue__) */
<file_sep>//
// LevelOfQuoteTest.cpp
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "LevelOfQuoteTestQueue.h"
namespace {
TEST(LevelOfQuoteQueueTest, matchQuoteSucceess) {
LevelOfQuoteQueue levelQueue;
security_billId_t billId = -1;
security_price_t price = -1;
ASSERT_EQ(0, levelQueue.level(billId, price));
security_billId_t billId = -1;
security_price_t price = -1;
ASSERT_EQ(0,matchQuote("e, ¬es));
security_billId_t billId = -1;
security_price_t price = 2;
ASSERT_EQ(1,matchQuote("e, ¬es));
security_billId_t billId = -1;
security_price_t price = 2;
ASSERT_EQ(1,matchQuote("e, ¬es));
security_billId_t billId = -1;
security_price_t price = -1;
ASSERT_EQ(2,matchQuote("e, ¬es));
security_billId_t billId = 0;
security_price_t price = -1;
ASSERT_EQ(0,matchQuote("e, ¬es));
}
} // namespace<file_sep>coinExchange
============
虚拟货币竞价交易平台
<file_sep>//
// BizAccount.h
// mycoin
//
// Created by lx on 13-12-28.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__BizAccount__
#define __mycoin__BizAccount__
#include <string>
#include "Account.h"
using namespace std;
class BizAccount{
public:
static const char* getDeposit(int code){
switch (code) {
case 0:
return ACCOUNT_DEPOSIT;
break;
case 1:
return ACCOUNT_BTC_DEPOSIT;
case 2:
return ACCOUNT_LTC_DEPOSIT;
default:
return "";
}
}
static const char* getExchange(int code){
switch (code) {
case 00:
return ACCOUNT_EXCHANGE;
break;
case 1:
return ACCOUNT_BTC_EXCHANGE;
case 2:
return ACCOUNT_LTC_EXCHANGE;
default:
return "";
}
}
static const char* getForsale(int code){
switch (code) {
case 0:
return "";
break;
case 1:
return ACCOUNT_BTC_FORSALE;
case 2:
return ACCOUNT_LTC_FORSALE;
default:
return "";
}
}
};
#endif /* defined(__mycoin__BizAccount__) */
<file_sep>/
// CoinExchangeTestEnvironment.cpp
// mycoin
//
// Created by lx on 13-12-21.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "CoinExchangeTestEnvironment.h"
void CoinExchangeTestEnvironment::SetUp()
{
srand((unsigned)time(0));
std::cout << "CoinExchange Environment SetUP" << std::endl;
}
void CoinExchangeTestEnvironment::TearDown()
{
std::cout << "CoinExchange Environment TearDown" << std::endl;
}<file_sep>//
// match.c
// mycoin
//
// Created by lx on 13-12-27.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include "match.h"
#include "message.h"
#include "Singleton.h"
#include "readerwriterqueue.h"
#include "WithdrawProcessor.h"
#include "QuoteProcessor.h"
#include "Singleton.h"
#include "match/match_quote.h"
using namespace std;
using namespace moodycamel;
template<> MessageProcessorMap * Singleton<MessageProcessorMap, 2>::_instance = NULL;
template<> MessageProcessorMap * Singleton<MessageProcessorMap, 3>::_instance = NULL;
void match_fn(void * arg){
struct thread_context_t *context = (struct threadContext *)arg;
ReaderWriterQueue<message_t> & msgs = *(context->msgs);
ReaderWriterQueue<message_t> & outs = *(context->outs);
MessageProcessorMap &processorMap = Singleton<MessageProcessorMap, 2>::instance();
WithdrawProcessor withdrawer(WITHDRAW_QUOTE, &processorMap, NULL, matchWithdraw, NULL);
QuoteProcessor quoteProcessor(SecurityQuote, &processorMap, NULL, matchQuote, NULL) ;
message_t msg;
list<message_t> out_msg_list;
extern bool g_run;
while(g_run){
while(msgs.try_dequeue(msg)){
MessageProcessorMap::iterator iter = processorMap.find(msg->quote.msg_type);
if(iter != processorMap.end()){
int status = iter->second->execute(msg, out_msg_list);
if(status == STATUS_INVALID){
//outs.enqueue(*iter);
}else{
for(list<message_t>::iterator iter = out_msg_list.begin(); iter!= out_msg_list.end(); iter++){
outs.enqueue(*iter);
}
out_msg_list.clear();
outs.enqueue(msg);
}
}
}
}
}
void io_fn(void *arg){
struct thread_context_t *context = (struct threadContext *)arg;
ReaderWriterQueue<message_t> & msgs = *(context->msgs);
ReaderWriterQueue<message_t> & outs = *(context->outs);
MessageProcessorMap &processorMap = Singleton<MessageProcessorMap, 3>::instance();
QuoteProcessor(SECURITY_QUOTE, &processorMap
, prepareQuote, NULL, accoutQuote);
WithdrawProcessor withdrawProcessor(WITHDRAW_QUOTE, &processorMap
, prepareWithdraw, NULL, accoutWithdraw);
ContractNoteProcessor noteProcessor(CONTRACT_NOTE, &processorMap
,accountNote);
AccountExchangeProcessor exchangeProcessor(ACCOUNT_EXCHANGE_NOTE, &processorMap
, accountExchange );
message_t msg;
list<message_t> out_msg_list;
extern bool g_run;
while(g_run){
if(! msgs.try_dequeue(msg))
continue;
MessageProcessorMap::iterator iter = processorMap.find(msg->quote.msg_type);
if(iter != processorMap.end()){
int status = iter->second->execute(msg, out_msg_list);
if(status == STATUS_INVALID){
// outs.enqueue(*iter);
}else{
for(list<message_t>::iterator iter = out_msg_list.begin(); iter!= out_msg_list.end(); iter++){
outs.enqueue(*iter);
}
out_msg_list.clear();
outs.enqueue(msg);
}
}
}
}
<file_sep>//
// match_quote.h
// mycoin
//
// Created by lx on 13-12-23.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__match_quote__
#define __mycoin__match_quote__
#include "../message.h"
int matchQuote(SecurityQuote "e);
int matchWithdraw(WithdrawQuote "e);
#endif
<file_sep>//
// QuoteWithdrawProcessorTest.h
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__QuoteWithdrawProcessorTest__
#define __mycoin__QuoteWithdrawProcessorTest__
#include "gtest/gtest.h"
#include "../QuoteWithDrawProcessor.h"
#endif
<file_sep>//
// matchTest.h
// mycoin
//
// Created by lx on 13-12-21.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__matchTest__
#define __mycoin__matchTest__
#include "gtest/gtest.h"
#endif /* defined(__mycoin__matchTest__) */
<file_sep>//
// QuoteProcessorSetTest.cpp
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "IdentifyQuoteQueueTest.h"
#include <typeinfo>
namespace {
TEST(IdentifyQuoteQueue, SelfBuy) {
BuyQuoteMultiMap buyQueue;
SellQuoteMultiMap sellQueue;
IdentifyQuoteQueue<BuyQuoteMultiMap,SellQuoteMultiMap> identify1;
ASSERT_EQ(&buyQueue, identify1.getSelfQueue(&buyQueue, &sellQueue));
ASSERT_EQ(&sellQueue, identify1.getPeerQueue(&buyQueue, &sellQueue));
}
TEST(IdentifyQuoteQueue, SelfSell) {
BuyQuoteMultiMap buyQueue;
SellQuoteMultiMap sellQueue;
IdentifyQuoteQueue<SellQuoteMultiMap,BuyQuoteMultiMap> identify2;
ASSERT_EQ(&sellQueue, identify2.getSelfQueue(&buyQueue, &sellQueue));
ASSERT_EQ(&buyQueue, identify2.getPeerQueue(&buyQueue, &sellQueue));
}
} // namespace<file_sep>//
// QuoteMatchProcessor.cpp
// mycoin
//
// Created by lx on 14-1-6.
// Copyright (c) 2014年 lx. All rights reserved.
//
#include "match_quote.h"
#include <algorithm>
#include <vector>
#include <map>
#include <functional>
#include "../quote.h"
#include "MatchStrategy.h"
#include "lost.h"
#include "QuoteQueue.h"
using namespace std;
int matchQuote(SecurityQuote "e){
do{
if(quote.status != STATUS_INQUEUE)
break;
QuoteQueue& quoteQueue = Singleton<QuoteQueue>::instance();
SellQuoteMultiMap * sellQueue = quoteQueue.getSellQuoteQueue(quote->code);
BuyQuoteMultiMap * buyQueue = quoteQueue.getBuyQuoteQueue(quote->code);
if(sellQueue == NULL || buyQueue == NULL)
return break;
security_price_t price = 0;
switch (quote.billType) {
case BUY_IN_LIMIT_PRICE:
price = matchQueue(quote,*buyQueue, *sellQueue, matchTopDown);
case BUY_IN_MARKET_PRICE:
price = matchQueue(quote,*buyQueue, *sellQueue, matchBottomUp);
case SELL_OUT_LIMIT_PRICE:
price = matchQueue(quote,*buyQueue, *sellQueue, marketPriceBuyIn );
case SELL_OUT_MARKET_PRICE:
price = matchQueue(quote,*buyQueue, *sellQueue, marketPriceSellOut);
default:
return STATUS_REJECTED;
}
//结束后如果要把quote转为限价订单
//guanrity 数量得从订单和那个来保证了
/* 转topone
BuyQuoteMultiMap* buyQueue, SellQuoteMultiMap *sellQueue){
SelfQuoteQueue *selfQueue = IdentifyQuoteQueue<SelfQuoteQueue, PeerQuoteQueue>::getSelfQueue(buyQueue, sellQueue);
quote->price = selfQueue->begin()->price ;
return quote;
还得通知客户端才好
*/
//这里只是撤销
if(quote.quality > 0){
SecurityQuote * quoteReserved = postmatch("e, buyQueue, sellQueue);
if(quoteReserved != NULL){
SelfQuoteQueue &selfQueue = identify.getSelfQueue(buyQueue, sellQueue);
selfQueue.insert(make_pair(quote.price,quote));
quote.status = STATUS_PROCESSING;
}
}
quote.status = STATUS_PROCESSED;
return quote.status;
}while(false);
return STATUS_REJECTED;
}
struct isQuoteFinished : public std::unary_function<SecurityQuote, bool> {
bool operator()(const SecurityQuote & x) const {
return x.quality <= 0;
}
};
template<typename SelfQuoteQueue, typename PeerQuoteQueue, typename MatchStrategy>
security_price_t QuoteMatchProcessor::matchQueue(SecurityQuote "e, SelfQuoteQueue& selfQueue, PeerQuoteQueue &peerQueue, MatchStrategy &matchStrategy){
security_price_t lastPrice =0;
typename PeerQuoteQueue::iterator iter;
for(iter = peerQueue.begin(); iter != peerQueue.end(); iter++){
security_quality_t quality = matchStrategy(quote, iter->second);
if(quality >0 ){
ContractNote note;
note.code = quote.code;
note.sourceBillId = quote.header.billId;
note.peerBillId = iter->second.header.billId;
memcpy(¬e.buyer, quote.client , sizeof(quote.client));
memcpy(¬e.seller, iter->second.client , sizeof(iter->second.client));
note.quality = quality;
note.price = iter->second.price;
notes_push_back(note);
lastPrice = note.price;
//对方数量==0时,生成quote完成单
if(iter->second.quality == 0){
finishQuote(&iter->second);
}
}else{
break;
}
}
map_erase_if(peerQueue,
compose1(isQuoteFinished(),select2nd<map<security_price_t, SecurityQuote>::value_type>()));
return lastPrice;
}
template<typename SelfQuoteQueue, typename PeerQuoteQueue>
static int withdraw(WithdrawQuote "e, SelfQuoteQueue &selfQueue, PeerQuoteQueue & peerQueue){
for(typename SelfQuoteQueue::iterator iter = selfQueue.begin(); iter!=selfQueue.end(); iter++){
if(quote.refBillId == iter->second.header.billId){
finishQuote(&iter->second); //原单完成
selfQueue.erase(iter);
break;
}
}
quote.status = STATUS_PROCESSED;
return quote.status;
}
int matchWithdraw(WithdrawQuote "e){
do{
QuoteQueue& quoteQueue = Singleton<QuoteQueue>::instance();
SellQuoteMultiMap * sellQueue = quoteQueue.getSellQuoteQueue(quote->code);
BuyQuoteMultiMap * buyQueue = quoteQueue.getBuyQuoteQueue(quote->code);
if(sellQueue == NULL || buyQueue == NULL)
return break;
switch (quote.billType) {
case BUY_WITHDRAW:
return withdraw(quote, *buyQueue, *sellQueue);
case SELL_WITHDRAW:
return withdraw(quote, *sellQueue, *buyQueue);
default:
break;
}
}while(false);
return STATUS_REJECTED;
}
<file_sep>//
// QuoteMatchProcessorTest.cpp
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "QuoteMatchProcessorTest.h"
#include <typeinfo>
namespace {
} // namespace<file_sep>struct s1{
int a;
};
struct s2{
int b;
};
union message{
struct {
int a;
};
struct {
int a;
int b;
};
};
int main(){
union message msg;
msg.b =20;
}
<file_sep>//
// QuoteQueueTest.h
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__QuoteQueueTest__
#define __mycoin__QuoteQueueTest__
#include "gtest/gtest.h"
#include "../QuoteQueue.h"
#endif /* defined(__mycoin__QuoteProcessorSetTest__) */
<file_sep>//
// test.cpp
// mycoin
//
// Created by lx on 13-12-17.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <uv.h>
#include <time.h>
#include "demo.h"
#include "quote.h"
static uv_shutdown_t shutdown_req;
static uv_write_t write_req;
struct sockaddr_in dest;
static uv_loop_t *loop;
static void write_cb(uv_write_t* req, int status) {
}
static void close_cb(uv_handle_t* handle) {
uv_tcp_t socket;
uv_tcp_init(loop, &socket);
uv_connect_t connect;
uv_tcp_connect(&connect, &socket, dest, on_connect);
}
static void shutdown_cb(uv_shutdown_t* req, int status) {
uv_close((uv_handle_t*)req->handle, close_cb);
}
void on_connect(uv_connect_t* req, int status){
SecurityQuote quote;
time("e.occurTime);
//撤销单
//撤销买单,撤销卖单-简单,空单时
// 有单时
// 单已全部成交
// 单成交部分
// 单完全没成交
//限价单
//市价单
quote.code = 1;//2
quote.billId = (long)random();//hash
quote.billType = (security_bill_t)random()%4; // BUY_IN_LIMIT_PRICE, SELL_OUT_LIMIT_PRICE,
quote.quality = random() %10;
if(quote.billType == BUY_IN_LIMIT_PRICE || quote.billType == SELL_OUT_LIMIT_PRICE ){
quote.price = 5000 + random()% 2000;
}else{
quote.guaranty = quote.quality * 6000; //BUY_IN_MARKET_PRICE,SELL_OUT_MARKET_PRICE,
}
uv_write(&write_req, req->handle, (char *)"e, 1, write_cb);
uv_shutdown(&shutdown_req, req->handle, shutdown_cb);
}
void thread_fn(void * arg){
srand((unsigned)time(0));
dest = uv_ip4_addr("127.0.0.1", 7000);
loop = uv_loop_new();
uv_tcp_t socket;
uv_tcp_init(loop, &socket);
uv_connect_t connect;
uv_tcp_connect(&connect, &socket, dest, on_connect);
uv_run(loop, UV_RUN_DEFAULT);
}
int main() {
int tracklen = 10;
for(int i=0; i< 2; i++){
uv_thread_t tortoise_id;
uv_thread_create(&tortoise_id, thread_fn, &tracklen);
uv_thread_join(&tortoise_id);
}
return 0;
}<file_sep>//
// lost.h
// mycoin
//
// Created by lx on 13-12-21.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef mycoin_lost_h
#define mycoin_lost_h
#define _LIBCPP_HAS_NO_RVALUE_REFERENCES
#include <stdlib.h>
using namespace std;
template <typename Map, typename F>
void map_erase_if(Map& m, F pred)
{
for (typename Map::iterator i = m.begin();
(i = find_if(i, m.end(), pred)) != m.end();
m.erase(i++));
}
template <typename F,typename G>
class Compose_F_Gx : public std::unary_function<typename G::argument_type,typename F::result_type>
{
public:
Compose_F_Gx(const F& _f,const G& _g):f(_f),g(_g)
{
}
typename F::result_type
operator()(const typename G::argument_type& x) const
{
return f(g(x));
}
private:
F f;
G g;
};
template <typename F,typename G>
inline Compose_F_Gx<F,G> compose1(const F& f,const G& g)
{
return Compose_F_Gx<F,G>(f,g);
}
template< typename Pair >
struct select1st:public unary_function<Pair, typename Pair::second_type>
{
const typename Pair::first_type & operator()(const Pair & p ) const
{
return p.first;
}
};
template< typename Pair >
struct select2nd:public unary_function<Pair,typename Pair::second_type>
{
const typename Pair::second_type & operator()(const Pair & p) const
{
return p.second;
}
};
#endif
<file_sep>//
// QuoteProcessorSetTest.cpp
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "LimitPriceStrategyTest.h"
#include <typeinfo>
namespace {
TEST(TopLimitPriceStrategy, match) {
TopLimitPriceStrategy strategy;
SecurityQuote quote,cpmQuote;
SecurityQuote peer,cpmPeer;
security_quality_t qty;
security_code_t code = random();
quote.code = code;
peer.code = code;
quote.quality = random();
peer.quality = random();
quote.price = random();
peer.price = random();
memcpy(&cpmQuote, "e);
memcpy(&cpmpeer, &peer);
qty = strategy.match(quote, peer);
ASSERT_EQ(qty, cmpQuote.quality - quote.quality);
ASSERT_EQ(qty, peer.quality - cmpPeer.quality);
quote.quality -= qty;
ASSERT_EQ(0, memcpm(&cmpQuote,"e));
peer.quality += qty;
ASSERT_EQ(0, memcpm(&cmpPeer,&peer));
if(quote.price >= peer.price){
ASSERT_GT(qty,0);
quote.price = peer.price -1;
ASSERT_EQ(strategy.match(quote, peer),0);
}else{
ASSERT_EQ(qty,0);
quote.price = peer.price +1;
ASSERT_GT(strategy.match(quote, peer),0);
}
quote.quality = - random();
qty = strategy.match(quote, peer);
ASSERT_EQ(0, qty);
}
TEST(BottomLimitPriceStrategy, match) {
BottomLimitPriceStrategy strategy;
SecurityQuote quote,cpmQuote;
SecurityQuote peer,cpmPeer;
security_quality_t qty;
security_code_t code = random();
quote.code = code;
peer.code = code;
quote.quality = random();
peer.quality = random();
quote.price = random();
peer.price = random();
memcpy(&cpmQuote, "e);
memcpy(&cpmpeer, &peer);
qty = strategy.match(quote, peer);
ASSERT_EQ(qty, cmpQuote.quality - quote.quality);
ASSERT_EQ(qty, peer.quality - cmpPeer.quality);
quote.quality -= qty;
ASSERT_EQ(0, memcpm(&cmpQuote,"e));
peer.quality += qty;
ASSERT_EQ(0, memcpm(&cmpPeer,&peer));
if(quote.price <= peer.price){
ASSERT_GT(qty,0);
quote.price = peer.price + 1;
ASSERT_EQ(strategy.match(quote, peer),0);
}else{
ASSERT_EQ(qty,0);
quote.price = peer.price - 1;
ASSERT_GT(strategy.match(quote, peer),0);
}
quote.quality = - random();
qty = strategy.match(quote, peer);
ASSERT_EQ(0, qty);
}
} // namespace<file_sep>//
// RoutineQuotation.cpp
// mycoin
//
// Created by lx on 13-12-24.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "RoutineQuotation.h"
#include "../Singleton.h"
template<> RoutineQuotation *Singleton<RoutineQuotation>::_instance = 0;
int RoutineQuotation::update(ContractNote ¬e){
innerMap[note.code].sum += note.price * note.qty;
innerMap[note.code].qty += note.qty;
updateTopQuote(innerMap[code].topBuys, note.price, -note.qty);
updateTopQuote(innerMap[code].topSells, price, -note.qty);
}
int RoutineQuotation::update(SecurityQuote "e){
switch(quote.billType){
case BUY_IN_LIMIT_PRICE:
case BUY_IN_MARKET_PRICE:
updateTopQuote(innerMap[code].topBuys, price, qty);
break;
case SELL_OUT_LIMIT_PRICE:
case SELL_OUT_MARKET_PRICE:
updateTopQuote(innerMap[code].topSells, price, qty);
break;
default:
break;
}
}
void RoutineQuotation::publish(Publisher &publisher){
for (InnerRoutineMap::iterator iter=innerMap.begin(); iter!=innerMap.end(); iter++) {
int i = 0;
security_price_t topBuyPrice[MAX_ROUTINE_LEVEL], topSellPrice[MAX_ROUTINE_LEVEL];
security_quality_t topBuyQty[MAX_ROUTINE_LEVEL], topSellQty[MAX_ROUTINE_LEVEL];
SellQuoteRoutine &topSells = iter->second.topSells;
BuyQuoteRoutine &topBuys = iter->second.topBuys;
for (SellQuoteRoutine::iterator iter2= topSells.begin(); iter2!=topSells.end() && i < MAX_ROUTINE_LEVEL ; iter2 ++ ) {
topSellQty[i] = iter2->second;
topSellPrice[i] = iter2->first;
i++;
}
int j =0;
for (BuyQuoteRoutine::iterator iter2= topBuys.begin(); iter2!=topBuys.end() && j < MAX_ROUTINE_LEVEL ; iter2 ++ ) {
topBuyQty[j] = iter2->second;
topBuyPrice[j] = iter2->first;
j++;
}
publisher.publish( iter->first, iter->second.qty >0? iter->second.sum/iter->second.qty :0, iter->second.qty, topBuyPrice, topBuyQty, j, topSellPrice, topSellQty, j);
}
reset();
}
<file_sep>//
// RedisAccount.cpp
// mycoin
//
// Created by lx on 14-1-11.
// Copyright (c) 2014年 lx. All rights reserved.
//
/*
使用nosql,在灾难恢复方面及其难处理。数据不一致,看起来可行的办法还是在源头保存事件,进行事件重演
*/
#include "RedisVoucher.h"
typdef struct account_context{
EventSwitcher *switcher;
Event event;
}account_context_t;
static void account_start(redisAsyncContext *c, void *r, void *privdata){
account_context_t context = (account_context_t *) privdata;
redisReply *reply = r;
if (reply == NULL) {
context->event.status = STATUS_ERROR;
}else{
switch(reply->type){
case REDIS_REPLY_STRING:
break;
case REDIS_REPLY_ARRAY:
for (j = 0; j < reply->elements; j++) {
printf("%u) %s\n", j, reply->element[j]->str);
}
break;
case REDIS_REPLY_INTEGER:
break;
case REDIS_REPLY_NIL:
break;
case REDIS_REPLY_STATUS:
break;
case REDIS_REPLY_ERROR:
break;
}
event.status = STATUS_ACCOUNTED;
}
typedef struct redisReply {
int type; /* REDIS_REPLY_* */
long long integer; /* The integer when type is REDIS_REPLY_INTEGER */
int len; /* Length of string */
char *str; /* Used for both REDIS_REPLY_ERROR and REDIS_REPLY_STRING */
size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */
struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */
} redisReply;
context->switcher->push(event);
}
static void account_cb(redisAsyncContext *c, void *r, void *privdata){
account_context_t context = (account_context_t *) privdata;
redisReply *reply = r;
if (reply == NULL) {
context->event.status = STATUS_ERROR;
}else{
switch(reply->type){
case REDIS_REPLY_STRING:
break;
case REDIS_REPLY_ARRAY:
for (j = 0; j < reply->elements; j++) {
printf("%u) %s\n", j, reply->element[j]->str);
}
break;
case REDIS_REPLY_INTEGER:
break;
case REDIS_REPLY_NIL:
break;
case REDIS_REPLY_STATUS:
break;
case REDIS_REPLY_ERROR:
break;
}
event.status = STATUS_ACCOUNTED;
}
typedef struct redisReply {
int type; /* REDIS_REPLY_* */
long long integer; /* The integer when type is REDIS_REPLY_INTEGER */
int len; /* Length of string */
char *str; /* Used for both REDIS_REPLY_ERROR and REDIS_REPLY_STRING */
size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */
struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */
} redisReply;
context->switcher->push(event);
}
bool RedisVoucher::account(const string& suit, const string& debitCode, const string& creditCode, money_t money){
const string key = suite +
redisAsyncCommand(context, NULL, NULL, "MULTI");
redisAsyncCommand(context, NULL, NULL, "WATCH %b");
//debit
redisAsyncCommand(context, account_start, NULL, "HMSET %b debit %b"
,json, strlen(json),debitCode, strlen(debitCode));
/*
sql << "insert into " << detail_table << "(occur_time, debit, credit, owner) values( ?, ?, 0,?)", use(occurTime), use(money), use(owner);
//balance_type 时间
sql << "update " << table << " set occur_time=:occur_time, balance =banalce + " <<money << " where balance_type=" << 0 <<" and owner=:owner ", use(occurTime, "occur_time"), use(owner, "owner");
//credit
sql << "insert into " << detail_table << "(occur_time, debit, credit, owner) values( ?, 0, ?,?)", use(occurTime), use(money),use(owner);
//balance_type 时间
sql << "update " << table << " set occur_time=:occur_time, balance =banalce - " <<money << " where balance_type=" <<0 <<" and owner=:owner ", use(occurTime, "occur_time"), use(owner, "owner");
*/
redisAsyncCommand(context, NULL, NULL, "EXEC");
return true;
}
<file_sep>//
// quote.h
// mycoin
//
// Created by lx on 13-12-9.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef mycoin_quote_h
#define mycoin_quote_h
#include <time.h>
#include "message.h"
#ifdef __cplusplus
extern "C"{
#endif
typedef unsigned long long security_code_t;
typedef unsigned int security_price_t;
typedef unsigned int security_quality_t;
typedef unsigned int security_billId_t;
#ifdef __cplusplus
}
#endif
//交割单
/* java
class DeliveryOrder{
int billId;
int sourceBillId;
time_t occrTime;
class Item{
int price;
int quliaty;
time_t occrTime;
}
public getItem();
};
*/
#endif
<file_sep>//
// BizAccount.cpp
// mycoin
//
// Created by lx on 13-12-28.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "BizAccount.h"
<file_sep>//
// MatchStrategy.cpp
// mycoin
//
// Created by lx on 13-12-21.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin__TopLimitPriceStrategy__
#define __mycoin__TopLimitPriceStrategy__
#include "../quote.h"
#include "MatchStrategy.h"
security_quality_t matchTopDown(SecurityQuote "e, SecurityQuote & peer){
if(quote.quality <=0 || quote.price < peer.price)
return 0;
security_quality_t qty = std::min(quote.quality, peer.quality);
quote.quality -= qty;
peer.quality -= qty;
return qty;
}
//sell out
security_quality_t matchBottomUp(SecurityQuote "e, SecurityQuote & peer){
if(quote.quality <=0 || quote.price > peer.price)
return 0;
security_quality_t qty = std::min(quote.quality, peer.quality);
quote.quality -= qty;
peer.quality -= qty;
return qty;
}
#define MAX_LEVEL 5;
static LevelOfQuoteQueue levelQueue;
security_quality_t marketPriceBuyIn(SecurityQuote "e, SecurityQuote & peer){
if(quote.quality > 0 || MAX_LEVEL > levelQueue.level(quote.billId, peer.price) ){
//结束后要把quote转为限价订单
//guanrity 转为price,是否要生成新的quote,在postMatch中处理
security_quality_t qty = min(quote.quality, peer.quality);
if(quote.guaranty < peer.price * qty){
qty = quote.guaranty / peer.price;
}
quote.guaranty -= peer.price * qty;
quote.quality -= qty;
peer.quality -= qty;
return qty;
}else{
return 0;
}
}
security_quality_t marketPriceSellOut(SecurityQuote "e, SecurityQuote & peer){
if(quote.quality > 0 || maxLevel > levelQueue.level(quote.billId, peer.price) ){
//市价卖出
security_quality_t qty = std::min(quote.quality, peer.quality);
quote.quality -= qty;
peer.quality -= qty;
return qty;
}else
return 0;
}
#endif
<file_sep>//
// QuoteQueue.cpp
// mycoin
//
// Created by lx on 13-12-22.
// Copyright (c) 2013年 lx. All rights reserved.
//
#include "QuoteQueue.h"
#include "../Singleton.h"
template<> QuoteQueue* Singleton<QuoteQueue>::_instance = NULL;<file_sep>//
// MycoinApplication.h
// mycoin-account
//
// Created by lx on 13-12-25.
// Copyright (c) 2013年 lx. All rights reserved.
//
#ifndef __mycoin_account__MycoinApplication__
#define __mycoin_account__MycoinApplication__
#include <Poco/Util/ServerApplication.h>
using namespace Poco;
using namespace Poco::Util;
using namespace std;
class MycoinApplication:public ServerApplication{
public:
int main( const std::vector < std::string > & args);
protected:
void handleOption(const std::string& name, const std::string& value){}
};
#endif /* defined(__mycoin_account__MycoinApplication__) */
| 1c63bc8a9605086f03d9d3191135cc11d7d0982f | [
"Markdown",
"C",
"Makefile",
"C++"
] | 68 | C | Roverok/coinExchange | bcd3c4bbd50b7bf299357b2bf686189cb6481f07 | 018098dfdea8b307e74e5c39a8a3b39c4ca2df9d | |
refs/heads/master | <file_sep>#include <iostream>
#include <opencv2/opencv.hpp>
#include <fstream>
#include <ctime>
#include <curl/curl.h>
#include <unistd.h>
using namespace std;
using namespace cv;
void good(String path)
{
vector<String> fn;
String arg = String(path);
glob(arg + "/*.jpg", fn, false);
ofstream good;
good.open("Good.dat");
size_t count = fn.size();
cout << "The count of images in folder is : " << count << endl;
std::clock_t start;
double duration;
start = std::clock();
for (size_t i = 1; i <= count ; i++)
{
cout << "Good" << "\\" << i << ".jpg " << "1 " << "0 " << "0 " << imread(fn[i]).cols << " " << imread(fn[i]).rows << endl;
good << "Good" << "\\" << i << ".jpg " << "1 " << "0 " << "0 " << imread(fn[i]).cols << " " << imread(fn[i]).rows << endl;
}
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
std::cout<<"time in seconds: "<< duration <<'\n';
good.close();
}
void bad(String path)
{
vector<String> fn;
String arg = String(path);
glob(arg + "/*.jpg", fn, false);
ofstream bad;
bad.open("Bad.dat");
size_t count = fn.size();
cout << "The count of images in folder is : " << count << endl;
std::clock_t start;
double duration;
start = std::clock();
for (size_t i = 0; i < count ; i++)
{
cout << "Bad" << "\\" << i << ".jpg" << endl;
bad << "Bad" << "\\" << i << ".jpg" << endl;
}
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
std::cout<<"time in seconds: "<< duration <<'\n';
bad.close();
}
size_t write_data(char *ptr, size_t size, size_t nmemb, void *userdata)
{
vector<uchar> *stream = (vector<uchar>*)userdata;
size_t count = size * nmemb;
stream->insert(stream->end(), ptr, ptr + count);
return count;
}
//Функция получения списка с сайта.
vector<uchar> curlStream(const char *img_url, int timeout=1000)
{
vector<uchar> stream;
CURL *curl = curl_easy_init();
if(curl)
{
// cout << curl << endl;
curl_easy_setopt(curl, CURLOPT_URL, img_url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &stream);
// curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, timeout);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
CURLcode res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
//вывод полученных данных
// for(auto i = 0; i < stream.size(); i++)
// cout << stream[i];
return stream;
}
//конвертация списка в str
string curlStr(vector<uchar>stream)
{
unsigned char *uch = &*stream.begin();
string str;
str.append(reinterpret_cast<const char*>(uch));
return str;
}
//конвертация в img
Mat curlImg(vector<uchar> img)
{
if(!img.empty())
return imdecode(img, -1);
}
char* appendCharToCharArray(char* array, char a)
{
size_t len = strlen(array);
char* ret = new char[len+2];
strcpy(ret, array);
ret[len] = a;
ret[len+1] = '\0';
return ret;
}
int main(int argc, char** argv) {
std::cout << "dat to train" << std::endl;
// good(argv[1]);
// bad(argv[2]);
// сылка на общей список
vector<uchar> vec_uch = curlStream("http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n04556533");
string str = curlStr(vec_uch);
// cout << str << endl;
// Парсинг списка
string start = "http";
string end = "jpg";
for(int k = 0 ; k < 10; k++)
{
unsigned first = str.find(start);
unsigned last = str.find(end);
//Сылку которую будем использовать
string strNew = str.substr(first, last + end.size());
cout << "STR : " << strNew << endl;
//Удаление из списка используемого элемента
str.erase(str.begin(), str.begin() + strNew.size() + 1);
//Конвертация в char
char * charNew = const_cast<char *>(strNew.c_str());
cout << "CHAR : " << charNew << endl;
char buf = '\0';
int ll = 0;
// while(*(charNew + ll) != 0)
// {
// cout << int(charNew[ll++]) << " ";
// }
if(int(charNew[strlen(charNew) - 1]) == 13)
{
// cout << int(charNew[strlen(charNew) - 1]) << endl;
charNew[strlen(charNew) - 1] = '\0';
cout << charNew << endl;
}
// while(*(charNew + ll) != 0)
// {
// cout << int(charNew[ll++]) << " ";
// }
vector<uchar>uimg = curlStream(charNew);//"https://i.pinimgcom/736x/56/37/e0/5637e06fe6fa24e028db8d3513cb4dbc--cartier-watches-women-ladies-watches.jpg"
for (auto iter = uimg.begin();
iter != uimg.end(); ++iter)
cout << *iter;
// Mat img = curlImg(uimg);
// for (auto iter = uimg.begin();
// iter != uimg.end(); ++iter)
// cout << *iter;
if(uimg.size() > 0)
cout << uimg.size() << endl;
Mat img = curlImg(uimg);
if(!img.empty()) {
imshow((k), img);
}else{
continue;
}
// if(!img.empty())
// {
// imshow("Img", img);
// } else
// {
// cout << "LOL : " << k << endl;
// continue;
// }
cout << "===========================================" << endl;
}
cvWaitKey(0);
return 0;
}<file_sep>LibCurl and OpenCV 3.3<file_sep>cmake_minimum_required(VERSION 3.8)
project(lesson_2)
set(CMAKE_CXX_STANDARD 11)
set(SOURCE_FILES main.cpp)
add_executable(lesson_2 ${SOURCE_FILES})
find_package( OpenCV REQUIRED )
target_link_libraries( lesson_2 ${OpenCV_LIBS} )
target_link_libraries( lesson_2 curl) | e549900937c96aa07ee4206e79887cc37b07244d | [
"Markdown",
"CMake",
"C++"
] | 3 | C++ | nafe93/LibCurl_OpenCV | d5c1654561cdf61aa9737558a163beaa6fb58266 | e3cc0bf37484c6ff39029771ce4841ad2aeb9942 | |
refs/heads/master | <repo_name>Rizki-SS/Unit-Testing-Simple-Cart-App<file_sep>/src/helpers.js
const kupon = [{
kode: 'diskon20',
tipe: 'persen',
jumlah: '20',
},
{
kode: 'diskon2000',
tipe: 'fix',
jumlah: '2000',
},
{
kode: 'diskon1000',
tipe: 'fix',
jumlah: '1000',
},
]
const incrementQty = (qty) => parseInt(qty) + 1;
const decrementQty = (qty) => (qty > 1) ? qty - 1 : qty;
const sum = (price, qty) => price * qty;
//get diskon code
const diskon = (kode) => {
const coupon = kupon.filter(kupon => kupon.kode === kode)
if (coupon.length === 0) {
throw ('kode tidak valid');
}
return coupon[0];
}
//cacluculate payOff
const payOff = (sum, coupon) => {
if (coupon.tipe === "persen") {
return sum * coupon.jumlah / 100;
} else {
return (coupon.jumlah > sum) ? sum : parseInt(coupon.jumlah);
}
}
//caclulate total with payoff
const sumDiskon = (sum, diskon) => sum - diskon;
module.exports = {
incrementQty,
decrementQty,
sum,
diskon,
sumDiskon,
payOff
};<file_sep>/src/app.js
import {
incrementQty,
decrementQty,
sum,
diskon,
sumDiskon,
payOff
} from './helpers.js';
const incrButton = document.querySelector('#incr');
const decrButton = document.querySelector('#decr');
const qtyInput = document.querySelector('#qty');
const price = document.querySelector('#price');
const subTotal = document.querySelector('#subtotal');
const comfirmBtn = document.querySelector('#confirmButton');
const codeInput = document.querySelector('#code');
const diskonTxt = document.querySelector('#diskon');
let Coupon;
const getDiskon = () => {
try {
Coupon = diskon(codeInput.value);
alert('success use code');
} catch (error) {
Coupon = null;
alert(error);
}
};
const hitung = () => {
if (Coupon != null) {
const total = sum(price.value, qtyInput.value);
const off = payOff(total, Coupon);
diskonTxt.textContent = `Rp. ${off}`;
subTotal.textContent = `Rp. ${sumDiskon(total,off)}`;
} else {
diskonTxt.textContent = `Rp. 0`;
subTotal.textContent = `Rp. ${sum(price.value, qtyInput.value)}`
}
}
price.addEventListener('change', () => {
if (price.value < 0) { price.value = 0 };
hitung();
});
qtyInput.addEventListener('change', () => {
if (qtyInput.value <= 0) { qtyInput.value = 1 };
hitung();
})
incrButton.addEventListener('click', () => {
qtyInput.value = incrementQty(qtyInput.value);
hitung();
});
decrButton.addEventListener('click', () => {
qtyInput.value = decrementQty(qtyInput.value);
hitung();
});
comfirmBtn.addEventListener('click', () => {
getDiskon();
hitung();
})<file_sep>/src/const.js
export const kupon = [{
kode: 'diskon60',
tipe: 'persen',
jumlah: '20',
},
{
kode: 'diskon2000',
tipe: 'fix',
jumlah: '2000',
},
]<file_sep>/README.md
# Simple Cart App
Aplikasi cart sederhana. Disadur dan dimodifikasi dari [https://github.com/kodeid-resources/simple-cart-app](https://github.com/kodeid-resources/simple-cart-app)
# Acknowledgment
[<NAME>](https://github.com/rizafahmi)
#error Handling yang saya tambahkan
- Harga tidak dapat bernilai minus, apabila minus nilai otomatis di set 0;
- Quantity terkecil bernilai 1
- input type qty dan harga berupa number agar tidak menerima inputan carakter atau yang lain
- Harga akhir/sub Totaol tidak dapat bernilai minus setelah mendapat diskon
- Apablia input kode kupon berhasil / gagal akan mendapat alert pemberitahuan
#test case
- [x] pembelian 2 bauh @500 (3ms)
- [x] mengurangi qty 1
- [x] mengurangi qty 3 (1ms)
- [x] menambah qty 2
- [x] cek kode diskon20 seharusnya ada (1ms)
- [x] cek kode "tidakada" seharusnya kode tidak valid (1ms)
- [x] payoff kupon off 20% dari 100 = 20
- [x] payoff kupon off 2000 dari 1000 = 1000 (1ms)
- [x] payoff kupon off 2000 dari 3000 = 2000
- [x] total dari pembelian 2000 dengan diskon 1000 maka = 1000 | b29b1d7b3f988dc96dd1a277a2853f45327462f9 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | Rizki-SS/Unit-Testing-Simple-Cart-App | 56b9b5fd26d053ea3d3ae9dc69b0d21fd6871e2e | 4889fe70f87d087976c31b65920357ac596df43d | |
refs/heads/master | <repo_name>imshashank/psychic-octo-wallhack<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
before_filter :load_user, only: [:show]
def index
@user = User.all
end
def show
end
def edit
end
def load_user
@user = User.where(username: params[:username]).first!
end
end
<file_sep>/Gemfile
source 'https://rubygems.org'
ruby '2.0.0'
gem 'rails', '4.0.0'
gem 'active_decorator', '~> 0.3.4'
gem 'bcrypt-ruby', '~> 3.1.1'
gem 'bourbon', '~> 3.1.8'
gem 'cancan', '~> 1.6.10'
gem 'cocoon', '~> 1.2.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'coveralls', '~> 0.6.7', require: false
gem 'jbuilder', '~> 1.2'
gem 'jquery-rails', '~> 3.0.4'
gem 'octokit', '~> 1.25.0'
gem 'omniauth', '~> 1.1.4'
gem 'omniauth-github', '~> 1.1.1'
gem 'pg', '~> 0.16.0'
gem 'sass-rails', '~> 4.0.0'
gem 'slim-rails', '~> 2.0.1'
gem 'simple_form', '~> 3.0.0.rc'
gem 'therubyracer', '~> 0.11.4', platforms: :ruby
gem 'turbolinks', '~> 1.3.0'
gem 'uglifier', '>= 1.3.0'
gem 'unicorn', '~> 4.6.3'
group :development, :test do
gem 'awesome_print', '~> 1.1.0'
gem 'better_errors', '~> 0.9.0'
gem 'pry-plus', '~> 1.0.0'
gem 'pry-rails', '~> 0.3.2'
gem 'rspec-rails', '~> 2.14.0'
gem 'quiet_assets', '~> 1.0.2'
end
group :doc do
gem 'sdoc', '~> 0.3.20', require: false
end
group :test do
gem 'capybara', '~> 2.1.0'
gem 'factory_girl_rails', '~> 4.2.0'
gem 'selenium-webdriver', '~> 2.33.0'
end
group :production do
gem 'rails_12factor', '~> 0.0.2'
end
| 577fca4fa45014f06cd2c5374e157d0f461c21b2 | [
"Ruby"
] | 2 | Ruby | imshashank/psychic-octo-wallhack | a7218cf6634cba2464afb15ce815f5b239dad1be | b702d69a5310ffd40084fa53915b35ff91361436 | |
refs/heads/main | <repo_name>ohadosnat/tailwind-collection<file_sep>/README.md
# Tailwind Collection
This repository contains all of my projects using only Tailwind CSS for practice purposes. <br>
The designs I used are all made by myself a while ago for the **"Daily UI"** Challange, using `Figma` and `Sketch`. <br>
You can view it [here](https://ohadosnat.github.io/tailwind-collection/pages/index.html) (Main page with links to all the projects).
### **The Projects:**
- [**Movie App**](https://ohadosnat.github.io/tailwind-collection/pages/movie.html) - The design was originally made as a TV App but I used it anyway since I like the layout.
- [**Subscribe Form**](https://ohadosnat.github.io/tailwind-collection/pages/subscribe.html) - A simple newsletter form with a unique design, fun and challenging.
- [**Car Music Interface**](https://ohadosnat.github.io/tailwind-collection/pages/car-music.html) - a Car Interface Design that I did.
- [**Product Page**](https://ohadosnat.github.io/tailwind-collection/pages/product.html) - This was my first Tailwind CSS project, It was on a different repository but I decided to move it to this one to keep all of my project in one place.
---
***As always, If you got any suggestions/feedback/tips about my code. Feel free to reach out and help me learn!*** :smile:
<br><br>
That's all for today! See you next time! <br>
<file_sep>/tailwind.config.js
module.exports = {
purge: ['./pages/*.html'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {
zIndex: {
'-1': '-1',
},
fontFamily: {
'roboto': ['Roboto, sans-serif']
},
gridTemplateColumns: {
// Main Grid config - min-content
'main': "min-content 1fr min-content",
},
gridTemplateRows: {
// Main Grid config - min-content
'main': "min-content auto min-content",
},
backgroundImage: theme => ({
'awaken-mob': "url('../img/music/img_awaken-my-love-mob.jpg')",
'bladerunner': "url('../img/movie/img_blade-runner.jpg')",
'bladerunner-mob': "url('../img/movie/img_blade-runner-mob.jpg')",
'ladyonfire': "url('../img/movie/img_PortraitofaLadyonFire.jpg')",
'soundofmetal': "url('../img/movie/img_sound-of-metal.jpg')",
'minari': "url('../img/movie/img_minari.jpg')",
'burning': "url('../img/movie/img_burning.jpg')",
'1917': "url('../img/movie/img_1917.jpg')",
'uncutgems': "url('../img/movie/img_uncut-gems.jpg')",
'prd-circle': "url('../img/product/bg_circle-1.svg')",
'prd-circle-2': "url('../img/product/bg_circle-2.svg')",
}),
colors: {
form: {
bg: "#FFF75E",
btn: "#41E9EA",
},
prd: {
main: "#C975B1",
dark: "#9E5188",
}
}
},
},
variants: {
extend: {},
},
plugins: [],
}
| 207590ec95cbafb2a4c5359034dbe4e321d21820 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | ohadosnat/tailwind-collection | 2b0014c154d7205010773085e2feb66a2f0f6940 | 3f7560146cc7c7cd68f7ebc23ab865f213baf191 | |
refs/heads/master | <file_sep>package com.azxx.picture.entity;
import javax.persistence.Id;
import java.util.Date;
public class GroupInfo {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column group_info.id
*
* @mbggenerated
*/
@Id
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column group_info.desc
*
* @mbggenerated
*/
private String description;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column group_info.name
*
* @mbggenerated
*/
private String name;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column group_info.record_time
*
* @mbggenerated
*/
private Date recordTime;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column group_info.id
*
* @return the value of group_info.id
*
* @mbggenerated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column group_info.id
*
* @param id the value for group_info.id
*
* @mbggenerated
*/
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column group_info.name
*
* @return the value of group_info.name
*
* @mbggenerated
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column group_info.name
*
* @param name the value for group_info.name
*
* @mbggenerated
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column group_info.record_time
*
* @return the value of group_info.record_time
*
* @mbggenerated
*/
public Date getRecordTime() {
return recordTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column group_info.record_time
*
* @param recordTime the value for group_info.record_time
*
* @mbggenerated
*/
public void setRecordTime(Date recordTime) {
this.recordTime = recordTime;
}
}<file_sep>package com.azxx.picture.configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.Charset;
import java.util.List;
/**
* @version V1.0
* @class: CustomWebMvcConfigurerAdapter
* @description:
* @author: xuzheng
* @create: 2019-02-03 09:17
**/
@Configuration
public class CustomWebMvcConfigurerAdapter implements WebMvcConfigurer {
@Value("${img.dir}")
private String localpath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//将templates目录下的CSS、JS文件映射为静态资源,防止Spring把这些资源识别成thymeleaf模版
registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");
//其他静态资源
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
//swagger增加url映射
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/picture/**").addResourceLocations("file:"+localpath);
}
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(
Charset.forName("UTF-8"));
return converter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// super.configureMessageConverters(converters);
converters.add(responseBodyConverter());
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
}
<file_sep>package com.azxx.picture.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.azxx.picture.vo.AppInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.azxx.picture.entity.AppInfo;
import com.azxx.picture.entity.FileInfo;
import com.azxx.picture.service.FileService;
import com.azxx.picture.vo.OperateTypeEm;
import com.azxx.picture.vo.fileInfo.FileReqVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
* @version V1.0
* @class: PictureController
* @description: 图片操作、查询类
* @author: xuzheng
* @create: 2019-02-02 10:08
**/
@RestController
@RequestMapping(path = "/apps")
@Api(tags = "apps", description = "图片管理")
public class FileController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
@Autowired
private FileService fileService;
private final ResourceLoader resourceLoader;
@Value("${img.dir}")
private String filePath;
@Value("${img.url}")
private String imgUrl;
@Value("${img.imgName}")
private String imgName;
@Autowired
public FileController(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@RequestMapping(path = "/uploadFile", method = RequestMethod.PUT)
@ApiOperation(value = "文件上传", notes = "文件上传")
@ApiResponses({@ApiResponse(code = 200, message = "处理成功")})
public String uploadFile(@RequestParam("fileToUpload") MultipartFile file, AppInfo appInfo) {
// String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
try {
if (null == appInfo.getAppId()) {
return paramsError();
}
String pathName = filePath + appInfo.getAppId() + "/" + imgName;
String imgFilePath = filePath + appInfo.getAppId();
File imgFilePath1 = new File(imgFilePath);
if (!imgFilePath1.exists()) {
imgFilePath1.mkdirs();
}
File tmpFile = new File(pathName);
if (!tmpFile.exists()) {
tmpFile.createNewFile();
}
InputStream in = file.getInputStream();
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] b = new byte[1024];
int length;
while ((length = in.read(b)) != -1) {
fos.write(b, 0, length);
}
in.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return queryOk(null);
}
@RequestMapping(path = "", method = RequestMethod.GET)
@ApiOperation(value = "分页获取微应用信息", notes = "分页获取微应用信息")
@ApiResponses({@ApiResponse(code = 200, message = "处理成功", response = AppInfo.class)})
public String getFiles(AppInfoVo appInfoVo) {
if (appInfoVo == null) {
return paramsError();
}
try {
PageInfo<AppInfo> result = fileService.getFiles(appInfoVo);
return queryOk(result);
} catch (Exception e) {
e.printStackTrace();
return error(null, OperateTypeEm.QUERY.toString());
}
}
@RequestMapping(path = "", method = RequestMethod.POST)
@ApiOperation(value = "增加或更新微应用管理信息", notes = "增加或更新微应用管理信息")
@ApiResponses({@ApiResponse(code = 200, message = "处理成功", response = FileInfo.class)})
public String addOrUpdateFile(AppInfoVo appInfoVo) {
if (appInfoVo == null || StringUtils.isBlank(appInfoVo.getAppId())) {
return paramsError();
}
logger.info("增加或更新图片信息,参数:{}", JSON.toJSON(appInfoVo));
try {
appInfoVo.setState(appInfoVo.getStateName());
System.err.println(appInfoVo.getState());
boolean result = fileService.insertOrUpdateFile(appInfoVo);
if (result) {
return updateOk(null);
} else {
return paramsError();
}
} catch (Exception e) {
e.printStackTrace();
return error(null, OperateTypeEm.UPDATE.toString());
}
}
@RequestMapping(path = "/selectState", method = RequestMethod.GET)
@ApiOperation(value = "查询微应用状态", notes = "查询微应用状态")
@ApiResponses({@ApiResponse(code = 200, message = "处理成功", response = FileInfo.class)})
public String selectState() {
List<AppInfo> list = fileService.selectState();
return queryOk(list);
}
/**
* 显示单张图片
*
* @return
*/
@RequestMapping(path = "/show", method = RequestMethod.GET)
public ResponseEntity showPhotos(String fileName) {
try {
// 由于是读取本机的文件,file是一定要加上的, path是在application配置文件中的路径
return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get("D:\\newcoding\\pricterManage\\src\\main\\resources\\static\\customer\\img", "bbbbbbb.jpg").toString()));
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
// @RequestMapping(path = "/pages", method = RequestMethod.POST)
// @ApiOperation(value = "获取图片列表", notes = "获取图片列表")
// @ApiResponses({@ApiResponse(code = 200, message = "处理成功", response = FileInfo.class)})
// public String pages(FileReqVo reqVo) {
//
// if (reqVo == null) {
// return paramsError();
// }
//
// logger.info("获取文件列表开始,参数:{}", JSON.toJSON(reqVo));
// try {
// PageInfo<FileInfo> result = fileService.pages(reqVo);
// return queryOk(result);
// } catch (Exception e) {
// e.printStackTrace();
// return error(null, OperateTypeEm.QUERY.toString());
// }
//
// }
// @RequestMapping(path = "/uploadFile", method = RequestMethod.POST)
// @ApiOperation(value = "文件上传", notes = "文件上传")
// @ApiResponses({@ApiResponse(code = 200, message = "处理成功")})
// public String uploadFile(@RequestParam("fileToUpload") MultipartFile file, FileReqVo reqVo, HttpServletRequest request) {
// if (reqVo == null) {
// return paramsError();
// }
// String fileName = file.getOriginalFilename();
// reqVo.setSize((int) (file.getSize() / 1000));
// if (StringUtils.isBlank(reqVo.getName())) {
// reqVo.setName(fileName);
// }
// if (StringUtils.isBlank(reqVo.getTitle())) {
// reqVo.setName(fileName);
// }
// if (fileName.indexOf(".") > -1) {
// reqVo.setType(fileName.substring(fileName.lastIndexOf(".")));
// }
// reqVo.setUrl(imgUrl+reqVo.getName());
// try {
// String pathname = filePath + reqVo.getName();
// if(reqVo.getName().indexOf(reqVo.getType())<0){
// reqVo.setUrl(imgUrl+reqVo.getName()+reqVo.getType());
// pathname = filePath + reqVo.getName()+reqVo.getType();
// }
// fileService.addOrUpdateFile(reqVo);
// String url = request.getContextPath();
// logger.info("绝对路径:{},工程路径:{}", filePath, url);
// File tmpFile = new File(pathname);
// if (!tmpFile.exists()) {
// tmpFile.createNewFile();
// }
// InputStream in = file.getInputStream();
// FileOutputStream fos = new FileOutputStream(tmpFile);
// byte[] b = new byte[1024];
// int length;
// while ((length = in.read(b)) != -1) {
// fos.write(b, 0, length);
// }
// in.close();
// fos.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// return queryOk(null);
// }
//
//
// @RequestMapping(path = "/deleteFile", method = RequestMethod.POST)
// @ApiOperation(value = "删除图片信息", notes = "删除图片信息")
// @ApiResponses({@ApiResponse(code = 200, message = "处理成功", response = FileInfo.class)})
// public String deleteFile(String id) {
// if (StringUtils.isBlank(id)) {
// return paramsError();
// }
// logger.info("删除图片信息,参数:{}", id);
// try {
// fileService.deleteFile(id);
// return updateOk(null);
// } catch (Exception e) {
// e.printStackTrace();
// return error(null, OperateTypeEm.UPDATE.toString());
// }
// }
}
<file_sep># thyeme
Thymeleaf 是一种模板语言。那模板语言或模板引擎是什么?常见的模板语言都包含以下几个概念:数据(Data)、模板(Template)、模板引擎(Template Engine)和结果文档(Result Documents)。
- 数据:数据是信息的表现形式和载体,可以是符号、文字、数字、语音、图像、视频等。数据和信息是不可分离的,数据是信息的表达,信息是数据的内涵。数据本身没有意义,数据只有对实体行为产生影响时才成为信息。
- 模板:模板,是一个蓝图,即一个与类型无关的类。编译器在使用模板时,会根据模板实参对模板进行实例化,得到一个与类型相关的类。
- 模板引擎:模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。
- 结果文档:一种特定格式的文档,比如用于网站的模板引擎就会生成一个标准的HTML文档。
模板语言用途广泛,常见的用途如下
- 页面渲染
- 文档生成
- 代码生成
- 所有 “数据+模板=文本” 的应用场景
# 集成
## 添加依赖
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
## 创建目录
* resources/static:存放css、js等资源文件
* resources/templates:存放视图模板文件
## 配置添加
```
spring:
thymeleaf:
cache: true # Enable template caching.
check-template: true # Check that the template exists before rendering it.
check-template-location: true # Check that the templates location exists.
enabled: true # Enable Thymeleaf view resolution for Web frameworks.
encoding: UTF-8 # Template files encoding.
excluded-view-names: # Comma-separated list of view names that should be excluded from resolution.
mode: HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
prefix: classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
suffix: .html # Suffix that gets appended to view names when building a URL.
template-resolver-order: # Order of the template resolver in the chain.
view-names: # Comma-separated list of view names that can be resolved.
reactive:
max-chunk-size: # Maximum size of data buffers used for writing to the response, in bytes.
media-types: # Media types supported by the view technology.
servlet:
content-type: text/html # Content-Type value written to HTTP responses.
```
```
spring.thymeleaf.cache=true # Enable template caching.
spring.thymeleaf.check-template=true # Check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Check that the templates location exists.
spring.thymeleaf.enabled=true # Enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.max-chunk-size= # Maximum size of data buffers used for writing to the response, in bytes.
spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.
```<file_sep># 图片管理系统
## 技术参数
* SpringBoot
* mybatis
* druid
* thymeleaf
* bootstrap
* swagger-ui
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath></relativePath>
</parent>
<groupId>com.azxx.system</groupId>
<artifactId>pictureManage</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>pictureManage</name>
<description> pictrue manage system</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger.version>2.7.0</swagger.version>
<druid.version>1.1.13</druid.version>
<mybatis.version>2.0.0</mybatis.version>
<tk.mybatis.versiong>2.1.5</tk.mybatis.versiong>
<mysql.version>8.0.12</mysql.version>
<pagehelper.version>5.1.8</pagehelper.version>
<pagehelper.starter.version>1.2.10</pagehelper.starter.version>
<httpclient.version>4.5.6</httpclient.version>
<fastjson.version>1.2.56</fastjson.version>
<gson.version>2.8.5</gson.version>
<commons.lang3.version>3.8.1</commons.lang3.version>
</properties>
<!-- Add typical dependencies for a web application -->
<dependencies>
<!-- 排除内置tomcat -->
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--swagger ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- JDBC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mapper -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${tk.mybatis.versiong}</version>
</dependency>
<!--pagehelper -->
<!--<dependency>-->
<!--<groupId>com.github.pagehelper</groupId>-->
<!--<artifactId>pagehelper</artifactId>-->
<!--<version>${pagehelper.version}</version>-->
<!--</dependency>-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper.starter.version}</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
<mainClass>com.azxx.picture.Starter</mainClass>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<!--<compilerArguments> -->
<!--<bootclasspath>${java.home}\lib\rt.jar;${java.home}\lib\jce.jar</bootclasspath> -->
<!--<bootclasspath>/data/java/jdk1.8.0_131/lib/rt.jar;/data/java/jdk1.8.0_131/lib/jce.jar</bootclasspath> -->
<!--</compilerArguments> -->
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.14</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project><file_sep># 集成
## 添加依赖
```
<!--swagger ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
```
## 配置
```
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket config() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(true)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.azxx.picture.controller"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("图片管理系统-api文档").description("图片管理系统-api文档").termsOfServiceUrl("").version("1.0.0").build();
}
}
```
## 访问
```
http://localhost:8080/swagger-ui.html
```
# 注解详解
## @Api
该注解将一个Controller(Class)标注为一个swagger资源(API)。在默认情况下,Swagger-Core只会扫描解析具有@Api注解的类,而会自动忽略其他类别资源(JAX-RS endpoints,Servlets等等)的注解。该注解包含以下几个重要属性:
- tags API分组标签。具有相同标签的API将会被归并在一组内展示。
- value 如果tags没有定义,value将作为Api的tags使用
- description API的详细描述,在1.5.X版本之后不再使用,但实际发现在2.0.0版本中仍然可以使用
## @ApiOperation
在指定的(路由)路径上,对一个操作或HTTP方法进行描述。具有相同路径的不同操作会被归组为同一个操作对象。不同的HTTP请求方法及路径组合构成一个唯一操作。此注解的属性有:
- value 对操作的简单说明,长度为120个字母,60个汉字。
- notes 对操作的详细说明。
- httpMethod HTTP请求的动作名,可选值有:"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"。
- code 默认为200,有效值必须符合标准的HTTP Status Code Definitions。
## @ApiImplicitParams
注解ApiImplicitParam的容器类,以数组方式存储。
## @ApiImplicitParam
对API的单一参数进行注解。虽然注解@ApiParam同JAX-RS参数相绑定,但这个@ApiImplicitParam注解可以以统一的方式定义参数列表,也是在Servelet及非JAX-RS环境下,唯一的方式参数定义方式。注意这个注解@ApiImplicitParam必须被包含在注解@ApiImplicitParams之内。可以设置以下重要参数属性:
- name 参数名称
- value 参数的简短描述
- required 是否为必传参数
- dataType 参数类型,可以为类名,也可以为基本类型(String,int、boolean等)
- paramType 参数的传入(请求)类型,可选的值有path, query, body, header or form
## @ApiParam
增加对参数的元信息说明。这个注解只能被使用在JAX-RS 1.x/2.x的综合环境下。其主要的属性有:
- required 是否为必传参数
- value 参数简短说明
## @ApiResponses
注解@ApiResponse的包装类,数组结构。即使需要使用一个@ApiResponse注解,也需要将@ApiResponse注解包含在注解@ApiResponses内。
## @ApiResponse
描述一个操作可能的返回结果。当REST API请求发生时,这个注解可用于描述所有可能的成功与错误码。可以用,也可以不用这个注解去描述操作的返回类型,但成功操作的返回类型必须在@ApiOperation中定义。如果API具有不同的返回类型,那么需要分别定义返回值,并将返回类型进行关联。但Swagger不支持同一返回码,多种返回类型的注解。注意:这个注解必须被包含在@ApiResponses注解中。
- code HTTP请求返回码。有效值必须符合标准的HTTP Status Code Definitions。
- message 更加易于理解的文本消息
- response 返回类型信息,必须使用完全限定类名,比如“com.xyz.cc.Person.class”
- responseContainer 如果返回类型为容器类型,可以设置相应的值。有效值为 "List", "Set" or "Map",其他任何无效的值都会被忽略
## @ApiModel
提供对Swagger model额外信息的描述。在标注@ApiOperation注解的操作内,所有的类将自动被内省(introspected),但利用这个注解可以做一些更加详细的model结构说明。主要属性有:
- value model的别名,默认为类名
- description model的详细描述
## @ApiModelProperty
对model属性的注解,主要的属性值有:
- value 属性简短描述
- example 属性的示例值
- required 是否为必须值
# 使用例子
```
@RestController
@RequestMapping(path = "/fileManage")
@Api(tags = "FileManage", description = "图片管理")
public class FileController extends BaseController{
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
@Autowired
private FileService fileService;
@RequestMapping(path = "/getFiles",method = RequestMethod.POST)
@ApiOperation(value = "获取图片列表" ,notes = "获取图片列表")
@ApiResponses({ @ApiResponse(code = 200, message = "处理成功", response = FileInfo.class) })
public String getFiles(FileReqVo reqVo){
if(reqVo == null){
return paramsError();
}
logger.info("获取文件列表开始,参数:{}", JSON.toJSON(reqVo));
try {
List<FileInfo> result = fileService.getFiles(reqVo);
return queryOk(result);
}catch (Exception e){
e.printStackTrace();
return error(null,OperateTypeEm.QUERY.toString());
}
}
}
```<file_sep>CREATE DATABASE `picture_manage` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE TABLE `file_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NULL COMMENT '文件名称',
`title` varchar(200) NULL COMMENT '相片标题',
`description` varchar(1000) NULL COMMENT '描述',
`size` int(11) NULL COMMENT '文件大小',
`type` varchar(50) NULL COMMENT '文件类型ID',
`group_id` int(11) NULL COMMENT '分组ID',
`group_name` varchar(100) NULL COMMENT '分组名称',
`url` varchar(255) NULL COMMENT '路径',
`create_time` timestamp(0) NULL COMMENT '文件创建时间',
`record_time` timestamp(0) NULL COMMENT '记录时间',
PRIMARY KEY (`id`)
);
CREATE TABLE `group_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(255) NULL COMMENT '分组描述',
`name` varchar(255) NULL COMMENT '分组名称',
`record_time` timestamp NULL COMMENT '记录时间',
PRIMARY KEY (`id`)
);<file_sep>package com.azxx.picture.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Component
public class EmailService {
private static Logger logger = LoggerFactory.getLogger(EmailService.class);
@Autowired
private JavaMailSender mailSender;
@Value("${email.emailFrom}")
private String emailFrom;
/**
*
* @param emailTo 邮件发送地址
* @param subject 主题
* @param content 内容
*/
public void sendSimpleEmail(String emailTo,String subject,String content){
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(emailFrom);
message.setTo(emailTo);
//同时发送邮件给多人
// String[] adds = {"<EMAIL>","<EMAIL>"};
// message.setTo(adds);
message.setSubject(subject);
message.setText(content);
try {
mailSender.send(message);
logger.info("email send successful!");
} catch (Exception e) {
logger.info("email send failure!",e);
}
}
/**
* 发送HTML邮件
* @param emailTo 要发送的邮件地址
* @param subject 主题
* @param content 内容
*/
public void sendHtmlEmail(String emailTo,String subject,String content){
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setFrom(emailFrom);
helper.setTo(emailTo);
helper.setSubject(subject);
helper.setText(content,true);
mailSender.send(message);
logger.info("email send successful!");
} catch (MessagingException e) {
logger.info("email send failure!",e);
}
}
/**
* 发送带附件的邮件
* @param to 要发送的邮件地址
* @param subject 主题
* @param content 内容
* @param filePath 附件地址
*/
public void sendAttachmentsEmail(String to, String subject, String content, String filePath) {
//创建一个MINE消息
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(emailFrom);
helper.setTo(to);
helper.setSubject(subject);
// true表示这个邮件是有附件的
helper.setText(content, true);
//创建文件系统资源
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
//添加附件
helper.addAttachment(fileName, file);
mailSender.send(message);
logger.info("带附件的邮件已经发送。");
} catch (MessagingException e) {
logger.error("发送带附件的邮件时发生异常!", e);
}
}
/**
* 发送嵌入静态资源的邮件
* @param to 要发送的邮件地址
* @param subject 主题
* @param content 内容
* @param rscPath 资源路径
* @param rscId 资源ID
*/
public void sendInlineResourceEmail(String to, String subject, String content, String rscPath, String rscId) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(emailFrom);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource res = new FileSystemResource(new File(rscPath));
//添加内联资源,一个id对应一个资源,最终通过id来找到该资源
helper.addInline(rscId, res);//添加多个图片可以使用多条 <img src='cid:" + rscId + "' > 和 helper.addInline(rscId, res) 来实现
mailSender.send(message);
logger.info("嵌入静态资源的邮件已经发送。");
} catch (MessagingException e) {
logger.error("发送嵌入静态资源的邮件时发生异常!", e);
}
}
}
<file_sep>package com.azxx.picture.vo;
/**
* @version V1.0
* @class: ResultCodeEm
* @description:
* @author: xuzheng
* @create: 2019-02-02 11:27
**/
public enum ResultCodeEm {
UPDATE_SUCCESS("200","修改成功!"),
QUERY_SUCCESS("200","查询成功!"),
DELETE_SUCCESS("200","删除成功!"),
UPDATE_FIALURE("500","修改失败!"),
QUERY_FIALURE("500","查询失败!"),
DELETE_FIALURE("500","删除失败!"),
PARAMS_ERROR("500","参数错误!")
;
ResultCodeEm(String code, String msg) {
this.code = code;
this.msg = msg;
}
private String code;
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
<file_sep>var grid_selector = "#grid-table";
var pager_selector = "#grid-pager";
var startTime = "";
var endTime = "";
var dateFormat = "YYYY-MM-DD HH:MM:SS";
var fileManage = {
query: function () {
$(grid_selector).jqGrid('clearGridData'); //清空表格
$(grid_selector).jqGrid('setGridParam', { // 重新加载数据
postData: {
appName: $("#appName").val(),
startTime: startTime,
endTime: endTime,
// state: $("#state").val()
}, // newdata 是符合格式要求的需要重新加载的数据
}).trigger("reloadGrid");
},
reset: function () {
$(grid_selector).jqGrid('clearGridData'); //清空表格
$("#timeRange").val("请选择日期");
$("#appName").val("")
startTime = "",
endTime = "",
$(grid_selector).jqGrid('setGridParam', { // 重新加载数据
postData: {
appName: "",
startTime: "",
endTime: "",
},
}).trigger("reloadGrid");
},
getSelect: function () {
var options = "";
$.ajax({
url: baseUrl + "/groupManage/getGroups",
type: "POST",
async: false,
data: {},
success: function (response) {
var data = $.parseJSON(response);
if (data.code == 200) {
if (data.data != null && data.data.length > 0) {
for (var i = 0; i < data.data.length; i++) {
var tmp = data.data[i];
if (i != data.data.length - 1) {
options += tmp.name + ":" + tmp.name + ";";
} else {
options += tmp.name + ":" + tmp.name;
}
}
} else {
options += "无:无";
}
}
}
});
return options;
},
initGroup: function () {
var self = this;
$.ajax({
url: baseUrl + "/groupManage/getGroups",
type: "POST",
data: {},
success: function (response) {
var data = $.parseJSON(response);
if (data.code == 200) {
if (data.data != null && data.data.length > 0) {
$("#state").empty();
$("#state").append("<option value=''>全部</option>");
for (var i = 0; i < data.data.length; i++) {
var tmp = data.data[i];
$("#state").append("<option value='" + tmp.name + "'>" + tmp.name + "</option>");
}
}
}
if (data.status == "error") {
alert(data.msg);
}
},
error: function () {
alert("请求失败!");
}
});
},
enterEvent: function () {
$(document).keydown(function (event) {
if (event.keyCode == 13) {
$(grid_selector).jqGrid('clearGridData'); //清空表格
$(grid_selector).jqGrid('setGridParam', { // 重新加载数据
postData: {
appName: $("#appName").val(),
startTime: startTime,
endTime: endTime,
},
}).trigger("reloadGrid");
}
});
},
initGridData: function () {
var self = this;
jQuery(grid_selector).jqGrid({
url: baseUrl + "/apps",
datatype: "json",
mtype: "get",
postData: {},
jsonReader: {
root: "data.list",
page: 10,
total: "data.pages",
records: "data.total"
},
colNames: ['id', '应用ID', '应用名称', '应用类型', '当前版本号', '区域', '当前状态', '发布日期', '操作', ''],
colModel: [
{name: 'id', index: 'id', width: 60, sorttype: "int", editable: true, edittype: 'text', hidden: true},
{
name: 'appId',
index: 'appId',
width: 100,
editable: true,
edittype: 'text',
editoptions: {size: "20", maxlength: "100"}
}, {
name: 'appName',
index: 'appName',
width: 100,
editable: true,
edittype: "text",
editoptions: {size: "20", maxlength: "100"}
}, {
name: 'appType',
index: 'appType',
width: 50,
editable: false
}, {
name: 'version',
index: 'version',
width: 50,
editable: true,
edittype: "text",
editoptions: {size: "20", maxlength: "100"}
}, {
name: 'region',
index: 'region',
width: 100,
editable: false,
hidden: true
}, {
name: 'stateName',
index: 'stateName',
width: 50,
editable: true,
edittype: "select",
editoptions: {style: "width:158.38px;height:37px", value: selectState()},
//formatter: fmatterFuuc
}, {
name: 'releaseDate',
index: 'releaseDate',
width: 80,
sortable: false,
editable: false,
formatter: function (cellvalue, options, rowObject) {
var date = new Date();
date.setTime(cellvalue);
return date.Format("yyyy-MM-dd HH:mm:ss");
}
}, {
name: '', index: '', width: 80, fixed: true, sortable: false, resize: false,
formatter: 'actions',
formatoptions: {
keys: true,
delbutton: false,//disable delete button
delOptions: {recreateForm: true, beforeShowForm: beforeDeleteCallback},
editformbutton: true,
editOptions: {
recreateForm: true,
closeAfterEdit: true,
beforeShowForm: beforeEditCallback,
beforeSubmit: beforeSumbitCallback,
afterSubmit: afterSubmitCallback
}
}
}, {
name: 'fileToUpload',
index: 'fileToUpload',
hidden: true,
editoptions: {enctype: "multipart/form-data"},
edittype: 'file',
// formatter: this.showPicture,
width: 150,
align: "left",
editable: true
}
],
viewrecords: true,
height: 'auto',
width: 'auto',
// height: 500,
rowNum: 10,
rowList: [10, 20, 50],
pager: pager_selector,
altRows: false,
multiselect: false,
multiboxonly: true,
rownumbers: true,
editurl: baseUrl + "/apps",//nothing is saved
loadComplete: function () {
var table = this;
setTimeout(function () {
$(grid_selector).jqGrid('setLabel', 'rn', '序号', {'text-align': 'left'}, '');
styleCheckbox(table);
updateActionIcons(table);
updatePagerIcons(table);
enableTooltips(table);
}, 0);
}
});
$(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size
//navButtons
jQuery(grid_selector).jqGrid('navGrid', pager_selector,
{ //navbar options
edit: false,
editicon: 'ace-icon fa fa-pencil blue',
add: true,
addicon: 'ace-icon fa fa-plus-circle purple',
del: false,
delicon: 'ace-icon fa fa-trash-o red',
search: false,
searchicon: 'ace-icon fa fa-search orange',
refresh: true,
refreshicon: 'ace-icon fa fa-refresh green',
view: true,
viewicon: 'ace-icon fa fa-search-plus grey',
},
{
//edit record form
closeAfterEdit: true,
recreateForm: true,
viewPagerButtons: true,
beforeShowForm: function (e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
style_edit_form(form);
$("#editmodgrid-table").css("top", "20%");
$("#editmodgrid-table").css("left", "40%");
},
onInitializeForm: function (formid) {
var addUrl = baseUrl + "/apps";
console.log($(grid_selector).jqGrid('getGridParam', 'editurl'));
$(grid_selector).jqGrid('setGridParam', {editurl: addUrl});
$("#tr_fileToUpload").css("display", "");
console.log(formid);
// alert(postdata);
// $(formid).attr('method', 'POST');
// $(formid).attr('action', '/abc');
// $(formid).attr('enctype', 'multipart/form-data');
},
afterSubmit: function (response, postdata) {
var res = $.parseJSON(response.responseText);
if (res.code != 200) {
// self.uploadFile(postdata);
alert("提交失败,请重新提交!");
return [false];
// return [false, res.msg];
} else {
alert("图片上传成功!");
self.uploadFile(postdata);
return [true];
}
}
},
{
//new record form
closeAfterAdd: true,
recreateForm: true,
viewPagerButtons: true,
beforeShowForm: function (e) {
$("#editmodgrid-table").css("top", "20%");
$("#editmodgrid-table").css("left", "40%");
e.find("#appId").attr('readOnly', false);
// $(grid_selector).setGridParam().hideCol("fileToUpload").trigger("reloadGrid");
// $(grid_selector).setGridParam().showCol("fileToUpload").trigger("reloadGrid");
// var form = $(e[0]);
// form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
// .wrapInner('<div class="widget-header" />')
// style_edit_form(form);
},
onInitializeForm: function (formid) {
var addUrl = baseUrl + "/apps";
// console.log($(grid_selector).jqGrid('getGridParam', 'editurl'));
$(grid_selector).jqGrid('setGridParam', {editurl: addUrl});
$("#tr_fileToUpload").css("display", "");
// console.log(formid);
// $(formid).attr('method', 'POST');
// $(formid).attr('action', '/abc');
// $(formid).attr('enctype', 'multipart/form-data');
},
beforeSubmit: function beforeSumbit() {
var fileTypes = [".jpeg", ".png",".jpg", ".gif"];
var filePath = $('#fileToUpload').val();
if (filePath) {
var isNext = false;
var fileEnd = filePath.substring(filePath.indexOf("."));
for (var i = 0; i < fileTypes.length; i++) {
if (fileTypes[i] === fileEnd) {
isNext = true;
break;
}
}
if (!isNext) {
alert(" 只接受图片类型!");
return false;
}
return [true];
} else {
alert("请选择图片!")
return false;
}
},
afterSubmit: function (response, postdata) {
var res = $.parseJSON(response.responseText);
if (res.code != 200) {
// self.uploadFile(postdata);
alert("提交失败,请重新提交!");
return [false];
// return [false, res.msg];
} else {
//alert("图片上传成功!");
self.uploadFile(postdata);
return [true];
}
}
},
{
//delete record form
recreateForm: true,
onInitializeForm: function (formid) {
var delUrl = baseUrl + "/fileManage/deleteFile";
$(grid_selector).jqGrid('setGridParam', {editurl: delUrl});
},
beforeShowForm: function (e) {
var delUrl = baseUrl + "/fileManage/deleteFile";
$(grid_selector).jqGrid('setGridParam', {editurl: delUrl});
var form = $(e[0]);
if (form.data('styled')) return false;
form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
style_delete_form(form);
form.data('styled', true);
},
onClick: function (e) {
alert(1);
}
},
{
//search form
recreateForm: true,
afterShowSearch: function (e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
style_search_form(form);
},
afterRedraw: function () {
style_search_filters($(this));
},
multipleSearch: true,
},
{
//view record form
recreateForm: true,
beforeShowForm: function (e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
}
}
)
function beforeDeleteCallback(e) {
var form = $(e[0]);
if (form.data('styled')) return false;
form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
style_delete_form(form);
form.data('styled', true);
var delUrl = baseUrl + "/fileManage/deleteFile";
$(grid_selector).jqGrid('setGridParam', {editurl: delUrl});
}
function selectState() {
var stateListResult = "";
$.ajax({
type: "get",
async: false,
url: baseUrl + "/apps/selectState",
success: function (result) {
var result = $.parseJSON(result);
var stateList = result.data;
for (i = 0; i < stateList.length; i++) {
stateListResult += stateList[i].dictId + ":" + stateList[i].name + ";";
}
}
});
if (stateListResult.length > 0) {
stateListResult=stateListResult.substring(0,stateListResult.length-1);
}
return stateListResult;
}
function beforeEditCallback(e) {
$("#editmodgrid-table").css("top", "20%");
$("#editmodgrid-table").css("left", "40%");
e.find('#appId').attr('readOnly', true);
e.find('#appName').attr('readOnly', true);
e.find('#version').attr('readOnly', true);
e.find('#stateName').attr('disabled', true);
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
style_edit_form(form);
var addUrl = baseUrl + "/apps";
$(grid_selector).jqGrid('setGridParam', {editurl: addUrl});
$("#tr_fileToUpload").css("display", "");
}
function afterSubmitCallback(response, postdata) {
var res = $.parseJSON(response.responseText);
if (res.code != 200) {
// self.uploadFile(postdata);
alert("提交失败,请重新提交!");
return [false];
// return [false, res.msg];
} else {
//alert("图片上传成功!");
self.uploadFile(postdata);
return [true];
}
}
function beforeSumbitCallback() {
var fileTypes = [".jpeg", ".png",".jpg",];
var filePath = $('#fileToUpload').val();
if (filePath) {
var isNext = false;
var fileEnd = filePath.substring(filePath.indexOf("."));
for (var i = 0; i < fileTypes.length; i++) {
if (fileTypes[i] === fileEnd) {
isNext = true;
break;
}
}
if (!isNext) {
alert("只接受图片类型");
return false;
}
return [true];
} else {
alert("请选择图片!")
return false;
}
}
// function onClickSubmitCallback(params, postdata) {
// alert("上传成功!");
// self.uploadFile(postdata);
// }
function fmatterFuuc(cellvalue, options, rowObject) {
if (cellvalue == 1) {
return "应用创建";
}
if (cellvalue == 2) {
return "提交审核";
}
if (cellvalue == 3) {
return "审核通过";
}
if (cellvalue == 4) {
return "申请灰度发布";
}
if (cellvalue == 5) {
return "灰度发布";
}
if (cellvalue == 6) {
return "申请上线";
}
if (cellvalue == 7) {
return "上线";
}
if (cellvalue == 8) {
return "申请下线";
}
if (cellvalue == 9) {
return "下线";
}
}
},
uploadFile: function (postdata) {
var formData = new FormData();
formData.append("fileToUpload", document.getElementById("fileToUpload").files[0]);
formData.append("appName", postdata.appName);
formData.append("appId", postdata.appId);
// formData.append("state",postdata.state);
// formData.append("description",postdata.description);
$.ajax({
url: baseUrl + "/apps/uploadFile",
type: "PUT",
data: formData,
contentType: false,
processData: false,
success: function (data) {
$("#queryBtn").click();
var data = $.parseJSON(data);
// console.log(">>>" + data);
if (data.code != 200) {
alert(data.msg);
} else {
alert("上传成功!");
}
},
error: function () {
alert("上传失败!");
}
});
},
showPicture: function (cellvalue, options, rowObject) {
// console.log("cellvalue:"+cellvalue);
// return "<img src='" + cellvalue + "' height='50' width='50' />";
},
initGirdAutoWidth: function () {
var parent_column = $(grid_selector).closest('[class*="col-"]');
//resize to fit page size
$(window).on('resize.jqGrid', function () {
$(grid_selector).jqGrid('setGridWidth', parent_column.width());
})
//resize on sidebar collapse/expand
$(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
//setTimeout is for webkit only to give time for DOM changes and then redraw!!!
setTimeout(function () {
$(grid_selector).jqGrid('setGridWidth', parent_column.width());
}, 20);
}
})
},
initDatePicker: function () {
$("#timeRange").val("请选择日期");
$('input[name=date-range-picker]').daterangepicker({
'applyClass': 'btn-sm btn-success',
'cancelClass': 'btn-sm btn-default',
showDropdowns: true,//当设置值为true的时候,允许年份和月份通过下拉框的形式选择 默认false
timePicker24Hour: true,//设置小时为24小时制 默认false
timePicker: true,//可选中时分 默认false
autoUpdateInput: false,//1.当设置为false的时候,不给与默认值(当前时间)2.选择时间时,失去鼠标焦点,不会给与默认值 默认true
locale: {
format: dateFormat,
separator: " 至 ",
applyLabel: '确定',
cancelLabel: '取消',
customRangeLabel: "自定义"
},
ranges: {
'今天': [moment(), moment()],
'昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'近7天': [moment().subtract(7, 'days'), moment()],
'这个月': [moment().startOf('month'), moment().endOf('month')],
'上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
}).on('cancel.daterangepicker', function (ev, picker) {
$("#timeRange").val("请选择日期");
startTime = '';
endTime = '';
}).on('apply.daterangepicker', function (ev, picker) {
startTime = picker.startDate.format(dateFormat);
endTime = picker.endDate.format(dateFormat);
$("#timeRange").val(picker.startDate.format(dateFormat) + " 至 " + picker.endDate.format(dateFormat));
});
},
init: function () {
$(document.body).css({
"overflow-x": "hidden"
});
// this.initGroup(); //查询所有组
this.initDatePicker(); //日期函数
this.initGirdAutoWidth(); //匹配宽度
this.initGridData();
this.enterEvent();
}
}<file_sep>var baseUrl = getBaseUrl();
function getBaseUrl(){
//获取当前网址,如: http://localhost:8083/myproj/view/my.jsp
var curWwwPath=window.document.location.href;
//获取主机地址之后的目录,如: myproj/view/my.jsp
var pathName=window.document.location.pathname;
var pos=curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8083
var localhostPaht=curWwwPath.substring(0,pos);
//获取带"/"的项目名,如:/myproj
var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
//得到了 http://localhost:8083/myproj
var realPath=localhostPaht+projectName;
return localhostPaht;
}
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"H+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}<file_sep>package com.azxx.picture.service;
import com.azxx.picture.entity.FileInfo;
import com.azxx.picture.entity.GroupInfo;
import com.azxx.picture.mapper.GroupInfoMapper;
import com.azxx.picture.vo.groupInfo.GroupReqVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* @version V1.0
* @class: GroupService
* @description: group service
* @author: xuzheng
* @create: 2019-02-02 10:15
**/
@Service
public class GroupService {
private static final Logger logger = LoggerFactory.getLogger(GroupService.class);
@Autowired
private GroupInfoMapper groupInfoMapper;
public List<GroupInfo> getGroups(GroupReqVo reqVo){
List<GroupInfo> result = null;
if(reqVo == null){
return result;
}
GroupInfo groupInfo = new GroupInfo();
BeanUtils.copyProperties(reqVo,groupInfo);
return groupInfoMapper.select(groupInfo);
}
public PageInfo<GroupInfo> pages(GroupReqVo reqVo){
GroupInfo groupInfo = new GroupInfo();
BeanUtils.copyProperties(reqVo,groupInfo);
return PageHelper.startPage(reqVo.getPage(), reqVo.getRows()).doSelectPageInfo(() -> groupInfoMapper.select(groupInfo));
}
public boolean addOrUpdateGroup(GroupReqVo reqVo){
int effectRows = 0;
if(reqVo == null) {
return false;
}
GroupInfo groupInfo = new GroupInfo();
BeanUtils.copyProperties(reqVo,groupInfo);
groupInfo.setRecordTime(new Date());
if(reqVo.getId()==null || reqVo.getId() == 0){
effectRows = groupInfoMapper.insert(groupInfo);
}else{
effectRows = groupInfoMapper.updateByPrimaryKeySelective(groupInfo);
}
return effectRows>0?true:false;
}
public boolean deleteGroup(Integer id){
int effectRows = 0;
if(id == null) {
return false;
}
effectRows = groupInfoMapper.deleteByPrimaryKey(id);
return effectRows>0?true:false;
}
}
<file_sep>package com.azxx.picture.controller;
import com.alibaba.fastjson.JSON;
import com.azxx.picture.vo.BaseResult;
import com.azxx.picture.vo.OperateTypeEm;
import com.azxx.picture.vo.ResultCodeEm;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @version V1.0
* @class: BaseController
* @description: base controller
* @author: xuzheng
* @create: 2019-02-02 11:16
**/
public class BaseController {
private static final Logger logger = LoggerFactory.getLogger(BaseController.class);
/**
* 返回结果
* @param object 返回对象
* @param operateType 操作类型
* @return
*/
public String ok(Object object,String operateType){
BaseResult result = new BaseResult();
if(StringUtils.isBlank(operateType)){
operateType = OperateTypeEm.QUERY.toString();
}
if(operateType.equals(OperateTypeEm.QUERY.toString())){
result.setCode(ResultCodeEm.QUERY_SUCCESS.getCode());
result.setMsg(ResultCodeEm.QUERY_SUCCESS.getMsg());
}else if(operateType.equals(OperateTypeEm.UPDATE.toString())){
result.setCode(ResultCodeEm.UPDATE_SUCCESS.getCode());
result.setMsg(ResultCodeEm.UPDATE_SUCCESS.getMsg());
}else if(operateType.equals(OperateTypeEm.DELETE.toString())){
result.setCode(ResultCodeEm.DELETE_SUCCESS.getCode());
result.setMsg(ResultCodeEm.DELETE_SUCCESS.getMsg());
}
result.setData(object);
return JSON.toJSONString(result);
}
public String queryOk(Object object){
BaseResult result = new BaseResult();
result.setCode(ResultCodeEm.QUERY_SUCCESS.getCode());
result.setMsg(ResultCodeEm.QUERY_SUCCESS.getMsg());
result.setData(object);
return JSON.toJSONString(result);
}
public String updateOk(Object object){
BaseResult result = new BaseResult();
result.setCode(ResultCodeEm.UPDATE_SUCCESS.getCode());
result.setMsg(ResultCodeEm.UPDATE_SUCCESS.getMsg());
result.setData(object);
return JSON.toJSONString(result);
}
public String ok(Object object,String code,String msg){
BaseResult result = new BaseResult();
result.setCode(code);
result.setMsg(msg);
result.setData(object);
return JSON.toJSONString(result);
}
public String paramsError(){
BaseResult result = new BaseResult();
result.setCode(ResultCodeEm.PARAMS_ERROR.getCode());
result.setMsg(ResultCodeEm.PARAMS_ERROR.getMsg());
return JSON.toJSONString(result);
}
/**
*
* @param object
* @param operateType
* @return
*/
public String error(Object object,String operateType){
BaseResult result = new BaseResult();
if(StringUtils.isBlank(operateType)){
operateType = OperateTypeEm.QUERY.toString();
}
if(operateType.equals(OperateTypeEm.QUERY.toString())){
result.setCode(ResultCodeEm.QUERY_FIALURE.getCode());
result.setMsg(ResultCodeEm.QUERY_FIALURE.getMsg());
}else if(operateType.equals(OperateTypeEm.UPDATE.toString())){
result.setCode(ResultCodeEm.UPDATE_FIALURE.getCode());
result.setMsg(ResultCodeEm.UPDATE_FIALURE.getMsg());
}else if(operateType.equals(OperateTypeEm.DELETE.toString())){
result.setCode(ResultCodeEm.DELETE_FIALURE.getCode());
result.setMsg(ResultCodeEm.DELETE_FIALURE.getMsg());
}
result.setData(object);
return JSON.toJSONString(result);
}
}
<file_sep>package com.azxx.picture.vo.groupInfo;
import io.swagger.annotations.ApiModelProperty;
/**
* @version V1.0
* @class: GroupReqVo
* @description: group request vo
* @author: xuzheng
* @create: 2019-02-02 10:44
**/
public class GroupReqVo {
@ApiModelProperty(value = "分组描述",dataType = "string")
private String description;
@ApiModelProperty(value = "分组名称",dataType = "string")
private String name;
@ApiModelProperty(value = "ID",dataType = "int")
private Integer id;
private Integer page;
private Integer rows;
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| cbd05b5d3e291257153dee79e263ca6b3d55c64e | [
"SQL",
"Markdown",
"JavaScript",
"Maven POM",
"Java"
] | 15 | Java | White1Horse/pictureManage | 2f42ece97d8261f1723444cad82fb4c5f21c9bd4 | 401f66a6198e0676e879cb9909fb1e0e5b6e85f7 | |
refs/heads/master | <file_sep>module.exports = function(config, grunt) {
return {
target: {
options: {
war_dist_folder: '<%= targetDir %>', /* Folder where to generate the WAR. */
war_name: 'kibana3.war', /* The name fo the WAR file (.war will be the extension) */
webxml_welcome: 'index.html',
webxml_display_name: 'Kibana 3'
},
files: [
{
expand: true,
cwd: '<%= destDir %>',
src: ['**'],
dest: ''
}
]
}
};
};<file_sep>#Kibana JS API
-
Built by Ikanow to expose some internal kibana functionality via a simple JavaScript API. Currently only tested using Kibana 3. Some simple tests for this application exist as a FlashBuilder application. The test application opens Kibana within an IFrame and tests the exposed functionality. For more information and source code [Check out the BitBucket git repository](https://bitbucket.org/mike_grill/com.ikanow.infinite.kibana.tests/src).
**Function Summary**
Dashboard Functions
* installToParent( void )
* refreshDashboard( void )
* exportConfig
* exportConfigJson
* importConfig
* importConfigJson
Query & Filter Functions
* addQuery( void )
* getQueryList( void )
* getQueryListJson( void )
* setQueryList( newList, skipReset, appendOnly )
* setQueryListJson( newListJson, skipReset, appendOnly )
* resetQueryList( void )
* getFilters( void )
* getFiltersJson( void )
* setFilters( filters, skipReset, appendOnly )
* setFiltersJson( filtersJson, skipReset, appendOnly )
* removeFilters( void )
**Sample Objects**
Query Item
```javascript
{
"alias": "",
"type": "lucene",
"enable": true,
"id": 0,
"pin": false,
"color": "#7EB26D",
"query": "*"
}
```
Filter
```javascript
{
"alias": "",
"type": "querystring",
"mandate": "either",
"query": "*",
"id": 0,
"active": true
}
```
**Sample Usage**
This distribution of Kibana has an additional Angular service. This service is already included in `/serc/app/services/all.js` and will be available upon app startup. Using Angular's dependency injection, we simply need to reference the service and the API will be avilable at `window.kibanaJsApi`.
>```javascript
>require(['app'], function (app) {
> //Inject the kibanaJsApi when angular is done loading the app
> app.run(function(kibanaJsApiSrv) {});
>});
>```
If the API needs to be installed on a parent window use the installToParent method during app startup.
>```javascript
>require(['app'], function (app) {
> //Inject the kibanaJsApi when angular is done loading the app
> app.run(function(kibanaJsApiSrv) {
> //Add the api to the window and the window's parent if it exists
> kibanaJsApiSrv.installToParent();
> });
>});
>```
#Function List#
-
###.installToParent()###
_Add this instance of the API to the window's parent element to expose this API to an IFrame's parent._
* **Params: none**
* **Returns:**
void
###.refreshDashboard()###
_Used to forcefully refresh the Kibana Dashboard after changes._
* **Params: none**
* **Returns: boolean**
True on success
###.addQuery()###
_Add a new (empty) query item._
* **Params: none**
* **Returns: boolean**
True on success
###.getQueryList()###
_Get the current queryList as an array of Query objects._
* **Returns:**
An array of Query Objects.
###.getQueryListJson()###
_Get the current query list as a JSON String. Useful for passing complex objects through simple interfaces. Eg. Flash's ExternalInterface._
* **Returns:**
JSON String representation of .getQueryList();
###.setQueryList( queryList, skipReset, appendOnly )###
_Update the QueryList by replacing all elements in the query. Or optionally appending the elements from QueryList._
* **Params**
**queryList: Array\<QueryItem\>**
**skipReset: Boolean**
When true,the current query list will not be removed before add or updating items.
**appendOnly: Boolean**
When append is boolean TRUE, IDs on new items will be ignored and all items are trested as new.
* **Returns: Boolean**
true on success
###.setQueryListJson( queryListJson, skipReset, appendOnly )###
_Same as setQueryList but accepts a JSON String as the source data. Useful for passing complex objects through simple interfaces. Eg. Flash's ExternalInterface._
###.resetQueryList()###
_Reset the current query to a single '*' query.
* **Params: none**
* **Returns: boolean**
True on success
###.getFilters()###
_Get the current filters as an array of Filter objects._
* **Returns:**
An array of Filter Objects.
###.getFiltersJson()###
_Get the current filters list as a JSON String. Useful for passing complex objects through simple interfaces. Eg. Flash's ExternalInterface._
* **Returns:**
JSON String representation of .getFilters();
###.setFilters( filters, skipReset, appendOnly )###
_Update the filters by replacing all filters. Or optionally only updating and appending using the new filters provided._
* **Params**
**filters: Array\<Filter\>**
**skipReset: Boolean**
When true,the current query list will not be removed before add or updating items.
**appendOnly: Boolean**
When append is boolean TRUE, IDs on new items will be ignored and all items are trested as new.
* **Returns: boolean**
True on success
###.setFiltersJson( filtersJson, skipReset, appendOnly )###
_Same as setFilters but accepts a JSON String as the source data. Useful for passing complex objects through simple interfaces. Eg. Flash's ExternalInterface._
###.removeFilters()###
_Remove all filters and refresh the dashboard._
* **Returns: boolean**
True on success
<file_sep>module.exports = function(config, grunt) {
return {
options: {
name: "ikanow-<%= pkg.name %>",
version: "<%= pkg.version %>",
release: "<%= pkg.buildNumber %>",
buildArch: "noarch",
summary: "Forked embeddable Kibana",
description: "Kibana3 Fork to support parent controllers and iframe embedding",
license: "AFL-2.0",
vendor: "Ikanow LLC",
rpmDestination: "<%= targetDir%>",
requires: ["ikanow-management_db-engine"]
},
release: {
files: [
{ cwd: "target", src: "*.war", dest: "/opt/tomcat-infinite/interface-engine/webapps/"}
]
}
};
};<file_sep>/**
* This service also exposes an interface to a parent container, given this application
* is within an IFrame. The file JSAPI.md in the root of this project has more information
* on how to use this API.
*
* @typedef {{}} QueryItem; //See JSAPI.md for more information
* @typedef {Object} Filter; //See JSAPI.md for more information
* @typedef {Config} Config; //Not yet implemented.
*
*/
define([
'angular',
'lodash'
], function (angular, _) {
'use strict';
var module = angular.module('kibana.services');
module.service('kibanaJsApiSrv', function ($rootScope, dashboard, querySrv, filterSrv) {
// Save a reference to this
var self = this;
/**
* Attach event listeners to some internal kibana events so we can expose them.
*/
self.init = function () {
//console.log("[kibanaJsApi] init");
window.kibanaJsApi = this;
//Monitor Kibana events so we can expose them
$rootScope.$on('refresh', function () {
//console.log("[kibanaJsApi] Refresh observed");
//TODO expose refresh event
});
};
/**
* Add the kibanaJsApi instance to this window's parent container.
* @returns {Boolean} True on success.
*/
self.installToParent = function(){
//Install the KibanaJsApi to Kibana's container's document if it exists
if (window.parent !== window) {
//console.log("[kibanaJsApi->installToParent] Install API to IFrame Parent");
window.parent.kibanaJsApi = this;
}
return true;
};
/**
* Refresh the current dashboard
* @returns {Boolean} True on success.
*/
self.refreshDashboard = function () {
//console.log("[KibanaJsApi->refreshDashboard] Refreshing dashboard");
dashboard.refresh();
$rootScope.$apply();
return true;
};
/**
* Add a new query item to the queryList
* @param {QueryItem} queryItem Query item definition
* @returns {Boolean} True on success.
*/
self.addQuery = function( queryItem ) {
//console.log("[KibanaJsApi->addQuery] New Item: ", queryItem);
//If nothing was passed add an empty query item
if( !queryItem ) {
queryItem = {};
}
//Add an empty item
querySrv.set(queryItem);
//refresh and apply
this.refreshDashboard();
return true;
};
/**
* Get the dashboards current queryList
* @returns {Array<QueryItem>} An array of query items
*/
self.getQueryList = function(){
//console.log("[KibanaJsApi->getQueryList]");
return querySrv.getQueryObjs();
};
/**
* Get the dashboards current queryList as a JSON String
* @returns {String} A JSON String representing the current array of query items
*/
self.getQueryListJson = function () {
//console.log("[KibanaJsApi->getQueryListJson]");
var queryListJson = angular.toJson( this.getQueryList(), false);
//console.log("[KibanaJsApi->getQueryListJson] Query: ", queryListJson);
return queryListJson;
};
/**
* Replace the current query list with a new one
* @param {Array<QueryItem>} newList An array of query items
* @param {Boolean} skipReset Don't reset the Query List to '*'
* @param {Boolean} appendOnly Only add elements, don't update using IDs
* @returns {Boolean} True on success.
*/
self.setQueryList = function( newList, skipReset, appendOnly ){
//console.log("[KibanaJsApi->setQueryList] Setting query", newList);
//If skip reset wasn't set or isn't true, then we reset.
if( skipReset !== true ) {
//console.log("[KibanaJsApi->setQueryList] Clearing query before setting items");
//Empty the query but don't $apply yet
this.resetQueryList(true /*No Refresh*/);
}
_.each( newList, function(q){
if( appendOnly === true && q.hasOwnProperty('id') ) {
delete q.id; //unset ID - Forces new item
}
if( q.hasOwnProperty('id') && q.id === 0 ) {
querySrv.set( q, 0 );
} else {
querySrv.set( q );
}
});
//refresh and apply
this.refreshDashboard();
return true;
};
/**
* Replace the current query list with a new one using a json string
* @param {String} queryListJson A JSON String representing an array of query items.
* @param {Boolean} skipReset Don't reset the Query List to '*'
* @param {Boolean} appendOnly Only add elements, don't update using IDs
* @returns {Boolean} True on success.
*/
self.setQueryListJson = function (queryListJson, skipReset, appendOnly) {
//console.log("[KibanaJsApi->setQueryListJson] setting query list from json text");
var queryList = angular.fromJson(queryListJson);
return this.setQueryList(queryList, skipReset, appendOnly );
};
/**
* Replace the current query list with a single '*'
* @param {Boolean} noRefresh When boolean true, the dashboard will not be refreshed
* @returns {Boolean} True on success.
*/
self.resetQueryList = function( noRefresh ){
//console.log("[KibanaJsApi->resetQueryList] Resetting query to single '*'");
_.each(querySrv.ids(), function(qId){
querySrv.remove(qId);
});
//Reset the first item to '*'
querySrv.set({
"query":"*",
"alias":"",
"color":"#7EB26D",
"pin":false,
"type":"lucene",
"enable":true
});
//refresh and apply
if( noRefresh !== true ) {
this.refreshDashboard();
}
return true;
};
/**
* Get the dashboards current filters as an array of Filters
* @returns Array<Filter>
*/
self.getFilters = function() {
//console.log("[KibanaJsApi->getFilters]");
return filterSrv.list();
};
/**
* Get the dashboards current filters as a JSON string representing array of filters
* @returns {String} JSON String representation of an array of Filters.
*/
self.getFiltersJson = function () {
//console.log("[KibanaJsApi->getFiltersJson]");
var filtersJson = angular.toJson(this.getFilters(), false);
//console.log("[KibanaJsApi->getFiltersJson] Filters: ", filtersJson);
return filtersJson;
};
/**
* Replace the dashboards current filters with a new set. UpdateOnly will not
* remove any items before setting the new ones in place.
* @param {Array<Filter>} filters An array of filters
* @param {Boolean} skipReset Don't clear all filters before adding / setting new items.
* @param {Boolean} appendOnly Only add elements, don't update using IDs
* @returns {Boolean} True on success.
*/
self.setFilters = function( filters, skipReset, appendOnly ){
//console.log("[KibanaJsApi->setFilters] setting filters", filters);
if (skipReset !== true) {
this.removeFilters( true ); //true for no refresh
}
_.each(filters, function (filter) {
if( appendOnly === true || !filter.hasOwnProperty('id') ) {
//Remove IDs for less confusion
if( filter.hasOwnProperty('id') ){
delete filter.id;
}
//console.log("[KibanaJsApi->setFilters] appending filter", filter);
filterSrv.set(filter, undefined, true); // true for no refresh
} else {
//Even if the filter has an ID, if that ID does not exist we must add it. Updating will fail.
var filterExists = false;
_.each( self.getFilters(), function(f){
if(f.id === filter.id) {
filterExists = true;
}
});
if( filterExists ) {
//console.log("[KibanaJsApi->setFilters] updating filter", filter);
filterSrv.set(filter, filter.id, true); // true for no refresh
} else {
//console.log("[KibanaJsApi->setFilters] adding filter", filter);
filterSrv.set(filter, undefined, true); // true for no refresh
}
}
});
//refresh and apply
this.refreshDashboard();
return true;
};
/**
* See setFilters above. Accepts a JSON String representing an array of filters.
* @param {String} filtersJson JSON String representing an array of Filters.
* @param {Boolean} skipReset Don't clear all filters before adding / setting new items.
* @param {Boolean} appendOnly Only add elements, don't update using IDs
* @returns {Boolean} True on success.
*/
self.setFiltersJson = function (filtersJson, skipReset, appendOnly) {
//console.log("[KibanaJsApi->setFiltersJson] setting filters", filtersJson);
var filters = angular.fromJson(filtersJson);
return this.setFilters(filters, skipReset, appendOnly);
};
/**
* Remove all the filters from the dashboard
* @returns {Boolean} True on success.
*/
self.removeFilters = function ( noRefresh ) {
//console.log("[KibanaJsApi->removeFilters]");
_.each( filterSrv.ids(), function(fId){
filterSrv.remove(fId, true); //true for noRefresh
});
if( noRefresh !== true ){
this.refreshDashboard();
}
return true;
};
/**
* Get an object representing the current state of the dashboard.
* This object can be used for the import functionality.
*
* This has not been tested
*
* @returns {{queryList: Array.<QueryItem>, filters: Array.<Filter>}}
*/
self.exportConfig = function(){
return {
queryList: this.getQueryList(),
filters: this.getFilters()
};
};
/**
* Get a JSON String representing the current config. See exportConfig above.
*
* This has not been tested
*
* @returns {String} JSON String of current dashboard config
*/
self.exportConfigJson = function(){
return angular.toJson(this.exportConfig(), true);
};
/**
* Import a previously exported dashboard state.
*
* This has not been tested.
*
* @param {Config} config
* @returns {Boolean} True on success.
*/
self.importConfig = function( config ){
this.setFilters( config.filters );
this.setQueryList( config.queryList );
this.refreshDashboard();
return true;
};
/**
* Import a previously exported dashboard state from a JSON String.
*
* This has not been tested
*
* @param {String} configJson JSON String representing a Config object.
* @returns {Boolean} True on success.
*/
self.importConfigJson = function( configJson ){
return this.importConfig( angular.fromJson(configJson) );
};
// Now init
self.init();
});
}
);<file_sep>/*******************************************************************************
* Copyright 2012 The Infinit.e Open Source Project
*
* 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.
******************************************************************************/
// INITIALIZATION
var infiniteJsConnector = infiniteJsConnector || {
_flashMovie: null, // Container FLEX Application
_jsConnectorParent: null,
_mode: 'stashed', // 'stashed' or 'live'
/**
* Initialization consists of defining flashMove in order to communicate
* with the actionscript
*/
init: function () {
if (null == this._flashMovie) {
if (document.getElementById) {
this._flashMovie = parent.document.getElementById("Index");
}
}
},
getFlashMovie: function(){
return this._flashMovie;
},
/**
* Grabs the infinit.e.parent js connector object;
*/
getJsConnectorParent: function(){
this._jsConnectorParent = parent.infiniteJsConnectorParent;
return parent.infiniteJsConnectorParent;
},
/**
* possible values:
* - live ... append: &mode=live
* - stashed ... append: &mode=stashed
* ignore for now - all records ... append: &mode=all_records
**/
getMode: function(){
return this._mode;
},
/** sets mode **/
setMode:function(modeString){
this._mode = modeString;
return this._mode;
},
/** returns set cids **/
getCIds: function(url){
return this.getCommunityIds(url);
},
getParentId: function() {
var parentDoc = window;
while(parentDoc !== parentDoc.parent)
{
parentDoc = parentDoc.parent;
}
parentDoc = parentDoc.document;
var iFrames = parentDoc.getElementsByTagName('iframe');
return iFrames[0].getAttribute("id");
},
/**
* Asks actionscript for communityIds.
*/
getCommunityIds: function(url)
{
var me = this;
try {
var cIdsStr = me.getFlashMovie().getCommunityIds(url);
}
catch (e) {
}
return cIdsStr;
},
/**
* Asks actionscript for data set flags (docs vs custom vs map/reduce).
*/
getDatasetFlags: function()
{
var me = this;
try {
var datasetFlags = me.getFlashMovie().getDatasetFlags();
}
catch (e) {
}
return datasetFlags;
},
/**
* grabs community ids and current search state
* returns string ex: ?cids=1,2,3&mode=live
**/
getExtraUrlParams:function(url)
{
try{
var params = { 'cids': this.getCIds(url), 'mode': this.getMode() };
var datasetFlags = this.getDatasetFlags();
if (datasetFlags && (datasetFlags.length > 0)) {
var datasetFlagsObj = datasetFlags.split('&');
for (var x in datasetFlagsObj) {
var paramPair = datasetFlagsObj[x].split("=", 2);
if ((2 == paramPair.length) && (paramPair[0].length > 0)) {
params[paramPair[0]] = paramPair[1];
}
}
}
if (url.length > 512) { // use substitution
var startOfIndex = url.indexOf('/proxy/');
if (startOfIndex > 0) {
var indexSet = url.substring(startOfIndex + 7);
var endOfIndex = indexSet.indexOf('/');
if (endOfIndex > 0) {
indexSet = indexSet.substring(0, endOfIndex);
params.indexes = indexSet;
url = url.replace(indexSet, '$indexes');
params.url = url;
}
}
}
return params;
}catch(error){
console.log("getExtraUrlParams: " + error.message)
return null;
}
},
/**
* Generally called from actionscript with a true if live, false if stashed.
* This function will set the mode within the infiniteJsConnector object
* to be grabbed whenever an httpservice call is made and "mode" is required.
**/
setLive:function(isLive){
if(isLive==true){
//development location
//window.location = "kibanaBin/dist/index.html#Kibana_LiveTemplate.json";
//production location
window.location = "/infinit.e.records/static/kibana/index.html#/dashboard/file/Kibana_LiveTemplate.json";
infiniteJsConnector.setMode('live');
}else if(isLive==false){
//development location
//window.location = "kibanaBin/dist/index.html#Kibana_StashedTemplate.json";
//production location
window.location = "/infinit.e.records/static/kibana/index.html#/dashboard/file/Kibana_StashedTemplate.json";
infiniteJsConnector.setMode('stashed');
}
},
/**
* Called before init when url parameters are provided.
* URL parameters are only ever supplied when the widget is run outside
* of an actionscript iframe.
*
* Takes the provided parameter string and grabs the cids and mode.
* With this information, cids and mode are stored in the infiniteJsConnector
* object to be used in anything kibana would need.
*
* (param) paramString:String example: "?cids=1,2,3&mode=live
*/
onWidgetLoadWithParameters:function(paramString){
var str = paramString;
var params = str.split("&");
if (params.length > 0) {
for (var x in params) {
var keyval = params[x].split('=');
if (keyval.length > 1) {
var key = keyval[0];
if ((key == '?cids') || (key == 'cids')) {
infiniteJsConnector.setCIds(keyval[1]);
}
if ((key == '?mode') || (key == 'mode')) {
infiniteJsConnector.setMode(keyval[1]);
}
}
}
}
}
};
/**
* If the widget is loaded on its own (outside of an iframe), the URL parameters
* must be checked in order to get cids and search mode.
*
* On Page load added in order to check URL parameters and set them appropriately.
*/
window.onload = function(){
try {
if (window.location.search.length > 0){
infiniteJsConnector.onWidgetLoadWithParameters(window.location.search);
}
infiniteJsConnector.init();
}
catch (e) {
//alert("infinite init error: " + e);
}
}
/**
* Helper function to allow a parent container to trigger the installation on the parent.
* After installation, window.kibanaJsApi should be available on the parent container.
*
* eg. ( from Flex )
* kibanaFrame.callIFrameFunction('installKibanaJsApiToParent'); //Trigger parent install
* ExternalInterface.call("kibanaJsApi.refreshDashboard"); //Use API Locally
*/
function installKibanaJsApiToParent(){
//console.log("Installing to parent via IFrame helper function.");
kibanaJsApi.installToParent();
}
function QueryTerm(q, index)
{
this.query = q;
this.alias = "";
this.id = index;
this.pin = false;
this.type = "lucene";
this.enable = true;
this.parent = index;
}
function TimeTerm(from_value, to_value)
{
this.type = "time";
this.field = "@timestamp";
this.from = from_value;
this.to = to_value;
this.mandate = "must";
this.active = true;
this.alias = "";
}
function FilterString(q, index)
{
this.id = index;
this.type = "querystring";
this.query = q;
this.mandate = "must";
this.active = true;
this.alias = "";
}
mirrorQuery = function(query_string){
var query = JSON.parse(query_string);
var kibana_q = [];
var kibana_f = [];
for( var i = 0; i < query.qt.length; i++ ){
var term = query.qt[i];
if ( null != term)
{
if (null != term.etext)
{
kibana_q.push(new QueryTerm(term.etext, kibana_q.length));
}
else if ( null != term.ftext)
{
kibana_q.push(new QueryTerm(term.ftext, kibana_q.length));
}
else if ( null != term.entity)
{
kibana_q.push(new QueryTerm(term.entity.split("/")[0], kibana_q.length));
}
else if ( null != term.time && null != term.time.min && null != term.time.max)
{
kibana_f.push(new TimeTerm(term.time.min, term.time.max));
}
}
}
if (null != kibana_q)
{
kibanaJsApi.setQueryList(kibana_q, false, false);
}
if (null != kibana_f)
{
kibanaJsApi.setFilters(kibana_f, false, false);
}
}
refreshKibana = function(){
kibanaJsApi.refreshDashboard();
}
ikanowObjectsToKibana = function(ikanowControlObject){
if (null != ikanowControlObject)
{
try{
var obj = JSON.parse(ikanowControlObject.toString());
}
catch (err) {
try{
var obj = JSON.parse(ikanowControlObject.toString().replace(/[\b]/g, '\\b').replace(/[\f]/g, '\\f').replace(/[\n]/g, '\\n').replace(/[\r]/g, '\\r').replace(/[\t]/g, '\\t'));
}
catch (err2) {
alert("Unable to Process Data: " + err2);
}
}
if (null != obj) {
var termsOverride = 'AND';
var decomposeInfiniteQuery = false;
var appendToExistingKibanaQueries = false;
var applyToFilter = false;
var singleQ = "";
var kibana_q = [];
var kibana_f = [];
if (null != obj.termsOverride){
termsOverride = obj.termsOverride;
}
if (null != obj.decomposeInfiniteQuery){
decomposeInfiniteQuery = obj.decomposeInfiniteQuery;
}
if (null != obj.appendToExistingKibanaQueries){
appendToExistingKibanaQueries = obj.appendToExistingKibanaQueries;
}
if (null != applyToFilter) {
applyToFilter = obj.applyToFilter;
}
//Entities
if ( null != obj.entities && null != obj.entities.source)
{
for( var i = 0; i < obj.entities.source.length; i++ ){
var ent = obj.entities.source[i];
if ( null != ent)
{
var ent_term = null;
if (null != ent.actual_name)
{
ent_term = ent.actual_name;
}
else if ( null != ent.etext)
{
ent_term = ent.etext;
}
else if ( null != ent.ftext)
{
ent_term = ent.ftext;
}
else if ( null != ent.entity)
{
ent_term = ent.entity.substring(0,ent.entity.lastIndexOf("/"));
}
else if ( null != ent.time && null != ent.time.min && null != ent.time.max)
{
kibana_f.push(new TimeTerm(ent.time.min, ent.time.max));
}
if (null != ent_term)
{
if (decomposeInfiniteQuery == true)
{
if (applyToFilter == true)
kibana_q.push(new FilterString('"' + ent_term + '"', kibana_q.length));
else
kibana_q.push(new QueryTerm('"' + ent_term + '"', kibana_q.length));
}
else
{
if (singleQ == '')
singleQ = '"' + ent_term + '"';
else
singleQ += ' ' + termsOverride + ' "' + ent_term + '"';
}
}
}// if (null != ent)
} //for loop
} //if ( null != obj.entities && null != obj.entities.source)
//Associations
if (null != obj.associations && null != obj.associations.source)
{
for( var i = 0; i < obj.associations.source.length; i++ ){
var association = obj.associations.source[i];
var entity1 = null;
var entity2 = null;
if (null != association.entity1)
entity1 = association.entity1;
if (null != association.entity2)
entity2 = association.entity2;
if (null == entity1 && null != association.entity1_index)
entity1 = association.entity1_index.substring(0,association.entity1_index.lastIndexOf("/"));
if (null == entity2 && null != association.entity2_index)
entity2 = association.entity2_index.substring(0,association.entity2_index.lastIndexOf("/"));
if ( null != association && (null != entity1 || null != entity2))
{
var term = '';
if (null != entity1 && null != entity2)
{
term = '("' + entity1 + '" AND "' + entity2 + '")';
}
else
{
if (null != entity1)
term = '"' + entity1 + "'";
else if (null != entity2)
term = '"' + entity2 + '"';
}
if (decomposeInfiniteQuery == true)
{
if (applyToFilter == true)
kibana_q.push(new FilterString(term, kibana_q.length));
else
kibana_q.push(new QueryTerm(term, kibana_q.length));
}
else
{
if (singleQ == '')
singleQ = term;
else
singleQ += ' ' + termsOverride + ' ' + term ;
}
}
}
}
if (null != singleQ && singleQ != '')
{
if (applyToFilter == true)
kibana_q.push(new FilterString(singleQ, kibana_q.length));
else
kibana_q.push(new QueryTerm(singleQ, kibana_q.length));
}
if (null != kibana_q && kibana_q.length > 0)
{
if (applyToFilter == true)
kibanaJsApi.setFilters(kibana_q, appendToExistingKibanaQueries, appendToExistingKibanaQueries);
else
kibanaJsApi.setQueryList(kibana_q, appendToExistingKibanaQueries, appendToExistingKibanaQueries);
}
if (null != kibana_f && kibana_f.length > 0)
{
if (applyToFilter == true)
kibanaJsApi.setFilters(kibana_f, true, true);
else
kibanaJsApi.setFilters(kibana_f, appendToExistingKibanaQueries, appendToExistingKibanaQueries);
}
}//Null check on JsonParse
}// Null Check on ikanowControlObject
}
| 37263e4660100152185ffe90fbf317c5fcd860b2 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | IKANOW/infinit.e-kibana3 | c7a8a0f330c492b210f5dbfa71f3603ba035b05d | d19074ba5b8b24976cdf173a16dda67dd20c8fc7 | |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
import json
import csv
import re
import sys
import time
import datetime
from datetime import timedelta
import io # for utf-8 encoding
import subprocess
from sys import stderr
# Python program to print from https://www.geeksforgeeks.org/print-colors-python-terminal/
# colored text and background
def prRed(skk): print(u"\033[91m {}\033[00m" .format(skk)),
def prGreen(skk): print(u"\033[92m {}\033[00m" .format(skk)),
def prYellow(skk): print(u"\033[93m {}\033[00m" .format(skk)),
def prLightPurple(skk): print(u"\033[94m {}\033[00m" .format(skk)),
def prPurple(skk): print(u"\033[95m {}\033[00m" .format(skk)),
def prCyan(skk): print(u"\033[96m {}\033[00m" .format(skk)),
def prLightGray(skk): print(u"\033[97m {}\033[00m" .format(skk)),
def prBlack(skk): print(u"\033[98m {}\033[00m" .format(skk)),
def prInverse(skk): print(u"\033[7m {}\033[00m" .format(skk)),
def prBold(skk): print(u"\033[1m {}\033[00m" .format(skk)),
def prUnderline(skk): print(u"\033[04m {}\033[00m" .format(skk)),
def prStrikethrough(skk): print(u"\033[09m {}\033[00Access_token_secretm" .format(skk)),
def prBoldStrikethrough(skk): print(u"\033[1m\033[09m {}\033[00m" .format(skk)),
def prBoldUnderline(skk): print(u"\033[1m\033[04m {}\033[00m" .format(skk)),
def prInverseStrikethrough(skk): print(u"\033[7m\033[09m {}\033[00m" .format(skk)),
def prInverseUnderline(skk): print(u"\033[7m\033[04m {}\033[00m" .format(skk)),
# MAIN SECTION
try:
with open('stats.json') as json_data2:
data = json.load(json_data2)
if bool(data) == False: # empty dictionary
prYellow('tweet.py: stats.json is empty')
sys.exit()
else:
print ("lookin g in")
print (str(data))
last_reading_datetime = data['last_reading_datetime']
except IOError:
prYellow('stats.py: cannot read twitter_keys.json')
sys.exit()
last_reading_datetime_dt = datetime.datetime.fromisoformat(last_reading_datetime)
a15_minutes_ago = datetime.datetime.now() - timedelta(minutes=29)
print ('time now=' + str(datetime.datetime.now()))
print ('last_reading_datetime=' + str(last_reading_datetime))
print ('15 minutes ago= ' + str(a15_minutes_ago))
if last_reading_datetime_dt < a15_minutes_ago:
shell_string = '"C:\Program Files\VideoLAN\VLC\vlc.exe" --loop morse_CO2.mp3'
shell_string = './alarm.sh'
subprocess.call([shell_string], shell = True)
<file_sep># -*- coding: utf-8 -*-
import json
import csv
import re
import sys
import time
import datetime
from datetime import timedelta
import twitter
import io # for utf-8 encoding
#import subprocess
from sys import stderr
# Python program to print from https://www.geeksforgeeks.org/print-colors-python-terminal/
# colored text and background
def prRed(skk): print(u"\033[91m {}\033[00m" .format(skk)),
def prGreen(skk): print(u"\033[92m {}\033[00m" .format(skk)),
def prYellow(skk): print(u"\033[93m {}\033[00m" .format(skk)),
def prLightPurple(skk): print(u"\033[94m {}\033[00m" .format(skk)),
def prPurple(skk): print(u"\033[95m {}\033[00m" .format(skk)),
def prCyan(skk): print(u"\033[96m {}\033[00m" .format(skk)),
def prLightGray(skk): print(u"\033[97m {}\033[00m" .format(skk)),
def prBlack(skk): print(u"\033[98m {}\033[00m" .format(skk)),
def prInverse(skk): print(u"\033[7m {}\033[00m" .format(skk)),
def prBold(skk): print(u"\033[1m {}\033[00m" .format(skk)),
def prUnderline(skk): print(u"\033[04m {}\033[00m" .format(skk)),
def prStrikethrough(skk): print(u"\033[09m {}\033[00Access_token_secretm" .format(skk)),
def prBoldStrikethrough(skk): print(u"\033[1m\033[09m {}\033[00m" .format(skk)),
def prBoldUnderline(skk): print(u"\033[1m\033[04m {}\033[00m" .format(skk)),
def prInverseStrikethrough(skk): print(u"\033[7m\033[09m {}\033[00m" .format(skk)),
def prInverseUnderline(skk): print(u"\033[7m\033[04m {}\033[00m" .format(skk)),
# MAIN SECTION
try:
with open('stats.json') as json_data2:
data = json.load(json_data2)
if bool(data) == False: # empty dictionary
prYellow('tweet.py: stats.json is empty')
sys.exit()
else:
print ("lookin g in")
line1 = data['line1']
line2 = data['line2']
line3 = data['line3']
site_location = data['site_location']
last_reading = data['last_reading']
lowest_reading = data['lowest_reading']
highest_reading = data['highest_reading']
except IOError:
prYellow('stats.py: cannot read twitter_keys.json')
sys.exit()
print (line1)
print (line2)
print (line3)
try:
with open('apikeys/twitter_keys.json') as json_data2:
data = json.load(json_data2)
if bool(data) == False: # empty dictionary
prYellow('tweet.py: twitter_keys.json is empty')
sys.exit()
else:
consumer_key = data['consumer_key']
consumer_secret = data['consumer_secret']
access_token_key = data['access_token_key']
access_token_secret = data['access_token_secret']
except IOError:
prYellow('tweet.py: cannot read twitter_keys.json')
sys.exit()
print (consumer_key)
print (consumer_secret)
print (access_token_key)
print (access_token_secret)
api = twitter.Api(consumer_key=consumer_key,
consumer_secret = consumer_secret,
access_token_key = access_token_key,
access_token_secret = access_token_secret)
print (api.VerifyCredentials())
#message = "Hello World! Lets try some ways to get a subscript '2': unicode:" + u"\u2082" + " and the html entity: ₂"
#post_update = api.PostUpdates(status=message)
line1_clean = line1.replace(' ','').replace('reading:','reading: ')
if last_reading == lowest_reading:
message = "Record low outdoor CO" + u"\u2082" + " at " + str(site_location) + line1_clean[12:] + ". This is the highest value recorded since 15th November 2018. Graphs and info at https://conwasa.github.io/CO2_play/ #CO2"
print (message)
elif last_reading == highest_reading:
message = "Record high outdoor CO" + u"\u2082" + " at " + str(site_location) + line1_clean[12:] + ". This is the highest value recorded since 15th November 2018. Graphs and info at https://conwasa.github.io/CO2_play/ #CO2"
else:
message = "Outdoor CO" + u"\u2082" + " at " + str(site_location) + ", " + line1_clean + ". Graphs and info at https://conwasa.github.io/CO2_play/ \n#CO2"
#message = "Record low outdoor CO" + u"\u2082" + " at " + str(site_location) + ': 389ppm at 01:59 on Sunday 27 Jan 2019' + ". This is the lowest value recorded since 15th November 2018. Graphs and info at https://conwasa.github.io/CO2_play/ #CO2"
try:
print ('null')
post_update = api.PostUpdates(status=message)
except Exception as e:
prYellow('tweet.py: twitter error')
prYellow('twitter.error.TwitterError')
prYellow('hello')
prYellow(e)
sys.exit()
# [{'code': 326, 'message': 'To protect our users from spam and other malicious activity, this account is temporarily locked.
#Please log in to https://twitter.com to unlock your account.'}
print (message)
<file_sep>wine /home/user2/SenselifeCamSoftware/CO2_Monitor.exe &
while [ true ]; do
rm alarm_flag_for_telegram_bot.flag
cat /home/user2/SenselifeCamSoftware/2018/11/*.CSV |grep "20" > all_readings.csv
cat /home/user2/SenselifeCamSoftware/2018/12/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2019/01/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2019/02/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2019/03/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2019/04/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2019/05/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2019/06/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2019/07/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2019/08/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2019/09/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2019/10/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2019/11/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2019/12/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2020/01/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2020/02/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2020/03/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2020/04/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2020/05/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2020/06/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2020/07/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2020/08/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2020/09/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2020/10/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2020/11/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2020/12/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2021/01/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2021/02/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2021/03/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2021/04/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2021/05/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2021/06/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2021/07/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2021/08/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2021/09/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2021/10/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2021/11/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2021/12/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2022/01/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2022/02/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2022/03/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2022/04/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2022/05/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2022/06/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2022/07/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2022/08/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2022/09/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2022/10/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2022/11/*.CSV |grep "20" >> all_readings.csv
cat /home/user2/SenselifeCamSoftware/2022/12/*.CSV |grep "20" >> all_readings.csv
# copy stats.json prev_stats.json
python3 process_csv.py #python3 because uses list2 = list.copy()
python tweet.py
gsutil -h "Cache-Control:public, max-age=0" -m cp outages.csv gs://uk_bn3_co2 | echo $?
gsutil -h "Cache-Control:public, max-age=0" -m cp todays_readings.csv gs://uk_bn3_co2 | echo $?
gsutil -h "Cache-Control:public, max-age=0" -m cp stats.json gs://uk_bn3_co2 | echo $?
if [ ! -f "done_daily_copy_flag.txt" ]; then
if [ $(date +%H) -eq '00' ]; then
gsutil -h "Cache-Control:public, max-age=0" cp all_historic_readings.csv gs://uk_bn3_co2 | echo $?
gsutil -h "Cache-Control:public, max-age=0" cp all_readings.csv gs://uk_bn3_co2 | echo $?
gsutil -h "Cache-Control:public, max-age=0" cp day_befores_readings.csv gs://uk_bn3_co2 | echo $?
gsutil -h "Cache-Control:public, max-age=0" cp last_months_readings.csv gs://uk_bn3_co2 | echo $?
gsutil -h "Cache-Control:public, max-age=0" cp last_weeks_readings.csv gs://uk_bn3_co2 | echo $?
gsutil -h "Cache-Control:public, max-age=0" cp week_before_lasts_readings.csv gs://uk_bn3_co2 | echo $?
gsutil -h "Cache-Control:public, max-age=0" cp yesterdays_readings.csv gs://uk_bn3_co2 | echo $?
copy flag.txt done_daily_copy_flag.txt
fi
fi
if [ $(date +%H) -eq '01' ]; then
rm done_daily_copy_flag.txt
echo "flag file deleted"
fi
python3 monitor_sensor_connection.py
echo $(date +%H:%M:%S)
# Script take 70s to run on Windows laptop, test again todo
echo "start timeout"
sleep 530
done
<file_sep>(function() {
var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['latest_co2_readings'] = template({"compiler":[8,">= 4.3.0"],"main":function(container,depth0,helpers,partials,data) {
var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=container.hooks.helperMissing, alias3="function", lookupProperty = container.lookupProperty || function(parent, propertyName) {
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
return parent[propertyName];
}
return undefined
};
return ((stack1 = ((helper = (helper = lookupProperty(helpers,"line1") || (depth0 != null ? lookupProperty(depth0,"line1") : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"line1","hash":{},"data":data,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":11}}}) : helper))) != null ? stack1 : "")
+ "<br>"
+ ((stack1 = ((helper = (helper = lookupProperty(helpers,"line2") || (depth0 != null ? lookupProperty(depth0,"line2") : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"line2","hash":{},"data":data,"loc":{"start":{"line":1,"column":15},"end":{"line":1,"column":26}}}) : helper))) != null ? stack1 : "")
+ "<br>"
+ ((stack1 = ((helper = (helper = lookupProperty(helpers,"line3") || (depth0 != null ? lookupProperty(depth0,"line3") : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"line3","hash":{},"data":data,"loc":{"start":{"line":1,"column":30},"end":{"line":1,"column":41}}}) : helper))) != null ? stack1 : "")
+ "<br>";
},"useData":true});
})();<file_sep># -*- coding: utf-8 -*-
import os
import json
import csv
import re
import sys
import time
import datetime
from datetime import timedelta
import io # for utf-8 encoding
from sys import stderr
# python-telegram-bot.org specific imports
import logging
from telegram import Update
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
#enable logging
logging.basicConfig(
format='%asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
def get_latest_stats():
try:
with open('stats.json') as json_data2:
data = json.load(json_data2)
if bool(data) == False: # empty dictionary
prYellow('telegram_bot.py: stats.json is empty')
sys.exit()
else:
line1 = data['line1']
line2 = data['line2']
line3 = data['line3']
site_location = data['site_location']
last_reading = data['last_reading']
lowest_reading = data['lowest_reading']
highest_reading = data['highest_reading']
weekly_trend = data['weekly_trend']
monthly_trend = data['monthly_trend']
annual_trend = data['annual_trend']
except IOError:
print ('stats.py: cannot read stats.json')
sys.exit()
line1_clean = line1.replace(' ','').replace('reading:','reading: ')
if last_reading == lowest_reading:
message = "Record low outdoor CO" + u"\u2082" + " at " + str(site_location) + line1_clean[12:] + ". This is the lowest value recorded since 15th November 2018. Graphs and info at https://conwasa.github.io/CO2_play/ #CO2"
print (message)
elif last_reading == highest_reading:
message = "Record high outdoor CO" + u"\u2082" + " at " + str(site_location) + line1_clean[12:] + ". This is the highest value recorded since 15th November 2018. Graphs and info at https://conwasa.github.io/CO2_play/ #CO2"
else:
message = "Outdoor CO" + u"\u2082" + " at " + str(site_location) + ", " + line1_clean + ". Graphs and info at https://conwasa.github.io/CO2_play/ \n#CO2"
if int(last_reading) > 1000:
co2_gt_1000_value = int(last_reading)
else:
co2_gt_1000_value = 0
return ([message, site_location, co2_gt_1000_value, weekly_trend, monthly_trend, annual_trend])
def get_spoken_time_since_last_char(time_since_last_chat):
mins_since_last_chat = int(time.strftime("%M", time.localtime(time_since_last_chat)))
hours_since_last_chat = int(time.strftime("%H", time.localtime(time_since_last_chat)))
days_since_last_chat = int(time.strftime("%j", time.localtime(time_since_last_chat))) - 1
years_since_last_chat = int(time.strftime("%Y", time.localtime(time_since_last_chat))) - 1970
if years_since_last_chat != 0:
days_since_last_chat = days_since_last_chat + years_since_last_chat * 365
if days_since_last_chat == 1:
hours_since_last_chat = hours_since_last_chat + 24
days_since_last_chat = 0
if hours_since_last_chat == 1:
mins_since_last_chat = mins_since_last_chat + 60
hours_since_last_chat = 0
spoken_time_since_last_chat = str(mins_since_last_chat) + " minutes"
if hours_since_last_chat != 0:
spoken_time_since_last_chat = str(hours_since_last_chat) + " hours and " + spoken_time_since_last_chat
if days_since_last_chat != 0:
spoken_time_since_last_chat = str(days_since_last_chat) + " days, " + spoken_time_since_last_chat
return (spoken_time_since_last_chat)
def load_subscriptions_dict():
# I didn't know about the pickle library at the time of writing.
# search 'python pickle dictionary' for more information.
subscriptions_dict = {}
try:
with open('subscriptions.json') as json_data:
subscriptions_dict = json.load(json_data)
if bool(subscriptions_dict) == False: # empty dictionary
prYellow('telegram_bot.py: subscription dictionary empty')
sys.exit()
except (ValueError, IOError):
# first run, create empty topic lists
subscriptions_dict = { 'new records' : [],
'all readings' : [],
'service msgs' : [],
'dev news' : [],
'weekly trend' : [],
'monthly trend' : [],
'annual trend' : []
}
with open('subscriptions.json', 'w') as write_file:
json.dump(subscriptions_dict, write_file, indent=2)
return subscriptions_dict
def add_subscription(subscriptions_dict, chat_id, topic, context):
chat_id_list = subscriptions_dict[topic]
if chat_id not in chat_id_list:
chat_id_list.append(chat_id)
subscriptions_dict[topic] = chat_id_list
with open('subscriptions.json', 'w') as write_file:
json.dump(subscriptions_dict, write_file, indent=2)
context.bot.send_message(chat_id=chat_id, text="you are subscribed to " + topic)
else:
context.bot.send_message(chat_id=chat_id, text="you are already subscribed to " + topic)
return subscriptions_dict
def remove_subscription(subscriptions_dict, chat_id, topic, context):
chat_id_list = subscriptions_dict[topic]
if chat_id in chat_id_list:
chat_id_list.remove(chat_id)
subscriptions_dict[topic] = chat_id_list
with open('subscriptions.json', 'w') as write_file:
json.dump(subscriptions_dict, write_file, indent=2)
context.bot.send_message(chat_id=chat_id, text="you are unsubscribed from " + topic)
else:
context.bot.send_message(chat_id=chat_id, text="you are already unsubscribed from " + topic)
return subscriptions_dict
def notify_subscribers(subscriptions_dict, topic, message):
chat_id_list = subscriptions_dict[topic]
for chat_id in chat_id_list:
updater.bot.send_message(chat_id=chat_id, text=message)
def send_start_and_reply_msg(update, context):
print ("telegram chatbot event chat_id=" + str(update.effective_chat.id) + " received message=" + update.message.text)
epoch_time_now = int(time.time())
time_since_last_chat = epoch_time_now - last_spoken_to_epoch_time
if time_since_last_chat > 6000: # 6000 seconds is 10 minutes
spoken_time_since_last_chat = get_spoken_time_since_last_char(time_since_last_chat)
context.bot.send_message(chat_id=update.effective_chat.id, text="Thank you, no-one has spoken to me for " + spoken_time_since_last_chat + ".")
stats_list = get_latest_stats()
co2_message = stats_list[0]
context.bot.send_message(chat_id=update.effective_chat.id, text=co2_message)
context.bot.send_message(chat_id=update.effective_chat.id, text="I measure local outdoor CO" + u"\u2082" + " levels and send messages about readings and trends.\n\nType or tap '/help' for commands.")
def format_service_message(update, context, activity_name):
chat_id = str(update.message.chat_id)
first_name = update.message.chat.first_name
last_name = update.message.chat.last_name
username = update.message.chat.username
print("chat_id : {} and firstname : {} lastname : {} username {}". format(chat_id, first_name, last_name , username))
message = first_name + " " + activity_name # chat_id removed as anyone can subscribe to 'service msgs' and it could be spammed
return message
def join_and_print(chat_id, cmd, list):
chat_id = str(chat_id)
parm = ' '.join(list)
print (chat_id + " command=/" + cmd + " " + parm)
return (parm)
# MAIN SECTION
subscriptions_dict = load_subscriptions_dict()
try:
with open('apikeys/telegram_keys.json') as json_data2:
data = json.load(json_data2)
if bool(data) == False: # empty dictionary
prYellow('telegram_bot.py: telegram_keys.json is empty')
sys.exit()
else:
telegram_co2_bot_token = data['telegram_co2_bot_token']
except IOError:
prYellow('telegram_bot.py: cannot read telegram_keys.json')
sys.exit()
last_spoken_to_epoch_time = int(time.time())
stats_list = get_latest_stats()
co2_message = stats_list[0]
site_location = stats_list[1]
from telegram.ext import Updater
updater = Updater(token=telegram_co2_bot_token, use_context=True)
dispatcher = updater.dispatcher
def start(update, context):
send_start_and_reply_msg(update, context)
message = format_service_message(update, context, 'has started this bot.')
notify_subscribers(subscriptions_dict, 'service msgs', message)
from telegram.ext import CommandHandler
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
def reply(update, context):
send_start_and_reply_msg(update, context)
message = format_service_message(update, context, 'is chatting: ' + update.message.text)
notify_subscribers(subscriptions_dict, 'service msgs', message)
from telegram.ext import MessageHandler, Filters
reply_handler = MessageHandler(Filters.text & (~Filters.command), reply)
dispatcher.add_handler(reply_handler)
def help(update, context):
message = """Commands:
/sub <topic> - subscribe to a topic
/unsub <topic> - unsubscribe
/info <topic> - details of a topic
/show <data> - interactive console
/help - this message
Topics are:
weekly trend - end of week summary of trend
monthly trend - end of month summary of trend
annual trend - end of year summary of trend
all trends - weekly, monthly and annual trends
new records - record high or low values
all readings - a message every 10 minutes
service msgs - mainly for the robot's owner
dev news - my software and maker stuff
all - all of the above
Data:
subs - list your subscriptions
trends - list the last trend records
last reading - shows the last reading
example:
/sub monthly trend\n"""
context.bot.send_message(chat_id=update.effective_chat.id, text=message)
message = format_service_message(update, context, '/help ')
notify_subscribers(subscriptions_dict, 'service msgs', message)
# /about - how school teachers can use this\n
help_handler = CommandHandler('help', help)
dispatcher.add_handler(help_handler)
# topic descriptions for the /info command
new_records_info = """Info: 'new records' topic. Messages look like this:\n
Record low outdoor CO""" + u"\u2082" + """ at """ + str(site_location) + """: 381ppm at 12:57 on Wednesday 24 Apr 2019. This is the lowest value recorded since 15th November 2018. Graphs and info at https://conwasa.github.io/CO2_play/ #CO2\n
Record high outdoor CO""" + u"\u2082" + """ at """ + str(site_location) + """: 625ppm at 09:24 on Thursday 05 Dec 2019. This is the highest value recorded since 15th November 2018. Graphs and info at https://conwasa.github.io/CO2_play/ #CO2"\n
Expect one message or so a year."""
all_readings_info = "Info: 'all readings' topic. A message wen a new reading is taken. Messages look like this:\n\n" + co2_message + "\n\nExpect a message every 10 minutes."
service_msgs_info = """Info: 'service msgs' topic. Messages for this Bot's owner. They look like this:\n
Alex has started this bot.
Bob is chatting: hello
Bob /info dev news
The CO2 sensor is offline.
High CO2 1500ppm. Possible fire.\n
Expect a few messages a week."""
dev_news_info = """Info: 'dev news' topic.\nNews of updates to this robot and others. \n
Expect one message every month or so."""
weekly_trend_info = "Info: 'weekly trend' topic. Sent at 9am (" + site_location + """) Mondays, giving the trend based the average of previous Monday's and Sunday's readings. Messages look like tis:
Weekly CO2 trend: up 3.0 percent from 492 to 502 ppm
Expect one message a week."""
monthly_trend_info = "Info: 'monthly trend' topic. Sent at 9am (" + site_location + """) on the first of each month, giving the trend based the average reading of the first and last days of the previous month. Messages look like tis:
Monthly CO2 trend: up 1.6 percent from 490 to 492 ppm
Expect one message a month."""
annual_trend_info = "Info: 'annual trend' topic. Sent at 9am (" + site_location + """) on the first day of year, giving the trend based the average reading of the first and last days of the previous year. Messages look like tis:
Annual CO2 trend: down 2.6 percent from 492 to 486 ppm
Expect one message a year."""
all_trends_info = """Info: 'all trends' topic. All three trend topics. Messages look like this:
Weekly CO2 trend: up 3.0 percent from 492 to 502 ppm
Monthly CO2 trend: up 1.6 percent from 490 to 492 ppm
Annual CO2 trend: down 2.6 percent from 492 to 486 ppm
Expect one or so message a week."""
all_info = """Info: 'all' topic. All messages from this Bot.\n
Expect one message every 10 minutes plus a few more a day."""
show_subs_info = """Info: 'show subs' topic. Lists your subscribed topics .\n
On demand."""
def info(update, context):
parm = join_and_print(update.effective_chat.id, 'info', context.args)
# parm = ' '.join(context.args)
if parm == 'new records':
message = new_records_info
elif parm == 'all readings':
message = all_readings_info
elif parm == 'service msgs':
message = service_msgs_info
elif parm == 'dev news':
message = dev_news_info
elif parm == 'weekly trend':
message = weekly_trend_info
elif parm == 'monthly trend':
message = monthly_trend_info
elif parm == 'annual trend':
message = annual_trend_info
elif parm == 'all trends':
message = all_trends_info
elif parm == 'all':
message = new_records_info + "\n\n" + all_readings_info + "\n\n" + service_msgs_info + "\n\n" + dev_news_info + "\n\n" + weekly_trend_info + "\n\n" + monthly_trend_info + "\n\n" + annual_trend_info + "\n\n" + all_trends_info + "\n\n" + all_info
elif parm == 'show_subs':
message = show_subs_info
elif parm == '':
context.bot.send_message(chat_id=update.effective_chat.id, text='you must specify one of tese topics:\n\nnew records\nall readings\nservice msgs\ndev news\nall')
else:
message = parm + " not found, see /help"
context.bot.send_message(chat_id=update.effective_chat.id, text=message)
message = format_service_message(update, context, '/info ' + parm)
notify_subscribers(subscriptions_dict, 'service msgs', message)
info_handler = CommandHandler('info', info)
dispatcher.add_handler(info_handler)
def sub(update, context):
parm = join_and_print(update.effective_chat.id, 'sub', context.args)
if parm in ['new records', 'all readings', 'service msgs', 'dev news', 'weekly trend', 'monthly trend', 'annual trend' ]:
add_subscription(subscriptions_dict, str(update.effective_chat.id), parm, context)
elif parm == 'all trends':
add_subscription(subscriptions_dict, str(update.effective_chat.id), 'weekly trend', context)
add_subscription(subscriptions_dict, str(update.effective_chat.id), 'monthly trend', context)
add_subscription(subscriptions_dict, str(update.effective_chat.id), 'annual trend', context)
elif parm == 'all':
add_subscription(subscriptions_dict, str(update.effective_chat.id), 'new records', context)
add_subscription(subscriptions_dict, str(update.effective_chat.id), 'all readings', context)
add_subscription(subscriptions_dict, str(update.effective_chat.id), 'service msgs', context)
add_subscription(subscriptions_dict, str(update.effective_chat.id), 'dev news', context)
add_subscription(subscriptions_dict, str(update.effective_chat.id), 'weekly trend', context)
add_subscription(subscriptions_dict, str(update.effective_chat.id), 'monthly trend', context)
add_subscription(subscriptions_dict, str(update.effective_chat.id), 'annual trend', context)
elif parm == '':
context.bot.send_message(chat_id=update.effective_chat.id, text='you must specify one of tese topics:\n\nnew records\nall readings\nservice msgs\ndev news\nall')
else:
message = parm + " is not a valid topic, see /help"
context.bot.send_message(chat_id=update.effective_chat.id, text=message)
message = format_service_message(update, context, '/sub ' + parm)
notify_subscribers(subscriptions_dict, 'service msgs', message)
sub_handler = CommandHandler('sub', sub)
dispatcher.add_handler(sub_handler)
def unsub(update, context):
parm = join_and_print(update.effective_chat.id, 'sub', context.args)
if parm in ['new records', 'all readings', 'service msgs', 'dev news', 'weekly trend', 'monthly trend', 'annual trend' ]:
remove_subscription(subscriptions_dict, str(update.effective_chat.id), parm, context)
elif parm == 'all trends':
remove_subscription(subscriptions_dict, str(update.effective_chat.id), 'weekly trend', context)
remove_subscription(subscriptions_dict, str(update.effective_chat.id), 'monthly trend', context)
remove_subscription(subscriptions_dict, str(update.effective_chat.id), 'annual trend', context)
elif parm == 'all':
remove_subscription(subscriptions_dict, str(update.effective_chat.id), 'new records', context)
remove_subscription(subscriptions_dict, str(update.effective_chat.id), 'all readings', context)
remove_subscription(subscriptions_dict, str(update.effective_chat.id), 'service msgs', context)
remove_subscription(subscriptions_dict, str(update.effective_chat.id), 'dev news', context)
remove_subscription(subscriptions_dict, str(update.effective_chat.id), 'weekly trend', context)
remove_subscription(subscriptions_dict, str(update.effective_chat.id), 'monthly trend', context)
remove_subscription(subscriptions_dict, str(update.effective_chat.id), 'annual trend', context)
elif parm == '':
context.bot.send_message(chat_id=update.effective_chat.id, text='you must specify one of tese topics:\n\nnew records\nall readings\nservice msgs\ndev news\nall')
else:
message = parm + " is not a valid topic, see /help"
context.bot.send_message(chat_id=update.effective_chat.id, text=message)
message = format_service_message(update, context, '/unsub ' + parm)
notify_subscribers(subscriptions_dict, 'service msgs', message)
unsub_handler = CommandHandler('unsub', unsub)
dispatcher.add_handler(unsub_handler)
def show_sub(subscriptions_dict, topic, update, context):
chat_id = update.message.chat_id
chat_id_list = subscriptions_dict[topic]
if str(chat_id) in chat_id_list:
context.bot.send_message(chat_id=chat_id, text="you are subscribed to " + topic)
return True
else:
return False
def show(update, context):
parm = join_and_print(update.effective_chat.id, 'show', context.args)
if parm == 'subs':
has_subs = False
for topic in ['new records', 'all readings', 'service msgs', 'dev news', 'weekly trend', 'monthly trend', 'annual trend' ]:
subbed = show_sub(subscriptions_dict, topic, update, context)
if subbed == True:
has_subs = True
if has_subs == False:
context.bot.send_message(chat_id=update.effective_chat.id, text='you have no subscriptions')
elif parm == 'trends':
context.bot.send_message(chat_id=update.effective_chat.id, text=weekly_trend)
context.bot.send_message(chat_id=update.effective_chat.id, text=monthly_trend)
context.bot.send_message(chat_id=update.effective_chat.id, text=annual_trend)
elif parm == 'last reading':
context.bot.send_message(chat_id=update.effective_chat.id, text=co2_message)
elif parm == '':
context.bot.send_message(chat_id=update.effective_chat.id, text='you must specify one of tese topics:\n\nnew records\nall readings\nservice msgs\ndev news\nall')
else:
message = parm + " is not a valid data set, see /help"
context.bot.send_message(chat_id=update.effective_chat.id, text=message)
show_handler = CommandHandler('show', show)
dispatcher.add_handler(show_handler)
# timer section
job_queue = updater.job_queue
def send_weekly_message(context):
notify_subscribers(subscriptions_dict, 'weekly trend', weekly_trend)
job_queue.run_daily(send_weekly_message, datetime.time(9, 00, 00, 000000),days=[0])
def send_monthly_message(context):
notify_subscribers(subscriptions_dict, 'monthly trend', monthly_trend)
job_queue.run_monthly(send_monthly_message, datetime.time(9, 00, 00, 000000), 1)
now = datetime.datetime.now()
next_year = now.year + 1
annual_msg_datetime = datetime.datetime(next_year, 1, 1, 9, 00)
def send_annual_message(context):
notify_subscribers(subscriptions_dict, 'annual trend', annual_trend)
next_year = now.year + 1
job_queue.run_once(send_annual_message, annual_msg_datetime)
job_queue.run_once(send_annual_message, annual_msg_datetime)
#this must be last
def unknown(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text="Sorry, I didn't understand that command.")
unknown_handler = MessageHandler(Filters.command, unknown)
dispatcher.add_handler(unknown_handler)
updater.start_polling()
old_co2_message = ''
while True:
stats_list = get_latest_stats()
co2_message = stats_list[0]
co2_gt_1000_value = stats_list[2]
weekly_trend = stats_list[3]
monthly_trend = stats_list[4]
annual_trend = stats_list[5]
if co2_message != old_co2_message:
now = datetime.datetime.now()
print (str(now.strftime("%Y-%m-%d %H:%M:%S")) + " " + co2_message)
old_co2_message = co2_message
notify_subscribers(subscriptions_dict, 'all readings', co2_message)
if 'Record' in co2_message:
notify_subscribers(subscriptions_dict, 'new records', co2_message)
try:
f = open("alarm_flag_for_telegram_bot.flag")
notify_subscribers(subscriptions_dict, 'service msgs', 'The CO2 sensor is offline')
f.close()
os.remove("alarm_flag_for_telegram_bot.flag")
except IOError:
pass
if co2_gt_1000_value > 0:
notify_subscribers(subscriptions_dict, 'service msgs', 'High CO2 ' + str(co2_gt_1000_value) + 'ppm. Possible fire.')
time.sleep (10)<file_sep># -*- coding: utf-8 -*-
import json
import csv
import re
import sys
import time
import datetime
from datetime import timedelta
import io # for utf-8 encoding
#import subprocess
import locale
from sys import stderr
#print '<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
#print 'parms passed to find_pips_v3.py:'
#print '$1=', sys.argv[1]
#print '$2=', sys.argv[2]
#print '$3=', sys.argv[3]
#print '$4=', sys.argv[4]
#print '<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
# Python program to print from https://www.geeksforgeeks.org/print-colors-python-terminal/
# colored text and background
def prRed(skk): print(u"\033[91m {}\033[00m" .format(skk)),
def prGreen(skk): print(u"\033[92m {}\033[00m" .format(skk)),
def prYellow(skk): print(u"\033[93m {}\033[00m" .format(skk)),
def prLightPurple(skk): print(u"\033[94m {}\033[00m" .format(skk)),
def prPurple(skk): print(u"\033[95m {}\033[00m" .format(skk)),
def prCyan(skk): print(u"\033[96m {}\033[00m" .format(skk)),
def prLightGray(skk): print(u"\033[97m {}\033[00m" .format(skk)),
def prBlack(skk): print(u"\033[98m {}\033[00m" .format(skk)),
def prInverse(skk): print(u"\033[7m {}\033[00m" .format(skk)),
def prBold(skk): print(u"\033[1m {}\033[00m" .format(skk)),
# underline='\033[04m'
# reverse='\033[07m'
# strikethrough='\033[09m'
def prUnderline(skk): print(u"\033[04m {}\033[00m" .format(skk)),
def prStrikethrough(skk): print(u"\033[09m {}\033[00m" .format(skk)),
def prBoldStrikethrough(skk): print(u"\033[1m\033[09m {}\033[00m" .format(skk)),
def prBoldUnderline(skk): print(u"\033[1m\033[04m {}\033[00m" .format(skk)),
def prInverseStrikethrough(skk): print(u"\033[7m\033[09m {}\033[00m" .format(skk)),
def prInverseUnderline(skk): print(u"\033[7m\033[04m {}\033[00m" .format(skk)),
def read_csv_file():
# with open(filename, mode="r", encoding="utf-8") as json_data:
with open('all_readings.csv', 'rt') as all_data_file:
try:
levels_reader1 = csv.reader(all_data_file, delimiter=',')
csv_data_list = list(levels_reader1)
except ValueError:
prRed('process_csv.py error reading file 1')
return(csv_data_list)
def get_subset(list, start_date, end_date, y_value):
returned_list = []
for i in range (0, len(list), 1):
row = []
if start_date <= list[i][0] <= end_date:
if y_value == 'day_of_week':
row.append(datetime.date.fromisoformat(list[i][0]).strftime("%a"))
elif y_value == 'day_of_month':
row.append('d' + str(datetime.date.fromisoformat(list[i][0]).strftime("%d"))) # prefix with 'd' so Google API doesn't treat as a number, as tht results in a smoothed line graph
elif y_value == 'month':
row.append(datetime.date.fromisoformat(list[i][0]).strftime("%b"))
else:
row.append(list[i][y_value]) # time
row.append(list[i][2]) # pm value
returned_list.append(row)
return(returned_list)
def write_subset(list, filename, header):
with open(filename, mode='w',newline='') as output_file: # newline = '' for Windows as otherwise it outputs an extra CR
output_writer = csv.writer(output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
output_writer.writerow(header)
for i in range (0, len(list), 1):
output_writer.writerow(list[i])
def write_outage_csv(list1):
last_record_datetime = datetime.datetime.fromisoformat('1970-01-01 00:00')
good_delta = datetime.datetime.fromisoformat('1970-01-01 00:20') - datetime.datetime.fromisoformat('1970-01-01 00:00')
with open('outages.csv', mode='w',newline='') as output_file: # newline = '' for Windows as otherwise it outputs an extra CR
output_writer = csv.writer(output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
output_writer.writerow(['outages > 10m','duration [hh:mm]'])
flag = False
last_outage_text = ''
for i in range (len(list1)-1, 0, -1):
record_datetime = datetime.datetime.fromisoformat(list1[i][0] + ' ' + list1[i][1])
delta = last_record_datetime - record_datetime
if delta > good_delta:
outage = delta
if len(str(outage)) == 7:
outage_str = '0' + str(outage)[:-3]
else:
outage_str = str(outage)[:-3]
output_writer.writerow([str(record_datetime), outage_str])
if flag == False:
last_outage_text = 'last outage: ' + str(record_datetime) + ' for ' + outage_str + ' [hh:mm]'
flag = True
# print (str(i) + ' ' + str(record_datetime) + ' ' + str(delta))
# print ('len=' + str(len(str(outage))))
last_record_datetime = record_datetime
return(last_outage_text)
def write_stats(list1):
lowest_reading = 99999
latest_reading = '000'
highest_reading = '000'
last_record_datetime = datetime.datetime.fromisoformat(list1[-1][0] + ' ' + list1[-1][1])
for i in range (0, len(list1), 1):
if int(list1[i][2]) < lowest_reading: # string comparison worked up to 999
lowest_reading = int(list1[i][2])
lowest_reading_datetime = datetime.datetime.fromisoformat(list1[i][0] + ' ' + list1[i][1])
if list1[i][2] > highest_reading: # these are strings not numbers
highest_reading = list1[i][2]
highest_reading_datetime = datetime.datetime.fromisoformat(list1[i][0] + ' ' + list1[i][1])
num_records = len(list1)
file_size = num_records * 20.0 / 1000
num_records_s = str(num_records)
num_records_f = str(num_records_s[0:len(num_records_s)-3]) + ',' + str(num_records_s[len(num_records_s)-3:len(num_records_s)+1])
file_size_f = str(file_size) + ' kB'
dl_file_text = num_records_f + ' records, ' + file_size_f
padded_dow = { "Monday" : "Monday ",
"Tuesday" : "Tuesday ",
"Wednesday" : "Wednesday",
"Thursday" : "Thursday ",
"Friday" : "Friday ",
"Saturday" : "Saturday ",
"Sunday" : "Sunday "
}
line1 = 'last reading: ' + list1[-1][2] + 'ppm at ' + list1[-1][1] + ' on ' + padded_dow[last_record_datetime.strftime("%A")] + ' ' + last_record_datetime.strftime("%d") + ' ' + last_record_datetime.strftime("%b") + ' ' + last_record_datetime.strftime("%Y")
line2 = 'lowest reading: ' + str(lowest_reading) + 'ppm at ' + lowest_reading_datetime.strftime("%H") + ':' + lowest_reading_datetime.strftime("%M") + ' on ' + padded_dow[lowest_reading_datetime.strftime("%A")] + ' ' + lowest_reading_datetime.strftime("%d") + ' ' + lowest_reading_datetime.strftime("%b") + ' ' + lowest_reading_datetime.strftime("%Y")
line3 = 'highest reading: ' + highest_reading + 'ppm at ' + highest_reading_datetime.strftime("%H") + ':' + highest_reading_datetime.strftime("%M") + ' on ' + padded_dow[highest_reading_datetime.strftime("%A")] + ' ' + highest_reading_datetime.strftime("%d") + ' ' + highest_reading_datetime.strftime("%b") + ' ' + highest_reading_datetime.strftime("%Y")
stats_dict = { 'line1' : line1,
'line2' : line2,
'line3' : line3,
'last_reading_datetime' : str(last_record_datetime),
'site_location' : 'Brighton England (sensor is indoors test development platform)',
'dl_file_text' : dl_file_text,
'last_reading' : list1[-1][2],
'lowest_reading' : str(lowest_reading),
'highest_reading' : highest_reading,
}
# print (stats_dict)
with open('stats.json', 'w') as write_file:
json.dump(stats_dict, write_file, indent=2)
def pad_rest_of_day_with_zeros(list1):
list2 = list1.copy()
lowest_reading = '999'
for i in range (0, len(list1), 1):
if list1[i][1] < lowest_reading: # these are strings not numbers
lowest_reading = list1[i][1]
padding_value = str((int(int(lowest_reading)/10))*10)
print (lowest_reading)
print ('padding_value')
print (padding_value)
print (list1)
last_record_datetime = datetime.datetime.fromisoformat('2018-01-01 ' + list1[-1][0])
end_of_day = last_record_datetime.replace(hour=23).replace(minute=59)
next_ts = last_record_datetime + timedelta(minutes=10)
while next_ts < end_of_day:
list2.append([str(next_ts.time())[:-3], padding_value])
next_ts = next_ts + timedelta(minutes=10)
return(list2)
# MAIN SECTION
list1=read_csv_file()
#sort into date and time
list1.sort(key=lambda x: x[0:1])
#list1=sorted(list1)
todays_date=datetime.date.isoformat(datetime.date.today())
todays_readings=get_subset(list1, todays_date, todays_date, 1)
todays_readings_padded_to_2359=pad_rest_of_day_with_zeros(todays_readings)
write_subset(todays_readings_padded_to_2359, 'todays_readings.csv', ['time','co2_ppm'])
yesterdays_date=datetime.date.isoformat(datetime.date.today() - timedelta(days=1))
yesterdays_readings=get_subset(list1, yesterdays_date, yesterdays_date, 1)
write_subset(yesterdays_readings, 'yesterdays_readings.csv', ['time','co2_ppm'])
day_befores_date=datetime.date.isoformat(datetime.date.today() - timedelta(days=2))
day_befores_readings=get_subset(list1, day_befores_date, day_befores_date, 1)
write_subset(day_befores_readings, 'day_befores_readings.csv', ['time','co2_ppm'])
num_days_since_monday=((datetime.date.today().weekday()))
num_days_to_sunday = 6 - num_days_since_monday
last_monday_week=datetime.date.isoformat(datetime.date.today() - timedelta(weeks=1) - timedelta(days=num_days_since_monday))
last_sunday=datetime.date.isoformat(datetime.date.today() - timedelta(weeks=1) + timedelta(days=num_days_to_sunday))
last_weeks_readings=get_subset(list1, last_monday_week, last_sunday, 'day_of_week')
write_subset(last_weeks_readings, 'last_weeks_readings.csv', ['day','co2_ppm'])
day_of_month=((datetime.date.today().weekday()))
num_days_to_sunday = 6 - num_days_since_monday
last_monday_week=datetime.date.isoformat(datetime.date.today() - timedelta(weeks=1) - timedelta(days=num_days_since_monday))
last_sunday=datetime.date.isoformat(datetime.date.today() - timedelta(weeks=1) + timedelta(days=num_days_to_sunday))
last_weeks_readings=get_subset(list1, last_monday_week, last_sunday, 'day_of_week')
write_subset(last_weeks_readings, 'last_weeks_readings.csv', ['day','co2_ppm'])
two_mondays_ago=datetime.date.isoformat(datetime.date.today() - timedelta(weeks=2) - timedelta(days=num_days_since_monday))
two_sundays_ago=datetime.date.isoformat(datetime.date.today() - timedelta(weeks=2) + timedelta(days=num_days_to_sunday))
week_before_lasts_readings=get_subset(list1, two_mondays_ago, two_sundays_ago, 'day_of_week')
write_subset(week_before_lasts_readings, 'week_before_lasts_readings.csv', ['day','co2_ppm'])
end_of_last_month=datetime.date.today().replace(day=1) - datetime.timedelta (days = 1)
start_of_last_month=end_of_last_month.replace(day=1)
last_months_readings=get_subset(list1, str(start_of_last_month), str(end_of_last_month), 'day_of_month')
write_subset(last_months_readings, 'last_months_readings.csv', ['day','co2_ppm'])
all_historic_readings=get_subset(list1, '2018-11-15', '2999-12-31', 'month')
write_subset(all_historic_readings, 'all_historic_readings.csv', ['month','co2_ppm'])
outage_text=write_outage_csv(list1)
write_stats(list1)
print ("Current year: ", datetime.date.today().strftime("%Y"))
print ("Month of year: ", datetime.date.today().strftime("%m"))
print ("Week number of the year: ", datetime.date.today().strftime("%W"))
print ("Weekday of the week: ", datetime.date.today().strftime("%w"))
print ("Day of year: ", datetime.date.today().strftime("%j"))
print ("Day of the month : ", datetime.date.today().strftime("%d"))
print ("Day of week: ", datetime.date.today().strftime("%A"))
print ("Day of week: ", datetime.date.today().strftime("%a"))
print ("ISO: ",datetime.date.isoformat(datetime.date.today()))
<file_sep>echo 'a' > alarm_flag_for_telegram_bot.flag
vlc --loop morse_CO2.mp3
| 678e82bfe6fbdafd5b1c73c3d9c6ccb32b327d25 | [
"JavaScript",
"Python",
"Shell"
] | 7 | Python | conwasa/CO2_play | ba7408802fee5d79532e8fa04876a2781eced66d | 1b1a2ed0aec3e5014a58de55edd4954fc565da64 | |
refs/heads/master | <repo_name>Tamas74/nexius<file_sep>/js/main.js
function calcAmount() {
let price = 1000;
let amountInput = document.querySelector("input[name='amount-input']");
let amountNumber = parseInt(amountInput.value);
amountNumber = isNaN(amountNumber) ? 0 : amountNumber;
showSumPrice(price, amountNumber)
}
function showSumPrice(price = 1000, amountNumber = 1) {
let showAmount = document.querySelector("span.show-amount");
if( amountNumber > 10 ) {
alert("Maximum 10 teméket vásárolhat!");
} else if ( amountNumber < 1 ) {
alert("Minimum 1 terméket kell vásárolnia!");
} else {
let amount = amountNumber * price;
showAmount.innerHTML = amount;
}
}
/*
// Clean code
// Nevek
let n;
let nrOfProducts;
let numberOfProducts;
// Ne legyen a név félrevezető.
function multiplier(x,y) {
return x * y;
}
// Kerüld az O és I
let IO; let l0;
// Komment: egy soros
// Felesleges: This function gives roles of user.
function getUserRoles(user, roles, id) {
if ( user.admin) {
return user.roles;
} else {
return user.roleObject;
}
}
// Találat az összes alfabetikus karakterre m és n között.
let idPattern = /m[a-z]n/;
// Formázás, behúzás
// Függvény max 4-6 sor, 10 felett már túl hosszú,
// érdemes ketté bontani két külön fgv-be.
// Függvény neve, (ige legyen: Mit csinál?)
// Függvény bemenő adat 3-nál több ne legyen ha lehet.
*/<file_sep>/js/scope.js
// Global scope
// a var function scope-ú
// a függvények határozzák meg a scope-ot
var globalName = "Joe";
function someThing() {
//var globalName = "Jack";
globalName = "Piri"; // a globális változót változtatom meg.
console.log(globalName);
}
someThing();
console.log(globalName);
// a let block scope-ú
// a blokkok határozzák meg a scope-ot
let name = "Sanyi";
// let name = "<NAME>";
/*
Memória takarékosság céljából
nem engedi meg, hogy a let-es változót,
újra deklaráljam.
A var-ral létrehozott változót engedi újra deklarálni.
A let-tel létrehozott változót nem engedi újra deklarálni.
*/
{
//let name = "Pisti";
name = "Pisti";
console.log(name);
}
console.log(name);
// const
/**
* A konstans változók nevét érdemes nagy betűvel írni.
* pl. NEV, ERTEK, ... stb.
* A konstans változó nem definiálható újra.
*
*/
const NEVE = "Géza";
//NEVE = "Béla";
{
//NEVE = "Ubul";
const NEVE = "Ubul";
console.log(NEVE);
}
console.log(NEVE);<file_sep>/js/algo.js
/*
Összegzés algoritmusa:
összeg = 0
CIKLUS AMÍG van még szám, ADDIG
szám = következő elem
összeg = összeg + szám
CIKLUS VÉGE
*/
console.log("Összegzés algoritmus pld:\n\n");
let numericArray = [1, 3, 2, 5, 4, 7, 6, 9];
let sum = 0;
for (let i = 0; i < numericArray.length; i++) {
sum += numericArray[i];
console.log(i + ". ciklus után az Összeg: ", sum);
}
console.log("Összeg: ", sum);
/*
Megszámlálás algoritmusa:
db = 0
CIKLUS AMÍG van még szám, ADDIG
szám = következő elem
HA igaz a feltétel a számra, AKKOR
db = db + 1
FELTÉTEL VÉGE
CIKLUS VÉGE
*/
// Számoljuk meg a páros számokat
console.log("Megszámlálás algoritmus pld: Megszámoljuk a páros számokat!\n\n");
let db = 0;
for (let i = 0; i < numericArray.length; i++) {
if (numericArray[i] % 2 == 0) {
db++;
}
}
console.log("Páros számok: ", db);
/*
Szélsőérték keresés algoritmusa:
legnagyobb = első elem
CIKLUS AMÍG van még szám, ADDIG
szám = következő szám
HA szám > lagnagyobb, AKKOR
legnagyobb = szám
FELTÉTEL VÉGE
CIKLUS VÉGE
*/
console.log("Szélső érték keresése: Maximum, Minimum érték keresése!\n\n");
let biggest = numericArray[0];
let smallest = numericArray[0];
for (let i = 0; i < numericArray.length; i++) {
if( numericArray[i] > biggest) {
biggest = numericArray[i];
} else if (numericArray[i] < smallest) {
smallest = numericArray[i];
}
}
console.log("A legnagyobb elem értéke: ", biggest);
console.log("A legkisebb elem értéke: ", smallest);
/*
Eldöntés tétele (algoritmusa):
találat = HAMIS
CIKLUS AMÍG van elem ÉS NEM találat
szám = következő elem
HA igaz a feltétel a számra, AKKOR
találat = IGAZ
FELTÉTEL VÉGE
CIKLUS VÉGE
*/
console.log("Eldöntés algoritmusa: Található a listában 5-ös szám?\n\n");
let contains = false;
for (let i = 0; i < numericArray.length && contains == false; i++) {
if (numericArray[i] == 5) {
contains = true;
}
}
console.log("Ez a tömb tatalmazza az 5-ös számot: ", contains);
<file_sep>/README.md
# nexius
nexius
| fca113060c07bbd521217c59a80dc152f2eb6f9e | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | Tamas74/nexius | 934693eaf99caf9aad3dbe6043a41ef9f92573e6 | 7e464ce30e26ec78e1e3eda57e1d89a83fa6e87d | |
refs/heads/main | <file_sep># Generated by Django 3.1.4 on 2020-12-10 12:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('coffee', '0004_createuser'),
]
operations = [
migrations.DeleteModel(
name='CreateUser',
),
]
<file_sep>from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib import messages
from django.contrib.auth import authenticate,login as dj_login,logout
from django.contrib.auth.models import User
from .models import Product,Contact
# Create your views here.
def index(request):
return render(request,'coffee/index.html')
def about(request):
return render(request,'coffee/about.html')
def menu(request):
products=Product.objects.all()
print(products)
params={'product':products}
return render(request,'coffee/menu.html',params)
def contact(request):
if request.method=='POST':
name=request.POST.get('name','')
email=request.POST.get('email','')
phone=request.POST.get('phone','')
msg=request.POST.get('msg','')
# print(name,email,phone,msg)
contact=Contact(name=name,email=email,phone=phone,msg=msg)
contact.save()
return render(request,'coffee/contact.html')
def login(request):
return render(request,'coffee/login.html')
def handleSignup(request):
if request.method=="POST":
# Get the post parameters
username=request.POST['username']
email=request.POST['email']
pass1=request.POST['pass1']
pass2=request.POST['pass2']
#Check for errors
if pass1 != pass2:
messages.warning(request,"Passwords do not match")
return redirect("Login")
# Create the user
myuser = User.objects.create_user(username, email, pass1)
myuser.username= username
myuser.email= email
myuser.save()
messages.success(request, " Your Account has been successfully created !")
return redirect('Login')
else:
return HttpResponse("You need to login first to access !!!")
def handleLogin(request):
signedusername=request.POST['signedusername']
signedpassword=request.POST['signedpassword']
user=authenticate(username=signedusername,password=<PASSWORD>password)
if user is not None:
dj_login(request, user)
messages.success(request,"Successfully Logged In")
return redirect('Menu')
else:
messages.warning(request,"Invalid Credentials !")
return redirect("Login")
return HttpResponse('Login')
<file_sep># Generated by Django 3.1.4 on 2020-12-03 20:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coffee', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='product',
name='image',
field=models.ImageField(default='', upload_to='coffee/images'),
),
migrations.AddField(
model_name='product',
name='price',
field=models.IntegerField(default=0),
),
]
<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name="Home"),
path('about/',views.about,name="About"),
path('menu/',views.menu,name="Menu"),
path('contact/',views.contact,name="Contact"),
path('login/',views.login,name="Login"),
path('signup',views.handleSignup,name="handleSignup"),
path('signin',views.handleLogin,name="handleLogin")
]
<file_sep>{% extends 'coffee/base.html' %}
{% load static %}
{% block css %} <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> {% endblock %}
{% block title %}Home{% endblock %}
{% block nav_item_home %}active{% endblock nav_item_home %}
{% block body %}
<!-- MAIN PAGE -->
<div class="container d-flex align-items-center h-100">
<div class="row">
<header class="text-center col-12">
<h1><strong>Awake your dreams with a cup of coffee !</strong></h1>
</header>
<div class="buffer col-12">
</div>
<section class="text-center col-12">
<a href="/coffee/menu">
<button class="btn btn-primary btn-xl">Get Set Coffee<span></span><i class="fas fa-coffee"></i></button>
</a>
</section>
</div>
</div>
{% endblock %}<file_sep># Generated by Django 3.1.4 on 2020-12-10 08:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coffee', '0003_contact'),
]
operations = [
migrations.CreateModel(
name='CreateUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.CharField(max_length=30)),
('email', models.CharField(default='', max_length=40)),
('pwd1', models.CharField(default='', max_length=30)),
('pwd2', models.CharField(default='', max_length=30)),
],
),
]
<file_sep>from django.db import models
# Create your models here.
class Product(models.Model):
product_id=models.AutoField
product_name=models.CharField(max_length=30)
desc=models.CharField(max_length=300)
pub_data=models.DateField()
price=models.IntegerField(default=0)
image=models.ImageField(upload_to='coffee/images',default='')
def __str__(self):
return self.product_name
class Contact(models.Model):
msg_id=models.AutoField(primary_key=True)
name=models.CharField(max_length=30)
email=models.CharField(max_length=40,default='')
phone=models.CharField(max_length=30,default='')
msg=models.CharField(max_length=500,default='')
def __str__(self):
return self.name
<file_sep># CoffeeRehab
Clone the project and to access the project type:
`python manage.py runserver`
Then just add `/coffee` to the URL
<file_sep># Generated by Django 3.1.4 on 2020-12-05 10:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coffee', '0002_auto_20201204_0209'),
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('msg_id', models.AutoField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=30)),
('email', models.CharField(default='', max_length=40)),
('phone', models.CharField(default='', max_length=30)),
('msg', models.CharField(default='', max_length=500)),
],
),
]
| f0835e984f2f366343fce96c014e8c0ce0297d6c | [
"Markdown",
"Python",
"HTML"
] | 9 | Python | KunalTakke/CoffeeRehab | df84127e9b3bc69d98b8a4502ccf095faa10aff2 | b1915a3ffdcb2d6f3ef61041b4aaf4b3baccc5cb | |
refs/heads/master | <repo_name>lazyjquery/2.10.3<file_sep>/2.10.3/J.LazyLoad.js
var n = Math.ceil(Math.random()*2);
function vl(str) {va=str; return va;}; | 5a0137493f7b8bdf262c6f487198ecdbc01cfb61 | [
"JavaScript"
] | 1 | JavaScript | lazyjquery/2.10.3 | 67b43e890efef066fb9fcc7ffece695409377d00 | 30ee6746cc72de19f22144a1170533e905020b26 | |
refs/heads/master | <repo_name>paparoni95/DataStructure<file_sep>/Doit/Array/chap02-8.cpp
/* 정수를 2진수 ~ 36진수로 기수 변환 */
#include <stdio.h>
/* 정수 값 x를 n진수로 변환하여 배열d에 아랫자리부터 저장 */
int card_convr(unsigned x, int n, char d[])
{
char dchar[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int digits = 0;
if (x == 0)
d[digits++] = dchar[0];
else
{
while (x)
{
d[digits++] = dchar[x % n];
x /= n;
}
}
return digits;
}
int main()
{
int i;
unsigned no; // 변환하는 정수
int cd; // 기수
int dno; // 변환 후 자릿수
char cno[512]; // 변환한 값의 각 자리의 숫자를 저장하는 문자 배열
int retry;
puts("10진수를 기수 변환");
do
{
printf("변환하는 음이 아닌 정수 : ");
scanf_s("%u", &no);
do
{
printf("어떤 진수로 변환할까?(2-36) : ");
scanf_s("%d", &cd);
dno = card_convr(no, cd, cno); // no를 cd진수로 변환
printf("%d진수로는", cd);
for (i = dno - 1; i >= 0; --i)
printf("%c", cno[i]);
printf("입니다.\n");
printf("한 번 더 할까요?(1 ... 예/0 ... 아니오) : ");
scanf_s("%d", &retry);
} while (cd < 2 || cd > 36);
} while (retry == 1);
return 0;
}<file_sep>/열혈자료구조/Tree/ListBaseTree/BinaryTree.h
#pragma once
typedef int BTData;
typedef struct _bTreeNode {
BTData data;
struct _bTreeNode* left;
struct _bTreeNode* right;
}BTreeNode;
BTreeNode* MakeBTreeNode(void); // 이진 트리 생성 및 주소 값을 반환
BTData GetData(BTreeNode* bt); // 노드에 저장된 데이터를 반환
void SetData(BTreeNode* bt, BTData data); // 노드에 데이터를 저장
BTreeNode* GetLeftSubTree(BTreeNode* bt); // 왼쪽 서브 트리의 주소 값을 반환
BTreeNode* GetRightSubTree(BTreeNode* bt); // 오른쪽 서브 트리의 주소 값을 반환
void MakeLeftSubTree(BTreeNode* main, BTreeNode* sub); // 왼쪽 서브 트리를 연결
void MakeRightSubTree(BTreeNode* main, BTreeNode* sub); // 오른쪽 서브 트리를 연결<file_sep>/Doit/List/SingleLinkedList/LinkedList.h
#ifndef ___LinkedList
#define ___LinkedList
#include "Member.h"
typedef struct
{
Member data;
struct __node* next;
}Node;
typedef struct
{
Node* head; // 머리 노드에 대한 포인터
Node* crnt; // 선택한 노드에 대한 포인터
}List;
void Initialize(List* list);
// 함수 compare로 x와 같은 노드를 검색
Node* search(List* list, const Member* x, int compare(const Member* x, const Member* y));
void InsertFront(List* list, const Member* x);
void InsertRear(List* list, const Member* x);
void RemoveFront(List* list);
void RemoveRear(List* list);
void RemoveCurrent(List* list);
// 모든 노드 삭제
void Clear(List* list);
// 선택한 노드의 데이터 출력
void PrintCurrent(const List* list);
void PrintLnCurrent(const List* list);
// 모든 노드의 데이터를 리스트 순서대로 출력
void Print(const List* list);
// 연결 리스트 종료
void Terminate(List* list);
#endif<file_sep>/Doit/Array/chap02-10.cpp
/* 1000 이하의 소수를 나열한다. */
#include <stdio.h>
int main()
{
int i, n;
int prime[500];
int ptr = 0;
unsigned long counter = 0;
prime[ptr++] = 2;
for (n = 3; n <= 1000; n += 2) // 홀수만 대상으로
{
for (i = 1; i < ptr; ++i)
{
++counter;
if (n % prime[i] == 0)
break;
}
if (ptr == i)
prime[ptr++] = n;
}
for (i = 0; i < ptr; ++i)
printf("%d\n", prime[i]);
printf("나눗셈을 실행한 횟수 : %d\n", counter);
return 0;
}
<file_sep>/Doit/Hash/OpenAddressing/ClosedHash.h
// 오픈 주소법으로 구현한 해시
#ifndef ___ClosedHash
#define ___ClosedHash
#include "Member.h"
typedef enum
{
Occupied, Empty, Deleted
}Status;
typedef struct
{
Member data; // 데이터
Status stat; // 요소의 상태
}Bucket;
typedef struct
{
int size;
Bucket* table;
}ClosedHash;
int Initialize(ClosedHash* h, int size);
Bucket* Search(const ClosedHash* h, const Member* x);
int Add(ClosedHash* h, const Member* x);
int Remove(ClosedHash* h, const Member* x);
void Dump(const ClosedHash* h);
void Clear(ClosedHash* h);
void Terminate(ClosedHash* h);
#endif<file_sep>/Doit/Recursive/queen_b.c
/* 각 열에 1개의 퀸을 배치하는 조합을 재귀적으로 나열 */
#include <stdio.h>
int pos[8];
int counter;
void print()
{
int i;
for (i = 0; i < 8; ++i)
printf("%2d", pos[i]);
putchar('\n');
}
void set(int i)
{
int j;
// 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 = 16,777,216 가지
for (j = 0; j < 8; ++j)
{
pos[i] = j;
if (i == 7)
{
print();
++counter;
}
else
set(i + 1);
}
}
int main()
{
set(0);
printf("출력횟수 : %d\n", counter); // 16,777,216가지
return 0;
}<file_sep>/Doit/Sorting/bubble3.c
/* 버블 정렬 */
#include <stdio.h>
#include <stdlib.h>
#define swap(type, x, y) do {type t = x; x = y; y = t;}while(0)
int counter;
// 비교, 교환을 하다가 어떤 시점 이후에 교환이 없다면,
// 그보다 앞쪽의 요소는 이미 정렬을 마친 상태
void bubble(int a[], int n)
{
int k = 0; // a[k]보다 앞쪽의 요소는 정렬을 마친 상태
while (k < n - 1)
{
++counter;
int j;
int last = n - 1; // 마지막으로 교환을 수행한 위치를 저장한다.
for (j = n - 1; j > k; --j)
{
if (a[j - 1] > a[j])
{
swap(int, a[j - 1], a[j]);
last = j;
}
}
k = last;
}
}
int main()
{
int i, nx;
int* x;
puts("버블 정렬");
printf("요소 개수 : ");
scanf_s("%d", &nx);
x = (int*)calloc(nx, sizeof(int));
for (i = 0; i < nx; ++i)
{
printf("x[%d] : ", i);
scanf_s("%d", &x[i]);
}
bubble(x, nx);
puts("오름차순으로 정렬한 결과");
for (i = 0; i < nx; ++i)
printf("x[%d] = %d\n", i, x[i]);
free(x);
printf("성능 척도 : %d\n", counter);
return 0;
}<file_sep>/열혈자료구조/Graph/DFS/ArrayBaseStack.h
#pragma once
#define TRUE 1
#define FALSE 0
#define STACK_LEN 100
// 배열 기반 스택 구현
typedef int Data;
typedef struct _arrayStack {
Data stackArr[STACK_LEN];
int topIndex;
}ArrayStack;
typedef ArrayStack Stack;
void StackInit(Stack* pstack); // 스택의 초기화
int SIsEmpty(Stack* pstack); // 스택이 비어있는지 확인
void SPush(Stack* pstack, Data data); // 스택의 push 연산
Data SPop(Stack* pstack); // 스택의 pop 연산
Data SPeek(Stack* pstack); // 스택의 peek 연산
<file_sep>/열혈자료구조/Search/BinarySearch/BinarySearch.c
#include <stdio.h>
//이진 탐색
//조건, 데이터가 정렬되어있어야 한다.
//시간복잡도 O(logN)
int BSearch(int ar[], int len, int target) {
int first = 0;
int last = len - 1;
int mid;
while (first <= last) {
mid = (first + last) / 2;
if (target == ar[mid]) {
return mid;
}
else {
if (target < ar[mid])
last = mid - 1;
else
first = mid + 1;
}
}
return -1;
}
int main() {
int arr[] = { 1,3,5,7,9 };
int idx;
idx = BSearch(arr, sizeof(arr) / sizeof(int), 7);
if (idx == -1)
printf("탐색 실패\n");
else
printf("타겟 저장 인덱스 : %d\n", idx);
return 0;
}<file_sep>/열혈자료구조/ArrayList/ArrayList.h
#pragma once
//#include "Point.h"
#include "NameCard.h"
#define TRUE 1
#define FALSE 0
#define LIST_LEN 100
//typedef int LData;
//typedef Point * LData;
typedef NameCard * LData;
typedef struct __ArrayList { //배열기반 리스트를 정의한 구조체
LData arr[LIST_LEN]; //리스트의 저장소인 배열
int numOfData; //저장된 데이터의 수
int curPosition; //데이터 참조위치를 기록
}ArrayList;
typedef ArrayList List;
void ListInit(List * plist); //초기화
void LInsert(List * plist, LData data); //데이터 저장
int LFirst(List * plist, LData * pdata);//첫 데이터 참조
int LNext(List * plist, LData * pdata); //두 번째 이후 데이터 참조
LData LRemove(List * plist); //참조한 데이터 삭제
int LCount(List * plist); //저장된 데이터의 수 반환
<file_sep>/Doit/String/Boyer-Moore.cpp
// 참고 : https://greatzzo.tistory.com/8?category=662568
#include <stdio.h>
#include <string.h>
// Boyer-Moore 알고리즘의
// Bad Character Heuristic의 예시
/*
1. 패턴의 현재 비교 문자와 일치하지 않는 텍스트의 문자를 bad character라고 부른다.
이런 bad character가 등장하면 패턴에서 이 bad character가 마지막으로 등장했던 위치로 패턴을 이동시킨다.
2. 전처리 과정에서 256의 배열을 만들고 패턴에 등장한 모든 문자의 마지막 위치를 저장한다.
3. 만약 전혀 나타나지 않는 어떤 문자를 만난다면 패턴은 패턴의 길이인 m만큼 이동할 수 있다.
따라서 BM방식의 best case는 O(N/M)이다.
패턴의 길이만큼 JUMP하므로
4. 하지만 BM의 worst case는 O(NM), 예를 들어서
txt[] = "AAAAAAAAAAAAAAA"
pat[] = "AAAAA"라고 하면,
Bad character가 등장하지 않으니 매번 일일이 다 검사한다.
*/
#define NUM_OF_CHARS 256
int max(int a, int b) { return (a > b) ? a : b; }
// The preprocessing function for Boyer Moore's bad Character heuristic
int* createBC(char* pat, int M)
{
int* bc = new int[NUM_OF_CHARS];
// Initialize all occurrences as -1
// 처음에는 -1로 초기화
for (int i = 0; i < NUM_OF_CHARS; ++i)
bc[i] = -1;
// Fill the actual value of last occurrence of a character
// 마지막으로 등장한 문자의 실제 값으로 채운다.
for (int i = 0; i < M - 1; ++i)
bc[(int)pat[i]] = i;
for (int i = 65; i < 66; ++i)
printf("%d\n", bc[i]);
return bc;
}
void searchBM(char* pat, char* txt)
{
int N = strlen(txt);
int M = strlen(pat);
int* bc = createBC(pat, M);
int s = 0; // 패턴의 첫 인덱스 위치
int j = 0; // 패턴의 현재 비교 위치
// 0 1 2 3 4 5 6 7 8
// A B A B B B A C A B A A B [txt]
// A B A A B [pat]
// A B A A B [pat]
// s는 N - M = 8까지만 확인해보면 된다.
// 이 이상 넘어가면 해당 패턴이 txt에 없다는 뜻
while (s <= (N - M))
{
j = M - 1;
// txt에 해당 pat을 뒤에서 부터 하나씩 비교해가면서 j를 감소시킨다.
// 일치한다면 계속해서 j가 감소하지만, 일치하지 않는다면 j를 감소하지 않고
// 빠져나오게 된다.
while (j >= 0 && pat[j] == txt[s + j])
j--;
// 모든 패턴이 txt와 일치했더라면 j는 0보다 작으므로
if (j < 0)
{
// 해당 패턴이 일치하는 첫 번째 인덱스를 출력
printf("Pattern found at index %d \n", s);
// Shift the pattern so that the next character in text
// aligns with the last occurence of it in pattern.
// 해당 패턴이 일치한 것만 출력하는 것이 아닌, 또 있을 수 있으므로
// 계속해서 조사해보기 위해 s의 값을 변경해준다.
// 여기서는 s + M이 txt의 길이를 넘지 않는다면, s + M의 문자를 확인해서
// 얼만큼 패턴을 넘길지 조사한다음 s의 값을 수정한다.
s += (s + M < N) ? M - bc[txt[s + M]] : 1;
}
else
{
// 일치하지 않는 문자가 있을 때,
// 이 때 bad character인 bc 배열 값을 보고 패턴을 그 만큼 이동시킨다.
// 예를 들어 j = 3에서 문자가 일치하지 않는다면,
// bc[txt[s + j]] = 1이므로,
// j - 1 = 3 - 1 = 2
// 따라서 해당 패턴을 2칸 이동시켜서 다시 비교한다.
// 경우에 따라서 음수가 나올 수 있으므로, 이럴 때는 1칸 이동시켜 다시 비교시킨다.
s += max(1, j - bc[txt[s + j]]);
}
}
delete bc;
}
int main()
{
// 0123456789
//char txt[] = "ABABBBACABAAB";
//char pat[] = "ABAAB";
// 0123456789
char txt[] = "AAAAAAAAAA";
char pat[] = "AAAAA";
searchBM(pat, txt);
return 0;
}<file_sep>/열혈자료구조/Graph/BFS/CircularQueue.h
#pragma once
#define TRUE 1
#define FALSE 0
#define QUE_LEN 100
typedef int Data;
// 배열 기반의 원형 큐 구현
// Circular Queue
typedef struct _cQueue {
int front; // front 멤버
int rear; // rear 멤버
Data queArr[QUE_LEN];
}CQueue;
typedef CQueue Queue;
void QueueInit(Queue* pq);
int QIsEmpty(Queue* pq);
void Enqueue(Queue* pq, Data data);
Data Dequeue(Queue* pq);
Data QPeek(Queue* pq);<file_sep>/Doit/Array/chap02-6.cpp
/* 배열 요소의 최댓값을 구한다.(값을 난수로 생성) */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// const int a[] = const int* a
// 읽기만 가능하도록
int maxof(const int a[], int n)
{
int i;
int max = a[0];
for (i = 1; i < n; ++i)
if (a[i] > max) max = a[i];
return max;
}
int main()
{
int i;
int* height;
int number;
printf("사람 수 : ");
scanf_s("%d", &number);
height = (int*)calloc(number, sizeof(int));
srand(time(NULL)); // 시간으로 난수의 seed를 초기화
for (i = 0; i < number; ++i)
{
height[i] = 100 + rand() % 90; // 100 + 0 ~ 89 => 100 ~ 189
printf("height[%d] : %d\n", i, height[i]);
}
printf("최댓값은 %d\n", maxof(height, number));
free(height);
return 0;
}<file_sep>/열혈자료구조/Tree/AVLTree/AVLRebalance.c
#include <stdio.h>
#include "BinaryTree3.h"
// LL회전
BTreeNode* RotateLL(BTreeNode* bst) {
BTreeNode* pNode; // parent node
BTreeNode* cNode; // child node
pNode = bst;
cNode = GetLeftSubTree(pNode);
// 실제 LL회전을 담당하는 코드
ChangeLeftSubTree(pNode, GetRightSubTree(cNode));
ChangeRightSubTree(cNode, pNode);
// LL회전으로 인해서 변경된 루트 노드의 주소 값을 반환
return cNode;
}
// RR회전
BTreeNode* RotateRR(BTreeNode* bst) {
BTreeNode* pNode; // parent node
BTreeNode* cNode; // child node
pNode = bst;
cNode = GetRightSubTree(pNode);
// 실제 RR회전을 담당하는 코드
ChangeRightSubTree(pNode, GetLeftSubTree(cNode));
ChangeLeftSubTree(cNode, pNode);
// RR회전으로 인해서 변경된 루트 노드의 주소 값을 반환
return cNode;
}
// RL회전
BTreeNode* RotateRL(BTreeNode* bst) {
BTreeNode* pNode; // parent node
BTreeNode* cNode; // child node
pNode = bst;
cNode = GetRightSubTree(bst);
// 실제 RL회전을 담당하는 코드
ChangeRightSubTree(pNode, RotateLL(cNode)); // 부분적 LL회전
return RotateRR(pNode);
}
// LR회전
BTreeNode* RotateLR(BTreeNode* bst) {
BTreeNode* pNode; // parent node
BTreeNode* cNode; // child node
pNode = bst;
cNode = GetLeftSubTree(bst);
// 실제 LR회전을 담당하는 코드
ChangeLeftSubTree(pNode, RotateRR(cNode)); // 부분적 RR회전
return RotateLL(pNode);
}
// 트리의 높이를 계산하여 반환
int GetHeight(BTreeNode* bst) {
int leftH; // left height
int rightH; // right height
if (bst == NULL)
return 0;
leftH = GetHeight(GetLeftSubTree(bst)); // 왼쪽 서브 트리 높이 계산
rightH = GetHeight(GetRightSubTree(bst)); // 오른쪽 서브 트리 높이 계산
// 큰 값의 높이를 반환한다.
if (leftH > rightH)
return leftH + 1;
else
return rightH + 1;
}
// 두 서브 트리의 높이의 차를 반환
int GetHeightDiff(BTreeNode* bst) {
int lsh; // left sub tree height
int rsh; // right sub tree height
if (bst == NULL)
return 0;
lsh = GetHeight(GetLeftSubTree(bst)); // 왼쪽 서브 트리의 높이
rsh = GetHeight(GetRightSubTree(bst)); // 오른쪽 서브 트리의 높이
return lsh - rsh; // 균형 인수 계산결과 반환
}
// 트리의 균형을 잡는다.
BTreeNode* Rebalance(BTreeNode** pRoot) {
int hDiff = GetHeightDiff(*pRoot); // 균형 인수 계산
// 균형 인수가 +2 이상이면 LL상태 또는 LR상태이다.
if (hDiff > 1) { // 왼쪽 서브 트리 방향으로 높이가 2 이상 크다면
if (GetHeightDiff(GetLeftSubTree(*pRoot)) > 0) {
*pRoot = RotateLL(*pRoot);
}
else {
*pRoot = RotateLR(*pRoot);
}
}
// 균형 인수가 -2 이하이면 RR상태 또는 RL상태이다.
if (hDiff < -1) { // 오른쪽 서브 트리 방향으로 높이가 2 이상 크다면
if (GetHeightDiff(GetRightSubTree(*pRoot)) < 0) {
*pRoot = RotateRR(*pRoot);
}
else {
*pRoot = RotateRL(*pRoot);
}
}
// 회전 과정에서 루트 노드가 변경될 수 있기 때문에, 루트 노드의 주소 값을 반환
return *pRoot;
}<file_sep>/Doit/Recursive/hanoi.c
/* 하노이의 탑 */
#include <stdio.h>
// no개의 원반을 1 -> 3으로 옮기고 싶을 때
// no-1의 원반을 1 -> 2로 옮기고,
// no의 원반을 1 -> 3으로 옮긴다.
// no-1의 원반을 2 -> 3으로 옮긴다.
void move(int no, int x, int y)
{
if (no > 1)
move(no - 1, x, 6 - x - y); // 그룹을 시작 기둥에서 중간 기둥으로
printf("원반[%d]을 %d기둥에서 %d기둥으로 옮김\n", no, x, y);
if (no > 1)
move(no - 1, 6 - x - y, y); // 그룹을 중간 기둥에서 목표 기둥으로
}
int main()
{
int n;
printf("하노이의 탑\n원반 개수 : ");
scanf_s("%d", &n);
move(n, 1, 3);
return 0;
}<file_sep>/Doit/Sorting/heap.c
/* 힙 정렬 */
#include <stdio.h>
#include <stdlib.h>
#define swap(type, x, y) do{type t = x; x = y; y = t;} while(0)
// 1. downheap 사용해서 배열 a를 heap으로 만들어준다.
// 2. 루트에 있는 가장 큰 값을 빼내어 배열 마지막 요소와 바꾸고,
// 배열의 나머지 부분을 다시 힙으로 만들어주는 과정을 반복하여 정렬을 수행한다.
// a, 4, 9
static void downheap(int a[], int left, int right)
{
int temp = a[left]; // 루트(여기의 값이 그 자리에 있을지, 아니면 자리를 변경해야 하는지 저장하는 값)
int child;
int parent;
// 부모가 될 수 있는 조건은 parent < (right + 1) / 2까지만이다. (자식이 있어야 가능)
for (parent = left; parent < (right + 1) / 2; parent = child)
{
int cl = parent * 2 + 1; // 왼쪽 자식
int cr = cl + 1; // 오른쪽 자식
child = (cr <= right && a[cr] > a[cl]) ? cr : cl; // 왼쪽 vs 오른쪽
if (temp >= a[child]) // 가장 큰 값과 루트를 비교해서, 루트가 크면 종료
break;
a[parent] = a[child]; // 아니라면, 부모에 자식을 넣어주고, 이어간다.
}
a[parent] = temp;
}
void heapsort(int a[], int n)
{
int i;
// 주어진 배열 a를 heap으로 구성해준다.
// 아랫부분의 작은 부분트리부터 시작해 올라가는 방식이다.
for (i = (n - 1) / 2; i >= 0; --i)
downheap(a, i, n - 1);
for (i = n - 1; i > 0; --i)
{
// 루트를 가장 맨 뒤의 값과 swap해서 정렬해준다.
swap(int, a[0], a[i]);
// 루트를 없애고 힙 상태를 유지하기 위해서 downheap을 한다.
downheap(a, 0, i - 1);
}
}
int main()
{
int i, nx;
int* x;
puts("힙 정렬");
printf("요소 개수 : "); scanf_s("%d", &nx);
x = (int*)calloc(nx, sizeof(int));
for (i = 0; i < nx; ++i)
{
printf("x[%d] : ", i);
scanf_s("%d", &x[i]);
}
heapsort(x, nx);
puts("오름차순으로 정렬");
for (i = 0; i < nx; ++i)
printf("x[%d] = %d\n", i, x[i]);
free(x);
return 0;
}<file_sep>/열혈자료구조/Graph/LinkedListBasedGraph/ALGraph.c
#include <stdio.h>
#include <stdlib.h>
#include "ALGraph.h"
#include "DLinkedList.h"
int WhoIsPrecede(int data1, int data2) {
if (data1 < data2)
return 0;
else
return 1;
}
void GraphInit(ALGraph* pg, int nv) {
int i;
// 정점의 수에 해당하는 길이의 리스트 배열을 생성한다.
pg->adjList = (List*)malloc(sizeof(List) * nv);
pg->numV = nv; // 정점의 수는 nv에 저장된 값으로 결정
pg->numE = 0; // 초기의 간선 수는 0개
// 정점의 수만큼 생선된 리스트들을 초기화한다.
for (i = 0; i < nv; i++) {
ListInit(&(pg->adjList[i])); // 인접리스트는 인덱스의 시작이 0부터
SetSortRule(&(pg->adjList[i]), WhoIsPrecede);
}
}
void GraphDestroy(ALGraph* pg) {
if (pg->adjList != NULL)
free(pg->adjList); // 동적으로 할당된 연결 리스트의 소멸
}
void AddEdge(ALGraph* pg, int fromV, int toV) {
// 구현은 무방향 그래프이므로 양쪽 모두 연결해준다.
// 정점 fromV의 연결 리스트에 정점 toV의 정보 추가
LInsert(&(pg->adjList[fromV]), toV);
// 정점 toV의 연결 리스트에 정점 fromV의 정보 추가
LInsert(&(pg->adjList[toV]), fromV);
pg->numE += 1;
}
void ShowGraphEdgeInfo(ALGraph* pg) {
int i;
int vx;
for (i = 0; i < pg->numV; i++) {
printf("%c와 연결된 정점: ", i + 65);
if (LFirst(&(pg->adjList[i]), &vx)) {
printf("%c ", vx + 65);
while (LNext(&(pg->adjList[i]), &vx)) {
printf("%c ", vx + 65);
}
}
printf("\n");
}
}<file_sep>/열혈자료구조/Tree/AVLTree/AVLRebalance.h
#pragma once
#include "BinaryTree3.h"
// 트리의 균형을 잡는다.
BTreeNode* Rebalance(BTreeNode** pRoot);<file_sep>/README.md
# DataStructure
자료구조에 대해서 공부 및 적용
* 참고한 책
* 열혈 자료구조 (저자 윤성우)
* 자료구조와 함께 배우는 알고리즘 입문(C 언어편)
<file_sep>/Doit/Set/IntSet/IntSet.h
#ifndef ___IntSet
#define ___IntSet
typedef struct
{
int max;
int num;
int* set;
}IntSet;
int Initialize(IntSet* s, int max);
// 집합 s에 n이 들어 있는지 확인
int IsMember(const IntSet* s, int n);
// 집합 s에 n 추가
void Add(IntSet* s, int n);
// 집합 s에 n을 삭제
void Remove(IntSet* s, int n);
int Capacity(const IntSet* s);
int Size(const IntSet* s);
// 집합 s2를 s1에 대입
void Assign(IntSet* s1, const IntSet* s2);
int Equal(const IntSet* s1, const IntSet* s2);
// 집합 s2와 s3의 합집합을 s1에 대입
IntSet* Union(IntSet* s1, const IntSet* s2, const IntSet* s3);
// 집합 s2에서 s3를 뺀 차집합을 s1에 대입
IntSet* Intersection(IntSet* s1, const IntSet* s2, const IntSet* s3);
// 집합 s2에서 s3을 뺀 차집합을 s1에 대입
IntSet* Difference(IntSet* s1, const IntSet* s2, const IntSet* s3);
void Print(const IntSet* s);
void PrintLn(const IntSet* s);
void Terminate(IntSet* s);
#endif<file_sep>/열혈자료구조/Stack/Calculator/InfixToPostfix.h
#pragma once
void ConvToRPNExp(char exp[]); // 중위 표기법 -> 후위 표기법<file_sep>/Doit/String/strary2.c
/* 문자열을 초기화하며 선언하는 방법 */
#include <stdio.h>
int main()
{
//char st[10] = { 'A','B','C','D', '\0' };
char st[10] = "ABCD"; // 가장 많이 쓰이는 방식
printf("문자열 st에는 %s가 들어있다.\n", st);
return 0;
}<file_sep>/열혈자료구조/Hash/Chaining(LinkedList)/Table2.h
#pragma once
#include "Slot2.h"
#include "DLinkedList.h"
#define MAX_TBL 100
typedef int HashFunc(Key k);
typedef struct _table {
List tbl[MAX_TBL];
HashFunc* hf;
}Table;
void TBLInit(Table* bt, HashFunc* f);
void TBLInsert(Table* bt, Key k, Value v);
Value TBLDelete(Table* bt, Key k);
Value TBLSearch(Table* bt, Key k);<file_sep>/Doit/Tree/BinarySearchTree/BinTree.h
#ifndef ___BinTree
#define ___BinTree
#include "Member.h"
typedef struct __bnode
{
Member data;
struct __bnode* left;
struct __bnode* right;
}BinNode;
BinNode* Search(BinNode* p, const Member* x);
BinNode* Add(BinNode* p, const Member* x);
int Remove(BinNode** root, const Member* x);
void PrintTree(const BinNode* p);
void FreeTree(BinNode* p);
#endif<file_sep>/열혈자료구조/Sorting/HeapSort/UsefulHeap.c
#include "UsefulHeap.h"
void HeapInit(Heap* ph, PriorityComp pc) {
ph->numOfData = 0;
ph->comp = pc; // 함수 등록
}
int HIsEmpty(Heap* ph) {
if (ph->numOfData == 0)
return TRUE;
else
return FALSE;
}
int GetParentIDX(int idx) { // 부모 노드의 인덱스 값 반환
return idx / 2;
}
int GetLChildIDX(int idx) { // 왼쪽 자식 노드의 인덱스 값 반환
return idx * 2;
}
int GetRChildIDX(int idx) { // 오른쪽 자식 노드의 인덱스 값 반환
return idx * 2 + 1;
}
// 두 개의 자식 노드 중 높은 우선순위 자식 노드 인덱스 값을 반환
int GetHiPriChildIDX(Heap* ph, int idx) {
// 자식 노드가 존재하지 않는다면,
if (GetLChildIDX(idx) > ph->numOfData)
return 0;
// 자식 노드가 왼쪽 자식 노드 하나만 존재한다면,
else if (GetLChildIDX(idx) == ph->numOfData)
return GetLChildIDX(idx);
// 자식 노드가 둘 다 존재한다면,
else {
// 오른쪽 자식 노드의 우선순위가 높다면
if(ph->comp(ph->heapArr[GetLChildIDX(idx)], ph->heapArr[GetRChildIDX(idx)]) < 0)
return GetRChildIDX(idx);
else
return GetLChildIDX(idx);
}
}
// 힙에 데이터 저장
void HInsert(Heap* ph, HData data) {
int idx = ph->numOfData + 1;
// 새 노드가 루트 노드의 위치가 아니라면 반복
while (idx != 1) {
// 새 노드와 부모 노드의 우선순위 비교
if (ph->comp(data, ph->heapArr[GetParentIDX(idx)]) > 0) {
// 새 노드가 부모 노드의 우선순위보다 높다면
ph->heapArr[idx] = ph->heapArr[GetParentIDX(idx)];
idx = GetParentIDX(idx);
}
else
break;
}
ph->heapArr[idx] = data;
ph->numOfData += 1;
}
// 힙에서 데이터 삭제
// 핵심은 마지막 노드가 있어야 할 위치를 parentIdx에 저장된 인덱스 값을
// 갱신해가며 찾는다
HData HDelete(Heap* ph) {
HData retData = ph->heapArr[1];
HData lastElem = ph->heapArr[ph->numOfData];
int parentIdx = 1;
int childIdx;
while (childIdx = GetHiPriChildIDX(ph, parentIdx)) {
if (ph->comp(lastElem, ph->heapArr[childIdx]) >= 0)
break;
ph->heapArr[parentIdx] = ph->heapArr[childIdx];
parentIdx = childIdx;
} // 반복문 탈출하면 parentIdx에 마지막 노드의 위치정보가 저장
// 그 위치에 마지막 노드의 정보를 넣는다
ph->heapArr[parentIdx] = lastElem;
ph->numOfData -= 1;
return retData;
}<file_sep>/Doit/String/str_len3.c
/* 문자열의 길이를 구해보자. */
#include <stdio.h>
int str_len(const char* s)
{
const char* p = s;
while (*s)
s++;
return s - p;
}
int main()
{
char str[256];
printf("문자열 : ");
scanf_s("%s", str, 256);
printf("이 문자열의 길이는 %d이다.\n", str_len(str));
return 0;
}<file_sep>/열혈자료구조/Search/InterpolSearch/InterpolSearch.c
#include <stdio.h>
// 보간 탐색의 구현
// 이진 탐색의 비효율성을 개선시킨 알고리즘이다.
// 단점은 정수형 나눗셈이 아닌 실수형 나눗셈을 진행 -> 이는 오차가 발생할 수 있음.
int ISearch(int ar[], int first, int last, int target) {
int mid;
if (ar[first] > target || ar[last] < target)
return -1; // -1의 반환은 탐색의 실패를 의미
// 이진 탐색과의 차이점을 반영한 문장
mid = ((double)(target - ar[first]) / (ar[last] - ar[first]) *
(last - first)) + first;
if (ar[mid] == target)
return mid; // 탐색된 타겟의 인덱스 값 반환
else if (target < ar[mid])
return ISearch(ar, first, mid - 1, target);
else
return ISearch(ar, mid + 1, last, target);
}
int main() {
int arr[] = { 1,3,5,7,9 };
int idx;
idx = ISearch(arr, 0, sizeof(arr) / sizeof(int) - 1, 2);
if (idx == -1)
printf("탐색 실패 \n");
else
printf("타겟 저장 인덱스 : %d \n", idx);
return 0;
}<file_sep>/열혈자료구조/Hash/SimpleHash/Slot.h
#pragma once
#include "Person.h"
typedef int Key; // 주민등록번호(ssn)
typedef Person* Value;
enum SlotStatus {EMPTY, DELETED, INUSE};
typedef struct _slot {
Key key;
Value val;
enum SlotStatus status;
}Slot;
<file_sep>/Doit/String/strary1.c
/* 배열에 문자열 저장하기 */
#include <stdio.h>
// 문자열 값을 char형 배열에 저장하면 자유롭게 값을 꺼내고 쓸 수 있다.
int main()
{
char st[10];
st[0] = 'A';
st[1] = 'B';
st[2] = 'C';
st[3] = 'D';
st[4] = '\0'; // 문자열의 끝을 의미하는 널 문자
st[5] = 'T';
printf("문자열 st에는 %s가 들어있다.\n", st);
return 0;
}<file_sep>/열혈자료구조/Graph/Kruskal/ALEdge.h
#pragma once
typedef struct _edge {
int v1;
int v2;
int weight; // 가중치 정보
}Edge;
<file_sep>/Doit/Stack&Queue/ArrayQueue(RingBuffer)/queueMain.c
#include <stdio.h>
#include "IntQueue.h"
int main()
{
IntQueue que;
if (Initialize(&que, 64) == -1)
{
puts("큐의 생성에 실패");
return 1;
}
while (1)
{
int m, x;
printf("현제 데이터 수 : %d / %d\n", Size(&que), Capacity(&que));
printf("(1)인큐 (2)디큐 (3)피크 (4)출력 (5)검색 (0)종료 : ");
scanf_s("%d", &m);
if (m == 0) break;
switch (m)
{
case 1:
printf("데이터 : ");
scanf_s("%d", &x);
if (Enque(&que, x) == -1)
puts("오류 : 인큐에 실패");
else
printf("디큐한 데이터는 %d\n", x);
break;
case 2:
if (Deque(&que, &x) == -1)
puts("오류 : 디큐에 실패");
else
printf("디큐한 데이터는 %d\n", x);
break;
case 3:
if (Peek(&que, &x) == -1)
puts("오류 : 피크에 실패");
else
printf("피크한 데이터는 %d\n", x);
break;
case 4:
Print(&que);
break;
case 5:
printf("검색할 데이터 : ");
scanf_s("%d", &x);
if (Search2(&que, x) == -1)
puts("오류 : 검색 실패");
else
printf("찾은 데이터는 front에서 %d만큼 떨어져있다.\n", Search2(&que, x));
break;
}
}
Terminate(&que);
return 0;
}<file_sep>/Doit/Recursive/euclid.c
/* 유클리드 호제법에 의해 최대공약수를 구한다. */
#include <stdio.h>
int gcd(int x, int y)
{
if (y == 0)
return x;
else
return gcd(y, x % y);
}
int main()
{
int x, y;
puts("두 정수의 최대공약수를 구해보자.");
printf("정수를 입력 : ");
scanf_s("%d", &x);
printf("정수를 입력 : ");
scanf_s("%d", &y);
printf("최대공약수는 %d\n", gcd(x, y));
printf("최대공약수는 %d\n", gcd(y, x));
return 0;
}<file_sep>/Doit/String/strstr_test.c
/* strstr 함수를 사용한 프로그램 */
#include <stdio.h>
#include <string.h>
int main()
{
char s1[256], s2[256];
char* p;
puts("strstr함수");
printf("텍스트 : "); scanf_s("%s", &s1, 256);
printf("패턴 : "); scanf_s("%s", &s2, 256);
p = strstr(s1, s2); // 문자열 s1에서 문자열 s2 검색
if (p == NULL)
printf("텍스트에 패턴이 없다.\n");
else
{
int ofs = p - s1;
printf("\n%s\n", s1);
printf("%*s|\n", ofs, "", s2);
printf("%*s%s\n", ofs, "", s2);
}
return 0;
}<file_sep>/열혈자료구조/Tree/ExpressionTree/ListBaseStack.h
#pragma once
#define TRUE 1
#define FALSE 0
#include "BinaryTree2.h"
// 연결 리스트 기반 스택 구현
typedef BTreeNode* Data;
typedef struct _node { // 연결 리스트의 노드를 표현한 구조체
Data data;
struct _node* next;
}Node;
typedef struct _listStack { // 연결 리스트 기반 스택을 표현한 구조체
Node* head;
}ListStack;
typedef ListStack Stack;
void StackInit(Stack* pstack); // 스택 초기화
int SIsEmpty(Stack* pstack); // 스택이 비어있는지 확인
void SPush(Stack* pstack, Data data); // 스택 push 연산
Data SPop(Stack* pstack); // 스택 pop 연산
Data SPeek(Stack* pstack); // 스택 peek 연산<file_sep>/열혈자료구조/Stack/Calculator/InfixCalculator.c
#include <string.h>
#include <stdlib.h>
#include "InfixToPostfix.h" // ConvRPNExp 함수 호출을 위해
#include "PostCalculator.h" // EvalRPNExp 함수 호출을 위해
int EvalInfixExp(char exp[]) {
int len = strlen(exp);
int ret;
char* expcpy = (char*)malloc(len + 1);
strcpy(expcpy, exp);
ConvToRPNExp(expcpy); // 중위 표기법 -> 후위 표기법
ret = EvalRPNExp(expcpy); // 후위 표기법 수식 계산
free(expcpy);
return ret;
}<file_sep>/Doit/String/strncmp_test.c
/* 문자열을 비교하는 프로그램(strncmp 함수 사용) */
#include <stdio.h>
#include <string.h>
int main()
{
char st[128];
puts("STRING의 처음 3개의 문자와 비교");
puts("XXXX를 입력하면 종료");
while (1)
{
printf("문자열 st : ");
scanf_s("%s", st, 128);
if (strncmp("XXXX", st, 3) == 0)
break;
printf("strncmp(\"STRING\",st, 3) = %d\n", strncmp("STRING", st, 3));
}
return 0;
}<file_sep>/Doit/String/swap_ptr.c
/* 두 포인터 값을 서로 교환하는 함수 */
#include <stdio.h>
// 이 함수가 s1, s2의 주소를 받아야 하기 때문에 char**형으로 받아야 한다.
void swap_ptr(char** x, char** y)
{
char* tmp = *x;
*x = *y;
*y = tmp;
}
int main()
{
char* s1 = "ABCD";
char* s2 = "EFGH";
printf("포인터 s1 : %s\n", s1);
printf("포인터 s2 : %s\n", s2);
swap_ptr(&s1, &s2);
puts("\n포인터 s1과 s2의 값을 서로 교환\n");
printf("포인터 s1 : %s\n", s1);
printf("포인터 s2 : %s\n", s2);
return 0;
}<file_sep>/Doit/Array/chap02-7.cpp
/* 배열 요소를 역순으로 정렬한다. */
#include <stdio.h>
#include <stdlib.h>
#define swap(type, x, y) do{ type t = x; x = y; y = t;} while(0)
void ary_reverse(int a[], int n)
{
int i;
for (i = 0; i < n / 2; ++i)
swap(int, a[i], a[n - i - 1]); // ;(세미콜론) 전까지 치환된다.
}
int main()
{
int i;
int* x;
int nx;
printf("요소 개수 : ");
scanf_s("%d", &nx);
x = (int*)calloc(nx, sizeof(int));
for (i = 0; i < nx; ++i)
{
printf("x[%d] : ", i);
scanf_s("%d", &x[i]);
}
ary_reverse(x, nx);
printf("배열의 요소를 역순으로 정렬한다.\n");
for (i = 0; i < nx; ++i)
printf("x[%d] = %d\n", i, x[i]);
free(x);
return 0;
}<file_sep>/열혈자료구조/Graph/Kruskal/ALGraphKruskal.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ALGraphKruskal.h"
#include "DLinkedList.h"
#include "ArrayBaseStack.h"
int WhoIsPrecede(int data1, int data2) {
if (data1 < data2)
return 0;
else
return 1;
}
int PQWeightComp(Edge d1, Edge d2) {
return d1.weight - d2.weight;
}
void GraphInit(ALGraph* pg, int nv) {
int i;
// 정점의 수에 해당하는 길이의 리스트 배열을 생성한다.
pg->adjList = (List*)malloc(sizeof(List) * nv);
pg->numV = nv; // 정점의 수는 nv에 저장된 값으로 결정
pg->numE = 0; // 초기의 간선 수는 0개
// 정점의 수만큼 생선된 리스트들을 초기화한다.
for (i = 0; i < nv; i++) {
ListInit(&(pg->adjList[i])); // 인접리스트는 인덱스의 시작이 0부터
SetSortRule(&(pg->adjList[i]), WhoIsPrecede);
}
pg->visitInfo = (int*)malloc(sizeof(int) * pg->numV);
memset(pg->visitInfo, 0, sizeof(int) * pg->numV);
// 우선순위 큐 초기화
PQueueInit(&(pg->pqueue), PQWeightComp);
}
void GraphDestroy(ALGraph* pg) {
if (pg->adjList != NULL)
free(pg->adjList); // 동적으로 할당된 연결 리스트의 소멸
if (pg->visitInfo != NULL)
free(pg->visitInfo);
}
void AddEdge(ALGraph* pg, int fromV, int toV, int weight) {
Edge edge = { fromV, toV, weight }; // 간선의 가중치 정보를 담는다.
// 구현은 무방향 그래프이므로 양쪽 모두 연결해준다.
// 정점 fromV의 연결 리스트에 정점 toV의 정보 추가
LInsert(&(pg->adjList[fromV]), toV);
// 정점 toV의 연결 리스트에 정점 fromV의 정보 추가
LInsert(&(pg->adjList[toV]), fromV);
pg->numE += 1;
// 간선의 가중치 정보를 우선순위 큐에 저장
PEnqueue(&(pg->pqueue), edge);
}
void RecoverEdge(ALGraph* pg, int fromV, int toV, int weight) {
LInsert(&(pg->adjList[fromV]), toV);
LInsert(&(pg->adjList[toV]), fromV);
(pg->numE)++;
}
// 한쪽 방향의 간선 소멸
void RemoveWayEdge(ALGraph* pg, int fromV, int toV) {
int edge;
if (LFirst(&(pg->adjList[fromV]), &edge)) {
if (edge == toV) {
LRemove(&(pg->adjList[fromV]));
return;
}
while (LNext(&(pg->adjList[fromV]), &edge)) {
if (edge == toV) {
LRemove(&(pg->adjList[fromV]));
return;
}
}
}
}
// 간선의 소멸
void RemoveEdge(ALGraph* pg, int fromV, int toV) {
RemoveWayEdge(pg, fromV, toV);
RemoveWayEdge(pg, toV, fromV);
(pg->numE)--;
}
void ShowGraphEdgeInfo(ALGraph* pg) {
int i;
int vx;
for (i = 0; i < pg->numV; i++) {
printf("%c와 연결된 정점: ", i + 65);
if (LFirst(&(pg->adjList[i]), &vx)) {
printf("%c ", vx + 65);
while (LNext(&(pg->adjList[i]), &vx)) {
printf("%c ", vx + 65);
}
}
printf("\n");
}
}
int VisitVertex(ALGraph* pg, int visitV) {
if (pg->visitInfo[visitV] == 0) {
pg->visitInfo[visitV] = 1; // 방문했다고 체크
return TRUE;
}
return FALSE;
}
void DFShowGraphVertex(ALGraph* pg, int startV) {
Stack stack;
int visitV = startV;
int nextV;
StackInit(&stack); // DFS을 위한 스택의 초기화
VisitVertex(pg, visitV); // 시작 정점을 방문
SPush(&stack, visitV); // 시작 정점의 정보를 스택으로 넣는다.
// visitV에 담긴 정점과 연결된 정점의 방문을 시도하는 while문
// visitV와 인접한 정점 중에서 찾아서 방문하지 않았다면 방문한다.
while (LFirst(&(pg->adjList[visitV]), &nextV) == TRUE) {
// visitV와 연결된 정점의 정보가 nextV에 담긴 상태에서 이하를 진행한다.
int visitFlag = FALSE;
if (VisitVertex(pg, nextV) == TRUE) {
SPush(&stack, visitV);
visitV = nextV;
visitFlag = TRUE;
}
else {
while (LNext(&(pg->adjList[visitV]), &nextV) == TRUE) {
if (VisitVertex(pg, nextV) == TRUE) {
SPush(&stack, visitV);
visitV = nextV;
visitFlag = TRUE;
break;
}
}
}
if (visitFlag == FALSE) { // 추가로 방문한 정점이 없었다면
// 스택이 비면 탐색의 시작점으로 되돌아 온 것이다.
if (SIsEmpty(&stack) == TRUE)
break;
else
visitV = SPop(&stack); // 길을 되돌아 간다.
}
}
// 이후의 다른 탐색을 위해서 방문 배열을 다시 초기화 시킨다.
memset(pg->visitInfo, 0, sizeof(int) * pg->numV);
}
// 간선의 가중치 정보 출력
void ShowGraphEdgeWeightInfo(ALGraph* pg) {
PQueue copyPQ = pg->pqueue;
Edge edge;
while (!PQIsEmpty(©PQ)) {
edge = PDequeue(©PQ);
printf("(%c-%c), w:%d \n", edge.v1 + 65, edge.v2 + 65, edge.weight);
}
}
// 인자로 전달된 두 정점이 연결되어 있다면 TRUE, 아니면 FALSE
int IsConnVertex(ALGraph* pg, int v1, int v2) {
Stack stack;
int visitV = v1;
int nextV;
StackInit(&stack);
VisitVertex(pg, visitV);
SPush(&stack, visitV);
while (LFirst(&(pg->adjList[visitV]), &nextV) == TRUE) {
int visitFlag = FALSE;
// 정점을 돌아다니는 도중에 목표를 찾는다면 TRUE반환
if (nextV == v2) {
// 함수가 반환하기 전에 초기화를 진행
memset(pg->visitInfo, 0, sizeof(int) * pg->numV);
return TRUE;
}
if (VisitVertex(pg, nextV) == TRUE) {
SPush(&stack, visitV);
visitV = nextV;
visitFlag = TRUE;
}
else {
while (LNext(&(pg->adjList[visitV]), &nextV) == TRUE) {
if (nextV == v2) {
memset(pg->visitInfo, 0, sizeof(int) * pg->numV);
return TRUE;
}
if (VisitVertex(pg, nextV) == TRUE) {
SPush(&stack, visitV);
visitV = nextV;
visitFlag = TRUE;
break;
}
}
}
if (visitFlag == FALSE) {
if (SIsEmpty(&stack) == TRUE)
break;
else
visitV = SPop(&stack);
}
}
memset(pg->visitInfo, 0, sizeof(int) * pg->numV);
return FALSE;
}
void ConKruskalMST(ALGraph* pg) { // 크루스칼 간선의 정보 저장
Edge recvEdge[20];
Edge edge;
int eidx = 0;
int i;
// MST를 형성할 때까지 반복
while (pg->numE + 1 > pg->numV) { // MST 간선의 수 + 1 == 정점의 수
// 우선순위 큐에서 가중치가 제일 높은 간선의 정보를 꺼낸다.
edge = PDequeue(&(pg->pqueue));
RemoveEdge(pg, edge.v1, edge.v2); // 그래프에서 간선을 삭제
// 간선을 삭제하고 나서도 두 정점을 연결하는 경로가 있는지 확인
if (!IsConnVertex(pg, edge.v1, edge.v2)) { // 두 정점이 연결되어 있는지 확인
// 경로가 없으면 삭제한 간선을 다시 복원
RecoverEdge(pg, edge.v1, edge.v2, edge.weight); // 삭제된 간선을 다시 삽입
// 복원한 간선의 정보를 별도로 저장한다.
recvEdge[eidx++] = edge;
}
}
// 우선순위 큐에서 삭제된 간선의 정보를 회복
for (i = 0; i < eidx; i++)
PEnqueue(&(pg->pqueue), recvEdge[i]);
}<file_sep>/열혈자료구조/LinkedList/Double_Linked_List/DBLikedList.h
#pragma once
#define TRUE 1
#define FALSE 0
// 양방향 연결 리스트의 구현
// double linked list
typedef int Data;
typedef struct _node {
Data data;
struct _node* next;
struct _node* prev;
}Node;
typedef struct _DLinkedList {
Node* head;
Node* cur;
int numOfData;
}DBLinkedList;
typedef DBLinkedList List;
void ListInit(List* plist); // 리스트 초기화
void LInsert(List* plist, Data data); // 새 노드 추가
int LFirst(List* plist, Data* pdata); // 데이터 조회 (첫 번째 노드의 데이터 조회)
int LNext(List* plist, Data* pdata); // 두 번째 이후의 노드 데이터 조회
int LPrevious(List* plist, Data* pdata); // LNext의 반대 방향으로 데이터 조회
int LCount(List* plist); // 리스트에 있는 노드의 개수 반환<file_sep>/열혈자료구조/LinkedList/Circular_Linked_List/CLinkedList.c
/* Circular Linked List */
#include <stdio.h>
#include <stdlib.h>
#include "CLinkedList.h"
void ListInit(List* plist) {
plist->tail = NULL;
plist->cur = NULL;
plist->before = NULL;
plist->numOfData = 0;
}
// 새 노드를 head에서 추가하는 함수
void LInsertFront(List* plist, Data data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
if (plist->tail == NULL) {
plist->tail = newNode;
newNode->next = newNode;
}
else {
newNode->next = plist->tail->next;
plist->tail->next = newNode;
}
(plist->numOfData)++;
}
// 새 노드를 tail에 추가하는 함수
void LInsert(List* plist, Data data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
if (plist->tail == NULL) {
plist->tail = newNode;
newNode->next = newNode;
}
else {
newNode->next = plist->tail->next;
plist->tail->next = newNode;
plist->tail = newNode;
}
(plist->numOfData)++;
}
// 데이터 조회 ( 머리 부분을 시작으로 가리킨다.)
int LFirst(List* plist, Data* pdata) {
if (plist->tail == NULL)
return FALSE;
plist->before = plist->tail;
plist->cur = plist->tail->next;
*pdata = plist->cur->data;
return TRUE;
}
// 다음 데이터 조회
int LNext(List* plist, Data* pdata) {
if (plist->tail == NULL)
return FALSE;
plist->before = plist->cur;
plist->cur = plist->cur->next;
*pdata = plist->cur->data;
return TRUE;
}
// 노드 삭제
Data LRemove(List* plist) {
Node* rpos = plist->cur;
Data rdata = rpos->data;
if (rpos == plist->tail) {
if (plist->tail == plist->tail->next)
plist->tail = NULL;
else
plist->tail = plist->before;
}
plist->before->next = plist->cur->next;
plist->cur = plist->before;
free(rpos);
(plist->numOfData)--;
return rdata;
}
// 남은 노드의 수 반환
int LCount(List* plist) {
return plist->numOfData;
}<file_sep>/Doit/Array/chap02-4.cpp
/* int형 배열을 동적으로 생성하고 해제한다. */
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
int* a;
int na;
printf("요소 개수 : ");
scanf_s("%d", &na);
a = (int*)calloc(na, sizeof(int));
if (a == NULL)
puts("메모리 할당에 실패");
else
{
printf("%d개의 정수를 입력.\n", na);
for (i = 0; i < na; ++i)
{
printf("a[%d] : ", i);
scanf_s("%d", &a[i]);
}
printf("각 요소의 값은 다음과 같다.\n");
for (i = 0; i < na; ++i)
printf("a[%d] = %d\n", i, a[i]);
free(a);
}
return 0;
}
<file_sep>/열혈자료구조/Recursive/RecursiveFunc.c
#include <stdio.h>
void Recursive(int num) {
if (num <= 0) return;
printf("Recursive call! %d\n", num);
Recursive(num - 1);
}
int main() {
Recursive(3);
return 0;
}<file_sep>/공부한것들/SegmentTree.c
#include <stdio.h>
#define NUMBER 7
int a[] = { 7,1,9,5,6,4,1 };
int tree[4 * NUMBER]; // 4를 곱하면 모든 범위가 커버 가능하다.
int init(int start, int end, int node)
{
if (start == end) return tree[node] = a[start]; // 리프 노드인 경우 배열의 값이 그대로 들어간다.
int mid = (start + end) / 2;
// 재귀적으로 두 부분으로 나눈 뒤에 그 합을 자기 자신으로 한다. (왼쪽 자식 합 + 오른쪽 자식 합)
return tree[node] = init(start, mid, node * 2) + init(mid + 1, end, node * 2 + 1);
}
// start : 시작, end : 끝
// left, right : 구간의 합을 구하고자 하는 범위
// node : 노드 인덱스
int sum(int start, int end, int node, int left, int right)
{
// 범위 밖에 있는 경우
if (left > end || right < start) return 0;
// 범위 안에 있는 경우
if (left <= start && end <= right) return tree[node];
// 그렇지 않다면 두 부분으로 나누어 합 구하기
int mid = (start + end) / 2;
return sum(start, mid, node * 2, left, right) + sum(mid + 1, end, node * 2 + 1, left, right);
}
// start : 시작, end : 끝
// index : 구간 합을 수정하고자 하는 노드
// dif : 수정할 값
void update(int start, int end, int node, int index, int dif)
{
// 범위 밖에 있는 경우
if (index < start || index > end) return;
// 범위 안에 있으면 내려가며 다른 원소도 갱신
tree[node] += dif;
// 리프 노드이면
if (start == end) return;
int mid = (start + end) / 2;
update(start, mid, node * 2, index, dif);
update(mid + 1, end, node * 2 + 1, index, dif);
}
int main()
{
// 구간 합 트리 생성하기
init(0, NUMBER - 1, 1);
// 구간 합 구하기
printf("0부터 6까지의 구간 합: %d\n", sum(0, NUMBER - 1, 1, 0, 6));
// 구간 합 갱신하기
printf("인덱스 5의 원소를 +3만큼 수정\n");
update(0, NUMBER - 1, 1, 5, 3);
// 구간 합 다시 구하기
printf("3부터 6까지의 구간 합: %d\n", sum(0, NUMBER - 1, 1, 3, 6));
printf("0부터 6까지의 구간 합: %d\n", sum(0, NUMBER - 1, 1, 0, 6));
return 0;
}<file_sep>/Doit/Array/chap02-9.cpp
/* 1000 이하의 소수를 나열한다. */
#include <stdio.h>
int main()
{
int i, n;
unsigned long counter = 0;
for (n = 2; n <= 1000; ++n)
{
for (i = 2; i < n; ++i)
{
++counter;
if (n % i == 0)
break;
}
if (n == i)
printf("%d\n", n);
}
printf("나눗셈을 실행한 횟수 : %lu\n", counter);
return 0;
}<file_sep>/Doit/Stack&Queue/RingBuffer.c
/* 원하는 개수만큼 데이터를 입력하고, 요소의 개수가 n인 배열에는 최근에 입력한 n개만 저장 */
#include <stdio.h>
#define N 10
int main()
{
int i;
int a[N];
int cnt = 0;
int retry;
puts("정수를 입력하세요.");
do
{
printf("%d번째 정수 : ", cnt + 1);
scanf_s("%d", &a[cnt++ % N]);
printf("계속할까요?(Yes ... 1 / No ... 0) : ");
scanf_s("%d", &retry);
} while (retry == 1);
i = cnt - N;
if (i < 0) i = 0;
for (; i < cnt; ++i)
printf("%2d번째 정수 = %d\n", i + 1, a[i % N]);
return 0;
}<file_sep>/Doit/Array/chap02-3.cpp
/* int형 객체를 동적으로 생성하고 해제한다. */
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* x;
x = (int*)calloc(1, sizeof(int));
if (x == NULL)
puts("메모리 할당에 실패");
else
{
*x = 57;
printf("*x = %d\n", *x);
free(x);
}
return 0;
}<file_sep>/열혈자료구조/ArrayList/NameCard.h
#pragma once
#define NAME_LEN 30
#define PHONE_LEN 30
typedef struct __namecard {
char name[NAME_LEN];
char phone[PHONE_LEN];
}NameCard;
//NameCard 구조체 변수의 동적 할당 및 초기화 후 주소 값 반환
NameCard * MakeNameCard(const char * name, const char * phone);
//NameCard 구조체 변수의 정보 출력
void ShowNameCardInfo(NameCard * pcard);
//이름이 같으면 0, 다르면 0이 아닌 값 반환
int NameCompare(NameCard *pcard, const char * name);
//전화번호 정보를 변경
void ChangePhoneNum(NameCard * pcard, const char * phone);<file_sep>/Doit/String/strptr.c
/* 문자열을 포인터를 사용해서 출력 */
#include <stdio.h>
int main()
{
char* pt = "12345"; // 포인터 pt는 문자열 리터널 "12345"의 첫 번째 문자 '1'를 가리킨다.
printf("포인터 pt는 %s를 가리킨다.\n", pt);
return 0;
}<file_sep>/Doit/Array/chap02-12.cpp
/* 한 해의 지난 날 수를 구한다. */
#include <stdio.h>
int mdays[][12] = {
{31,28,31,30,31,30,31,31,30,31,30,31},
{31,29,31,30,31,30,31,31,30,31,30,31}
};
// 윤년인지?
// 4로 나누어 떨어지는 년도는 윤년이다.
// 그 중 100으로 나누어 떨어지는 년도는 윤년이 아니다.
// 400으로 나누어 떨어지는 년도는 무조건 윤년이다.
int isleap(int year)
{
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
int dayofyear(int y, int m, int d)
{
int i;
int days = d;
for (i = 1; i < m; ++i)
days += mdays[isleap(y)][i - 1];
return days;
}
int main()
{
int year, month, day;
int retry;
do
{
printf("년 : "); scanf_s("%d", &year);
printf("월 : "); scanf_s("%d", &month);
printf("일 : "); scanf_s("%d", &day);
printf("%d년의 %d일째입니다.\n", year, dayofyear(year, month, day));
printf("다시 할까요?(1... 예/0 ... 아니오) : ");
scanf_s("%d", &retry);
} while (retry == 1);
return 0;
}<file_sep>/Doit/String/bf_match.c
/* 브루트-포스법으로 문자열 검색 */
#include <stdio.h>
//int bf_match(const char txt[], const char pat[])
int bf_match(const char* txt, const char* pat)
{
int pt = 0; // text 인덱스
int pp = 0; // pattern 인덱스
while (txt[pt] != '\0' && pat[pp] != '\0')
{
if (txt[pt] == pat[pp])
{
pt++;
pp++;
}
// 중간에 일치하지 않는 부분이 나오면
else
{
pt = pt - pp + 1;
pp = 0;
}
}
if (pat[pp] == '\0')
return pt - pp;
return -1;
}
int main()
{
int idx;
char s1[256]; // text
char s2[256]; // pattern
puts("bruteforce");
printf("text : "); scanf_s("%s", s1, 256);
printf("pattern : "); scanf_s("%s", s2, 256);
idx = bf_match(s1, s2);
if (idx == -1)
puts("text에 pattern이 없다.");
else
printf("%d번째 문자부터 match하다.\n", idx + 1);
return 0;
}<file_sep>/열혈자료구조/Graph/BFS/ALGraphBFS.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ALGraphBFS.h"
#include "DLinkedList.h"
#include "CircularQueue.h"
int WhoIsPrecede(int data1, int data2) {
if (data1 < data2)
return 0;
else
return 1;
}
void GraphInit(ALGraph* pg, int nv) {
int i;
// 정점의 수에 해당하는 길이의 리스트 배열을 생성한다.
pg->adjList = (List*)malloc(sizeof(List) * nv);
pg->numV = nv; // 정점의 수는 nv에 저장된 값으로 결정
pg->numE = 0; // 초기의 간선 수는 0개
// 정점의 수만큼 생선된 리스트들을 초기화한다.
for (i = 0; i < nv; i++) {
ListInit(&(pg->adjList[i])); // 인접리스트는 인덱스의 시작이 0부터
SetSortRule(&(pg->adjList[i]), WhoIsPrecede);
}
pg->visitInfo = (int*)malloc(sizeof(int) * pg->numV);
memset(pg->visitInfo, 0, sizeof(int) * pg->numV);
}
void GraphDestroy(ALGraph* pg) {
if (pg->adjList != NULL)
free(pg->adjList); // 동적으로 할당된 연결 리스트의 소멸
if (pg->visitInfo != NULL)
free(pg->visitInfo);
}
void AddEdge(ALGraph* pg, int fromV, int toV) {
// 구현은 무방향 그래프이므로 양쪽 모두 연결해준다.
// 정점 fromV의 연결 리스트에 정점 toV의 정보 추가
LInsert(&(pg->adjList[fromV]), toV);
// 정점 toV의 연결 리스트에 정점 fromV의 정보 추가
LInsert(&(pg->adjList[toV]), fromV);
pg->numE += 1;
}
void ShowGraphEdgeInfo(ALGraph* pg) {
int i;
int vx;
for (i = 0; i < pg->numV; i++) {
printf("%c와 연결된 정점: ", i + 65);
if (LFirst(&(pg->adjList[i]), &vx)) {
printf("%c ", vx + 65);
while (LNext(&(pg->adjList[i]), &vx)) {
printf("%c ", vx + 65);
}
}
printf("\n");
}
}
int VisitVertex(ALGraph* pg, int visitV) {
if (pg->visitInfo[visitV] == 0) {
pg->visitInfo[visitV] = 1;
printf("%c ", visitV + 65);
return TRUE;
}
return FALSE;
}
void BFShowGraphVertex(ALGraph* pg, int startV) {
Queue queue;
int visitV = startV;
int nextV;
QueueInit(&queue);
VisitVertex(pg, visitV); // 시작 정점을 탐색한다.
// 아래의 while문에서는 visitV와 연결된 모든 정점에 방문한다.
while (LFirst(&(pg->adjList[visitV]), &nextV) == TRUE) {
if (VisitVertex(pg, nextV) == TRUE) {
Enqueue(&queue, nextV); // nextV에 방문했으니 큐에 저장한다.
}
while (LNext(&(pg->adjList[visitV]), &nextV) == TRUE) {
if (VisitVertex(pg, nextV) == TRUE) {
Enqueue(&queue, nextV);
}
}
if (QIsEmpty(&queue) == TRUE) // 큐가 비면 BFS 종료
break;
else
visitV = Dequeue(&queue); // 큐에서 하나 꺼내어 while문 다시 시작
}
memset(pg->visitInfo, 0, sizeof(int) * pg->numV); // 탐색 정보 초기화
}<file_sep>/Doit/Stack&Queue/ArrayStack/stack.h
#ifndef ___IntStack // ___IntStack를 define 하지 않았다면, (if not defined)
#define ___IntStack // endif가 나오기 전까지 이 부분을 포함시켜라
typedef struct
{
int max;
int ptr;
int* stk;
}IntStack;
int Initialize(IntStack* s, int max);
int Push(IntStack* s, int x);
int Pop(IntStack* s, int* x);
int Peek(const IntStack* s, int* x);
void Clear(IntStack* s);
int Capacity(const IntStack* s);
int Size(const IntStack* s);
int IsEmpty(const IntStack* s);
int IsFull(const IntStack* s);
int Search(const IntStack* s, int x);
void Print(const IntStack* s);
void Terminate(IntStack* s);
#endif<file_sep>/Doit/String/str_len2.c
/* 문자열의 길이를 구해보자. */
#include <stdio.h>
int str_len(const char* s)
{
int len = 0;
while (*s++)
len++;
return len;
}
int main()
{
char str[256];
printf("문자열 : ");
scanf_s("%s", str, 256);
printf("이 문자열의 길이는 %d이다.\n", str_len(str));
return 0;
}<file_sep>/Doit/Recursive/eight_queen.c
/* 8퀸 문제 풀이 */
#include <stdio.h>
int flag_a[8]; // 각 행에 퀸을 배치했는지 체크하는 배열
int flag_b[15]; // 대각선 ↗에 퀸을 배치했는지 체크하는 배열
int flag_c[15]; // 대각선 ↘에 퀸을 배치했는지 체크하는 배열
int pos[8];
int counter;
void print()
{
int i;
for (i = 0; i < 8; ++i)
printf("%2d", pos[i]);
putchar('\n');
}
void set(int i)
{
int j;
for (j = 0; j < 8; ++j)
{
if (!flag_a[j] && !flag_b[i + j] && !flag_c[i - j + 7])
{
pos[i] = j; // i열 j행에 퀸을 배치
if (i == 7)
{
print();
++counter;
}
else
{
flag_a[j] = flag_b[i + j] = flag_c[i - j + 7] = 1;
set(i + 1);
flag_a[j] = flag_b[i + j] = flag_c[i - j + 7] = 0;
}
}
}
}
int main()
{
int i;
for (i = 0; i < 8; ++i)
flag_a[i] = 0;
for (i = 0; i < 15; ++i)
flag_b[i] = flag_c[i] = 0;
set(0);
printf("출력횟수 : %d\n", counter); // 92 가지
return 0;
} | fbc45de654bf7828b77df1a2c5906924ffbea16a | [
"Markdown",
"C",
"C++"
] | 55 | C++ | paparoni95/DataStructure | 326f3b092d773613e2ba5020d5842c286f5da67d | 18bd77676bfd2e76a6b471b21a332b4987fb47b6 | |
refs/heads/master | <file_sep>using System.Collections.Generic;
using System.Threading.Tasks;
using Tasks.Api.Entities;
namespace Tasks.Api.Data.Interfaces
{
public interface IRoomRoleRepository : IRepository<RoomRole>
{
Task<IEnumerable<RoomRole>> FindAllRoles();
Task<RoomRole> FindWithName(string roleName);
}
}<file_sep>using Microsoft.AspNetCore.Http;
namespace Tasks.Api.Exceptions
{
public class AccessRightApiException : ApiException
{
public AccessRightApiException(string message) : base(message)
{
}
public override int StatusCode => StatusCodes.Status403Forbidden;
}
}<file_sep>using System;
namespace Tasks.Api.Exceptions
{
[Serializable]
public abstract class ApiException : Exception
{
protected ApiException(string message) : base(message)
{
}
public abstract int StatusCode { get; }
}
}<file_sep>using Microsoft.EntityFrameworkCore;
namespace Users.Api.Data
{
public class DatabaseInitializer
{
private readonly ApplicationContext _applicationContext;
public DatabaseInitializer(ApplicationContext applicationContext) => _applicationContext = applicationContext;
public void Initialize() => _applicationContext.Database.Migrate();
}
}<file_sep>using System.Collections.Generic;
namespace Tasks.Api.Entities
{
public class Roles
{
public const string Owner = "Owner";
public const string Administrator = "Admin";
public const string Member = "Member";
public static IEnumerable<string> AllRoles()
{
yield return Owner;
yield return Administrator;
yield return Member;
}
}
}<file_sep>using System;
namespace Tasks.Api.Entities
{
public class UserInTheRoom
{
public Guid RoomId { get; set; }
public Room Room { get; set; }
public Guid UserId { get; set; }
public User User { get; set; }
public Guid RoomRoleId { get; set; }
public RoomRole RoomRole { get; set; }
}
}<file_sep>using System.ComponentModel.DataAnnotations;
namespace Tasks.Api.ViewModels.RoomViewModels
{
public class AddOrUpdateRoomViewModel
{
[StringLength(30)]
[Required]
public string RoomName { get; set; }
public string? RoomDescription { get; set; }
}
}<file_sep>using AutoMapper;
using Tasks.Api.Entities;
using Tasks.Api.ViewModels.RoleViewModels;
namespace Tasks.Api.Profiles
{
public class RoleProfile : Profile
{
public RoleProfile()
{
CreateMap<RoomRole, RoleViewModel>();
}
}
}<file_sep>using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityServer4;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Identity;
using Users.Data.Entities;
namespace IdentityServer
{
public class ProfileService : IProfileService
{
private readonly IUserClaimsPrincipalFactory<User> _claimsFactory;
private readonly UserManager<User> _userManager;
public ProfileService(IUserClaimsPrincipalFactory<User> claimsFactory, UserManager<User> userManager)
{
_claimsFactory = claimsFactory;
_userManager = userManager;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var user = await _userManager.FindByIdAsync(context.Subject.GetSubjectId());
var principal = await _claimsFactory.CreateAsync(user);
var claims = principal.Claims.ToList();
claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();
if (context.Caller == IdentityServerConstants.ProfileDataCallers.UserInfoEndpoint &&
context.RequestedClaimTypes.Contains("full_name"))
{
claims.Add(new Claim("last_name", user.LastName));
claims.Add(new Claim("first_name", user.FirstName));
claims.Add(new Claim("patronymic", user.Patronymic));
}
context.IssuedClaims = claims;
}
public async Task IsActiveAsync(IsActiveContext context)
{
var user = await _userManager.FindByIdAsync(context.Subject.GetSubjectId());
context.IsActive = user != null;
}
}
}<file_sep>using System;
namespace Users.Data
{
public class UserRegistered
{
public Guid UserId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Patronymic { get; set; }
}
}<file_sep>using System;
using System.ComponentModel.DataAnnotations;
namespace Tasks.Api.ViewModels.TaskViewModels
{
public class AddTaskViewModel
{
[Required]
[StringLength(30, MinimumLength = 1)]
public string TaskName { get; set; }
[Required]
[MinLength(1)]
public string? TaskContent { get; set; }
public string? Details { get; set; }
public DateTime DeadlineTime { get; set; }
}
}<file_sep>using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Tasks.Api.Migrations
{
public partial class FixedIncorrectRelatioRoomTaskWithUser : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_RoomTasks_UserInTheRoom_TaskCreatorRoomId_TaskCreatorUserId",
table: "RoomTasks");
migrationBuilder.DropIndex(
name: "IX_RoomTasks_TaskCreatorRoomId_TaskCreatorUserId",
table: "RoomTasks");
migrationBuilder.DropColumn(
name: "TaskCreatorRoomId",
table: "RoomTasks");
migrationBuilder.DropColumn(
name: "TaskCreatorUserId",
table: "RoomTasks");
migrationBuilder.CreateIndex(
name: "IX_RoomTasks_TaskCreatorId",
table: "RoomTasks",
column: "TaskCreatorId");
migrationBuilder.AddForeignKey(
name: "FK_RoomTasks_Users_TaskCreatorId",
table: "RoomTasks",
column: "TaskCreatorId",
principalTable: "Users",
principalColumn: "UserId",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_RoomTasks_Users_TaskCreatorId",
table: "RoomTasks");
migrationBuilder.DropIndex(
name: "IX_RoomTasks_TaskCreatorId",
table: "RoomTasks");
migrationBuilder.AddColumn<Guid>(
name: "TaskCreatorRoomId",
table: "RoomTasks",
type: "uuid",
nullable: true);
migrationBuilder.AddColumn<Guid>(
name: "TaskCreatorUserId",
table: "RoomTasks",
type: "uuid",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_RoomTasks_TaskCreatorRoomId_TaskCreatorUserId",
table: "RoomTasks",
columns: new[] { "TaskCreatorRoomId", "TaskCreatorUserId" });
migrationBuilder.AddForeignKey(
name: "FK_RoomTasks_UserInTheRoom_TaskCreatorRoomId_TaskCreatorUserId",
table: "RoomTasks",
columns: new[] { "TaskCreatorRoomId", "TaskCreatorUserId" },
principalTable: "UserInTheRoom",
principalColumns: new[] { "RoomId", "UserId" },
onDelete: ReferentialAction.Restrict);
}
}
}
<file_sep>using System;
namespace Tasks.Api.ViewModels.RoleViewModels
{
public class RoleViewModel
{
public Guid RoomRoleId { get; set; }
public string RoomRoleName { get; set; }
public string? RoomRoleDescription { get; set; }
}
}<file_sep>using System;
namespace Users.Api.Exceptions
{
public abstract class ApiException : Exception
{
public abstract int StatusCode { get; }
}
public abstract class ApiException<T> : ApiException
{
protected ApiException(T errorData) => ErrorData = errorData;
public T ErrorData { get; set; }
}
}<file_sep>using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Tasks.Api.Migrations
{
public partial class UserNowCanHaveOnlyOneRole : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "RoomRoleUserInRoom");
migrationBuilder.DropColumn(
name: "OwnerId",
table: "Rooms");
migrationBuilder.AddColumn<Guid>(
name: "RoomRoleId",
table: "UsersInRoom",
type: "uuid",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"));
migrationBuilder.CreateIndex(
name: "IX_UsersInRoom_RoomRoleId",
table: "UsersInRoom",
column: "RoomRoleId");
migrationBuilder.AddForeignKey(
name: "FK_UsersInRoom_RoomRoles_RoomRoleId",
table: "UsersInRoom",
column: "RoomRoleId",
principalTable: "RoomRoles",
principalColumn: "RoomRoleId",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_UsersInRoom_RoomRoles_RoomRoleId",
table: "UsersInRoom");
migrationBuilder.DropIndex(
name: "IX_UsersInRoom_RoomRoleId",
table: "UsersInRoom");
migrationBuilder.DropColumn(
name: "RoomRoleId",
table: "UsersInRoom");
migrationBuilder.AddColumn<Guid>(
name: "OwnerId",
table: "Rooms",
type: "uuid",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"));
migrationBuilder.CreateTable(
name: "RoomRoleUserInRoom",
columns: table => new
{
RoomRolesRoomRoleId = table.Column<Guid>(type: "uuid", nullable: false),
UserInRoomsRoomId = table.Column<Guid>(type: "uuid", nullable: false),
UserInRoomsUserId = table.Column<Guid>(type: "uuid", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RoomRoleUserInRoom", x => new { x.RoomRolesRoomRoleId, x.UserInRoomsRoomId, x.UserInRoomsUserId });
table.ForeignKey(
name: "FK_RoomRoleUserInRoom_RoomRoles_RoomRolesRoomRoleId",
column: x => x.RoomRolesRoomRoleId,
principalTable: "RoomRoles",
principalColumn: "RoomRoleId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_RoomRoleUserInRoom_UsersInRoom_UserInRoomsRoomId_UserInRoom~",
columns: x => new { x.UserInRoomsRoomId, x.UserInRoomsUserId },
principalTable: "UsersInRoom",
principalColumns: new[] { "RoomId", "UserId" },
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_RoomRoleUserInRoom_UserInRoomsRoomId_UserInRoomsUserId",
table: "RoomRoleUserInRoom",
columns: new[] { "UserInRoomsRoomId", "UserInRoomsUserId" });
}
}
}
<file_sep>using System;
namespace Tasks.Api.ViewModels.TaskViewModels
{
public class TaskViewModel
{
public Guid RoomTaskId { get; set; }
public string TaskName { get; set; }
public string TaskContent { get; set; }
public string Details { get; set; }
public bool IsCompleted { get; set; }
public DateTime TaskCreationTime { get; set; } = DateTime.Now;
public Guid TaskCreatorId { get; set; }
public DateTime DeadlineTime { get; set; }
}
}<file_sep>using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Tasks.Api.Data
{
public interface IRepository<T> where T : class
{
public Task<T> Create(T element);
public Task<T?> Find(Expression<Func<T, bool>> expression);
public void Update(T element);
public void Delete(T element);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using IdentityServer4.AccessTokenValidation;
using MassTransit;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Tasks.Api.Data;
using Tasks.Api.MassTransit;
using Tasks.Api.Services;
namespace Tasks.Api
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration) => _configuration = configuration;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationContext>(options =>
{
options.UseNpgsql(_configuration.GetConnectionString("TasksDb") + _configuration["DbName"]);
});
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = _configuration["IdentityServer:Authority"];
options.RequireHttpsMetadata = false;
});
services.AddSwaggerGen(options =>
{
options.EnableAnnotations();
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "RoomsApi",
Description = "Service for managing rooms and tasks",
Version = "v1",
Contact = new OpenApiContact
{
Email = "<EMAIL>",
Name = "<NAME>"
}
});
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
Password = new OpenApiOAuthFlow
{
TokenUrl = new Uri(_configuration["IdentityServer:TokenUrl"])
}
}
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "oauth2"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header
},
new List<string>()
}
});
string xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
string filePath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(filePath);
});
services.AddAutoMapper(Assembly.GetExecutingAssembly());
services.AddScoped<UnitOfWork>();
services.AddScoped<UserService>();
services.AddScoped<RoomService>();
services.AddScoped<RoomTaskService>();
services.AddScoped<RoleService>();
services.AddTransient<DatabaseInitializer>();
services.AddControllers();
services.AddMassTransit(x =>
{
x.AddConsumer<UserRegisteredConsumer>();
x.AddConsumer<ProfileUpdatedConsumer>();
x.UsingRabbitMq((context, configurator) =>
{
configurator.Host(_configuration["MassTransit:Host"],
_configuration["MassTransit:VirtualHost"], options =>
{
options.Username(_configuration["MassTransit:Username"]);
options.Password(_configuration["MassTransit:Password"]);
});
configurator.ReceiveEndpoint("registered-users",
e => { e.ConfigureConsumer<UserRegisteredConsumer>(context); });
configurator.ReceiveEndpoint("updated-profiles",
e => { e.ConfigureConsumer<ProfileUpdatedConsumer>(context); });
});
});
services.AddMassTransitHostedService();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DatabaseInitializer databaseInitializer)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
databaseInitializer.Initialize();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.RoutePrefix = "";
options.SwaggerEndpoint("/swagger/v1/swagger.json", "TasksApi");
options.DocumentTitle = "TasksApi";
options.OAuthClientId(_configuration["IdentityServer:ClientId"]);
options.OAuthClientSecret(_configuration["IdentityServer:Secret"]);
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<ExceptionMiddleware>();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
}<file_sep>using IdentityServer.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Users.Data.Entities;
namespace IdentityServer
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration) => _configuration = configuration;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationContext>(options =>
{
options.UseNpgsql(_configuration.GetConnectionString("Identity") + _configuration["DbName"]);
})
.AddIdentity<User, Role>()
.AddEntityFrameworkStores<ApplicationContext>();
services.AddIdentityServer(options => { options.IssuerUri = _configuration["IssuerUri"]; })
.AddInMemoryApiScopes(Config.ApiScopes)
.AddInMemoryClients(Config.GetConfiguredClients(_configuration))
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddAspNetIdentity<User>()
.AddProfileService<ProfileService>()
.AddDeveloperSigningCredential();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseIdentityServer();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
}<file_sep>using System;
using Tasks.Api.ViewModels.UserViewModel;
namespace Tasks.Api.ViewModels.RoleViewModels
{
public class UserWithRoleViewModel
{
public UserFullNameViewModel User { get; set; }
public Guid RoleId { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Tasks.Api.Data;
using Tasks.Api.Entities;
using Tasks.Api.Exceptions;
using Tasks.Api.ViewModels.RoomViewModels;
namespace Tasks.Api.Services
{
public class RoomService
{
private readonly IMapper _mapper;
private readonly UnitOfWork _unitOfWork;
private readonly UserService _userService;
public RoomService(IMapper mapper, UnitOfWork unitOfWork, UserService userService)
{
_mapper = mapper;
_unitOfWork = unitOfWork;
_userService = userService;
}
public async Task<RoomViewModel> CreateRoom(AddOrUpdateRoomViewModel viewModel, Guid userId)
{
var room = _mapper.Map<Room>(viewModel);
room.UsersInRoom = new List<UserInTheRoom>
{
new()
{
UserId = userId,
RoomRole = await _unitOfWork.RoomRoleRepository.FindWithName(Roles.Owner)
}
};
var createdRoom = await _unitOfWork.RoomRepository.Create(room);
await _unitOfWork.SaveChangesAsync();
return _mapper.Map<RoomViewModel>(createdRoom);
}
public async Task UpdateRoom(AddOrUpdateRoomViewModel viewModel, Guid roomId, Guid userId)
{
var room = await _unitOfWork.RoomRepository.Find(x => x.RoomId == roomId);
if (room == null)
throw new NotFoundApiException(AppExceptions.RoomNotFoundException);
if (!await _userService.CheckUserHasAnyRole(roomId, userId, Roles.Owner, Roles.Administrator))
throw new AccessRightApiException(AppExceptions.CreatorOrAdministratorOnlyCanDoThisException);
room = _mapper.Map(viewModel, room);
_unitOfWork.RoomRepository.Update(room);
await _unitOfWork.SaveChangesAsync();
}
public async Task DeleteRoom(Guid roomId, Guid userId)
{
var room = await _unitOfWork.RoomRepository.Find(x => x.RoomId == roomId);
if (room == null)
throw new NotFoundApiException(AppExceptions.RoomNotFoundException);
if (!await _userService.CheckUserIsInRole(roomId, userId, Roles.Owner))
throw new AccessRightApiException(AppExceptions.CreatorOnlyCanPerformThisActionException);
_unitOfWork.RoomRepository.Delete(room);
await _unitOfWork.SaveChangesAsync();
}
public async Task<IEnumerable<RoomViewModel>> FindRoomsForUser(Guid userId)
{
var rooms = await _unitOfWork.RoomRepository.FindRoomsForUser(userId);
return _mapper.Map<IEnumerable<RoomViewModel>>(rooms);
}
public async Task<Room?> FindRoomWithUsers(Guid roomId) =>
await _unitOfWork.RoomRepository.FindRoomWithUsers(roomId);
public async Task<RoomViewModel?> FindById(Guid roomId)
{
var room = await _unitOfWork.RoomRepository.Find(x => x.RoomId == roomId);
return _mapper.Map<RoomViewModel>(room);
}
public async Task<RoomViewModel?> JoinUserToRoom(Guid roomId, Guid userId)
{
var room = await _unitOfWork.RoomRepository.FindRoomWithUsers(roomId);
if (room == null)
throw new NotFoundApiException(AppExceptions.IncorrectUrlException);
var mappedRoom = _mapper.Map<RoomViewModel>(room);
if (await _unitOfWork.RoomRepository.FindUserInRoom(roomId, userId) != null)
throw new AlreadyDoneApiException(AppExceptions.AlreadyMember);
room.UsersInRoom.Add(new UserInTheRoom
{
UserId = userId,
RoomRole = await _unitOfWork.RoomRoleRepository.FindWithName(Roles.Member)
});
await _unitOfWork.SaveChangesAsync();
return mappedRoom;
}
public async Task ThrowIfRoomNotFound(Guid roomId)
{
if (await FindById(roomId) == null)
throw new NotFoundApiException(AppExceptions.RoomNotFoundException);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Tasks.Api.Entities;
namespace Tasks.Api.Data.Interfaces
{
public interface IRoomTaskRepository : IRepository<RoomTask>
{
Task<IEnumerable<RoomTask>> FindTasksInRoom(Guid roomId);
}
}<file_sep>using System;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using MassTransit;
using Tasks.Api.Data;
using Users.Data;
namespace Tasks.Api.MassTransit
{
public class ProfileUpdatedConsumer : IConsumer<ProfileUpdated>
{
private readonly ApplicationContext _applicationContext;
private readonly IMapper _mapper;
public ProfileUpdatedConsumer(IMapper mapper, ApplicationContext applicationContext)
{
_mapper = mapper;
_applicationContext = applicationContext;
}
public async Task Consume(ConsumeContext<ProfileUpdated> context)
{
var updatedProfile = context.Message;
var user = _applicationContext.Users.FirstOrDefault(x => x.UserId == updatedProfile.UserId);
var updatedUser = _mapper.Map(updatedProfile, user);
_applicationContext.Users.Update(updatedUser ?? throw new Exception("Can`t map updated profile"));
await _applicationContext.SaveChangesAsync();
}
}
}<file_sep>using Microsoft.EntityFrameworkCore;
using Tasks.Api.Entities;
namespace Tasks.Api.Data
{
public class ApplicationContext : DbContext
{
public ApplicationContext(DbContextOptions options) : base(options)
{
}
public DbSet<Room> Rooms { get; set; }
public DbSet<UserInTheRoom> UsersInRoom { get; set; }
public DbSet<RoomRole> RoomRoles { get; set; }
public DbSet<RoomTask> RoomTasks { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<UserInTheRoom> UsersInTheRooms { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder
.Entity<UserInTheRoom>()
.HasKey(x => new {x.RoomId, RoomUserId = x.UserId});
}
}<file_sep>using System;
using System.Collections.Generic;
namespace Tasks.Api.Entities
{
public class Room
{
public Guid RoomId { get; set; }
public string RoomName { get; set; }
public string? RoomDescription { get; set; }
public DateTime CreationDate { get; set; } = DateTime.Now;
public List<UserInTheRoom> UsersInRoom { get; set; }
public List<RoomTask> RoomTasks { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using Tasks.Api.Services;
using Tasks.Api.ViewModels.TaskViewModels;
using Tasks.Api.ViewModels.UserViewModel;
namespace Tasks.Api.Controllers
{
/// <summary>
/// Everything about tasks
/// </summary>
[Authorize]
[ApiController]
[Route("api/room/{roomId:guid}/[controller]")]
[SwaggerTag("Everything about tasks")]
public class TasksController : ControllerBase
{
private readonly RoomTaskService _roomTaskService;
/// <inheritdoc />
public TasksController(RoomTaskService roomTaskService) => _roomTaskService = roomTaskService;
/// <summary>
/// Finds all tasks in room
/// </summary>
/// <param name="roomId"></param>
/// <returns></returns>
[HttpGet]
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status204NoContent)]
[SwaggerResponse(StatusCodes.Status403Forbidden)]
[SwaggerResponse(StatusCodes.Status404NotFound)]
[ProducesDefaultResponseType]
public async Task<ActionResult<IEnumerable<TaskViewModel>>> AllTasksInRoom(Guid roomId)
{
var tasks = await _roomTaskService.FindAllTasksInRoom(roomId);
if (!tasks.Any())
return NoContent();
return Ok(tasks);
}
/// <summary>
/// Finds task in room by id
/// </summary>
/// <param name="roomId"></param>
/// <param name="taskId"></param>
/// <returns></returns>
[HttpGet("{taskId:guid}")]
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status403Forbidden)]
[SwaggerResponse(StatusCodes.Status404NotFound)]
public async Task<ActionResult<TaskViewModel>> Find(Guid roomId, Guid taskId)
{
var task = await _roomTaskService.FindTask(roomId, taskId, UserService.GetCurrentUserId(HttpContext));
if (task == null)
return NotFound();
return Ok(task);
}
/// <summary>
/// Finds creator of the task in room
/// </summary>
/// <param name="roomId"></param>
/// <param name="taskId"></param>
/// <returns></returns>
[HttpGet("{taskId:guid}/creator")]
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status403Forbidden)]
[SwaggerResponse(StatusCodes.Status404NotFound)]
public async Task<ActionResult<UserFullNameViewModel>> FindCreator(Guid roomId, Guid taskId)
{
var creator =
await _roomTaskService.FindTaskCreator(roomId, taskId, UserService.GetCurrentUserId(HttpContext));
return Ok(creator);
}
/// <summary>
/// Marks task completed
/// </summary>
/// <param name="roomId"></param>
/// <param name="taskId"></param>
/// <returns></returns>
[HttpGet("{taskId:guid}/complete")]
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status403Forbidden)]
[SwaggerResponse(StatusCodes.Status404NotFound)]
public async Task<ActionResult<UserFullNameViewModel>> CompleteTask(Guid roomId, Guid taskId) => Ok(
await _roomTaskService.CompleteTask(roomId, taskId, UserService.GetCurrentUserId(HttpContext)));
/// <summary>
/// Creates task
/// </summary>
/// <param name="roomId"></param>
/// <param name="viewModel"></param>
/// <returns></returns>
[HttpPost]
[SwaggerResponse(StatusCodes.Status201Created)]
[SwaggerResponse(StatusCodes.Status403Forbidden)]
[SwaggerResponse(StatusCodes.Status404NotFound)]
public async Task<CreatedAtActionResult> Create(Guid roomId, AddTaskViewModel viewModel)
{
var addedTask =
await _roomTaskService.CreateTask(roomId, viewModel, UserService.GetCurrentUserId(HttpContext));
return CreatedAtAction(nameof(Find), new {roomId = addedTask.RoomTaskId, taskId = addedTask.RoomTaskId},
addedTask);
}
/// <summary>
/// Updates task by id
/// </summary>
/// <param name="roomId"></param>
/// <param name="taskId"></param>
/// <param name="viewModel"></param>
/// <returns></returns>
[HttpPut("{taskId:guid}")]
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status403Forbidden)]
[SwaggerResponse(StatusCodes.Status404NotFound)]
public async Task<ActionResult> Update(Guid roomId, Guid taskId, AddTaskViewModel viewModel)
{
await _roomTaskService.UpdateTask(roomId, taskId, viewModel, UserService.GetCurrentUserId(HttpContext));
return Ok();
}
/// <summary>
/// Deletes task by id
/// </summary>
/// <param name="roomId"></param>
/// <param name="taskId"></param>
/// <returns></returns>
[HttpDelete("{taskId:guid}")]
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status403Forbidden)]
[SwaggerResponse(StatusCodes.Status404NotFound)]
public async Task<ActionResult> Delete(Guid roomId, Guid taskId)
{
await _roomTaskService.DeleteTask(roomId, taskId, UserService.GetCurrentUserId(HttpContext));
return Ok();
}
}
}<file_sep>namespace Tasks.Api.Exceptions
{
public static class AppExceptions
{
public const string RoomNotFoundException = "Room with given id was not found!";
public const string TaskNotFoundException = "Task with given id was not found!";
public const string TaskInRoomNotFoundException = "Task with given id was not found in room!";
public const string RoleNotFoundException = "Role with given id was not found!";
private const string InsufficientRightsException = "Insufficient rights! ";
public const string NotRoomMemberException =
InsufficientRightsException + "The user is not a member of the room!";
public const string CreatorOnlyCanPerformThisActionException =
InsufficientRightsException + "Only owner can perform this action!";
public const string CreatorOrAdministratorOnlyCanDoThisException =
InsufficientRightsException + "Only owner or administrator can perform this action!";
public const string IncorrectUrlException = "Incorrect link!";
public const string AlreadyMember = "You are already a member of the room!";
public const string CreatorNotFound = "Creator of the task was not found!";
}
}<file_sep>using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Tasks.Api.Data;
using Tasks.Api.Exceptions;
namespace Tasks.Api.Services
{
public class UserService
{
private readonly UnitOfWork _unitOfWork;
public UserService(UnitOfWork unitOfWork) => _unitOfWork = unitOfWork;
public async Task<bool> CheckUserHasAnyRole(Guid roomId, Guid userId, params string[] rolesNames)
{
foreach (string roleName in rolesNames)
{
if (await CheckUserIsInRole(roomId, userId, roleName))
return true;
}
return false;
}
public static Guid GetCurrentUserId(HttpContext context) =>
Guid.Parse(context.User.FindFirstValue("sub") ?? string.Empty);
public async Task<bool> CheckUserIsInRole(Guid roomId, Guid userId, string roleName) =>
await _unitOfWork.RoomRepository.FindRoomWithUserInRole(roomId, userId, roleName) != null;
private async Task<bool> CheckUserIsInRoom(Guid roomId, Guid userId)
{
var room = await _unitOfWork.RoomRepository.FindRoomWithUsers(roomId);
return room?.UsersInRoom.Any(x => x.UserId == userId) ?? false;
}
public async Task ThrowIfNotRoomMember(Guid roomId, Guid userId)
{
if (!await CheckUserIsInRoom(roomId, userId))
throw new AccessRightApiException(AppExceptions.NotRoomMemberException);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Tasks.Api.Data;
using Tasks.Api.Entities;
using Tasks.Api.Exceptions;
using Tasks.Api.ViewModels.RoleViewModels;
using Tasks.Api.ViewModels.UserViewModel;
namespace Tasks.Api.Services
{
public class RoleService
{
private readonly IMapper _mapper;
private readonly RoomService _roomService;
private readonly UnitOfWork _unitOfWork;
private readonly UserService _userService;
public RoleService(UnitOfWork unitOfWork, UserService userService, RoomService roomService, IMapper mapper)
{
_unitOfWork = unitOfWork;
_userService = userService;
_roomService = roomService;
_mapper = mapper;
}
public async Task<IEnumerable<RoleViewModel>> AllRoles()
{
var roles = await _unitOfWork.RoomRoleRepository.FindAllRoles();
return _mapper.Map<IEnumerable<RoleViewModel>>(roles);
}
public async Task UpdateRoleForUser(Guid roomId, UpdateUserRoleViewModel viewModel, Guid userId)
{
await _roomService.ThrowIfRoomNotFound(roomId);
await _userService.ThrowIfNotRoomMember(roomId, userId);
if (!await _userService.CheckUserIsInRole(roomId, userId, Roles.Owner))
throw new AccessRightApiException(AppExceptions.CreatorOnlyCanPerformThisActionException);
if (viewModel.UserId == userId)
return;
var role = await _unitOfWork.RoomRoleRepository.Find(x => x.RoomRoleId == viewModel.RoomRoleId);
if (role == null)
throw new NotFoundApiException(AppExceptions.RoleNotFoundException);
var user = await _unitOfWork.RoomRepository.FindUserInRoom(roomId, viewModel.UserId);
if (user != null)
user.RoomRole = role;
await _unitOfWork.SaveChangesAsync();
}
public async Task<List<UserWithRoleViewModel>> GetUsersInRoomWithRoles(Guid roomId, Guid userId)
{
await _roomService.ThrowIfRoomNotFound(roomId);
await _userService.ThrowIfNotRoomMember(roomId, userId);
var room = await _unitOfWork.RoomRepository.FindRoomWithUsers(roomId);
if (room == null)
throw new NotFoundApiException(AppExceptions.RoomNotFoundException);
return room.UsersInRoom.Select(x => new UserWithRoleViewModel
{
User = _mapper.Map<UserFullNameViewModel>(x.User),
RoleId = x.RoomRoleId
}).ToList();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using Tasks.Api.Services;
using Tasks.Api.ViewModels.RoomViewModels;
namespace Tasks.Api.Controllers
{
/// <summary>
/// Everything about rooms
/// </summary>
[Authorize]
[ApiController]
[Route("api/[controller]")]
[SwaggerResponse(StatusCodes.Status401Unauthorized, "If user is unauthorized")]
[SwaggerTag("Everything about rooms")]
public class RoomsController : ControllerBase
{
private readonly RoomService _roomService;
/// <inheritdoc />
public RoomsController(RoomService roomService) => _roomService = roomService;
/// <summary>
/// Finds all rooms for user
/// </summary>
/// <returns></returns>
[HttpGet]
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status204NoContent, "If user hasn`t any rooms")]
public async Task<ActionResult<IEnumerable<RoomViewModel>>> AllRoomsForUser()
{
var rooms = await _roomService.FindRoomsForUser(UserService.GetCurrentUserId(HttpContext));
if (!rooms.Any())
return NoContent();
return Ok(rooms);
}
/// <summary>
/// Updates room information by id
/// </summary>
/// <param name="viewModel"></param>
/// <param name="roomId"></param>
/// <returns></returns>
[HttpPut("{roomId:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status404NotFound, "If id is incorrect", typeof(ProblemDetails))]
[SwaggerResponse(StatusCodes.Status403Forbidden, "If user has insufficient rights", typeof(ProblemDetails))]
public async Task<ActionResult> Update(AddOrUpdateRoomViewModel viewModel, Guid roomId)
{
await _roomService.UpdateRoom(viewModel, roomId, UserService.GetCurrentUserId(HttpContext));
return Ok();
}
/// <summary>
/// Creates new room for user
/// </summary>
/// <param name="viewModel"></param>
/// <returns></returns>
[HttpPost]
[SwaggerResponse(StatusCodes.Status201Created, Type = typeof(RoomViewModel))]
public async Task<CreatedAtActionResult> Create(AddOrUpdateRoomViewModel viewModel)
{
var createdRoom = await _roomService.CreateRoom(viewModel, UserService.GetCurrentUserId(HttpContext));
return CreatedAtAction(nameof(Find), new {roomId = createdRoom.RoomId}, createdRoom);
}
/// <summary>
/// Deletes room by id
/// </summary>
/// <param name="roomId"></param>
/// <returns></returns>
[HttpDelete("{roomId:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status404NotFound, "If id is incorrect", typeof(ProblemDetails))]
[SwaggerResponse(StatusCodes.Status403Forbidden, "If user has insufficient rights", typeof(ProblemDetails))]
public async Task<ActionResult> Delete(Guid roomId)
{
await _roomService.DeleteRoom(roomId, UserService.GetCurrentUserId(HttpContext));
return Ok();
}
/// <summary>
/// Finds room by id
/// </summary>
/// <param name="roomId"></param>
/// <returns></returns>
[HttpGet("{roomId:guid}")]
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status404NotFound, "If id is incorrect", typeof(ProblemDetails))]
public async Task<ActionResult<RoomViewModel>> Find(Guid roomId)
{
var room = await _roomService.FindById(roomId);
if (room == null)
return NotFound();
return Ok(room);
}
/// <summary>
/// Joins user to new room by id
/// </summary>
/// <param name="roomId"></param>
/// <returns></returns>
[HttpGet("join/{roomId:guid}")]
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(RoomViewModel))]
[SwaggerResponse(StatusCodes.Status404NotFound, "If link is incorrect", typeof(ProblemDetails))]
public async Task<ActionResult<RoomViewModel>> JoinRoom(Guid roomId)
{
var room = await _roomService.JoinUserToRoom(roomId, UserService.GetCurrentUserId(HttpContext));
return Ok(room);
}
}
}<file_sep>using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace Tasks.Api.Data
{
public abstract class Repository<T> : IRepository<T> where T : class
{
protected readonly ApplicationContext _context;
protected Repository(ApplicationContext context) => _context = context;
public async Task<T> Create(T element)
{
var addedElement = await _context.Set<T>().AddAsync(element);
return addedElement.Entity;
}
public async Task<T?> Find(Expression<Func<T, bool>> expression) =>
await _context.Set<T>().FirstOrDefaultAsync(expression);
public void Update(T element) => _context.Set<T>().Update(element);
public void Delete(T element) => _context.Set<T>().Remove(element);
}
}<file_sep>FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /app
COPY *.csproj ./
RUN dotnet restore
FROM build AS publish
COPY ./ ./
RUN dotnet publish -c Release -o out
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS runtime
WORKDIR /app
COPY --from=publish /app/out ./
ENTRYPOINT ["dotnet", "Tasks.Api.dll"]
EXPOSE 80
<file_sep>using System.Threading.Tasks;
using Tasks.Api.Data.Interfaces;
using Tasks.Api.Data.Repositories;
namespace Tasks.Api.Data
{
public class UnitOfWork
{
private readonly ApplicationContext _context;
private IRoomRepository? _roomRepository;
private IRoomRoleRepository? _roomRoleRepository;
private IRoomTaskRepository? _roomTaskRepository;
public UnitOfWork(ApplicationContext context) => _context = context;
public IRoomRepository RoomRepository => _roomRepository ??= new RoomRepository(_context);
public IRoomRoleRepository RoomRoleRepository => _roomRoleRepository ??= new RoomRoleRepository(_context);
public IRoomTaskRepository RoomTaskRepository => _roomTaskRepository ??= new RoomTaskRepository(_context);
public async Task SaveChangesAsync() => await _context.SaveChangesAsync();
}
}<file_sep>using System;
namespace Tasks.Api.ViewModels.RoomViewModels
{
public class RoomViewModel
{
public Guid RoomId { get; set; }
public string RoomName { get; set; }
public string? RoomDescription { get; set; }
public DateTime CreationDate { get; set; }
}
}<file_sep>using Microsoft.AspNetCore.Http;
namespace Users.Api.Exceptions
{
public class UserNotFoundApiException : ApiException<string>
{
public UserNotFoundApiException(string message) : base(message)
{
}
public override int StatusCode => StatusCodes.Status400BadRequest;
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Tasks.Api.Data.Interfaces;
using Tasks.Api.Entities;
namespace Tasks.Api.Data.Repositories
{
public class RoomTaskRepository : Repository<RoomTask>, IRoomTaskRepository
{
public RoomTaskRepository(ApplicationContext context) : base(context)
{
}
public async Task<IEnumerable<RoomTask>> FindTasksInRoom(Guid roomId)
{
var room = await _context.Rooms.Include(x => x.RoomTasks).FirstOrDefaultAsync(r => r.RoomId == roomId);
return room?.RoomTasks ?? new List<RoomTask>();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using IdentityServer4.AccessTokenValidation;
using MassTransit;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Users.Api.Data;
using Users.Api.Services;
using Users.Data.Entities;
namespace Users.Api
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration) => _configuration = configuration;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationContext>(options =>
{
options.UseNpgsql(_configuration.GetConnectionString("Identity") + _configuration["DbName"]);
})
.AddIdentity<User, Role>(config =>
{
config.User.RequireUniqueEmail = true;
config.Password.RequiredLength = 6;
config.Password.RequireDigit = true;
config.Password.RequireUppercase = false;
})
.AddEntityFrameworkStores<ApplicationContext>()
.AddDefaultTokenProviders();
services.AddSwaggerGen(options =>
{
options.EnableAnnotations();
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "UsersApi",
Version = "v1",
Description = "Service for register users, email confirm and update profile information",
Contact = new OpenApiContact
{
Email = "<EMAIL>",
Name = "<NAME>"
}
});
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
Password = new OpenApiOAuthFlow
{
TokenUrl = new Uri(_configuration["IdentityServer:TokenUrl"])
}
}
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "oauth2"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header
},
new List<string>()
}
});
string xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
string filePath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(filePath);
});
services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
})
.AddIdentityServerAuthentication(options =>
{
options.Authority = _configuration["IdentityServer:Authority"];
options.RequireHttpsMetadata = false;
});
services.AddAutoMapper(Assembly.GetExecutingAssembly());
services.AddTransient<DatabaseInitializer>();
services.AddScoped<UserService>();
services.AddSingleton<EmailService>();
services.AddControllers();
services.AddMassTransit(x =>
x.UsingRabbitMq((_, configurator) =>
{
configurator.Host(_configuration["MassTransit:Host"],
_configuration["MassTransit:VirtualHost"], options =>
{
options.Username(_configuration["MassTransit:Username"]);
options.Password(_configuration["MassTransit:Password"]);
});
}));
services.AddMassTransitHostedService();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DatabaseInitializer initializer)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
initializer.Initialize();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.RoutePrefix = "";
options.SwaggerEndpoint("/swagger/v1/swagger.json", "TasksApi");
options.DocumentTitle = "TasksApi";
options.OAuthClientId(_configuration["IdentityServer:ClientId"]);
options.OAuthClientSecret(_configuration["IdentityServer:Secret"]);
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<ExceptionMiddleware>();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
}<file_sep>using System;
using System.Collections.Generic;
namespace Tasks.Api.Entities
{
public class RoomRole
{
public Guid RoomRoleId { get; set; }
public string RoomRoleName { get; set; }
public string? RoomRoleDescription { get; set; }
public List<UserInTheRoom> UserInRooms { get; set; }
}
}<file_sep>using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Tasks.Api.Migrations
{
public partial class AddedRegisteredUsersTable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_RoomTasks_UsersInRoom_TaskCreatorRoomId_TaskCreatorUserId",
table: "RoomTasks");
migrationBuilder.DropTable(
name: "UsersInRoom");
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
UserId = table.Column<Guid>(type: "uuid", nullable: false),
LastName = table.Column<string>(type: "text", nullable: false),
FirstName = table.Column<string>(type: "text", nullable: false),
Patronymic = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.UserId);
});
migrationBuilder.CreateTable(
name: "UserInTheRoom",
columns: table => new
{
RoomId = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<Guid>(type: "uuid", nullable: false),
RoomRoleId = table.Column<Guid>(type: "uuid", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserInTheRoom", x => new { x.RoomId, x.UserId });
table.ForeignKey(
name: "FK_UserInTheRoom_RoomRoles_RoomRoleId",
column: x => x.RoomRoleId,
principalTable: "RoomRoles",
principalColumn: "RoomRoleId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_UserInTheRoom_Rooms_RoomId",
column: x => x.RoomId,
principalTable: "Rooms",
principalColumn: "RoomId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_UserInTheRoom_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "UserId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_UserInTheRoom_RoomRoleId",
table: "UserInTheRoom",
column: "RoomRoleId");
migrationBuilder.CreateIndex(
name: "IX_UserInTheRoom_UserId",
table: "UserInTheRoom",
column: "UserId");
migrationBuilder.AddForeignKey(
name: "FK_RoomTasks_UserInTheRoom_TaskCreatorRoomId_TaskCreatorUserId",
table: "RoomTasks",
columns: new[] { "TaskCreatorRoomId", "TaskCreatorUserId" },
principalTable: "UserInTheRoom",
principalColumns: new[] { "RoomId", "UserId" },
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_RoomTasks_UserInTheRoom_TaskCreatorRoomId_TaskCreatorUserId",
table: "RoomTasks");
migrationBuilder.DropTable(
name: "UserInTheRoom");
migrationBuilder.DropTable(
name: "Users");
migrationBuilder.CreateTable(
name: "UsersInRoom",
columns: table => new
{
RoomId = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<Guid>(type: "uuid", nullable: false),
RoomRoleId = table.Column<Guid>(type: "uuid", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UsersInRoom", x => new { x.RoomId, x.UserId });
table.ForeignKey(
name: "FK_UsersInRoom_RoomRoles_RoomRoleId",
column: x => x.RoomRoleId,
principalTable: "RoomRoles",
principalColumn: "RoomRoleId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_UsersInRoom_Rooms_RoomId",
column: x => x.RoomId,
principalTable: "Rooms",
principalColumn: "RoomId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_UsersInRoom_RoomRoleId",
table: "UsersInRoom",
column: "RoomRoleId");
migrationBuilder.AddForeignKey(
name: "FK_RoomTasks_UsersInRoom_TaskCreatorRoomId_TaskCreatorUserId",
table: "RoomTasks",
columns: new[] { "TaskCreatorRoomId", "TaskCreatorUserId" },
principalTable: "UsersInRoom",
principalColumns: new[] { "RoomId", "UserId" },
onDelete: ReferentialAction.Restrict);
}
}
}
<file_sep>using System.Collections.Generic;
using IdentityModel;
using IdentityServer4;
using IdentityServer4.Models;
using Microsoft.Extensions.Configuration;
namespace IdentityServer
{
public static class Config
{
public static IEnumerable<ApiScope> ApiScopes =>
new List<ApiScope>
{
new("TaskAPI"),
new("AccountAPI"),
new("IdentityServer"),
};
public static IEnumerable<Client> GetConfiguredClients(IConfiguration configuration) =>
new List<Client>
{
new()
{
ClientId = "SwaggerApp",
ClientSecrets =
{
new Secret(configuration["Clients:SwaggerApp:Secret"].ToSha256())
},
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
AllowedCorsOrigins =
{
configuration["Clients:SwaggerApp:Origin1"],
configuration["Clients:SwaggerApp:Origin2"]
},
RequireClientSecret = true,
AllowedScopes =
{
"IdentityServer",
IdentityServerConstants.StandardScopes.OpenId,
}
},
new()
{
ClientId = "Gateway",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
AllowedCorsOrigins =
{
configuration["Clients:Gateway:Origin"]
},
RequireClientSecret = true,
ClientSecrets =
{
new Secret(configuration["Clients:Gateway:Secret"].ToSha256())
},
AllowedScopes =
{
"IdentityServer",
IdentityServerConstants.StandardScopes.OpenId,
}
},
new()
{
ClientId = "MobileApp",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
RequireClientSecret = false,
AllowedScopes =
{
"TaskAPI",
"FullName",
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Email,
IdentityServerConstants.StandardScopes.Phone
}
},
};
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.Email(),
new IdentityResources.OpenId(),
new IdentityResources.Phone(),
new("FullName", new List<string>
{
"full_name"
})
};
}
}
}<file_sep>using Microsoft.AspNetCore.Http;
namespace Tasks.Api.Exceptions
{
public class AlreadyDoneApiException : ApiException
{
public AlreadyDoneApiException(string message) : base(message)
{
}
public override int StatusCode => StatusCodes.Status400BadRequest;
}
}<file_sep>using System.Linq;
using Microsoft.EntityFrameworkCore;
using Tasks.Api.Entities;
namespace Tasks.Api.Data
{
public class DatabaseInitializer
{
private readonly ApplicationContext _database;
public DatabaseInitializer(ApplicationContext database) => _database = database;
public void Initialize()
{
_database.Database.Migrate();
EnsureRolesAdded();
_database.SaveChanges();
}
private void EnsureRolesAdded()
{
if (!_database.RoomRoles.Any())
{
_database.RoomRoles.AddRange(Roles.AllRoles().Select(name => new RoomRole
{
RoomRoleName = name
}));
}
}
}
}<file_sep>using System;
namespace Tasks.Api.Entities
{
public class RoomTask
{
public Guid RoomTaskId { get; set; }
public string TaskName { get; set; }
public string TaskContent { get; set; }
public string? Details { get; set; }
public bool IsCompleted { get; set; }
public Guid RoomId { get; set; }
public Room Room { get; set; }
public DateTime TaskCreationTime { get; set; } = DateTime.Now;
public Guid TaskCreatorId { get; set; }
public User TaskCreator { get; set; }
public DateTime DeadlineTime { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using Tasks.Api.Services;
using Tasks.Api.ViewModels.RoleViewModels;
namespace Tasks.Api.Controllers
{
/// <summary>
/// Everything about roles
/// </summary>
[ApiController]
[Route("api/")]
[SwaggerTag("Everything about roles")]
public class RolesController : ControllerBase
{
private readonly RoleService _roleService;
public RolesController(RoleService roleService) => _roleService = roleService;
/// <summary>
/// Finds all roles in rooms
/// </summary>
/// <returns></returns>
[HttpGet("[controller]")]
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(List<RoleViewModel>))]
public async Task<ActionResult<List<string>>> AllRoles() => Ok(await _roleService.AllRoles());
/// <summary>
/// Updates user role in room
/// </summary>
/// <param name="roomId"></param>
/// <param name="viewModel"></param>
/// <returns></returns>
[Authorize]
[HttpPut("rooms/{roomId:guid}/[controller]")]
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status401Unauthorized, "If user is unauthorized")]
[SwaggerResponse(StatusCodes.Status404NotFound, "If id is incorrect", typeof(ProblemDetails))]
[SwaggerResponse(StatusCodes.Status403Forbidden, "If user has insufficient rights", typeof(ProblemDetails))]
public async Task<ActionResult> UpdateRoleForUser(Guid roomId, UpdateUserRoleViewModel viewModel)
{
await _roleService.UpdateRoleForUser(roomId, viewModel, UserService.GetCurrentUserId(HttpContext));
return Ok();
}
/// <summary>
/// Returns information about user role in room
/// </summary>
/// <param name="roomId"></param>
/// <returns></returns>
[Authorize]
[HttpGet("rooms/{roomId:guid}/[controller]")]
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(List<UserWithRoleViewModel>))]
[SwaggerResponse(StatusCodes.Status401Unauthorized, "If user is unauthorized")]
[SwaggerResponse(StatusCodes.Status404NotFound, "If id is incorrect", typeof(ProblemDetails))]
[SwaggerResponse(StatusCodes.Status403Forbidden, "If user has insufficient rights", typeof(ProblemDetails))]
public async Task<ActionResult<List<UserWithRoleViewModel>>> UsersInRoomWIthRoles(Guid roomId)
{
var result = await _roleService.GetUsersInRoomWithRoles(roomId, UserService.GetCurrentUserId(HttpContext));
return Ok(result);
}
}
}<file_sep>using AutoMapper;
using Tasks.Api.Entities;
using Tasks.Api.ViewModels.RoleViewModels;
using Tasks.Api.ViewModels.UserViewModel;
using Users.Data;
namespace Tasks.Api.Profiles
{
public class UserProfile : Profile
{
public UserProfile()
{
CreateMap<UserInTheRoom, UpdateUserRoleViewModel>();
CreateMap<UserRegistered, User>();
CreateMap<User, UserFullNameViewModel>();
CreateMap<ProfileUpdated, User>();
}
}
}<file_sep>using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Tasks.Api.Migrations
{
public partial class AddedTasks : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "RoomTasks",
columns: table => new
{
RoomTaskId = table.Column<Guid>(type: "uuid", nullable: false),
TaskName = table.Column<string>(type: "text", nullable: false),
TaskContent = table.Column<string>(type: "text", nullable: false),
Details = table.Column<string>(type: "text", nullable: false),
RoomId = table.Column<Guid>(type: "uuid", nullable: false),
TaskCreationTime = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
TaskCreatorId = table.Column<Guid>(type: "uuid", nullable: false),
TaskCreatorRoomId = table.Column<Guid>(type: "uuid", nullable: true),
TaskCreatorUserId = table.Column<Guid>(type: "uuid", nullable: true),
DeadlineTime = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RoomTasks", x => x.RoomTaskId);
table.ForeignKey(
name: "FK_RoomTasks_Rooms_RoomId",
column: x => x.RoomId,
principalTable: "Rooms",
principalColumn: "RoomId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_RoomTasks_UsersInRoom_TaskCreatorRoomId_TaskCreatorUserId",
columns: x => new { x.TaskCreatorRoomId, x.TaskCreatorUserId },
principalTable: "UsersInRoom",
principalColumns: new[] { "RoomId", "UserId" },
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_RoomTasks_RoomId",
table: "RoomTasks",
column: "RoomId");
migrationBuilder.CreateIndex(
name: "IX_RoomTasks_TaskCreatorRoomId_TaskCreatorUserId",
table: "RoomTasks",
columns: new[] { "TaskCreatorRoomId", "TaskCreatorUserId" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "RoomTasks");
}
}
}
<file_sep>using System.ComponentModel.DataAnnotations;
namespace Users.Api.ViewModels
{
public class UpdateProfileViewModel
{
[Required]
[StringLength(50)]
public string LastName { get; set; }
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string Patronymic { get; set; }
[Phone]
public string PhoneNumber { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AutoMapper;
using MassTransit;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Users.Api.Exceptions;
using Users.Api.ViewModels;
using Users.Data;
using Users.Data.Entities;
namespace Users.Api.Services
{
public class UserService
{
private readonly IConfiguration _configuration;
private readonly EmailService _emailService;
private readonly IWebHostEnvironment _environment;
private readonly IMapper _mapper;
private readonly IPublishEndpoint _publishEndpoint;
private readonly UserManager<User> _userManager;
public UserService(IWebHostEnvironment environment, IPublishEndpoint publishEndpoint,
IConfiguration configuration, UserManager<User> userManager, EmailService emailService, IMapper mapper)
{
_environment = environment;
_publishEndpoint = publishEndpoint;
_configuration = configuration;
_userManager = userManager;
_emailService = emailService;
_mapper = mapper;
}
public async Task Register(RegisterViewModel viewModel)
{
var user = _mapper.Map<User>(viewModel);
var result = await _userManager.CreateAsync(user, viewModel.Password);
if (result.Succeeded)
{
await _publishEndpoint.Publish(_mapper.Map<UserRegistered>(user));
try
{
await SendConfirmationMail(viewModel.Email);
}
catch (Exception)
{
// ignored
}
return;
}
var validationProblemDetails = new ValidationProblemDetails();
List<string> passwordErrors = new();
List<string> emailErrors = new();
List<string> otherErrors = new();
result.Errors.Select(x => x.Description).ToList().ForEach(x =>
{
if (x.Contains("password", StringComparison.InvariantCultureIgnoreCase))
passwordErrors.Add(x);
else if (x.Contains("email", StringComparison.InvariantCultureIgnoreCase))
emailErrors.Add(x);
else
otherErrors.Add(x);
});
AddErrorsForKeyIfNotEmpty(validationProblemDetails, "Email", emailErrors);
AddErrorsForKeyIfNotEmpty(validationProblemDetails, "Password", passwordErrors);
AddErrorsForKeyIfNotEmpty(validationProblemDetails, "Other", otherErrors);
throw new RegistrationException(validationProblemDetails);
}
public async Task SendConfirmationMail(string email)
{
var createdUser = await _userManager.FindByEmailAsync(email);
string token =
Uri.EscapeDataString(await _userManager.GenerateEmailConfirmationTokenAsync(createdUser));
string callbackUrl =
$"{_configuration["Gateway:Host"]}/{_configuration["Gateway:ConfirmMailRoute"]}/{createdUser.Id}/{token}";
await _emailService.SendEmailAsync(email, "Email confirmation",
string.Format(await File.ReadAllTextAsync(Path.Combine(_environment.ContentRootPath, "mail.html")),
callbackUrl));
}
public async Task UpdateProfileAsync(Guid userId, UpdateProfileViewModel viewModel)
{
var user = await _userManager.FindByIdAsync(userId.ToString());
if (user == null)
throw new UserNotFoundApiException("Token is invalid: user with given id was not found!");
var updatedProfile = _mapper.Map<ProfileUpdated>(viewModel);
updatedProfile.UserId = user.Id;
await _publishEndpoint.Publish(updatedProfile);
user = _mapper.Map(viewModel, user);
await _userManager.UpdateAsync(user);
}
public static Guid GetCurrentUserId(HttpContext context) =>
Guid.Parse(context.User.FindFirstValue("sub") ?? string.Empty);
private static void AddErrorsForKeyIfNotEmpty(ValidationProblemDetails details, string key, List<string> errors)
{
if (!errors.Any())
return;
details.Errors[key] = errors.ToArray();
}
}
}<file_sep>using System;
using System.Collections.Generic;
namespace Tasks.Api.Entities
{
public class User
{
public Guid UserId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Patronymic { get; set; }
public List<UserInTheRoom> UserInTheRooms { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Tasks.Api.Entities;
namespace Tasks.Api.Data.Interfaces
{
public interface IRoomRepository : IRepository<Room>
{
Task<UserInTheRoom?> FindUserInRoom(Guid roomId, Guid userId);
Task<Room?> FindRoomWithUserInRole(Guid roomId, Guid userId, string roleName);
Task<IEnumerable<Room>> FindRoomsForUser(Guid userId);
Task<Room?> FindRoomWithUsers(Guid roomId);
}
}<file_sep>using System;
using Microsoft.AspNetCore.Http;
namespace Tasks.Api.Exceptions
{
[Serializable]
public class NotFoundApiException : ApiException
{
public NotFoundApiException(string message) : base(message)
{
}
public override int StatusCode => StatusCodes.Status404NotFound;
}
}<file_sep>using AutoMapper;
using Users.Api.ViewModels;
using Users.Data;
using Users.Data.Entities;
namespace Users.Api.Profiles
{
public class UserProfile : Profile
{
public UserProfile()
{
CreateMap<RegisterViewModel, User>()
.ForMember(dst => dst.UserName, options => options.MapFrom(src => src.Email));
CreateMap<UpdateProfileViewModel, User>();
CreateMap<User, UserRegistered>().ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.Id));
CreateMap<UpdateProfileViewModel, ProfileUpdated>();
}
}
}<file_sep>using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Tasks.Api.Data.Interfaces;
using Tasks.Api.Entities;
namespace Tasks.Api.Data.Repositories
{
public class RoomRoleRepository : Repository<RoomRole>, IRoomRoleRepository
{
public RoomRoleRepository(ApplicationContext context) : base(context)
{
}
public async Task<IEnumerable<RoomRole>> FindAllRoles() =>
await _context.RoomRoles.ToListAsync();
public async Task<RoomRole> FindWithName(string roleName) =>
await _context.RoomRoles.FirstAsync(x => x.RoomRoleName == roleName);
}
}<file_sep>using System.Threading.Tasks;
using AutoMapper;
using MassTransit;
using Tasks.Api.Data;
using Tasks.Api.Entities;
using Users.Data;
namespace Tasks.Api.MassTransit
{
public class UserRegisteredConsumer : IConsumer<UserRegistered>
{
private readonly ApplicationContext _applicationContext;
private readonly IMapper _mapper;
public UserRegisteredConsumer(IMapper mapper, ApplicationContext applicationContext)
{
_mapper = mapper;
_applicationContext = applicationContext;
}
public async Task Consume(ConsumeContext<UserRegistered> context)
{
await _applicationContext.Users.AddAsync(_mapper.Map<User>(context.Message));
await _applicationContext.SaveChangesAsync();
}
}
}<file_sep>using System;
namespace Tasks.Api.ViewModels.UserViewModel
{
public class UserFullNameViewModel
{
public Guid UserId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Patronymic { get; set; }
}
}<file_sep>using AutoMapper;
using Tasks.Api.Entities;
using Tasks.Api.ViewModels.TaskViewModels;
namespace Tasks.Api.Profiles
{
public class TaskProfile : Profile
{
public TaskProfile()
{
CreateMap<AddTaskViewModel, RoomTask>()
.ForMember(dest => dest.RoomId, cfg => cfg.Ignore());
CreateMap<RoomTask, TaskViewModel>();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Tasks.Api.Data;
using Tasks.Api.Entities;
using Tasks.Api.Exceptions;
using Tasks.Api.ViewModels.TaskViewModels;
using Tasks.Api.ViewModels.UserViewModel;
namespace Tasks.Api.Services
{
public class RoomTaskService
{
private readonly IMapper _mapper;
private readonly UnitOfWork _unitOfWork;
private readonly UserService _userService;
public RoomTaskService(IMapper mapper, UnitOfWork unitOfWork, UserService userService)
{
_mapper = mapper;
_unitOfWork = unitOfWork;
_userService = userService;
}
public async Task<IEnumerable<TaskViewModel>> FindAllTasksInRoom(Guid roomId)
{
var tasks = await _unitOfWork.RoomTaskRepository.FindTasksInRoom(roomId);
return _mapper.Map<IEnumerable<TaskViewModel>>(tasks);
}
public async Task<TaskViewModel?> FindTask(Guid roomId, Guid taskId, Guid userId)
{
var task = await _unitOfWork.RoomTaskRepository.Find(x => x.RoomTaskId == taskId);
if (task?.RoomId != roomId)
throw new NotFoundApiException(AppExceptions.TaskInRoomNotFoundException);
await _userService.ThrowIfNotRoomMember(roomId, userId);
return _mapper.Map<TaskViewModel>(task);
}
public async Task<TaskViewModel?> CompleteTask(Guid roomId, Guid taskId, Guid userId)
{
var task = await _unitOfWork.RoomTaskRepository.Find(x => x.RoomTaskId == taskId);
if (task?.RoomId != roomId)
throw new NotFoundApiException(AppExceptions.TaskInRoomNotFoundException);
await _userService.ThrowIfNotRoomMember(roomId, userId);
task.IsCompleted = true;
await _unitOfWork.SaveChangesAsync();
return _mapper.Map<TaskViewModel>(task);
}
public async Task<TaskViewModel> CreateTask(Guid roomId, AddTaskViewModel viewModel, Guid userId)
{
var room = await _unitOfWork.RoomRepository.Find(r => r.RoomId == roomId);
if (room == null)
throw new NotFoundApiException(AppExceptions.RoomNotFoundException);
await _userService.ThrowIfNotRoomMember(roomId, userId);
if (!await _userService.CheckUserHasAnyRole(roomId, userId, Roles.Owner, Roles.Administrator))
throw new AccessRightApiException(AppExceptions.CreatorOrAdministratorOnlyCanDoThisException);
var task = _mapper.Map<RoomTask>(viewModel);
task.TaskCreatorId = userId;
task.Room = room;
var addedTask = await _unitOfWork.RoomTaskRepository.Create(task);
await _unitOfWork.SaveChangesAsync();
return _mapper.Map<TaskViewModel>(addedTask);
}
public async Task UpdateTask(Guid roomId, Guid taskId, AddTaskViewModel viewModel, Guid userId)
{
var task = await _unitOfWork.RoomTaskRepository.Find(x => x.RoomTaskId == taskId);
if (task == null)
throw new NotFoundApiException(AppExceptions.TaskNotFoundException);
ThrowIfTaskNotInRoom(task, roomId);
await _userService.ThrowIfNotRoomMember(roomId, userId);
if (!await _userService.CheckUserHasAnyRole(task.RoomId, userId, Roles.Owner, Roles.Administrator))
throw new AccessRightApiException(AppExceptions.CreatorOrAdministratorOnlyCanDoThisException);
task = _mapper.Map(viewModel, task);
_unitOfWork.RoomTaskRepository.Update(task);
await _unitOfWork.SaveChangesAsync();
}
public async Task DeleteTask(Guid roomId, Guid taskId, Guid userId)
{
var task = await _unitOfWork.RoomTaskRepository.Find(x => x.RoomTaskId == taskId);
if (task == null)
throw new NotFoundApiException(AppExceptions.TaskNotFoundException);
ThrowIfTaskNotInRoom(task, roomId);
await _userService.ThrowIfNotRoomMember(roomId, userId);
if (!await _userService.CheckUserHasAnyRole(task.RoomId, userId, Roles.Owner, Roles.Administrator))
throw new AccessRightApiException(AppExceptions.CreatorOrAdministratorOnlyCanDoThisException);
_unitOfWork.RoomTaskRepository.Delete(task);
await _unitOfWork.SaveChangesAsync();
}
private static void ThrowIfTaskNotInRoom(RoomTask roomTask, Guid roomId)
{
if (roomTask.RoomId != roomId)
throw new NotFoundApiException(AppExceptions.TaskInRoomNotFoundException);
}
public async Task<UserFullNameViewModel> FindTaskCreator(Guid roomId, Guid taskId, Guid userId)
{
var task = await _unitOfWork.RoomTaskRepository.Find(x => x.RoomTaskId == taskId);
if (task == null)
throw new NotFoundApiException(AppExceptions.TaskNotFoundException);
ThrowIfTaskNotInRoom(task, roomId);
await _userService.ThrowIfNotRoomMember(roomId, userId);
var userInRoom = await _unitOfWork.RoomRepository.FindUserInRoom(roomId, task.TaskCreatorId);
if (userInRoom == null)
{
throw new NotFoundApiException(AppExceptions.CreatorNotFound);
}
return _mapper.Map<UserFullNameViewModel>(userInRoom.User);
}
}
}<file_sep>using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using Users.Api.Services;
using Users.Api.ViewModels;
using Users.Data.Entities;
namespace Users.Api.Controllers
{
/// <summary>
/// Operations about users
/// </summary>
[ApiController]
[Route("api/[controller]")]
[SwaggerTag("Operations about users")]
public class AccountsController : ControllerBase
{
private readonly UserManager<User> _userManager;
private readonly UserService _userService;
/// <inheritdoc />
public AccountsController(UserService userService, UserManager<User> userManager)
{
_userService = userService;
_userManager = userManager;
}
/// <summary>
/// Registers a new user
/// </summary>
/// <param name="viewModel"></param>
/// <returns></returns>
[HttpPost("[action]")]
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status400BadRequest, "If data is invalid", typeof(ValidationProblemDetails))]
public async Task<ActionResult> RegisterAsync(RegisterViewModel viewModel)
{
await _userService.Register(viewModel);
return Ok();
}
/// <summary>
/// Confirms email for user
/// </summary>
/// <param name="userId"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("confirm-email/{userId}/{token}")]
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status404NotFound)]
[SwaggerResponse(StatusCodes.Status400BadRequest)]
public async Task<ActionResult> ConfirmEmailAsync(string userId, string token)
{
if (!Guid.TryParse(userId, out _))
return BadRequest("User id is not guid");
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
return BadRequest("User id is invalid");
var result = await _userManager.ConfirmEmailAsync(user, Uri.UnescapeDataString(token));
if (!result.Succeeded)
return BadRequest("Token is invalid");
return Ok("Ok");
}
/// <summary>
/// Resends confirmation mail for registered email
/// </summary>
/// <param name="registeredEmail"></param>
/// <returns></returns>
[HttpGet("resend-confirmation-mail")]
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status400BadRequest, "If email if not registered", typeof(ProblemDetails))]
[SwaggerResponse(StatusCodes.Status409Conflict, "If email if already confirmed", typeof(ProblemDetails))]
public async Task<ActionResult> ReSendEmailAsync([FromHeader] string registeredEmail)
{
var user = await _userManager.FindByEmailAsync(registeredEmail);
if (user == null)
return BadRequest(new ProblemDetails
{
Detail = "Email is not registered!"
});
if (user.EmailConfirmed)
return Conflict(new ProblemDetails
{
Detail = "Already confirmed"
});
await _userService.SendConfirmationMail(registeredEmail);
return Ok();
}
/// <summary>
/// Returns user profile information
/// </summary>
/// <param name="viewModel"></param>
/// <returns></returns>
[Authorize]
[HttpPut("[action]")]
[SwaggerResponse(StatusCodes.Status200OK)]
[SwaggerResponse(StatusCodes.Status400BadRequest, "If token is invalid", typeof(ProblemDetails))]
public async Task<ActionResult> Profile(UpdateProfileViewModel viewModel)
{
await _userService.UpdateProfileAsync(UserService.GetCurrentUserId(HttpContext), viewModel);
return Ok();
}
}
}<file_sep># Work planner Backend Web API
Backend part for my project "Work planner"
See also [frontend part](https://github.com/Inozpavel/WorkPlanner.Android)
The main idea of the project is a work execution planner. Users can create rooms and tasks within them. They can then
invite other users to join their rooms or join existing room then issue tasks and view their statuses.
The security system is made using identity server 4. There are registration, authorization systems. After registration,
the user will be sent an email for confirmation. Users have roles inside the rooms.
It is microservice architecture project. All access to microservices is implemented through the api gateway. Also, each
microservice is located in a docker container.
| Status | Master | Develop |
| ------ | ------ | ------- |
| Build | [](https://github.com/Inozpavel/WorkPlanner.WebApi/actions/workflows/dotnet.yml) | [](https://github.com/Inozpavel/WorkPlanner.WebApi/actions/workflows/dotnet.yml) |
## Prerequisites for launching
[Docker Desktop](https://www.docker.com/products/docker-desktop)
## Run system locally using Docker images
To run project open console in folder with [docker-compose.yml](docker-compose.yml?raw=true) file and run this commands
1. Pull services images from Docker Hub
```cmd
docker-compose pull
```
2. Run services
```cmd
docker-compose up -d
```
After starting API will be available on [localhost:4000](http://localhost:4000)
Documentation will be available on [localhost:4000/swagger](http://localhost:4000/swagger)
## Project Information
### Project technologies stack
Main framework
- [ASP.Net Core](https://dotnet.microsoft.com/apps/aspnet)
Database
- [PostgreSQL](https://www.postgresql.org/)
Security
- [Identity Server 4](https://identityserver4.readthedocs.io/en/latest/)
ORM
- [Entity Framework Core for PostgreSQL](https://www.nuget.org/packages?q=postgre)
API Gateway
- [Ocelot](https://github.com/ThreeMammals/Ocelot)
Message broker
- [RabbitMQ (MassTransit)](https://masstransit-project.com/usage/transports/rabbitmq.html)
Documentation
- [Swagger](https://swagger.io/)
Packages
- [AutoMapper](https://github.com/AutoMapper/AutoMapper)
- [AspNetCore.Identity](https://www.nuget.org/packages/Microsoft.AspNetCore.Identity.EntityFrameworkCore/)
## Project Architecture

Patterns
- UnitOfWork
- Repository
- Microservices architecture<file_sep>using System;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Users.Data.Entities;
namespace IdentityServer.Data
{
public class ApplicationContext : IdentityDbContext<User, Role, Guid>
{
public ApplicationContext(DbContextOptions options) : base(options)
{
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Tasks.Api.Data.Interfaces;
using Tasks.Api.Entities;
namespace Tasks.Api.Data.Repositories
{
public class RoomRepository : Repository<Room>, IRoomRepository
{
public RoomRepository(ApplicationContext context) : base(context)
{
}
public async Task<UserInTheRoom?> FindUserInRoom(Guid roomId, Guid userId)
{
return await _context.UsersInRoom.Include(x => x.RoomRole)
.Include(x => x.User)
.FirstOrDefaultAsync(x => x.RoomId == roomId && x.UserId == userId);
}
public async Task<Room?> FindRoomWithUserInRole(Guid roomId, Guid userId, string roleName)
{
return await _context.Rooms.FirstOrDefaultAsync(x =>
x.RoomId == roomId &&
x.UsersInRoom.Any(u => u.UserId == userId && u.RoomRole.RoomRoleName == roleName));
}
public async Task<IEnumerable<Room>> FindRoomsForUser(Guid userId) =>
await _context.Rooms.Where(x => x.UsersInRoom.Any(u => u.UserId == userId)).ToListAsync();
public async Task<Room?> FindRoomWithUsers(Guid roomId) =>
await _context.Rooms.Include(x => x.UsersInRoom).ThenInclude(x => x.User)
.FirstOrDefaultAsync(x => x.RoomId == roomId);
}
}<file_sep>using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Users.Api.Exceptions
{
public class RegistrationException : ApiException<ValidationProblemDetails>
{
public RegistrationException(ValidationProblemDetails problemDetails) : base(problemDetails)
{
}
public override int StatusCode => StatusCodes.Status400BadRequest;
}
}<file_sep>using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Users.Api.Exceptions;
namespace Users.Api
{
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next) => _next = next;
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (RegistrationException e)
{
context.Response.StatusCode = e.StatusCode;
await context.Response.WriteAsJsonAsync(e.ErrorData);
}
catch (ApiException e)
{
context.Response.StatusCode = e.StatusCode;
await context.Response.WriteAsJsonAsync(new ProblemDetails
{
Detail = e.Message,
Status = e.StatusCode,
});
}
}
}
}<file_sep>using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace Users.Api.Services
{
public class EmailService
{
private readonly IConfiguration _configuration;
public EmailService(IConfiguration configuration) => _configuration = configuration;
public async Task SendEmailAsync(string email, string subject, string body)
{
var emailMessage = new MailMessage
{
From = new MailAddress(_configuration["SmtpServer:Login"]),
Subject = subject,
Body = body,
IsBodyHtml = true
};
emailMessage.To.Add(email);
var client = new SmtpClient
{
Host = _configuration["SmtpServer:Host"],
Port = _configuration.GetValue<int>("SmtpServer:Port"),
EnableSsl = _configuration.GetValue<bool>("SmtpServer:EnableSsl"),
Credentials = new NetworkCredential(_configuration["SmtpServer:Login"],
_configuration["SmtpServer:Password"])
};
await client.SendMailAsync(emailMessage);
}
}
}<file_sep>using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Tasks.Api.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
"RoomRoles",
table => new
{
RoomRoleId = table.Column<Guid>("uuid", nullable: false),
RoomRoleName = table.Column<string>("text", nullable: false),
RoomRoleDescription = table.Column<string>("text", nullable: true)
},
constraints: table => { table.PrimaryKey("PK_RoomRoles", x => x.RoomRoleId); });
migrationBuilder.CreateTable(
"Rooms",
table => new
{
RoomId = table.Column<Guid>("uuid", nullable: false),
OwnerId = table.Column<Guid>("uuid", nullable: false),
RoomName = table.Column<string>("text", nullable: false),
RoomDescription = table.Column<string>("text", nullable: true),
CreationDate = table.Column<DateTime>("timestamp without time zone", nullable: false)
},
constraints: table => { table.PrimaryKey("PK_Rooms", x => x.RoomId); });
migrationBuilder.CreateTable(
"UsersInRoom",
table => new
{
RoomId = table.Column<Guid>("uuid", nullable: false),
UserId = table.Column<Guid>("uuid", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UsersInRoom", x => new {x.RoomId, x.UserId});
table.ForeignKey(
"FK_UsersInRoom_Rooms_RoomId",
x => x.RoomId,
"Rooms",
"RoomId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
"RoomRoleUserInRoom",
table => new
{
RoomRolesRoomRoleId = table.Column<Guid>("uuid", nullable: false),
UserInRoomsRoomId = table.Column<Guid>("uuid", nullable: false),
UserInRoomsUserId = table.Column<Guid>("uuid", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RoomRoleUserInRoom",
x => new {x.RoomRolesRoomRoleId, x.UserInRoomsRoomId, x.UserInRoomsUserId});
table.ForeignKey(
"FK_RoomRoleUserInRoom_RoomRoles_RoomRolesRoomRoleId",
x => x.RoomRolesRoomRoleId,
"RoomRoles",
"RoomRoleId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
"FK_RoomRoleUserInRoom_UsersInRoom_UserInRoomsRoomId_UserInRoom~",
x => new {x.UserInRoomsRoomId, x.UserInRoomsUserId},
"UsersInRoom",
new[] {"RoomId", "UserId"},
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
"IX_RoomRoleUserInRoom_UserInRoomsRoomId_UserInRoomsUserId",
"RoomRoleUserInRoom",
new[] {"UserInRoomsRoomId", "UserInRoomsUserId"});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
"RoomRoleUserInRoom");
migrationBuilder.DropTable(
"RoomRoles");
migrationBuilder.DropTable(
"UsersInRoom");
migrationBuilder.DropTable(
"Rooms");
}
}
}<file_sep>using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ApiGateway.Ocelot
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); })
.ConfigureLogging(options => { options.AddConsole(); }).ConfigureAppConfiguration(
(hostingContext, config) =>
{
if (hostingContext.HostingEnvironment.IsDevelopment())
config.AddJsonFile("ocelot.json", false, true);
else if (hostingContext.HostingEnvironment.IsProduction())
config.AddJsonFile("ocelot.production.json", false, true);
});
}
}<file_sep>using System;
using System.Collections.Generic;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Swashbuckle.AspNetCore.SwaggerUI;
namespace ApiGateway.Ocelot
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration) => _configuration = configuration;
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddOcelot();
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(
options =>
{
options.Authority = _configuration["IdentityServer:Authority"];
options.RequireHttpsMetadata = false;
});
services.AddSwaggerForOcelot(_configuration, o =>
{
o.GenerateDocsDocsForGatewayItSelf(opt =>
{
opt.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
Password = new <PASSWORD>
{
TokenUrl = new Uri(_configuration["IdentityServer:TokenUrl"])
}
}
});
opt.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "oauth2"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header
},
new List<string>()
}
});
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwaggerForOcelotUI(options =>
{
options.OAuthConfigObject = new OAuthConfigObject
{
ClientId = _configuration["IdentityServer:ClientId"],
ClientSecret = _configuration["IdentityServer:Secret"]
};
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/",
async context => await context.Response.WriteAsync("Here is ocelot!\n Try also /swagger"));
endpoints.MapControllers();
});
app.UseOcelot().Wait();
}
}
}<file_sep>using System;
namespace Tasks.Api.ViewModels.RoleViewModels
{
public class UpdateUserRoleViewModel
{
public Guid UserId { get; set; }
public Guid RoomRoleId { get; set; }
}
}<file_sep>using AutoMapper;
using Tasks.Api.Entities;
using Tasks.Api.ViewModels.RoomViewModels;
namespace Tasks.Api.Profiles
{
public class RoomProfile : Profile
{
public RoomProfile()
{
CreateMap<AddOrUpdateRoomViewModel, Room>();
CreateMap<Room, RoomViewModel>();
}
}
} | ee5e8a2a02b1023612f8a2a4cfc76210b4f0b7b9 | [
"Markdown",
"C#",
"Dockerfile"
] | 69 | C# | a4200/WorkPlanner.WebApi | 4c2175f52f3a9ef02b4b74554f91ffad13f8aca0 | f6f76bc971151150848f5f81ed6f0b92e0320605 | |
refs/heads/master | <repo_name>dvn123/SINF<file_sep>/app/partials/edituser/edituser.js
'use strict';
angular.module('myApp.editUser', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/edituser', {
controller: 'editUserCtrl',
templateUrl: 'partials/edituser/edituser.html'
})
}])
.controller('editUserCtrl', function ($http, $scope, Auth, $log, $location) {
$scope.errorMessage = "";
$scope.newuser = {};
$scope.differentPasswords = function () {
return $scope.newuser.password !== $scope.<PASSWORD>;
};
$scope.editUser = function () {
$("#editFormSubmitButton").blur();
Auth.edit($scope.newuser,
function (data) {
$scope.newuser = {};
$location.path('/history');
},
function (error) {
$scope.errorMessage = error.message;
});
}
});<file_sep>/app/partials/history/history.js
'use strict';
var link = 'http://127.0.0.1:49822/api/';
angular.module('myApp.history', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/history', {
controller: 'historyCtrl',
templateUrl: 'partials/history/history.html'
})
}])
.controller('historyCtrl', function ($http, $log, $scope, Auth, $location, $route, $modal) {
$scope.orders = [];
$scope.goToEdit = function () {
$location.path('edituser');
};
//$http.get(link + '/orders/?Customer=' + Auth.getCurrentUser().id)
//$http.get('partials/history/history.json')
$scope.refreshOrders = function () {
$http.get(link + 'orders/?Customer=' + Auth.getCurrentUser().id).success(function (res) {
$log.log("Novas orders: ");
$log.log(res);
$scope.orders = res['orders'];
}).error(function (error) {
$log.error(error);
});
};
$scope.$on('$routeChangeSuccess', function () {
$scope.refreshOrders();
});
//ng-click="changePage(line.product_id)" style="color: #b19d6f;"
$scope.open = function (size, index) {
$modal.open({
templateUrl: 'historyModal.html',
controller: 'historyModalCtrl',
size: size,
resolve: {
item: function () {
return $scope.orders[index];
}
}
});
};
})
.controller('historyModalCtrl', function ($scope, $http, $log, item, $modalInstance, $location) {
$scope.order = {};
$http.get(link + 'orders/' + item.id).success(function (res) {
$scope.order = res;
}).error(function (error) {
$log.error(error);
});
$scope.close = function(productId) {
$modalInstance.close();
};
})
.filter('translateState', function () {
return function (state) {
switch (state) {
case 'P':
return 'Pending';
case 'A':
return 'Cancelled';
case 'F':
return 'Closed';
default:
return state;
}
};
});<file_sep>/app/partials/viewProduct/singleProduct.js
'use strict';
function capitaliseFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
angular.module('myApp.viewProduct', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/products/:productID', {
templateUrl: 'partials/viewProduct/single-product.html',
controller: 'viewProductCtrl'
});
}])
.controller('viewProductCtrl', ['$http', '$scope', '$routeParams', 'ngCart' ,function($http, $scope, $routeParams, ngCart) {
//$http.get('partials/viewProduct/1.json').success(function(data) {
$http.get('http://127.0.0.1:49822/api/products/' + $routeParams['productID']).success(function(data) {
console.log(JSON.stringify(data));
$scope.product = data.product;
$scope.current = {};
$scope.current.mainId = $scope.product.id;
$http.get('http://127.0.0.1:49822/api/products/bycategory/' + $scope.product.category).success(function(data) {
console.log(data.products.length);
for(var i = 0; i < data.products.length; i++) {
console.log("Testing: ");
//console.log($scope.product);
//console.log(data.products[i]);
if($scope.product.id == data.products[i].id) {
console.log("FOUND");
data.products.splice(i, 1);
}
}
$scope.related = data.products.slice(0,4);
});
/****set iva and shipping ***/
ngCart.setTax(23);
ngCart.setShipping(0);
$scope.keys = Object.keys($scope.product.subproducts[0]);
for(var i = 0; i < $scope.keys.length; i++) {
if($scope.keys[i] != "stock" && $scope.keys[i] != "id" && $scope.keys[i] != "stock_shops")
$scope.keys[i] = capitaliseFirstLetter($scope.keys[i]);
}
$scope.master_select = $scope.keys[0];
for(var i = 0; i < $scope.product.subproducts.length; i++) {
for(var key in $scope.product.subproducts[i]){
if(key != "stock" && key != "id" && key != "stock_shops") {
$scope.product.subproducts[i][capitaliseFirstLetter(key)] = $scope.product.subproducts[i][key];
delete $scope.product.subproducts[i][key];
}
}
}
//console.log($scope.product);
$scope.select_options = {};
$scope.selected_image = $scope.product.image_links[0];
$scope.image_n = $scope.product.image_links.length % 4;
for(var i = 0; i < $scope.keys.length; i++) {
//Set defaults
$scope.current[$scope.keys[i]] = $scope.product.subproducts[0][$scope.keys[i]];
if($scope.keys[i] != "stock" && $scope.keys[i] != "id" && $scope.keys[i] != "stock_shops") {
$scope.select_options[$scope.keys[i]] = [];
}
}
//console.log("Keys: ");
//console.log($scope.keys);
for(var i = 0; i < $scope.product.subproducts.length; i++) {
for(var key in $scope.product.subproducts[i]){
if(key != "stock" && key != "id" && key != "stock_shops" && $scope.select_options[key].indexOf(data.product.subproducts[i][key]) == -1) {
$scope.select_options[key].push(data.product.subproducts[i][key]);
}
}
}
$scope.select_options_full = $scope.select_options;
//console.log("Select Options:");
//console.log($scope.select_options_full);
$scope.filter = {};
$scope.filter_update($scope.master_select);
});
$scope.buildStockString = function(stock_shops) {
var string = "Online: " + $scope.current["stock"] + "<br>";
for(var i = 0; i < stock_shops.length; i++) {
string += stock_shops[i] + "<br>";
}
$scope.stockString = string;
};
$scope.updateSelected = function(obj) {
if(obj != $scope.master_select) {
$scope.updateStock(obj);
return;
}
$scope.filter_update(obj);
};
$scope.filter_update = function(obj) {
var selected_object = null;
for(var i = 0; i < $scope.keys.length; i++) {
if($scope.keys[i] != $scope.master_select) {
$scope.filter[$scope.keys[i]] = [];
}
}
//console.log($scope.filter);
for(var i = 0; i < $scope.product.subproducts.length; i++) {
if ($scope.current[obj] == $scope.product.subproducts[i][obj]) {
selected_object = $scope.product.subproducts[i];
//console.log(selected_object);
for (var key in selected_object) {
//console.log(key);
if(key != $scope.master_select && $scope.filter[key].indexOf(selected_object[key]) == -1)
$scope.filter[key].push(selected_object[key]);
}
}
}
console.log("Filter:");
console.log($scope.filter);
for(key in $scope.select_options) {
if(key != obj) {
$scope.select_options[key] = $scope.filter[key];
$scope.current[key] = $scope.filter[key][0];
}
}
$scope.current["stock"] = $scope.filter["stock"][0];
$scope.current["id"] = $scope.filter["id"][0];
$scope.current["stock_shops"] = $scope.filter["stock_shops"][0];
console.log("Current:");
console.log($scope.current);
$scope.buildStockString($scope.current["stock_shops"]);
};
$scope.updateStock = function(obj) {
for(var i = 0; i < $scope.product.subproducts.length; i++) {
var tmp = jQuery.extend(true, {}, $scope.product.subproducts[i]);
delete tmp['id'];
delete tmp['stock'];
delete tmp['mainId'];
delete tmp['stock_shops'];
var tmp2 = jQuery.extend(true, {}, $scope.current);
delete tmp2['id'];
delete tmp2['stock'];
delete tmp2['mainId'];
delete tmp2['stock_shops'];
//console.log(tmp);
//console.log($scope.product.subproducts[i]["stock"]);
//console.log(tmp2);
//console.log(tmp == tmp2);
if(angular.equals(tmp, tmp2)) {
//console.log("FOUND - Stock = " + $scope.product.subproducts[i]["id"]);
$scope.current["stock"] = $scope.product.subproducts[i]["stock"];
$scope.current["id"] = $scope.product.subproducts[i]["id"];
$scope.current["stock_shops"] = $scope.product.subproducts[i]["stock_shops"];
}
}
console.log("Current: ");
console.log($scope.current);
};
$scope.updateImage = function(obj) {
if(obj < $scope.product.image_links.length) {
$scope.selected_image = $scope.product.image_links[obj];
//$('body').scrollTo('.item_image');
}
};
}]);
| 2e07cbb7f89fde31f97242866366e89a7082699f | [
"JavaScript"
] | 3 | JavaScript | dvn123/SINF | b64d3d9a6b1919536ed97ff1ae0bd0c4a7369740 | ca6127de9e5aa378460591d8b13c98f996370044 | |
refs/heads/master | <file_sep>package com.cubetech.facturador.emisor.application.impl;
import java.util.List;
import javax.persistence.PersistenceException;
import javax.transaction.Transactional;
import javax.validation.ValidationException;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cubetech.facturador.emisor.application.EmisorService;
import com.cubetech.facturador.emisor.application.assembler.EmisorAssembler;
import com.cubetech.facturador.emisor.domain.cuenta.ArchivoCuenta;
import com.cubetech.facturador.emisor.domain.cuenta.Cuenta;
import com.cubetech.facturador.emisor.domain.cuenta.CuentaRepository;
import com.cubetech.facturador.emisor.domain.cuenta.Emisor;
import com.cubetech.facturador.emisor.interfaces.facade.CatalogosService;
import com.cubetech.facturador.emisor.interfaces.facade.dto.ArchivoDTO;
import com.cubetech.facturador.emisor.interfaces.facade.dto.CertificadoDTO;
import com.cubetech.facturador.emisor.interfaces.facade.dto.CuentaDTO;
import com.cubetech.facturador.emisor.interfaces.facade.dto.DireccionDTO;
import com.cubetech.facturador.emisor.interfaces.facade.dto.EmisorDTO;
import com.cubetech.facturador.emisor.interfaces.facade.dto.EmitirDTO;
import com.cubetech.facturador.emisor.interfaces.facade.dto.ImprimirDTO;
import com.cubetech.facturador.emisor.interfaces.facade.dto.RegistroEmisorDTO;
import com.cubetech.facturador.emisor.interfaces.rest.archivos.ArchivoRepDTO;
import com.cubetech.facturador.emisor.interfaces.rest.archivos.ArchivoRepository;
@Service
public class EmisorServiceImpl implements EmisorService{
private final static Logger logger = LoggerFactory.getLogger(EmisorServiceImpl.class);
private CuentaRepository cuentaRepository;
private ModelMapper modelMapper;
private ArchivoRepository archivoRepository;
private EmisorAssembler emisorAssembler;
@Autowired
public EmisorServiceImpl(CuentaRepository cuentaRepository, ModelMapper modelMapper,
ArchivoRepository archivoRepository, CatalogosService catalogoService){
this.cuentaRepository = cuentaRepository;
this.modelMapper = modelMapper;
this.archivoRepository = archivoRepository;
this.emisorAssembler = new EmisorAssembler(catalogoService, this.modelMapper );
}
@Override
public RegistroEmisorDTO creaEmisor(String cuenta, EmisorDTO emisor) {
RegistroEmisorDTO ret;
Cuenta cta;
Emisor e;
Emisor tmp;
boolean banUpdate = true;
try{
cta = consultaCuenta(cuenta);
logger.debug("Cuenta:" + cta.toString());
}catch(Exception exp){
logger.error("Cuenta: " + cuenta, exp);
throw exp;
}
try{
if(emisor.getCorrelacion() != null && !emisor.getCorrelacion().isEmpty() ){
logger.info("Registro Correlation: " + emisor.getCorrelacion());
tmp = emisorAssembler.toEmisor(emisor);
try{
e = cta.buscaEmisor(emisor.getCorrelacion());
logger.debug("EmisorEncontrado: {}", e.toString());
consultaArchivos(cta,e);
if(e.sameIdentityAs(tmp)){
banUpdate = false;
}else{
tmp.correlacion(e);
e = tmp;
}
}catch(ValidationException excep){
logger.info("New emisor: {}" , tmp.toString());
e = tmp;
}
if(banUpdate){
e.valida();
actualizaCorrelaciones(e);
save(cta, e);
}
}else{
throw new ValidationException("No se puede registrar un emisor sin un identificado de correlacion");
}
}catch(Exception exp){
logger.error(emisor.toString(), exp);
throw exp;
}
ret = emisorAssembler.emisorToRegistroEmisorDTO(e);
return ret;
}
private void actualizaCorrelaciones(Emisor e){
//Consultar el repositorio de comprobantes por numero de certificado
//Si encuentra alguno se genera un nuevo correlacion para el certificado de clave publica
}
@Transactional
private void save(Cuenta cuenta, Emisor emisor) throws PersistenceException{
List<ArchivoRepDTO> archs = this.emisorAssembler.emisorToListArchivoRepDTO(emisor);
cuenta.upsert(emisor);
this.cuentaRepository.save(cuenta);
archivoRepository.save(cuenta.getCorrelacion(), archs);
}
/*
private ArchivoCuenta consultaArchivo(Cuenta cuenta, String correlacion){
ArchivoCuenta ret;
ArchivoRepDTO archivo;
if(correlacion != null){
archivo = archivoRepository.findbyCuentaCorrelacion(cuenta.getCorrelacion(), correlacion);
if(archivo == null){
logger.debug("No se encutra el archivo: {}", correlacion);
throw new IllegalArgumentException("No se encuetra el archivo: " + correlacion);
}
ret = this.modelMapper.map(archivo, ArchivoCuenta.class);
ret.setContent(ArchivoCuenta.toByteArray(archivo.getContent()));
}else{
throw new IllegalArgumentException("la correlacion no puede ser null");
}
return ret;
}
*/
private void consultaArchivos(Cuenta cuenta, Emisor emisor){
ArchivoRepDTO archivo;
ArchivoCuenta tmp;
if(emisor.getLogo() != null && emisor.getLogo().getCorrelacion()!= null ){
archivo = archivoRepository.findbyCuentaCorrelacion(cuenta.getCorrelacion(), emisor.getLogo().getCorrelacion());
if(archivo == null){
logger.error("No se encutra el archivo: {}", emisor.getLogo());
throw new IllegalArgumentException("No se encuetra el archivo: " + emisor.getLogo().toString());
}
tmp = this.modelMapper.map(archivo, ArchivoCuenta.class);
tmp.setContent(ArchivoCuenta.toByteArray(archivo.getContent()));
emisor.getLogo().actualiza(tmp);
}
if(emisor.getCertificado() != null && emisor.getCertificado().getPrivado() != null && emisor.getCertificado().getPrivado().getCorrelacion()!= null){
archivo = archivoRepository.findbyCuentaCorrelacion(cuenta.getCorrelacion(), emisor.getCertificado().getPrivado().getCorrelacion());
if(archivo == null){
logger.error("No se encutra el archivo: {}", emisor.getCertificado().getPrivado());
throw new IllegalArgumentException("No se encutra el archivo: " + emisor.getCertificado().getPrivado().toString());
}
tmp = this.modelMapper.map(archivo, ArchivoCuenta.class);
tmp.setContent(ArchivoCuenta.toByteArray(archivo.getContent()));
emisor.getCertificado().getPrivado().actualiza(tmp);
}else{
logger.error("No se encutra el archivo: {}", emisor.getCertificado().getPrivado());
throw new IllegalArgumentException("No se encutra el archivo Logo: " + emisor.toString());
}
if(emisor.getCertificado() != null && emisor.getCertificado().getPublico() != null && emisor.getCertificado().getPublico().getCorrelacion()!= null){
archivo = archivoRepository.findbyCuentaCorrelacion(cuenta.getCorrelacion(), emisor.getCertificado().getPublico().getCorrelacion());
if(archivo == null){
logger.error("No se encutra el archivo: {}", emisor.getCertificado().getPublico());
throw new IllegalArgumentException("No se encutra el archivo: " + emisor.getCertificado().getPublico().toString());
}
tmp = this.modelMapper.map(archivo, ArchivoCuenta.class);
tmp.setContent(ArchivoCuenta.toByteArray(archivo.getContent()));
emisor.getCertificado().getPublico().actualiza(tmp);
}else{
logger.error("No se encutra el archivo: {}", emisor.getCertificado().getPublico());
throw new IllegalArgumentException("No se encutra el archivo Logo: " + emisor.toString());
}
}
private Cuenta consultaCuenta(String cuenta){
Cuenta ret = null;
ret = cuentaRepository.findOneByCorrelacion(cuenta);
if(ret == null)
throw new ValidationException("La cuenta no existe");
if(!ret.isActiva())
throw new ValidationException("Cuenta Inactiva");
return ret;
}
@Override
public List<EmisorDTO> consulta(String cuenta) {
CuentaDTO ret = new CuentaDTO();
EmisorDTO emisortmp = new EmisorDTO();
CertificadoDTO certificadotmp = new CertificadoDTO();
DireccionDTO direcciontmp = new DireccionDTO();
ArchivoDTO logo = new ArchivoDTO();
ArchivoDTO privado = new ArchivoDTO();
ArchivoDTO publico = new ArchivoDTO();
direcciontmp.setCalle("Av siempre viva");
direcciontmp.setCodigoPostal("78398");
direcciontmp.setColonia("El paseo");
direcciontmp.setEstado("San Luis Potosi");
direcciontmp.setMunicipio("SLP");
direcciontmp.setNumeroExterior("322");
direcciontmp.setPais("Mexico");
logo.setNombre("LogotipoCompañia.jpg");
logo.setTipo("JPG/Image");
logo.setContent("<KEY>//<KEY>);
privado.setNombre("archivo.key");
privado.setTipo("Application/certificate");
privado.setContent("<KEY>
publico.setNombre("archivo.cer");
publico.setTipo("Application/certificate");
publico.setContent("<KEY>
certificadotmp.setPassword("<PASSWORD>");
certificadotmp.setPrivado(privado);
certificadotmp.setPublico(publico);
emisortmp.setCertificado(certificadotmp);
emisortmp.setCorrelacion("1");
emisortmp.setDireccion(direcciontmp);
emisortmp.setLugarExpedicion("78398");
emisortmp.setLogo(logo);
emisortmp.setNombre("CUBETECHNOLOGIC");
emisortmp.setRegimenFiscal("601");
emisortmp.setRfc("CMC161114E10");
ret.setCorrelacion("123456789-987654321");
ret.getEmisores().add(emisortmp);
return ret.getEmisores();
}
@Override
public EmitirDTO consultaDatosEmitir(String cuenta, String emisor) {
Cuenta cta;
Emisor e;
EmitirDTO ret;
try{
cta = consultaCuenta(cuenta);
logger.debug("Cuenta:" + cta.toString());
}catch(Exception exp){
logger.error("Cuenta: " + cuenta, exp);
throw exp;
}
e = cta.buscaEmisor(emisor);
logger.debug("EmisorEncontrado: {}", e);
try{
ret = emisorAssembler.emisorToEmitirDTO(e);
logger.debug("Emitir: {}", ret);
}catch(Exception exp){
logger.error("No se encuentra el certificado emisor: {}: ", e, exp);
throw exp;
}
return ret;
}
@Override
public ImprimirDTO consultaDatosImprimir(String cuenta, String emisor) {
Cuenta cta;
Emisor e;
ImprimirDTO ret;
try{
cta = consultaCuenta(cuenta);
logger.debug("Cuenta:" + cta.toString());
}catch(Exception exp){
logger.error("Cuenta: " + cuenta, exp);
throw exp;
}
e = cta.buscaEmisor(emisor);
try{
ret = emisorAssembler.emisorToImprimirDTO(e);
logger.debug("Emitir: {}", ret);
}catch(Exception exp){
logger.error("construccion de respuesta emisro: {} ", e, exp);
throw exp;
}
return ret;
}
}
<file_sep>package com.cubetech.facturador.emisor.interfaces.facade.dto.catalogos;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.cubetech.facturador.emisor.interfaces.facade.internal.deserializer.DatosJsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.Data;
import lombok.ToString;
@Data
public class CatalogosDTO implements Serializable{
private String nombre;
//@JsonDeserialize(using = DatosJsonDeserializer.class)
List<String> datos;
public CatalogosDTO(String nombre){
this.nombre = nombre;
datos = new ArrayList<String>();
}
public CatalogosDTO(){
/*this.nombre = nombre;*/
datos = new ArrayList<String>();
}
}
<file_sep>package com.cubetech.facturador.emisor.application;
import com.cubetech.facturador.emisor.interfaces.facade.dto.CuentaDTO;
public interface CuentaService {
public void creaCuenta(CuentaDTO cuenta);
}
<file_sep>package com.cubetech.facturador.emisor.domain.common;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import com.cubetech.facturador.emisor.domain.shared.ValueObject;
import lombok.Data;
@Data
@Embeddable
public class Vigencia implements ValueObject<Vigencia> {
@Column(name = "inicial")
private Date fechaInicial;
@Column(name="final")
private Date fechaFinal;
public Vigencia(Date ini, Date fin){
this.fechaInicial = ini;
this.fechaFinal = fin;
}
public Vigencia(Date ini){
this.fechaInicial = ini;
this.fechaFinal = null;
}
public Vigencia(){
this.fechaInicial = null;
this.fechaFinal = null;
}
@Override
public boolean sameValueAs(Vigencia other) {
boolean ret = false;
ret = (this.fechaInicial.equals(other.fechaInicial) && this.fechaFinal.equals(other.fechaFinal));
return ret;
}
public boolean vigente() {
boolean ret = false;
Date ahora = new Date();
ret = this.vigenteEn(ahora);
return ret;
}
public boolean vigenteEn(Date fecha) {
boolean ret = false;
if (this.fechaInicial != null)
ret = this.fechaInicial.before(fecha);
if (fechaFinal != null)
ret = ret && this.fechaFinal.after(fecha);
return ret;
}
public String fechaLegible(){
String ret;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
ret = "Vigencia:[" + formatter.format(fechaInicial) + " - " + formatter.format(fechaFinal) + "]";
return ret;
}
}
<file_sep>package com.cubetech.facturador.emisor.interfaces.facade.internal;
/*
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import com.cubetech.facturador.emisor.AppConfigTest;
import com.cubetech.facturador.emisor.interfaces.facade.CatalogosService;
import com.cubetech.facturador.emisor.interfaces.facade.dto.catalogos.CatalogoDTO;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes=AppConfigTest.class)
public class CatalogosServiceImplTest {
@Autowired
CatalogosService catalogosService;
@Test
public void test2catalogos() {
Map<String, String> catalogos = new HashMap<String, String>();
Map<String, CatalogoDTO> respuesta;
boolean asser = true;
catalogos.put("regimenFiscal", "601");
catalogos.put("codigoPostal", "78398");
respuesta = catalogosService.consultaCatalogos(catalogos);
asser = respuesta.containsKey("regimenFiscal") && respuesta.containsKey("codigoPostal");
assertTrue(asser);
}
@Test
public void testVigenteFalse() {
Map<String, String> catalogos = new HashMap<String, String>();
Map<String, CatalogoDTO> respuesta;
boolean asser = true;
catalogos.put("regimenFiscal", "628");
catalogos.put("codigoPostal", "78398");
respuesta = catalogosService.consultaCatalogos(catalogos);
asser = respuesta.containsKey("regimenFiscal") && respuesta.containsKey("codigoPostal")
&& !respuesta.get("regimenFiscal").isVigente();
assertTrue(asser);
}
}
*/
<file_sep>package com.cubetech.facturador.emisor.interfaces.rest.archivos.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.ws.http.HTTPException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;
import com.cubetech.facturador.emisor.AppProperties;
import com.cubetech.facturador.emisor.interceptor.RequestLoggingInterceptor;
import com.cubetech.facturador.emisor.interfaces.rest.archivos.ArchivoRepDTO;
import com.cubetech.facturador.emisor.interfaces.rest.archivos.ArchivoRepository;
@Repository
public class ArchivoRepositoryImpl implements ArchivoRepository {
@Autowired
AppProperties properties;
private RestTemplate rest;
private HttpStatus status;
public ArchivoRepositoryImpl() {
this.rest = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
List<ClientHttpRequestInterceptor> tmp = new ArrayList<ClientHttpRequestInterceptor>();
tmp.add(new RequestLoggingInterceptor());
rest.setInterceptors(tmp);
}
@Override
public ArchivoRepDTO findbyCuentaCorrelacion(String cuenta, String correlation) {
ArchivoRepDTO ret = null;
final String url = properties.getArchivourl() + "/Archivo" + "/" + correlation;
HttpHeaders headers = ArchivoRepositoryImpl.HedersJson();
headers.set("cuenta", cuenta);
HttpEntity<ArchivoRepDTO> request = new HttpEntity<>(headers);
ResponseEntity<ArchivoRepDTO> response = rest.exchange(url, HttpMethod.GET, request, ArchivoRepDTO.class);
status = response.getStatusCode();
if(status == HttpStatus.ACCEPTED){
ret = response.getBody();
}
return ret;
}
public static HttpHeaders HedersJson(){
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
headers.add("Accept", "*/*");
headers.add("Authorization","Basic dXNlcjo1RFtqWjRSXyRyOHdZLlNM");
return headers;
}
@Override
public List<ArchivoRepDTO> save(String cuenta, List<ArchivoRepDTO> archivo) {
final String url = properties.getArchivourl() + "/Archivo";
ArchivoRepDTO[] tmp = archivo.toArray( new ArchivoRepDTO[0]);
ArchivoRepDTO[] respuesta;
List<ArchivoRepDTO> ret;
HttpHeaders headers = ArchivoRepositoryImpl.HedersJson();
headers.set("cuenta", cuenta);
HttpEntity<ArchivoRepDTO[]> request = new HttpEntity<>(tmp, headers);
ResponseEntity<ArchivoRepDTO[]> response = rest.exchange(url, HttpMethod.POST, request, ArchivoRepDTO[].class);
status = response.getStatusCode();
if(status == HttpStatus.OK){
respuesta = response.getBody();
ret = Arrays.asList(respuesta);
}else{
throw new HTTPException(status.value());
}
return ret;
}
}
<file_sep>package com.cubetech.facturador.emisor.interfaces.facade.dto;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=true)
public class ImprimirDTO extends DireccionDTO {
private String logo;
}
<file_sep>package com.cubetech.facturador.emisor.interfaces.facade.dto.catalogos;
import java.util.Map;
import lombok.Data;
import lombok.ToString;
@Data
@ToString(callSuper=true)
public class RegimenFiscalDTO extends CatalogoDTO {
private static final String NAME = "regimenFiscal";
private boolean fisica;
private boolean moral;
@Override
public String url() {
return NAME + "=" + super.getClaveSat();
}
@Override
public String getName(){
return NAME;
}
public RegimenFiscalDTO(){
}
}
<file_sep>package com.cubetech.facturador.emisor.domain.common;
public enum EnumPersonaFiscal {
FISICA(1),
MORAL(2);
//true fisica
private int valor;
EnumPersonaFiscal(int valor){
this.valor = valor;
}
public int getValue(){
return this.valor;
}
}
<file_sep>package com.cubetech.facturador.emisor.domain.common;
import javax.persistence.Embeddable;
import com.cubetech.facturador.emisor.domain.shared.ValueObject;
import com.cubetech.facturador.emisor.domain.shared.ValueObjectBase;
import lombok.Data;
@Data
@Embeddable
public class Direccion extends ValueObjectBase implements ValueObject<Direccion> {
private String calle;
private String numeroExterior;
private String numeroInterior;
private String codigoPostal;
private String colonia;
private String pais;
private String estado;
private String municipio;
@Override
public boolean sameValueAs(Direccion other) {
return other != null && (
compara(this.calle, other.calle) &&
compara(this.numeroExterior, other.numeroExterior) &&
compara(this.numeroInterior, other.numeroInterior) &&
compara(this.codigoPostal, other.codigoPostal) &&
compara(this.colonia, other.colonia) &&
compara(this.pais, other.pais) &&
compara(this.estado, other.estado) &&
compara(this.municipio, other.municipio)
)
;
}
}
<file_sep>package com.cubetech.facturador.emisor.interfaces.facade.dto;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
@Data
public class CuentaDTO {
private String correlacion;
private List<EmisorDTO> emisores = new ArrayList<EmisorDTO>();
}
<file_sep>package com.cubetech.facturador.emisor.interfaces.facade.dto;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import lombok.Data;
@Data
public class EmisorDTO {
@NotEmpty
private String correlacion;
@NotEmpty
@Length(max=14)
private String rfc;
private String nombre;
@NotEmpty
private String regimenFiscal;
@NotEmpty
private String LugarExpedicion;
private ArchivoDTO logo;
private DireccionDTO direccion;
private CertificadoDTO certificado;
}
<file_sep>package com.cubetech.facturador.emisor;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.cubetech.facturador.emisor.interceptor.ComprobantesFiscalesInterceptor;
import com.cubetech.facturador.emisor.interfaces.facade.internal.assembler.EmisorDtoTOEmisor;
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter{
@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.addMappings(new EmisorDtoTOEmisor());
return modelMapper;
}
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new ComprobantesFiscalesInterceptor());
}
}
<file_sep>package com.cubetech.facturador.emisor.domain.common;
import javax.persistence.Embeddable;
import javax.persistence.Transient;
import javax.validation.ValidationException;
import com.cubetech.facturador.emisor.domain.catalogo.RegimenFiscal;
import lombok.Data;
@Data
@Embeddable
public class PersonaFiscal{
@Transient
private EnumPersonaFiscal tipo;
private Rfc rfc;
private RazonSocial razonSocial;
public boolean sameValueAs(PersonaFiscal other) {
boolean ret = true;
ret = rfc.canEqual(other.rfc);
ret = ret && ((razonSocial == null && other.razonSocial == null) || (razonSocial != null && razonSocial.sameValueAs(other.razonSocial)));
return ret;
}
public void validaRegimenFiscal(RegimenFiscal regimenFisal) throws ValidationException{
tipo = this.rfc.tipoPersonaFiscal();
regimenFisal.valida(tipo);
}
public void setRfc(Rfc rfc){
this.rfc = rfc;
//tipo = rfc.tipoPersonaFiscal();
}
}
<file_sep>package com.cubetech.facturador.emisor.domain.cuenta;
import org.springframework.data.repository.Repository;
public interface CuentaRepository extends Repository<Cuenta, Long>{
public Cuenta findOneByCorrelacion (String correlacion);
public Cuenta save(Cuenta cuenta);
public void delete(Cuenta cuenta);
}
<file_sep>package com.cubetech.facturador.emisor.application.impl;
import org.springframework.stereotype.Service;
import com.cubetech.facturador.emisor.application.CuentaService;
import com.cubetech.facturador.emisor.interfaces.facade.dto.CuentaDTO;
@Service
public class CuentaServiceImpl implements CuentaService {
@Override
public void creaCuenta(CuentaDTO cuenta) {
// TODO Auto-generated method stub
}
}
<file_sep>package com.cubetech.facturador.emisor.application.impl;
/*
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import com.cubetech.facturador.emisor.AppConfigTest;
import com.cubetech.facturador.emisor.application.EmisorService;
import com.cubetech.facturador.emisor.interfaces.facade.dto.ArchivoDTO;
import com.cubetech.facturador.emisor.interfaces.facade.dto.CertificadoDTO;
import com.cubetech.facturador.emisor.interfaces.facade.dto.DireccionDTO;
import com.cubetech.facturador.emisor.interfaces.facade.dto.EmisorDTO;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes=AppConfigTest.class)
public class EmisorServiceImpl_tempTest {
@Autowired
EmisorService emisorService;
@Test
public void consultaEmisortest() {
EmisorDTO emisortmp = new EmisorDTO();
CertificadoDTO certificadotmp = new CertificadoDTO();
DireccionDTO direcciontmp = new DireccionDTO();
ArchivoDTO logo = new ArchivoDTO();
ArchivoDTO privado = new ArchivoDTO();
ArchivoDTO publico = new ArchivoDTO();
direcciontmp.setCalle("Av siempre viva");
direcciontmp.setCodigoPostal("78398");
direcciontmp.setColonia("El paseo");
direcciontmp.setEstado("San Luis Potosi");
direcciontmp.setMunicipio("SLP");
direcciontmp.setNumeroExterior("322");
direcciontmp.setPais("Mexico");
logo.setNombre("LogotipoCompañia.jpg");
logo.setTipo("JPG/Image");
logo.setContent("<KEY>);
privado.setNombre("archivo.key");
privado.setTipo("Application/certificate");
privado.setContent("<KEY>
publico.setNombre("archivo.cer");
publico.setTipo("Application/certificate");
publico.setContent("<KEY>
certificadotmp.setPassword("<PASSWORD>");
certificadotmp.setPrivado(privado);
certificadotmp.setPublico(publico);
emisortmp.setCertificado(certificadotmp);
emisortmp.setCorrelacion("1");
emisortmp.setDireccion(direcciontmp);
emisortmp.setLugarExpedicion("78398");
emisortmp.setLogo(logo);
emisortmp.setNombre("CUBETECHNOLOGIC");
emisortmp.setRegimenFiscal("601");
emisortmp.setRfc("CMC161114E10");
}
}
*/<file_sep>VERSION=0.0.1
IMAGEN=kster/emisor
NAME=emisor
docker service rm $NAME || true
mvn package
docker service rm $NAME || true
docker rmi $IMAGEN:$VERSION || true
docker build -t $IMAGEN:$VERSION .
docker service create \
--name $NAME \
--network revnet \
--network appnet \
--restart-condition any \
--replicas=1 \
--restart-delay 5s \
--update-delay 10s \
--update-parallelism 1 \
-p 57778:57778 \
--mount type=bind,source=/etc/localtime,destination=/etc/localtime \
$IMAGEN:$VERSION
<file_sep>package com.cubetech.facturador.emisor.domain;
import static org.junit.Assert.*;
import org.junit.Test;
import com.cubetech.facturador.emisor.domain.common.RazonSocial;
public class RazonSocialTest {
@Test
public void valido() {
//fail("Not yet implemented");
assertEquals(true, RazonSocial.Valido("CUBETECHNOLOGIC SAS DE CV"));
assertEquals(false, RazonSocial.Valido("|CUBETECHNOLOGIC SAS DE CV"));
assertEquals(true, RazonSocial.Valido("CUBE Ññ!\"%&'´-:;<=>@_,{}`~áéíóúÁÉÍÓÚüÜTECHNOLOGIC SAS DE CV"));
assertEquals(false, RazonSocial.Valido(".CUBETECHNOLOGIC SAS DE CV"));
assertEquals(true, RazonSocial.Valido("CUBETECHNOLOGIC SAS DE CVksmfklsdmfangkjdnfgmdfngmjsnfdnsjglrnvfjdngdfgbsrjkn,,dfnfjdngsrjngk;rtsntgirengdfngkjrengrengnzdfkgnarel-ngadfkgndz,:mngz-kjdnv zdsjrengarenjengjerg mdngjdfngkjdzfngkjdfngjznv kzdfgnzdmdhjsndfkjsdfkjdnfdgbjfddbfdbgfdbgfdmnfbfd"));
assertEquals(false, RazonSocial.Valido("CUBETECHNOLOGIC SAS DE CVksmfklsdmfangkjdnfgmdfngmjsnfdnsjglrnvfjdngdfgbsrjkn,,dfnfjdngsrjngk;rtsntgirengdfngkjrengrengnzdfkgnarel-ngadfkgndz,:mngz-kjdnv zdsjrengarenjengjerg mdngjdfngkjdzfngkjdfngjznv kzdfgnzdmdhjsndfkjsdfkjdnfdgbjfddbfdbgfdbgfdmnfbfdab"));
}
@Test( expected = IllegalArgumentException.class)
public void constructorException(){
new RazonSocial(".CUBETECHNOLOGIC SAS DE CV");
}
@Test
public void constructorOK(){
new RazonSocial("CUBETECHNOLOGIC SAS DE CV");
}
}
| 9a92778bb775f480bcf7fe0e71ec50fc3432c136 | [
"Java",
"Shell"
] | 19 | Java | njmube/Emisor | f45996ea811897d997d785a9f00cabd0f9d284fb | 89e5c2fd6e927408aa4cfd63c230890257bffe44 | |
refs/heads/master | <file_sep>#!/bin/bash
set -e
cabal build
exec ./dist/build/hipam/hipam
| 588e3fea2af0a5e6882ac5952199a41018d26edc | [
"Shell"
] | 1 | Shell | bearice/hipam | 6d7f7a3195ecf3f27459daf72146d7400004a719 | 59fe4dc535684758ed4bea79eec3da199dfd9738 | |
refs/heads/master | <file_sep>myApp.service('regenService', function(){
this.regenLetter = function(claimId){
}
});<file_sep>var myControllers = angular.module('myControllers', []);
myControllers.
controller('testController', function($scope, $location,$route, Patient, EditPatients, GetPatient, currentEntityService){
$scope.patients = Patient.query();
$scope.editVar="New Patient";
$scope.dataObj = {};
$scope.pfields = [
{fieldName: 'Name', placeholder: 'First Last', type: 'text', fieldId: 'name', pattern: '^[a-zA-Z ]+$', required: 'true'},
{fieldName: 'Account Id', placeholder: 'Enter Account Id', type: 'number', fieldId: 'accountId', pattern: '^[0-9]+$', required: "false"},
{fieldName: 'Insurance Id', placeholder: 'Enter Insurance Id', type: 'text', fieldId: 'insId', pattern: '^[0-9A-Za-z-]+$', required: "false"},
{fieldName: 'Date of Birth', placeholder: 'MM/DD/YYYY', type: 'date', fieldId: 'dateOfBirth', pattern: '', required: "true"},
{fieldName: 'Street', placeholder: 'Enter Street Name', type: 'text', fieldId: 'ptStreet',pattern: '^[a-zA-Z0-9 ]+$', required: "false"},
{fieldName: 'Town', placeholder: 'Enter Town Name', type: 'text', fieldId: 'ptTown', pattern: '^[a-zA-Z ]+$', required: "false"},
{fieldName: 'State', placeholder: 'Enter State Abbreviation',type: 'text', fieldId: 'ptState', pattern: '^[A-Z]{2}', required: "false"},
{fieldName: 'ZipCode', placeholder: 'Enter ZipCode', type: 'text', fieldId: 'ptZip', pattern: '^[0-9]+$', required: "false"}];
$scope.cancel = function(){
}
$scope.removePatient = function(id){
EditPatients.remove({id: id}, function(){
$route.reload();
});
};
$scope.goEditRoute = function(id){
GetPatient.get({id: id}, function(data){
var pat = data;
pat.dateOfBirth = new Date(pat.dateOfBirth);
currentEntityService.setCurrentEntity(pat);
$location.path('/editpatient');
});
};
$scope.savePatient = function() {
Patient.save($scope.dataObj, function(){
currentEntityService.setCurrentEntity($scope.dataObj);
$location.path('/dashboard');
});
}
}).
controller('editController', function($scope, $location, EditPatients, currentEntityService){
$scope.editVar = "Edit Patient";
$scope.pfields = currentEntityService.getPfields();
$scope.dataObj = {};
$scope.dataObj = currentEntityService.getCurrentEntity();
$scope.savePatient = function(){
EditPatients.save($scope.dataObj, function(){
$location.path('/patients');
});
}
}).
controller('facilityController', function($scope, $route, Facility, $location, currentEntityService, EditFacility){
$scope.editVar = "New Facility";
$scope.facilityFields = currentEntityService.getFacilityFields();
$scope.dataObj = {};
$scope.facilities = Facility.query();
$scope.saveFacility = function() {
Facility.save($scope.dataObj, function(){
$location.path("/facilities");
});
};
$scope.getTableHeight = function() {
var rowHeight = 41; // your row height
var headerHeight = 30; // your header height
return {
height: ($scope.facilities.length * 42 + headerHeight + 200) + "px"
};
};
$scope.gridOptions = {
data: 'facilities', rowHeight: 41,enableHorizontalScrollbar: 0,
columnDefs: [
{field: 'facilityName', displayName: 'Facility Name'}, {field: 'npi', displayName: 'NPI'}, {field: 'taxId', displayName: 'Tax ID'},
{field: 'address', displayName: 'Address', cellTemplate:
"<div class='ngCellText'>{{row.entity.street}}</br>{{row.entity.town}}, {{row.entity.state}} {{row.entity.zip}}</div>"},
{field: 'phone', displayName: 'Telephone'}, {field: 'fax', displayName: 'Fax'}, {field: 'billingPhone', displayName: "Billing Phone"},
{name: 'remove', displayName: 'Remove', cellTemplate: '<button class="btn btn-danger btn-sm" ng-click="grid.appScope.removeFacility(row.entity)"><span class="glyphicon glyphicon-remove-circle"></span></button>'},
{name: 'edit', displayName: 'Edit', cellTemplate: '<button class="btn btn-info btn-sm" ng-click="grid.appScope.goEditRoute(row.entity)"><span class="glyphicon glyphicon-edit"></span></button>'}]
};
$scope.removeFacility = function(entity){
if (confirm("Are you sure you want to delete this facility?") == true){
EditFacility.remove({id: entity.id}, function(){
$route.reload();
});
}
}
$scope.goEditRoute = function(entity){
currentEntityService.setCurrentEntity(entity);
$location.path('/editfacility');
}
}).
controller('editFacilityController', function($scope, currentEntityService, $location, EditFacility){
$scope.editVar = "Edit Facility";
$scope.facilityFields = currentEntityService.getFacilityFields();
$scope.dataObj = {};
$scope.dataObj = currentEntityService.getCurrentEntity();
$scope.saveFacility = function(){
EditFacility.save($scope.dataObj, function(){
$location.path("/facilities");
})
}
}).
controller('doctorController', function($scope, Doctors, $location, $route, GetDoctor, currentEntityService, GetFacility){
$scope.editVar="New Doctor";
$scope.doctors = Doctors.query();
$scope.dataObj = {};
$scope.doctorFields = [
{fieldName: 'Name', placeholder: 'First Last', type: 'text', fieldId: 'name', pattern: '^[a-zA-Z ]+$', required: "true"},
{fieldName: 'NPI', placeholder: 'Enter NPI Number', type: 'number', fieldId: 'npi', pattern: '^[0-9]+$', required: "true"},
{fieldName: 'Facility Tax ID', placeholder: 'Enter Affiliated Facility Tax ID Number', type: 'text', fieldId: 'facility', pattern: '^[0-9-]+$', required: "true"}];
$scope.gridOptions = {
data: 'doctors', rowHeight: 35, enableHorizontalScrollbar: 0,
columnDefs: [
{field: 'name', displayName: 'Doctor Name'}, {field: 'npi', displayName: 'Doctor NPI'}, {field: 'facility', displayName: 'Facility Name'},
{name: 'remove', displayName: 'Remove', cellTemplate: '<button class="btn btn-danger btn-sm" ng-click="grid.appScope.removeDoctor(row.entity)"><span class="glyphicon glyphicon-remove-circle"></span></button>'},
{name: 'edit', displayName: 'Edit', cellTemplate: '<button class="btn btn-info btn-sm" ng-click="grid.appScope.goEditRoute(row.entity)"><span class="glyphicon glyphicon-edit"></span></button>'}]
};
$scope.saveDoctor = function() {
Doctors.save($scope.dataObj, function(){
$location.path("/doctors");
});
}
$scope.goEditRoute = function(entity){
GetFacility.get({id: entity.facilityId}, function(facilityData){
GetDoctor.get({id: entity.id}, function(doctorData){
var doctor = {};
doctor.name = doctorData.name;
doctor.npi = doctorData.npi;
doctor.id = doctorData.id;
doctor.facility = facilityData.taxId;
currentEntityService.setCurrentEntity(doctor);
$location.path('/editdoctor');
});
});
}
$scope.removeDoctor = function(entity){
if (confirm("Are you sure you want to delete this doctor?") == true) {
Doctors.remove({id: entity.id}, function(){
$route.reload();
});
}
}
}).
controller('editDoctorController', function(currentEntityService, $scope, GetDoctor, $location){
$scope.editVar = "Edit Doctor";
$scope.doctorFields = currentEntityService.getDoctorFields();
$scope.dataObj = {};
$scope.dataObj = currentEntityService.getCurrentEntity();
$scope.saveDoctor = function(){
GetDoctor.save($scope.dataObj, function(){
$location.path('/doctors');
});
}
}).
controller('insuranceController', function($scope, Insurances, $location, $route, currentEntityService, EditInsurance){
$scope.dataObj = {};
$scope.editVar = "New Insurance";
$scope.insuranceFields = currentEntityService.getInsuranceFields();
$scope.saveInsurance = function() {
Insurances.save($scope.dataObj, function(){
$location.path("/appeals");
});
};
$scope.insurances = Insurances.query();
$scope.getTableHeight = function() {
var rowHeight = 41; // your row height
var headerHeight = 30; // your header height
return {
height: ($scope.insurances.length * 42 + headerHeight + 200) + "px"
};
};
$scope.gridOptions = {
data: 'insurances', rowHeight: 41,enableHorizontalScrollbar: 0,
columnDefs: [
{field: 'name', displayName: 'Insurance Name'}, {field: 'dept', displayName: 'Department'},
{field: 'address', displayName: 'Address', cellTemplate:
"<div class='ngCellText'>{{row.entity.street}}</br>{{row.entity.town}}, {{row.entity.state}} {{row.entity.zip}}</div>"},
{field: 'phone', displayName: 'Telephone'},
{name: 'remove', displayName: 'Remove', cellTemplate: '<button class="btn btn-danger btn-sm" ng-click="grid.appScope.removeInsurance(row.entity)"><span class="glyphicon glyphicon-remove-circle"></span></button>'},
{name: 'edit', displayName: 'Edit', cellTemplate: '<button class="btn btn-info btn-sm" ng-click="grid.appScope.goEditRoute(row.entity)"><span class="glyphicon glyphicon-edit"></span></button>'}]
};
$scope.removeInsurance = function(entity){
EditInsurance.remove({id: entity.id});
$route.reload();
};
$scope.goEditRoute = function(entity){
currentEntityService.setCurrentEntity(entity);
$location.path('/editinsurance');
};
}).
controller('editInsController', function($scope, currentEntityService, EditInsurance){
$scope.editVar = "Edit Insurance";
$scope.insuranceFields = currentEntityService.getInsuranceFields();
$scope.dataObj = {};
$scope.dataObj = currentEntityService.getCurrentEntity();
}).
controller('collectionController', function($scope, $location, $http, $q, Patient, Doctors, Facility, $route, Collection, batchService){
$scope.patients = Patient.query();
$scope.doctors = Doctors.query();
$scope.facilities = Facility.query();
$scope.selectedValue = [];
$scope.collectionFields = [
{fieldName: 'Patient', data: $scope.patients, showValue: 'name', addLink: 'patient'},
{fieldName: 'Facility', data: $scope.facilities, showValue: 'facilityName', addLink: 'facility'}
];
$scope.addEntity = function(addEntityLink) {
//currentEntityService.setCurrentEntity({});
$location.path("/"+addEntityLink);
};
$scope.genCollectionLetter = function() {
$scope.collectionDto = {patientId: "", facilityId: "", dateCreated: "", payment: ""};
$scope.collectionDto.patientId = $scope.selectedValue.Patient.id;
$scope.collectionDto.facilityId = $scope.selectedValue.Facility.id;
$scope.collectionDto.dateCreated = new Date();
$scope.collectionDto.payment = $scope.selectedAmountDue;
$scope.collectionDto.letterType = $scope.letterType;
if($scope.selectedValue.Patient.ptStreet != null && $scope.selectedValue.Patient.ptStreet != ""){
var deferred = $q.defer();
$http({
method: "POST",
data: $scope.collectionDto,
url: '/customdocs/service/collectionletter'
}).success(function(data, status){
deferred.resolve(data);
deferred.promise.then(function(data){
window.location.href = "/customdocs/service/gencollectionletter?collectionId=" + data;
$location.path("/dashboard");
});
});
} else {
alert("Patient Address is Required!!");
}
//Collection.save($scope.collectionDto).$promise.then(function(data)
//window.location.href = "http://192.168.12.184:8080/customdocs/service/gencollectionletter?collectionId=" + $scope.collectionDto.collectionId;
//currentEntityService.setCurrentAppealLetter(null);
//});
};
}).
controller('appealsController', function($scope, $location, Patient, Doctors, Facility, Insurances, AppealsLetter, currentEntityService){
$scope.patients = Patient.query();
$scope.doctors = Doctors.query();
$scope.facilities = Facility.query();
$scope.insurances = Insurances.query();
$scope.selectedValue = [];
if(currentEntityService.getCurrentAppealLetter() != null){
$scope.selectedParOne = currentEntityService.getCurrentAppealLetter().parOne;
$scope.selectedParTwo = currentEntityService.getCurrentAppealLetter().parTwo;
$scope.selectedClaimId = currentEntityService.getCurrentAppealLetter().claimId;
}
$scope.appealFields = [
{fieldName: 'Patient', data: $scope.patients, showValue: 'name', addLink: 'patient'},
{fieldName: 'Insurance', data: $scope.insurances, showValue: 'name', addLink: 'insurance'},
{fieldName: 'Facility', data: $scope.facilities, showValue: 'facilityName', addLink: 'facility'},
{fieldName: 'Doctor', data: $scope.doctors, showValue: 'name', addLink: 'doctor'},
];
$scope.addEntity = function(addEntityLink) {
//currentEntityService.setCurrentEntity({});
$location.path("/"+addEntityLink);
};
$scope.genAppealsLetter = function() {
$scope.appealsDto = {patientId: "", doctorId: "", facilityId: "", insuranceId: "", dateOfService: "", claimId: "", dateCreated: "", parOne: "", parTwo: ""};
$scope.appealsDto.patientId = $scope.selectedValue.Patient.id;
$scope.appealsDto.doctorId = $scope.selectedValue.Doctor.id;
$scope.appealsDto.facilityId = $scope.selectedValue.Facility.id;
$scope.appealsDto.insuranceId = $scope.selectedValue.Insurance.id;
$scope.appealsDto.dateOfService = $scope.selectedDateOfService;
$scope.appealsDto.claimId = $scope.selectedClaimId;
$scope.appealsDto.dateCreated = new Date();
$scope.appealsDto.parOne = $scope.selectedParOne;
$scope.appealsDto.parTwo = $scope.selectedParTwo;
if(($scope.selectedValue.Patient.accountId != null) && ($scope.selectedValue.Patient.accountId != 0) && ($scope.selectedValue.Patient.insId != null) &&
($scope.selectedValue.Patient.insId != "")){
AppealsLetter.save($scope.appealsDto).$promise.then(function(){
window.location.href = "/customdocs/service/appealsletter?claimId=" + $scope.appealsDto.claimId;
currentEntityService.setCurrentAppealLetter(null);
$location.path("/dashboard");
});
}
else {
alert("Patient Insurance Id and Account Id is required!!");
}
}
}).
controller('pcpController', function($scope, Patient, Doctors, Facility, $location, $http){
$scope.patients = Patient.query();
$scope.doctors = Doctors.query();
$scope.facilities = Facility.query();
$scope.selectedValue = [];
$scope.addEntity = function(addEntityLink) {
$location.path("/"+addEntityLink);
};
$scope.genPCPLetter = function(){
$scope.pcpLetterDetails = {patientId: "", doctorId: "", facilityId: "", dosNotPaid: "", startDate: "", amountDue: "", dateCreated: ""};
$scope.pcpLetterDetails.patientId = $scope.selectedValue.Patient.id;
$scope.pcpLetterDetails.doctorId = $scope.selectedValue.Doctor.id;
$scope.pcpLetterDetails.facilityId = $scope.selectedValue.Facility.id;
$scope.pcpLetterDetails.dosNotPaid = $scope.selectedDatesOfServices;
$scope.pcpLetterDetails.startDate = $scope.selectedStartDate;
$scope.pcpLetterDetails.amountDue = $scope.selectedAmountDue;
$scope.pcpLetterDetails.dateCreated = new Date();
$http({
method: 'POST',
url: '/customdocs/service/genpcpletter',
data: $scope.pcpLetterDetails}).success(function(data){
var file = new Blob([data], {type: "application/octet-stream"});
saveAs(file, "pcpletter.html");
$location.path("/dashboard");
});
}
$scope.pcpFields = [
{fieldName: 'Patient', data: $scope.patients, showValue: 'name', addLink: 'patient'},
{fieldName: 'Facility', data: $scope.facilities, showValue: 'facilityName', addLink: 'facility'},
{fieldName: 'Doctor', data: $scope.doctors, showValue: 'name', addLink: 'doctor'}
];
}).
controller('dashboardController', function($scope, $filter, $location, $http, $route, GetPCPLetters, OpenAppealsLetters, Collection, batchService, AppealsLetter, EditAppealLetter, currentEntityService){
$scope.appealDetails = OpenAppealsLetters.query();
$scope.collectionDetails = Collection.query();
$scope.pcpLetters = GetPCPLetters.query();
$scope.dash = false;
$scope.pcp = false;
$scope.secondDash = true;
$scope.recordFlag = [];
$(function(){
var handler;
var isActive = $(".nav-tabs li")
handler = isActive.click(function(){
isActive.removeClass("btn-primary");
isActive.addClass("btn-default");
$(this).toggleClass("btn-primary");
})
})
$scope.reverse = false;
$scope.orderValue = 'patientName';
$scope.setOrder = function(orderValue){
if(orderValue === 'payment' || (typeof orderValue === 'function')){
$scope.reverse = !$scope.reverse;
$scope.orderValue = function(details){
return Number(details.payment);
}
} else {
$scope.reverse = ($scope.orderValue === orderValue) ? !$scope.reverse : false;
$scope.orderValue = orderValue;
}}
$scope.setPageSize = function(size){
$scope.pageSize = size;
}
$scope.pageSize = 10;
$scope.currentStart = 0;
$scope.numPages;
$scope.$watch('collectionFilter', function(){
$scope.currentStart = 0;
})
$scope.nextPage = function(){
var length = $scope.collectionDetails.length;
if ($scope.currentStart+$scope.pageSize < length){
$scope.currentStart +=$scope.pageSize;
}
}
$scope.prevPage = function(){
if ($scope.currentStart-$scope.pageSize < 0){
$scope.currentStart = 0;
} else {
$scope.currentStart -= $scope.pageSize;
}
}
$scope.addToBatch = function(object, index) {
index+=2;
$("#coltable tr:eq("+index+") #batchid").toggleClass("btn-primary");
if (batchService.objectExists(object) == true){
batchService.removeObject(object);
console.log(batchService.getBatchArray());
} else {
batchService.addObject(object);
console.log(batchService.getBatchArray());
}
}
$scope.genCollectionBatch = function(){
console.log(batchService.getBatchArray);
if (batchService.getBatchArray().length > 0){
$http({
method: 'POST',
url: '/customdocs/service/collectionbatch',
headers: {accept: 'application/zip'},
responseType: 'arraybuffer',
data: batchService.getBatchArray(),
}).success(function(data){
batchService.cleanBatchArray();
var file = new Blob([data], {type: "application/zip"});
saveAs(file, "temp.zip");
$scope.collectionDetails = Collection.query();
})
}else {alert("None selected!");}
}
$scope.showAppeals = function(){
$scope.dash = true;
$scope.secondDash = false;
$scope.pcp = false;
}
$scope.showCollections = function(){
$scope.dash = false;
$scope.secondDash = true;
$scope.pcp = false;
}
$scope.showPCPLetters = function(){
$scope.dash = false;
$scope.secondDash = false;
$scope.pcp = true;
}
$scope.edit = function(claimId){
EditAppealLetter.get({claimId: claimId}, function(data){
currentEntityService.setCurrentAppealLetter(data);
$location.path('/appeals')
});
}
$scope.editCollection = function(collectionId){
$http({
method: 'POST',
url: '/customdocs/service/collectionletter',
data: collectionId
}).success(function(data){
$scope.recordFlag[data] = true;
})
}
$scope.removePCPLetter = function(pcpId){
GetPCPLetters.remove({pcpId: pcpId}, function(){
$scope.pcpLetters = GetPCPLetters.query();
});
}
$scope.remove = function(claimId){
AppealsLetter.remove({claimId: claimId}, function(){
$scope.appealDetails = OpenAppealsLetters.query();
});
}
$scope.removeCollection = function(id){
Collection.remove({collectionId: id}, function(){
$scope.collectionDetails = Collection.query();
});
}
});<file_sep>var myApp = angular.module('myApp', ['ngRoute','routeModule', 'ngResource', 'ui.grid', 'ui.grid.autoResize','myControllers']);
myApp.service('currentEntityService', function(){
var currentEntity = {};
var currentAppealLetter = {};
var pfields = [
{fieldName: 'Name', placeholder: 'First Last', type: 'text', fieldId: 'name', pattern: '^[a-zA-Z ]+$', required: "true"},
{fieldName: 'Account Id', placeholder: 'Enter Account Id', type: 'number', fieldId: 'accountId', pattern: '^[0-9]+$', required: "false"},
{fieldName: 'Insurance Id', placeholder: 'Enter Insurance Id', type: 'text', fieldId: 'insId', pattern: '^[0-9A-Za-z-]+$', required: "false"},
{fieldName: 'Date of Birth', placeholder: 'MM/DD/YYYY', type: 'date', fieldId: 'dateOfBirth', pattern: '', required: "true"},
{fieldName: 'Street', placeholder: 'Enter Street Name', type: 'text', fieldId: 'ptStreet',pattern: '^[a-zA-Z0-9 ]+$', required: "false"},
{fieldName: 'Town', placeholder: 'Enter Town Name', type: 'text', fieldId: 'ptTown', pattern: '^[a-zA-Z ]+$', required: "false"},
{fieldName: 'State', placeholder: 'Enter State Abbreviation',type: 'text', fieldId: 'ptState', pattern: '^[A-Z]{2}', required: "false"},
{fieldName: 'ZipCode', placeholder: 'Enter ZipCode', type: 'text', fieldId: 'ptZip', pattern: '^[0-9]+$', required: "false"}];
var doctorFields = [
{fieldName: 'Name', placeholder: 'First Last', type: 'text', fieldId: 'name', pattern: '^[a-zA-Z ]+$', required: "true"},
{fieldName: 'NPI', placeholder: 'Enter NPI Number', type: 'number', fieldId: 'npi', pattern: '^[0-9]+$', required: "true"},
{fieldName: 'Facility Tax ID', placeholder: 'Enter Affiliated Facility Tax ID Number', type: 'text', fieldId: 'facility', pattern: '^[0-9-]+$', required: "true"}];
var insuranceFields = [
{fieldName: 'Name', placeholder: 'First Last', type: 'text', fieldId: 'name', pattern: '^[a-zA-Z ]+$', required: "true"},
{fieldName: 'Department', placeholder: 'Enter Department Name', type: 'text', fieldId: 'dept', pattern: '^[a-zA-Z0-9 ]+$', required: "true"},
{fieldName: 'Street', placeholder: 'Enter Street Name', type: 'text', fieldId: 'street', pattern: '^[a-zA-Z0-9 ]+$', required: "true"},
{fieldName: 'Town', placeholder: 'Enter Town Name', type: 'text', fieldId: 'town', pattern: '^[a-zA-Z ]+$', required: "true"},
{fieldName: 'State', placeholder: 'Enter State Abbreviation', type: 'text', fieldId: 'state', pattern: '^[A-Z]{2}', required: "true"},
{fieldName: 'ZipCode', placeholder: 'Enter ZipCode', type: 'text', fieldId: 'zip', pattern: '^[0-9]+$', required: "true"},
{fieldName: 'Phone', placeholder: '#-###-###-####', type: 'text', fieldId: 'phone', pattern: '^[0-9-]+$', required: "true"}];
var facilityFields = [
{fieldName: 'Facility Name',placeholder: 'Enter Facility Name', type: 'text', fieldId: 'facilityName', pattern: '^[a-zA-Z& ]+$', required: "true"},
{fieldName: 'Street', placeholder: 'Enter Street Name', type: 'text', fieldId: 'street', pattern: '^[a-zA-Z0-9 ]+$', required: "true"},
{fieldName: 'Town', placeholder: 'Enter Town Name', type: 'text', fieldId: 'town', pattern: '^[a-zA-Z ]+$', required: "true"},
{fieldName: 'State', placeholder: 'Enter State Abbreviation', type: 'text', fieldId: 'state', pattern: '^[A-Z]+$', required: "true"},
{fieldName: 'ZipCode', placeholder: 'Enter ZipCode', type: 'text', fieldId: 'zip', pattern: '^[0-9]+$', required: "true"},
{fieldName: 'Phone', placeholder: '#-###-###-####', type: 'text', fieldId: 'phone', pattern: '^[0-9-]+$', required: "true"},
{fieldName: 'Fax', placeholder: '#-###-###-####', type: 'text', fieldId: 'fax', pattern: '^[0-9-]+$', required: "true"},
{fieldName: 'Billing Phone',placeholder: '#-###-###-####', type: 'text', fieldId: 'billingPhone', pattern: '^[0-9-]+$', required: "true"},
{fieldName: 'NPI', placeholder: 'Enter NPI Number', type: 'number', fieldId: 'npi', pattern: '^[0-9]+$', required: "true"},
{fieldName: 'Tax ID', placeholder: 'Enter Tax ID Number', type: 'text', fieldId: 'taxId', pattern: '^[0-9-]+$', required: "true"}];
this.setCurrentEntity = function(obj){
currentEntity = obj;
return true;
};
this.getCurrentEntity = function(){
return currentEntity;
};
this.setCurrentAppealLetter = function(obj){
currentAppealLetter = obj;
return true;
};
this.getCurrentAppealLetter = function(){
return currentAppealLetter;
};
this.formatDate = function(obj){
"'"+obj+"'";
};
this.getPfields = function(){
return pfields;
}
this.getDoctorFields = function(){
return doctorFields;
}
this.getInsuranceFields = function(){
return insuranceFields;
}
this.getFacilityFields = function(){
return facilityFields;
}
}).
service('batchService', function(){
var batchArray = [];
this.objectExists = function(object) {
var i = 0;
do {
if((batchArray[i] != null) && (batchArray[i].collectionId == object.collectionId)){
return true;
}
i++;
}
while (i < batchArray.length);
}
this.addObject = function(object){
if (!this.objectExists(object)) {
batchArray.push(object);
}
}
this.removeObject = function(object){
var position = batchArray.map(function(x){return x.collectionId}).indexOf(object.collectionId);
if (position != -1){
var removed = batchArray.splice(position, 1);
}}
this.getBatchArray = function(){
return batchArray;
}
this.cleanBatchArray = function(){
batchArray = [];
}
});
<file_sep> myApp.factory('Patient', function($resource){
return $resource('/customdocs/service/patient');
}).
factory('Facility', function($resource){
return $resource('/customdocs/service/facility');
}).
factory('GetFacility', function($resource){
return $resource('/customdocs/service/getfacility');
}).
factory('EditFacility', function($resource){
return $resource('/customdocs/service/editfacility');
}).
factory('Doctors', function($resource){
return $resource('/customdocs/service/doctor');
}).
factory('GetDoctor', function($resource){
return $resource('/customdocs/service/getdoctor');
}).
factory('Insurances', function($resource) {
return $resource('/customdocs/service/insurance');
}).
factory('EditInsurance', function($resource) {
return $resource('/customdocs/service/editinsurance');
}).
factory('AppealsLetter', function($resource){
return $resource('/customdocs/service/appealsletter');
}).
factory('OpenAppealsLetters', function($resource){
return $resource('/customdocs/service/openappealsletters');
}).
factory('EditAppealLetter', function($resource){
return $resource('/customdocs/service/editappealletter');
}).
factory('EditPatients', function($resource){
return $resource('/customdocs/service/editpatient');
}).
factory('Collection', function($resource){
return $resource('/customdocs/service/collectionletter');
}).
factory('GetPatient', function($resource){
return $resource('/customdocs/service/getpatient');
}).
factory('GetPCPLetters', function($resource){
return $resource('/customdocs/service/pcpletters');
});<file_sep><!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
.bodyBody {
margin: 10px;
font-size: 12px;
}
.facilityHeader{
text-align: left;
}
.divHeader {
text-align: right;
border: 1px solid;
}
.divInsuranceInfo {
text-align: left;
float: left;
width: 1288px;
}
.newDate {
float: left;
text-align: left;
width: 1288px;
}
.divSubject {
clear: both;
font-weight: bold;
padding-top: 80px;
}
.referenceInfo{
float: left;
text-align: left;
}
.divAdios {
float: left;
padding-top: 50px;
}
</style>
<title>Appeal Letter</title>
</head>
<body class="bodyBody">
<div class="facilityHeader">
<h3>${facility.facilityName}</h3>
<h6>${facility.street}, ${facility.town}, ${facility.state} ${facility.zip} <br>
Phone: ${facility.phone} Fax: ${facility.fax} </h6>
</div>
<div class="divInsuranceInfo">
${insurance.name}<br/>
ATTN: ${insurance.dept}<br/>
${insurance.street}, ${insurance.state} ${insurance.zip}
</div>
<div class="newDate">
<br/>
${dateCreated?date}
</div>
<br/>
<div class="referenceInfo">
Ref: ${patient.name} <br>
ID: ${patient.insId}<br>
DOB: ${patient.dateOfBirth}<br>
DOS: ${dateOfService?date}<br>
ClaimID: ${claimId}<br>
Tax ID: ${facility.taxId}<br>
NPI: ${facility.npi?c}<br>
</div>
<div class="divSubject">
Dear Sir or Madam,
</div>
<div class="divContents">
<p>
<br>
${parOne}
</p>
<p>
Please find the follwing documents and reprocess the claim.
<ul>
<li>Medicaid EOB</li>
<li>Timely filling proof</li>
<li>Other Insurance EOB</li>
<li>Medical Notes as required</li>
<li>Preexisting form</li>
<li>Any other forms</li>
</ul>
</p>
<p>
${parTwo}
</p>
<br>
<p>
In case of any questions, you are free to call me at 732-290-1014 or
email me at <EMAIL>
</p>
</div>
<div class="divAdios">
Thank You, <br/>
<br/>
<NAME> <br/>
Billing Manager <br/>
</div>
</body>
</html> | de1006e647486ed800d738714b2dbb714d93916c | [
"JavaScript",
"HTML"
] | 5 | JavaScript | initalcode/customdocs-new | fa91591c5e4cebf61e320c608f2a287092fb1103 | a4a8c34180f240f9e60dcb909d42175755a25ac1 | |
refs/heads/master | <repo_name>herrsorgenfrei/sqsservice<file_sep>/src/main/java/de/tschumacher/sqsservice/consumer/SQSMessageReceiver.java
/*
Copyright 2015 <NAME>
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.
*/
package de.tschumacher.sqsservice.consumer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazonaws.services.sqs.model.Message;
import de.tschumacher.sqsservice.SQSQueue;
import de.tschumacher.sqsservice.supplier.SQSMessageFactory;
public class SQSMessageReceiver<F> {
private static final Logger logger = LoggerFactory
.getLogger(SQSMessageReceiver.class);
private static final int WORKER_COUNT = 5;
protected static final int MAX_RETRYS = 5;
protected static final int RETRY_SECONDS = 60 * 2;
private final SQSMessageHandler<F> handler;
private final ExecutorService executorService;
private boolean running = false;
private final Runnable worker;
final SQSMessageFactory<F> factory;
public SQSMessageReceiver(final SQSQueue queue,
final SQSMessageHandler<F> handler,
final SQSMessageFactory<F> factory) {
super();
this.handler = handler;
this.worker = newWorker(queue);
this.executorService = Executors.newFixedThreadPool(WORKER_COUNT);
this.factory = factory;
start();
}
public void start() {
this.running = true;
for (int i = 0; i < WORKER_COUNT; i++) {
this.executorService.submit(this.worker);
}
}
public void stop() throws InterruptedException {
this.running = false;
}
private Runnable newWorker(final SQSQueue queue) {
return new Runnable() {
@Override
public void run() {
while (SQSMessageReceiver.this.running) {
try {
final Message receiveMessage = queue.receiveMessage();
if (receiveMessage != null) {
try {
SQSMessageReceiver.this.handler
.receivedMessage(
queue,
SQSMessageReceiver.this.factory
.createMessage(receiveMessage
.getBody()));
queue.deleteMessage(receiveMessage
.getReceiptHandle());
} catch (final Throwable e) {
logger.error("could not process message", e);
queue.changeMessageVisibility(
receiveMessage.getReceiptHandle(),
RETRY_SECONDS);
}
}
} catch (final Throwable e) {
logger.error("could not handle message", e);
}
}
}
};
}
@Override
protected void finalize() throws Throwable {
stop();
super.finalize();
}
}
<file_sep>/README.md
# SQS Service
-------------
Simple Implementation of Amazon Simple Queue Service | f5c6b2b24a18cc360db6ae34136ac3ba0c50ba79 | [
"Markdown",
"Java"
] | 2 | Java | herrsorgenfrei/sqsservice | c38dacaabc919d4ee359746fe49aaa9e2b536d8d | 21513e74d166d6fa15dcb6fb1734e7e3f53e4839 | |
refs/heads/master | <repo_name>GabrielCTroia/ionic-component-router<file_sep>/www/js/components/RootComponentAsDirective.js
const RootComponentAsDirective = () => ({
//replace: 'true',
template: `
<ion-view>
<h3>Root Component (as directive)</h3>
<button ng-click="pushNextViewCtrl()">
Component as View Controller
</button>
<br/>
<button ng-click="pushNextDirective()">
Component as Directive
</button>
</ion-view>
`,
scope: {
nav: '=',
params: '@',
},
controller: ['$scope', ($scope) => {
console.log('root component as directive', $scope);
const nextParams = {
msg: 23
};
$scope.pushNextViewCtrl = $scope.nav.push.bind($scope.nav, ComponentAsViewController, nextParams);
$scope.pushNextDirective = $scope.nav.push.bind($scope.nav, 'component-as-directive', nextParams);
}]
});
<file_sep>/README.md
# ionic-component-router
**This is a really early conceptualization of some ideas I had as a solution to the shortcomings
of ui-router in a mobile app.**
### Why
- Because ionic v2's navigation system is awesome but unfortunately it's also months away.
Besides, ionic v1 apps that are not ready to migrate yet can make use this approach.
- I am planning to use it in my own Ionic v1 medium to large project
### What does it do?
- It mostly tries to follow what react-native, ios or Ionic v2 navigation looks like, but in Ionic & Angular 1.
- Eliminates the need to define routes/states at config time. There is no idea of route anymore,
just what will the next screen show. Each screen shows a *component* at a time, which is represented by:
- a directive that has a `<ion-view>...</ion-view>` template
- a View Controller pair which is simply an object looking like:
```
{
template: "<ion-view>...</ion-view>",
controller: ['$scope', ($scope) => {...}]
}
```
### To Do:
- Ask more people if they think this can be useful!!! Please share your thoughts with me at [@gabrielctroia](https://twitter.com/gabrielctroia) on twitter.
- To make the migration easier from ui-router, it can support an already defined state
- Optimize the changes made to the DOM
- Cache a limited amount of viewed components
- Connect it to angular's animation system for transitions
- look into lazy loading the templates??
### How:
I promise I will update this as I move further, but for now please look at www/index.html and www/js/components<file_sep>/www/js/components/provider.js
angular.module('starter')
.directive('app', [RootComponentAsDirective])
.directive('componentAsDirective', [ComponentAsDirective])
<file_sep>/www/js/components/ComponentAsDirective.js
const ComponentAsDirective = () => ({
//replace: 'true',
template: `
<ion-view>
<button ng-click="nav.pop()">back</button>
<h3>Component As Directive</h3>
passed params: {{ params }}
<br/>
local vars: {{ local }}
<br/>
<br/>
<button ng-click="pushNextViewCtrl()">
Go To Component As View
</button>
</ion-view>
`,
scope: {
nav: '=',
params: '=',
},
controller: ['$scope', ($scope) => {
$scope.local = 'just a local var';
const nextParams = {
msg: 'params from directive'
};
$scope.pushNextViewCtrl = $scope.nav.push.bind($scope.nav, ComponentAsViewController, nextParams);
}]
});
<file_sep>/www/js/ComponentRouter.js
angular.module('ionic-component-router', [])
.directive('navController', [
'$compile', '$controller', '$interpolate',
($compile, $controller) => {
return {
//transclude: true,
//replace: true,
restrict: 'E',
priority: 99999, // highest priority
terminal: true, // needs to be terminal so the child directive will not render 2 times
scope: {},
compile(tElm) {
let $rootElm = tElm.children();
return {
pre($scope, $elm) {
const nav = new Nav($compile, $scope, $elm, angular, $controller);
nav.push({root: $rootElm});
nav.onChange((history) => {
console.log('Current View', history.slice(-1)[0]);
console.log(' history:', history);
});
}
}
}
}
}
]);
class Nav {
constructor($compile, $scope, $wrapperElm, angular, $controller) {
this._history = [];
this._rendered = {};
this._onChangeSubscribers = [];
this._$parentScope = $scope;
this._$wrapperElm = $wrapperElm;
this._$compile = $compile;
this._$controller = $controller;
this._angular = angular;
}
push(viewController, params = {}) {
if (typeof viewController === 'string') {
console.log('is a registered directive view controller');
} else {
console.log('is an unregistered view ctrl');
}
this._history.push({viewController, params});
this._publishOnChange();
}
pop() {
this._history.pop();
this._publishOnChange();
}
onChange(fn) {
if (typeof fn === 'function') {
this._onChangeSubscribers.push(fn);
} else {
console.warn('Nav.onChange(fn) must be a function!');
}
}
_publishOnChange() {
const last = this._history.slice(-1)[0];
this._render(last.viewController, last.params);
Array.prototype.map.call(this._onChangeSubscribers, f => f(this._history));
}
_compile({template, controller}, params) {
const localScope = this._$parentScope.$new();
localScope.nav = this;
localScope.params = params;
if (controller) {
const c = this._$controller(controller, {
$scope: localScope
});
template.data('$ngControllerController', c);
}
return this._$compile(template)(localScope);
}
_render(vc, params) {
const nextId = 'vc-' + this.history.length;
if (this._rendered[nextId]) {
console.log("I'm already rendered", this._rendered);
this._cleanDOM();
document.getElementById(nextId).style.display = '';
return this._rendered[nextId];
}
// normalize vc
let template;
// if directive
if (typeof vc === 'string') {
template = `<${vc} id="${nextId}" nav="nav" params="params"></${vc}>`;
// if root
} else if (vc.root) {
template = vc.root;
template.attr('id', nextId);
template.attr('nav', 'nav');
template.attr('params', 'params');
// if view-controller pair
} else {
template = this._angular.element(vc.template);
}
//
const compiled = this._compile({template, controller: vc.controller}, params);
// append to the DOM only if the VC is not root
if (this.history.length > 0) {
//this._cleanDOM();
this._$wrapperElm.append(compiled);
}
//this._rendered[nextId] = compiled;
};
_cleanDOM() {
const lastID = 'vc-' + (this.history.length - 1);
document.getElementById(lastID).style.display = 'none';
}
get history() {
return this._history;
}
}
| 6cfac8bbfd6f4345d713875785e045e6eecb2935 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | GabrielCTroia/ionic-component-router | 4844dab4b021a90d09be1eaaa130632094d74840 | 4fd6e4cd4d21dbecc84e03ec5c0ba823b338e84d | |
refs/heads/master | <repo_name>manuel1606/mx-ms-sapi-cross-security-secret-key<file_sep>/src/main/java/mx/bs/cross/security/provisioning/controllers/SecurityMethodController.java
package mx.bs.cross.security.provisioning.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import mx.bs.cross.db.commons.controllers.PersistentController;
import mx.bs.cross.security.db.model.SecurityMethodEntity;
import mx.bs.cross.security.db.services.SecurityMethodService;
@RestController
@RequestMapping("/securitymethod")
@CrossOrigin(origins = "*")
public class SecurityMethodController extends PersistentController<SecurityMethodService, SecurityMethodEntity> {
@Autowired
protected SecurityMethodController(SecurityMethodService service) {
super(service);
}
}
<file_sep>/src/main/java/mx/bs/cross/security/provisioning/SecurityProvisioningApplication.java
package mx.bs.cross.security.provisioning;
import java.util.Date;
import java.util.TimeZone;
import javax.annotation.PostConstruct;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import mx.bs.cross.security.core.app.SecuritySAPIApplication;
@SpringBootApplication
@EnableEurekaClient
@EnableAutoConfiguration
@EnableScheduling
@ComponentScan(basePackages = "mx.bs.cross.security.db.config")
@ComponentScan(basePackages = "mx.bs.cross.security.provisioning.controllers")
public class SecurityProvisioningApplication extends SecuritySAPIApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityProvisioningApplication.class, args);
}
@PostConstruct
void init() {
Date current = new Date();
System.out.println(current);
//TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
current = new Date();
System.out.println(current);
}
}
<file_sep>/src/main/java/mx/bs/cross/security/provisioning/controllers/SecurityApplicationSecretController.java
package mx.bs.cross.security.provisioning.controllers;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import mx.bs.cross.db.commons.controllers.PersistentController;
import mx.bs.cross.security.db.model.SecurityApplicationSecretEntity;
import mx.bs.cross.security.db.services.SecurityApplicationSecretService;
@RestController
@RequestMapping("/")
@CrossOrigin(origins = "*")
public class SecurityApplicationSecretController
extends PersistentController<SecurityApplicationSecretService, SecurityApplicationSecretEntity> {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
protected SecurityApplicationSecretController(SecurityApplicationSecretService service) {
super(service);
}
@Autowired
private SecurityApplicationSecretService securityApplicationSecretService;
@RequestMapping(value = "secrets", method = RequestMethod.GET)
public ResponseEntity<List<SecurityApplicationSecretEntity>> getSecrets() {
List<SecurityApplicationSecretEntity> secretEntity = new ArrayList<SecurityApplicationSecretEntity>();
secretEntity = securityApplicationSecretService.findAll();
return new ResponseEntity<List<SecurityApplicationSecretEntity>>(secretEntity, HttpStatus.OK);
}
@RequestMapping(value = "secrets/{secretId}", method = RequestMethod.GET)
public ResponseEntity<SecurityApplicationSecretEntity> getSecret(@PathVariable String secretId) {
SecurityApplicationSecretEntity secretEntity = new SecurityApplicationSecretEntity();
secretEntity = securityApplicationSecretService.findById(secretId);
return new ResponseEntity<SecurityApplicationSecretEntity>(secretEntity, HttpStatus.OK);
}
@RequestMapping(value = "applications/{securityApplicationId}/secrets", method = RequestMethod.GET)
public ResponseEntity<SecurityApplicationSecretEntity> getSecretsBysecrurityApp(
@PathVariable String securityApplicationId) {
SecurityApplicationSecretEntity secretEntity = new SecurityApplicationSecretEntity();
secretEntity = securityApplicationSecretService.findSecretById(securityApplicationId);
return new ResponseEntity<SecurityApplicationSecretEntity>(secretEntity, HttpStatus.OK);
}
@RequestMapping(value = "/applications/{securityApplicationId}/secrets/{secretId}", method = RequestMethod.GET)
public ResponseEntity<SecurityApplicationSecretEntity> getBySecurityAppAndSecretId(
@PathVariable String securityApplicationId, @PathVariable String secretId) {
SecurityApplicationSecretEntity secretEntity = new SecurityApplicationSecretEntity();
secretEntity = securityApplicationSecretService.findSecretById(secretId);
return new ResponseEntity<SecurityApplicationSecretEntity>(secretEntity, HttpStatus.OK);
}
@RequestMapping(value = "applications/{securityApplicationId}/secrets", method = RequestMethod.POST)
public ResponseEntity<SecurityApplicationSecretEntity> saveSecret(
@RequestBody SecurityApplicationSecretEntity request) {
SecurityApplicationSecretEntity secretEntity = new SecurityApplicationSecretEntity();
secretEntity = securityApplicationSecretService.save(request);
return new ResponseEntity<SecurityApplicationSecretEntity>(secretEntity, HttpStatus.OK);
}
@RequestMapping(value = "applications/{securityApplicationId}/secrets", method = RequestMethod.PUT)
public ResponseEntity<SecurityApplicationSecretEntity> updateSecret(@PathVariable String secretId,
@RequestBody SecurityApplicationSecretEntity request) {
SecurityApplicationSecretEntity secretEntity = new SecurityApplicationSecretEntity();
secretEntity = securityApplicationSecretService.findById(secretId);
secretEntity.setActive(request.getActive());
securityApplicationSecretService.save(secretEntity);
return new ResponseEntity<SecurityApplicationSecretEntity>(secretEntity, HttpStatus.OK);
}
@RequestMapping(value = "applications/{securityApplicationId}/secrets", method = RequestMethod.DELETE)
public ResponseEntity<SecurityApplicationSecretEntity> deleteSecret(@PathVariable String secretId) {
SecurityApplicationSecretEntity secretEntity = new SecurityApplicationSecretEntity();
secretEntity = securityApplicationSecretService.findById(secretId);
secretEntity.setActive(false);
securityApplicationSecretService.save(secretEntity);
return new ResponseEntity<SecurityApplicationSecretEntity>(secretEntity, HttpStatus.OK);
}
}
| c126c79f8bac2f6dbe507213448f157a7cc284f8 | [
"Java"
] | 3 | Java | manuel1606/mx-ms-sapi-cross-security-secret-key | fcd2358e9ef2045715bc51de87c344eedead3b31 | c9a9677bc69b0fa5a83b6b1494cfb75cf0faaac6 | |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Trshcan : MonoBehaviour
{
MainParticleLifeCycle[] recycleObjectList;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
recycleObjectList = transform.GetComponentsInChildren<MainParticleLifeCycle>();
foreach(MainParticleLifeCycle particle in recycleObjectList)
{
if(particle.m_stage == mainParticleStage.end)
{
Destroy(particle.transform.gameObject);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[System.Serializable]
public class EmitterHunter : Hunter
{
/*
* public LayerManager m_Layer;
* public LayerManager[] HuntingTargets;
* public GameObject HuntingSensor;
* [HideInInspector] public bool ifHasTarget;
* [HideInInspector] public List<GameObject> HuntingList;
*/
public EmitterHunter(EmitterParticleBehaiour _emitterParticle)
{
if(_emitterParticle != null)
emitterParticle = _emitterParticle;
}
public float TracingSpeed;
[HideInInspector]public EmitterParticleBehaiour emitterParticle;
int eatingNumber;
public GameObject currentTarget = null;
public GameObject getCurrentTarget{ get { return currentTarget; } }
public int getEatingNumber{get{return eatingNumber;}}
public bool isTracing{get{ return (currentTarget != null);}}
public void Hunting()
{
//Debug.Log("enter hunting");
if (!isTracing && ifHasTarget)
{
SelectTracingTarget(emitterParticle.transform);
//Debug.Log("select target");
return;
}
else if (!ifHasTarget)
{
//Debug.Log("currentTarget = null");
return;
}
//Debug.Log("ifHasTarget : " + ifHasTarget + " ; isTracing : " + isTracing);
//TracingTarget();
}
public void SelectTracingTarget(Transform m_transform)
{
if (HuntingList.Count > 0)
{
//Debug.Log("select hunting target");
float mostCloseDistance = 0;
GameObject mostCloseTarget = null;
if(mouse.HuntingTargets.Length == 0){
mouse.setHunigTarget(HuntingTargets);
Debug.Log("Hunting Targets" + mouse.HuntingTargets[0]);
}
for (int i = 0; i < HuntingList.Count; i++)
{
if(HuntingList[i] == null)continue;
float distanceToTarget = Vector3.Distance(m_transform.position, HuntingList[i].transform.position);
if(distanceToTarget > 10)
{
HuntingList.Remove(HuntingList[i]);
return;
}
if (mostCloseTarget == null)
{
currentTarget = HuntingList[i];
mostCloseDistance = Vector3.Distance(m_transform.position, currentTarget.transform.position);
}
else if (distanceToTarget < mostCloseDistance)
{
currentTarget = HuntingList[i];
mostCloseDistance = distanceToTarget;
}
}
}
else if(HuntingList.Count == 0)
{
currentTarget = null;
//Debug.Log("hunting List is empty");
}
}
//public void TracingTarget(Transform m_transform)
//{
// float sensorRadius = HuntingSensor.GetComponent<SphereCollider>().radius * HuntingSensor.transform.localScale.x;
// float distanceToTarget = Vector3.Distance(m_transform.position, currentTarget.transform.position);
// TracingMove(m_transform);
// if(distanceToTarget < sensorRadius)
// {
// EatingBehaviour();
// }
//}
//void TracingMove(Transform m_transform)
//{
// float _distance = Vector3.Distance(currentTarget.transform.position, m_transform.position);
// Vector3 dir = (currentTarget.transform.position - m_transform.transform.position).normalized;
// float t = Time.deltaTime * _distance / 2 * TracingSpeed * 0.35f;
// if (t > 0.5) t = 0.5f;
// m_transform.GetComponent<Rigidbody>().MovePosition(
// Vector3.Slerp(m_transform.position, currentTarget.transform.position, t));
//}
//void EatingBehaviour()
//{
// eatingNumber += 1;
// if(eatingNumber > emitterParticle.HowMuchNumberForEatingToGrowUp)
// {
// emitterParticle.GrowUp();
// eatingNumber = 0;
// }
// emitterParticle.motionStateNow = ParticleMotionState.Eating;
//}
}
[RequireComponent(typeof(Rigidbody),typeof(SphereCollider))]
public class EmitterParticleBehaiour : ParticleBehaiour{
/* 參考用
//public ApearenceStructure apearence;
//public PhysicMotionSetting physicMotion;
//public Hunter hunter;
//public ParticleLifeState stateNow;
//public ParticleMotionState motionStateNow;
//public int HowMuchNumberForEatingToGrowUp;
//public bool canItGrowUp = false;
//public bool isHunter = false;
//public bool ifNeedRandomReborn;
//int index;
//ScreenSpaceBoundary m_Boundary;
//Rigidbody m_rigidbody;
//SphereCollider m_collider;
*/
private static EmitterParticleBehaiour _instance ;
public EmitterParticleBehaiour instance{
get{
if (_instance == null) _instance = this;
return _instance;
}
}
int index;
int direction = 1;
float timer;
float timerAtEnd;
float rebornDelayTime;
public EmitterHunter m_hunter = new EmitterHunter(_instance);
[Header("Motion Related Attribbute")]
public Vector2 rebornDelay = new Vector2(2, 5);
[Tooltip("How long will it reborn after leaving boundary")]
public float endingDelay = 1.5f;
[Tooltip("(min,max)")]
public Vector2 stepRandomMoveDistance = new Vector2(1,2);
public Vector2 maxMoveAngle = new Vector2(60,120);
private Vector3 nextPosition;
[Header("ParticleEffect")]
public ParticleSystem TraceEffect;
public ParticleSystem ExplosionEffect;
// Use this for initialization
void Awake()
{
if(instance == null){
Debug.Log("initialize");
}
}
void Start () {
saveData();
Initialize();
}
// Update is called once per frame
void Update ()
{
LifeCycleStateSelector();
}
public override void Initialize()
{
InitializeComponent();
m_hunter.emitterParticle = instance;
if(isUseRandomReborn)
{
RandomReborn();
}
}
public override void RandomReborn()
{
direction = UnityEngine.Random.Range(0, 100) > 50 ? 1 : -1;
transform.position = RegenerateStartPosition(direction);
PositionInitialize();
}
public override void LifeCycleStateSelector()
{
timer += Time.deltaTime;
//switch
switch (stateNow)
{
case ParticleLifeState.RebornDelay:
RebornDelayBehaviour();
break;
case ParticleLifeState.Start:
StartBehaviour();
break;
case ParticleLifeState.Update:
UpdateBehaviour();
break;
case ParticleLifeState.End:
EndBehaviour();
break;
}
}
void RebornDelayBehaviour()
{
if (timer > rebornDelayTime)
{
stateNow = ParticleLifeState.Start;
}
}
void StartBehaviour()
{
timer = 0;
m_hunter.mouse.isBeEaten = false;
stateNow = ParticleLifeState.Update;
direction = UnityEngine.Random.Range(0, 100) > 50 ? 1 : -1;
transform.localPosition = RegenerateStartPosition(direction);
PositionInitialize();
m_hunter.HuntingList.Clear();
m_hunter.currentTarget = null;
transform.localScale = scale;
ExplosionEffect.Stop();
TraceEffect.Play();
GetComponent<MeshRenderer>().material.SetFloat("_Alpha", 1);
}
void UpdateBehaviour()
{
UpdateCycleStateSelector();
}
void EndBehaviour()
{
StartCoroutine(fadeOut(0.5f));
}
Vector3 nextRandomPos;
public override void UpdateCycleStateSelector()
{
//Debug.Log(m_updateStage);
EventManagement();
switch (motionStateNow)
{
case ParticleMotionState.Idle:
GerridaeMoveWay();
break;
case ParticleMotionState.Hunting:
GerridaeMoveWay();
//Hunter();
break;
case ParticleMotionState.Eating:
if (!isgrowing)
StartCoroutine(growing(1f));
motionStateNow = ParticleMotionState.Idle;
break;
case ParticleMotionState.BeEaten:
StartCoroutine(scaleDown(ExplosionEffect.main.duration, ExplosionEffect));
break;
}
//if particle leave boundary it will translate to end state
//but here I do is for avoiding particle stuck on the boundary line
if(!m_Boundary.isPointInside(transform) && timer > 5)
{
timerAtEnd += Time.deltaTime;
//Debug.Log("isPointInside : " + m_Boundary.isPointInside(transform) + "; timer : " + timer + " ; timerAtEnd : " + timerAtEnd);
if (timerAtEnd > endingDelay)
{
timer = 0;
timerAtEnd = 0;
nextPosition = Vector3.zero;
stateNow = ParticleLifeState.End;
//Debug.Log("enter end state");
}
}
}
public void EventManagement()
{
if(m_hunter.mouse.isBeEaten)
{
motionStateNow = ParticleMotionState.BeEaten;
}
else if(m_hunter.ifHasTarget && !m_hunter.getIsEating)
{
motionStateNow = ParticleMotionState.Hunting;
}
else if (m_hunter.getIsEating)
{
motionStateNow = ParticleMotionState.Eating;
m_hunter.mouse.Reset();
}
else
{
motionStateNow = ParticleMotionState.Idle;
}
}
void HuntingTracingMove()
{
LerpMove(nextPosition, this.transform.position, moveDistance);
}
/// <summary>
/// 水皿移動
/// </summary>
void GerridaeMoveWay()
{
float currentDistance = Vector3.Distance(transform.position, nextPosition);
//Debug.Log("transform.position : " + transform.position + " ; nextPosition : " + nextPosition + "Vector3.Distance(transform.position, nextPosition) : " + Vector3.Distance(transform.position, nextPosition));
if (currentDistance < 1.5f || currentDistance > 10f)
{
if(motionStateNow == ParticleMotionState.Idle)
GeneratNextPosion();
else if(motionStateNow == ParticleMotionState.Hunting)
{
//Debug.Log("GerridaeMoveWay hunting");
m_hunter.Hunting();
if(m_hunter.isTracing)
{
if (Vector3.Distance(transform.position, m_hunter.currentTarget.transform.position) > 15)
{
m_hunter.currentTarget = null;
motionStateNow = ParticleMotionState.Idle;
//Debug.Log("tracing 2");
return;
}
nextPosition = this.transform.position + (m_hunter.getCurrentTarget.transform.position - transform.position).normalized * 5;
//Debug.Log("tracing 1");
//Debug.Log("reset next position in hunting : current distance " + currentDistance);
}
else
{
motionStateNow = ParticleMotionState.Idle;
//Debug.Log("return to idle");
return;
}
//Debug.Log("nothing happen");
}
}
else if(currentDistance < 10f && currentDistance > 1.5f)
LerpMove(nextPosition, this.transform.position, moveDistance);
//LerpMove(nextPosition, this.transform.position, moveDistance);
}
float moveDistance;
void GeneratNextPosion()
{
float mediumAngle = direction == 1 ? (maxMoveAngle.x + maxMoveAngle.y) * Mathf.Deg2Rad * 0.5f : (maxMoveAngle.x + maxMoveAngle.y ) * Mathf.Deg2Rad * 0.5f + 180f* Mathf.Deg2Rad;
float moveAngle = UnityEngine.Random.Range(maxMoveAngle.x * Mathf.Deg2Rad - mediumAngle, maxMoveAngle.y * Mathf.Deg2Rad - mediumAngle);
moveDistance = UnityEngine.Random.Range(stepRandomMoveDistance.x, stepRandomMoveDistance.y);
float newX = (float)(moveDistance * Mathf.Cos(moveAngle));
float newY = (float)(moveDistance * Mathf.Sin(moveAngle));
//if(m_Boundary.isPointInside())
nextPosition = this.transform.position + new Vector3(newX, newY,0);
//Debug.Log("reset next position in idle");
}
void LerpMove(Vector3 forwardPosition, Vector3 currentPosition, float minCloseDistance)
{
float _distance = Vector3.Distance(forwardPosition, currentPosition);
Vector3 dir = (forwardPosition - currentPosition).normalized;
float t = Time.deltaTime * _distance / minCloseDistance * physicMotion.speed;
if (t > 0.5) t = 0.5f;
m_rigidbody.MovePosition(
Vector3.Slerp(currentPosition, forwardPosition, t));
}
private void OnTriggerEnter(Collider other)
{
for (int i = 0; i < m_hunter.HuntingTargets.Length;i++)
{
if(other.gameObject.layer == (int)m_hunter.HuntingTargets[i])
{
if(!m_hunter.HuntingList.Contains(other.gameObject))
m_hunter.HuntingList.Add(other.gameObject);
ForceSelector(100, other.gameObject, ForceType.attractive);
}
}
}
private void OnTriggerStay(Collider other)
{
for (int i = 0; i < m_hunter.HuntingTargets.Length; i++)
{
if (other.gameObject.layer == (int)m_hunter.HuntingTargets[i])
{
if (!m_hunter.HuntingList.Contains(other.gameObject))
m_hunter.HuntingList.Add(other.gameObject);
ForceSelector(100, other.gameObject, ForceType.attractive);
}
}
}
private void OnTriggerExit(Collider other)
{
if(m_hunter.HuntingList.Contains(other.gameObject))
{
m_hunter.HuntingList.Remove(other.gameObject);
}
}
public void ForceSelector(float forceMagnitude,GameObject _collisionObject, ForceType type)
{
Vector3 Force = Vector3.zero;
Rigidbody pRigidbody = _collisionObject.GetComponent<Rigidbody>();
float distance = Vector3.Distance(transform.position, _collisionObject.transform.position);
switch (type)
{
case ForceType.attractive:
Force = (this.transform.position - _collisionObject.transform.position).normalized *
Mathf.Lerp(forceMagnitude, forceMagnitude / 2, distance / GetComponent<SphereCollider>().radius * transform.localScale.x);
break;
case ForceType.explosition:
Force = (_collisionObject.transform.position - this.transform.position).normalized *
Mathf.Lerp(0, forceMagnitude, distance / GetComponent<SphereCollider>().radius * transform.localScale.x);
break;
}
pRigidbody.AddForce(Force);
}
Vector3 scale;
void saveData()
{
scale = transform.localScale;
}
bool checkLossyScale(Vector3 _scale)
{
return _scale.x * _scale.y * _scale.z > 0;
}
IEnumerator scaleDown(float lerpTime,ParticleSystem explosionEffect)
{
float time = 0;
explosionEffect.Play();
while(checkLossyScale(transform.localScale))
{
time += Time.deltaTime;
transform.localScale = Vector3.Slerp(scale, Vector3.zero, time / lerpTime);
yield return new WaitForEndOfFrame();
}
stateNow = ParticleLifeState.End;
TraceEffect.Stop();
}
IEnumerator fadeOut(float lerpTime)
{
float alpha = GetComponent<MeshRenderer>().material.GetFloat("_Alpha");
float time = 0;
TraceEffect.Stop();
while(GetComponent<MeshRenderer>().material.GetFloat("_Alpha") > 0)
{
time += Time.deltaTime;
float _a = Mathf.Lerp(alpha, 0, time / lerpTime);
GetComponent<MeshRenderer>().material.SetFloat("_Alpha", _a);
yield return new WaitForEndOfFrame();
}
stateNow = ParticleLifeState.RebornDelay;
}
bool isgrowing = false;
IEnumerator growing(float _timer)
{
float time = 0;
isgrowing = true;
TraceEffect.emissionRate = 120;
while(time/_timer < 1)
{
time += Time.deltaTime;
transform.localScale = Vector3.Slerp(scale, scale + Vector3.one*0.2f , time / _timer);
yield return new WaitForEndOfFrame();
}
TraceEffect.emissionRate = 8;
time = 0;
while (time / _timer < 1)
{
time += Time.deltaTime;
transform.localScale = Vector3.Slerp(scale +Vector3.one * 0.2f,scale, time / _timer);
yield return new WaitForEndOfFrame();
}
transform.localScale = scale;
isgrowing = false;
}
}
<file_sep>using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;
namespace Klak.Hap
{
[ExecuteInEditMode, AddComponentMenu("Klak/HAP/HAP Player")]
public sealed class HapPlayer : MonoBehaviour, ITimeControl, IPropertyPreview
{
#region Editable attributes
public enum PathMode { StreamingAssets, LocalFileSystem }
[SerializeField] PathMode _pathMode = PathMode.StreamingAssets;
[SerializeField] string _filePath = "";
[SerializeField] float _time = 0;
[SerializeField, Range(-10, 10)] float _speed = 1;
[SerializeField] bool _loop = true;
[SerializeField] RenderTexture _targetTexture = null;
[SerializeField] Renderer _targetRenderer = null;
[SerializeField] string _targetMaterialProperty = "_MainTex";
#endregion
#region Public properties
public float time {
get { return _time; }
set { _time = value; }
}
public float speed {
get { return _speed; }
set { _speed = value; }
}
public bool loop {
get { return _loop; }
set { _loop = value; }
}
public RenderTexture targetTexture {
get { return _targetTexture; }
set { _targetTexture = value; }
}
public Renderer targetRenderer {
get { return _targetRenderer; }
set { _targetRenderer = value; }
}
public string targetMaterialProperty {
get { return _targetMaterialProperty; }
set { _targetMaterialProperty = value; }
}
#endregion
#region Read-only properties
public bool isValid { get { return _demuxer != null; } }
public int frameWidth { get { return _demuxer?.Width ?? 0; } }
public int frameHeight { get { return _demuxer?.Height ?? 0; } }
public int frameCount { get { return _demuxer?.FrameCount ?? 0; } }
public double streamDuration { get { return _demuxer?.Duration ?? 0; } }
public CodecType codecType { get {
return Utility.DetermineCodecType(_demuxer?.VideoType ?? 0);
} }
public string resolvedFilePath { get {
if (_pathMode == PathMode.StreamingAssets)
return System.IO.Path.Combine(Application.streamingAssetsPath, _filePath);
else
return _filePath;
} }
public Texture2D texture { get { return _texture; } }
#endregion
#region Public methods
public void Open(string filePath, PathMode pathMode = PathMode.StreamingAssets)
{
if (_demuxer != null)
{
Debug.LogError("Stream has already been opened.");
return;
}
_filePath = filePath;
_pathMode = pathMode;
OpenInternal();
}
#endregion
#region Private members
Demuxer _demuxer;
StreamReader _stream;
Decoder _decoder;
Texture2D _texture;
TextureUpdater _updater;
float _storedTime;
float _storedSpeed;
void OpenInternal()
{
// Demuxer instantiation
_demuxer = new Demuxer(resolvedFilePath);
if (!_demuxer.IsValid)
{
if (Application.isPlaying)
{
// In play mode, show an error message, then disable itself
// to prevent spamming the console.
Debug.LogError("Failed to open stream (" + resolvedFilePath + ").");
enabled = false;
}
_demuxer.Dispose();
_demuxer = null;
return;
}
// Stream reader instantiation
_stream = new StreamReader(_demuxer, _time, _speed / 60);
(_storedTime, _storedSpeed) = (_time, _speed);
// Decoder instantiation
_decoder = new Decoder(
_stream, _demuxer.Width, _demuxer.Height, _demuxer.VideoType
);
// Texture initialization
_texture = new Texture2D(
_demuxer.Width, _demuxer.Height,
Utility.DetermineTextureFormat(_demuxer.VideoType), false
);
_texture.wrapMode = TextureWrapMode.Clamp;
_texture.hideFlags = HideFlags.DontSave;
_updater = new TextureUpdater(_texture, _decoder);
}
#endregion
#region External object updaters
Material _blitMaterial;
MaterialPropertyBlock _propertyBlock;
void UpdateTargetTexture()
{
if (_targetTexture == null) return;
// Material lazy initialization
if (_blitMaterial == null)
{
_blitMaterial = new Material(Utility.DetermineBlitShader(_demuxer.VideoType));
_blitMaterial.hideFlags = HideFlags.DontSave;
}
// Blit
Graphics.Blit(_texture, _targetTexture, _blitMaterial, 0);
}
void UpdateTargetRenderer()
{
if (_targetRenderer == null) return;
// Material property block lazy initialization
if (_propertyBlock == null)
_propertyBlock = new MaterialPropertyBlock();
// Read-modify-write
_targetRenderer.GetPropertyBlock(_propertyBlock);
_propertyBlock.SetTexture(_targetMaterialProperty, _texture);
_targetRenderer.SetPropertyBlock(_propertyBlock);
}
#endregion
#region ITimeControl implementation
bool _externalTime;
public void OnControlTimeStart()
{
_externalTime = true;
// In the external time mode, we can't know the actual playback
// speed but sure that it's positive (Control Track doesn't support
// reverse playback), so we assume that the speed is 1.0.
// Cons: Resync could happen every frame for high speed play back.
_speed = 1;
}
public void OnControlTimeStop()
{
_externalTime = false;
}
public void SetTime(double time)
{
_time = (float)time;
_speed = 1;
}
#endregion
#region IPropertyPreview implementation
public void GatherProperties(PlayableDirector director, IPropertyCollector driver)
{
driver.AddFromName<HapPlayer>(gameObject, "_time");
}
#endregion
#region MonoBehaviour implementation
void OnDestroy()
{
if (_updater != null)
{
_updater.Dispose();
_updater = null;
}
if (_decoder != null)
{
_decoder.Dispose();
_decoder = null;
}
if (_stream != null)
{
_stream.Dispose();
_stream = null;
}
if (_demuxer != null)
{
_demuxer.Dispose();
_demuxer = null;
}
Utility.Destroy(_texture);
Utility.Destroy(_blitMaterial);
}
void LateUpdate()
{
// Lazy initialization of demuxer
if (_demuxer == null && !string.IsNullOrEmpty(_filePath))
OpenInternal();
// Do nothing if the demuxer hasn't been instantiated.
if (_demuxer == null) return;
var duration = (float)_demuxer.Duration;
// Check if _time is still in the same frame of _storedTime.
// Resync is needed when it went out of the frame.
var dt = duration / _demuxer.FrameCount;
var resync = _time < _storedTime || _time > _storedTime + dt;
// Check if the speed was externally modified.
if (_speed != _storedSpeed)
{
resync = true; // Resync to adapt to the new speed.
_storedSpeed = _speed;
}
// Time clamping
var t = _loop ? _time : Mathf.Clamp(_time, 0, duration);
// Determine if background decoding is available.
// Resync shouldn't happen. Not preferable in edit mode.
var bgdec = !resync && Application.isPlaying;
// Restart the stream reader on resync.
if (resync) _stream.Restart(t, _speed / 60);
if (TextureUpdater.AsyncSupport)
{
// Asynchronous texture update supported:
// Decode a frame and request a texture update.
if (bgdec) _decoder.UpdateAsync(t); else _decoder.UpdateSync(t);
_updater.RequestAsyncUpdate();
}
else if (bgdec)
{
// Synchronous texture update with background decoding:
// Update first, then start background decoding. This
// introduces a single frame delay but makes it possible to
// offload decoding load to a background thread.
_updater.UpdateNow();
_decoder.UpdateAsync(t);
}
else
{
// Synchronous decoding and texture update.
_decoder.UpdateSync(t);
_updater.UpdateNow();
}
// Update the stored time.
if (Application.isPlaying && !_externalTime)
_time += Time.deltaTime * _speed;
_storedTime = _time;
// External object updates
UpdateTargetRenderer();
UpdateTargetTexture();
}
#endregion
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StarCellMove : ParticleBase {
[HideInInspector] public int index;
[Range(0, 1000)] public float spinAroundSpeed = 100;
[Range(0, 1000)] public float localMoveSpeed = 100;
//public bool isUseSphereBoundary = false;
public float distance;
// Use this for initialization
void Start () {
Initialized();
StartCoroutine(spinAround());
}
// Update is called once per frame
void Update () {
Run();
OutputValue();
}
void RandomRotation()
{
}
public float speed = 10f;
IEnumerator spinAround()
{
while (true)
{
transform.Rotate(0, 0, ((spinAroundSpeed * Mathf.PerlinNoise(Time.time, Time.time)) * Time.deltaTime));
Run();
yield return new WaitForEndOfFrame();
}
}
void Run()
{
direction += new Vector3(
Mathf.Sin(Mathf.Rad2Deg * Random.Range(-Mathf.PI, Mathf.PI)),
Mathf.Cos(Mathf.Rad2Deg * Random.Range(-Mathf.PI, Mathf.PI)), 0);
direction = direction.normalized;
direction.Set(direction.x, direction.y, 0);
velocity = Mathf.PerlinNoise(Time.time + index, index) * direction * localMoveSpeed * Time.deltaTime;
//distance = transform.parent.localScale.x * transform.parent.GetComponent<SphereCollider>().radius;
//if(Vector3.Distance(this.transform.localPosition,transform.parent.position) > distance * 0.5f && isUseSphereBoundary)
//{
// velocity = -velocity;
//}
}
Rigidbody m_rigidbody;
void OutputValue()
{
m_rigidbody.velocity = velocity;
m_rigidbody.angularVelocity = angVelocity;
}
public void AttributeInitialze()
{
velocity = Vector3.zero;
angVelocity = Vector3.zero;
index = Random.Range(0, 823231);
}
public void Initialized()
{
m_rigidbody = GetComponent<Rigidbody>();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CircleBoundary : MonoBehaviour {
float radius;
Vector3 center;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class SpingWormCornerBehaviour : MonoBehaviour {
MovingMode state;
public enum MovingMode
{
SinWave,
ScaleUp,
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StraightMove : ParticleBase {
int index = 1;
public float localMoveSpeed = 0.5f;
Rigidbody m_rigidbody;
private void Start()
{
m_rigidbody = GetComponent<Rigidbody>();
PositionInitialize();
}
private void Update()
{
Run();
OutputValue();
}
void PositionInitialize()
{
this.transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, 0);
}
void Run()
{
//direction = direction.normalized;
//direction.Set(direction.x, direction.y, 0);
direction = Vector3.right;
velocity = Mathf.PerlinNoise(Time.time + index, index) * direction * localMoveSpeed * Time.deltaTime;
}
void OutputValue()
{
//m_rigidbody.velocity = velocity;
m_rigidbody.MovePosition(transform.position + velocity);
//m_rigidbody.AddForce(velocity);
//m_rigidbody.angularVelocity = angVelocity;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class SpringJointWormHunter : Hunter
{
}
public class SpringJointWormBehaviour : ParticleBehaiour
{
[Header("Move motion setting")]
[Tooltip("multiply")] public float globalMoveSpeed = 1;
public float moveSpeed = 1;
public int direction = 1;
private int index;
private float timer;
private float timerAtFirst;
float nextTimeToEatOrBeEaten;
private void Start()
{
InitializeComponent();
}
private void FixedUpdate()
{
LifeCycleStateSelector();
}
#region state setting function
//state setting function
//life state funtion region
public override void LifeCycleStateSelector()
{
timer += Time.deltaTime;
switch (stateNow)
{
case ParticleLifeState.RebornDelay:
stateNow = ParticleLifeState.Start;
break;
case ParticleLifeState.Start:
Initialize();
break;
case ParticleLifeState.Update:
IdldeEventHandler();
break;
case ParticleLifeState.End:
EndBehaviour();
break;
}
}
public override void Initialize()
{
direction = m_Boundary.worldCenter.x - transform.position.x > 0 ? 1 : -1;
RegenerateStartPosition(direction);
//GetComponent<SpriteRenderer>().color = firstColor;
stateNow = ParticleLifeState.Update;
timer = 0;
}
public void EndBehaviour()
{
stateNow = ParticleLifeState.RebornDelay;
}
void FirstUpdateEventHandler()
{
timerAtFirst += Time.deltaTime;
}
void IdldeEventHandler() {
if (!m_Boundary.isPointInside(transform) && timer > 5)
{
stateNow = ParticleLifeState.End;
}
Run();
}
void EndOfUpdateEventHandler(){}
#endregion
#region behaviour function
//behaviour function
void Run()
{
float velocity = Mathf.PerlinNoise(Time.time + index, index) * direction * moveSpeed * Time.deltaTime;
m_rigidbody.MovePosition(transform.position + velocity * Vector3.right);
}
#endregion
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(ScreenSpaceBoundary))]
public class ParticleEmitter : MonoBehaviour {
public int maxNumber = 100;
public GameObject particle;
//public MainParticleLifeCycleAttribbute allParticleAttribute = new MainParticleLifeCycleAttribbute();
[HideInInspector]public List<GameObject> particleList;
private void Initialized()
{
if(particleList.Count > 0)
{
particleList.Clear();
}
}
private void Awake()
{
Initialized();
Emitter();
}
void Emitter()
{
for (int i = 0; i < maxNumber;i++)
{
GameObject clone = Instantiate(particle);
clone.transform.parent = this.transform;
particleList.Add(clone);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
using System.Security.Cryptography.X509Certificates;
//using System.Runtime.Remoting;
//using System.Security.Policy;
public class SpringJointWormGenerator : MonoBehaviour {
[Header("Single Shape Setting")]
[Range(5,12)]public int frequency = 5;
[Range(1, 10)] public float radius;
public Material material;
public Mesh mesh;
public Color centerColor;
public Color cornerColor;
[Header("Single Worm Physic Attribute Setting")]
public float mass = 50;
public float drag = 1.5f;
public float spring = 50f;
public RigidbodyConstraints constraints = RigidbodyConstraints.FreezeRotation;
[Header("Moving Attribute")]
public float minSpeedOfSpinAround = 50;
public float maxSpeedOfSpinArdoun = 150;
[Header("Random Attribute range")]
public bool isUseRandomAttribute = true;
public Gradient randomCenterColor;
public Gradient randomCornerColor;
public Vector2 randomFrequencyBetweenTwoConstant = new Vector2(5,12);
public Vector2 randomRadiusBetweenTwoConstant = new Vector2(1, 15);
public Vector2 minSpinAroundBetweenTwoConstant = new Vector2(75, 100);
public Vector2 maxSpinAroundBetweenTwoConstant = new Vector2(100, 200);
#region private attribute
bool alreadyBuild = false;
float index;
public GameObject center;
public List<GameObject> cornerList;
ScreenSpaceBoundary m_Boundary;
#endregion
//List<GameObject> particles;
// Use this for initialization
void Start ()
{
PositionInitialize();
RandomBornSetting();
StartCoroutine(checkEveryCorner());
GameObjectGenerator();
}
IEnumerator checkEveryCorner()
{
while(true)
{
for (int i = 0; i < cornerList.Count;i++)
{
if(cornerList[i].GetComponent<ParticleBase>().isBeaten)
{
cornerList[i].GetComponent<ParticleBase>().FadeIn();
}
}
yield return new WaitForSeconds(10f);
}
}
void PositionInitialize()
{
this.transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, 0);
}
void RandomBornSetting()
{
if (!isUseRandomAttribute) return;
m_Boundary = transform.parent.GetComponent<ScreenSpaceBoundary>();
this.transform.localPosition = new Vector3(
Random.Range(m_Boundary.minX, m_Boundary.maxX),
Random.Range(m_Boundary.minY, m_Boundary.maxY), 0);
index = Random.Range(12452, 59291241);
frequency = (int)Random.Range(randomFrequencyBetweenTwoConstant.x, randomFrequencyBetweenTwoConstant.y);
radius = (int)Random.Range(randomRadiusBetweenTwoConstant.x, randomRadiusBetweenTwoConstant.y);
minSpeedOfSpinAround = Random.Range(minSpinAroundBetweenTwoConstant.x, minSpinAroundBetweenTwoConstant.y);
maxSpeedOfSpinArdoun = Random.Range(maxSpinAroundBetweenTwoConstant.x, maxSpinAroundBetweenTwoConstant.y);
//color setting
float randomSeed = Mathf.Sin(minSpeedOfSpinAround + maxSpeedOfSpinArdoun) *
Mathf.Cos(maxSpeedOfSpinArdoun - minSpeedOfSpinAround);
centerColor = randomCenterColor.Evaluate(Mathf.PerlinNoise(index, randomSeed));
cornerColor = randomCornerColor.Evaluate(Mathf.PerlinNoise(index * randomSeed, index));
//Debug.Log(Mathf.PerlinNoise(index * Mathf.Sin(index), index * Mathf.Sin(index)));
}
void GeneratorCenter()
{
center = GameObject.CreatePrimitive(PrimitiveType.Sphere);
center.name = "Center";
center.tag = "SpringJointWorm";
center.layer = 12;
center.GetComponent<MeshFilter>().mesh = mesh;
center.GetComponent<MeshRenderer>().material = material;
center.GetComponent<SphereCollider>().enabled = false;
center.AddComponent<Rigidbody>();
center.AddComponent<SpinAround>();
center.AddComponent<ParticleBase>();
Rigidbody rigidbody = center.GetComponent<Rigidbody>();
rigidbody.constraints = RigidbodyConstraints.FreezePosition | RigidbodyConstraints.FreezeRotation;
rigidbody.useGravity = false;
center.transform.parent = this.transform;
center.transform.localPosition = Vector3.zero;
center.GetComponent<SpinAround>().minSpeed = minSpeedOfSpinAround;
center.GetComponent<SpinAround>().maxSpeed = maxSpeedOfSpinArdoun;
center.GetComponent<SpinAround>().direction = ((int)index % 2 == 0) ? 1:-1;
center.GetComponent<Renderer>().material.SetColor("_Color", centerColor);
}
void GameObjectGenerator()
{
if (center == null) GeneratorCenter();
for (int i = 0; i < frequency;i++)
{
float angle = (360 * i / (frequency)) * Mathf.Deg2Rad;
float x = transform.position.x + radius * Mathf.Sin(angle);
float y = transform.position.y + radius * Mathf.Cos(angle);
GameObject corner = new GameObject();
corner.name = "corner" + i;
corner.layer = 12;
corner.transform.parent = this.transform;
corner.transform.localScale *= transform.localScale.x;
corner.transform.position = new Vector3(x,y,transform.position.z);
//add composnent
corner.AddComponent<MeshFilter>();
corner.AddComponent<MeshRenderer>();
corner.AddComponent<Rigidbody>();
corner.AddComponent<SphereCollider>();
corner.AddComponent<SpringJoint>();
corner.AddComponent<ParticleBase>();
//setting stage
material = Instantiate(material);
material.SetColor("_Color", cornerColor);
corner.GetComponent<MeshFilter>().mesh = mesh;
corner.GetComponent<MeshRenderer>().material = material;
Rigidbody rigidbody = corner.GetComponent<Rigidbody>();
rigidbody.mass = mass;
rigidbody.drag = drag;
rigidbody.constraints = constraints;
rigidbody.useGravity = false;
SpringJoint joint = corner.GetComponent<SpringJoint>();
joint.connectedBody = center.GetComponent<Rigidbody>();
joint.autoConfigureConnectedAnchor = true;
joint.spring = 50;
joint.damper = 5;
cornerList.Add(corner);
//particles.Add(corner);
}
alreadyBuild = true;
}
}
<file_sep># AIParticleSystem
an Ai Particle system
[link](https://www.instagram.com/p/ByuZsNYA7yz/?utm_source=ig_web_copy_link)
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Security.Cryptography;
using System;
using UnityEngine.Experimental.UIElements;
/// <summary>
/// tip : need change the project setting collision let same tag object wont happen collision
/// </summary>
//[System.Serializable]
//public struct Snake
//{
// public GameObject headPrefab;
// public GameObject bodyPrefab;
// public Color headColor;
// public Color bodyColor;
// public List<GameObject> bodyList;
// public bool[] bodyStayBoundaryCheckList;
//}
//using UnityEditor.ShaderGraph;
public enum SnakeLifeStage
{
RebornDelay,
Start,
Update,
End
}
public enum SnakeMotionStage
{
Idle,
Hunting,
Eating,
BeEaten
}
public class SnakeParticleGenerator : MonoBehaviour
{
[Header("Prefabs Attribute setting")]
public GameObject headPrefab;
public GameObject bodyPrefab;
[Header("Apearence Attribbute")]
public Color headColor;
public Color bodyColor;
[Tooltip("only affect at fisrt time(start)")] public int numberOfBody = 5;
public int minBodyNunber = 3;
[Tooltip("change by realtime")] public float bodyDistance;
[Header("Motion Related Attribbute")]
public Vector2 rebornDelay = new Vector2(2, 5);
[Tooltip("How long will it reborn after leaving boundary")]
public float endingDelay = 1.5f;
[Tooltip("The moving speed")]
public float speed = 1;
public float maxMoveSpeed = 3.4f;
[Header("Sensor Related Attribute")]
[Tooltip("defalt value : o.5 so at least bigger than 0.5f")]
public float SensorTriggerRadius = 1f;
public SortingLayer HuntingTarget;
public int HowMuchNumberForEatingToGrowUp = 5;
[Tooltip("the max number that you can add to snake")]
public int snakeAddingMaxNumber = 10;
[Header("Snake body animation")]
public bool isUseSnakeBodyAnimation = true;
public Color color1 = Color.white;
public Color color2 = Color.white;
public Color beEatenColor = Color.red;
public float animationClipTime = 1;
public float animationFreshRate = 20f;
public float AnimationSpeed = 1;
bool isUseAntiOrder=false;
public int maxIntervalNumber = 3;
[Header("state visualizer")]
public AnimationState animationState;
public enum AnimationState
{
start,
update,
end
}
[HideInInspector] public bool ifAllStayInBoundary;
[HideInInspector] public int direction = 1;
int index;
float timer;
float timerAtEnd;
float rebbornDelayTime;
int eatNumber;
//stage control
public SnakeLifeStage m_stage = SnakeLifeStage.Update;
public SnakeMotionStage m_updateStage = SnakeMotionStage.Idle;
[HideInInspector] public List<GameObject> bodyList = new List<GameObject>();
GameObject head;
ScreenSpaceBoundary m_Boundary;
public ParticleSystem deathParticleEffect;
SnakeHead m_head
{
get
{
return bodyList[0].GetComponent<SnakeHead>();
}
}
bool isBeEaten
{
get{
foreach(GameObject body in bodyList)
{
bool _isBeEaten = body.GetComponent<ParticleBase>().isBeaten;
if(_isBeEaten)return true;
}
return false;
}
}
//[Header("setting Boundary Attribute ")]
//public bool isUseBoundarySystem;
//public bool isUseRandomAttributeToReborn;
// Use this for initialization
void Start()
{
PositionInitialize();
SnakeGenerator();
AttributeIniate();
StartCoroutine(SnakeColorLerpAnimation());
}
// Update is called once per frame
void Update()
{
LifeCycleStageSelector();
//SnakeMove();
}
IEnumerator StageController()
{
while (true)
{
LifeCycleStageSelector();
yield return new WaitForEndOfFrame();
}
}
void LifeCycleStageSelector()
{
timer += Time.deltaTime;
//switch
switch (m_stage)
{
case SnakeLifeStage.RebornDelay:
if (timer > rebbornDelayTime)
{
m_stage = SnakeLifeStage.Start;
UpdateCycleStageSelector();
}
break;
case SnakeLifeStage.Start:
timer = 0;
SnakeInitializer();
m_stage = SnakeLifeStage.Update;
break;
case SnakeLifeStage.Update:
UpdateCycleStageSelector();
break;
case SnakeLifeStage.End:
m_stage = SnakeLifeStage.RebornDelay;
break;
}
}
bool isTimerEnd = true;
IEnumerator animationSpeedUp(float _timeLength,float _speed)
{
if(!isTimerEnd)yield break;
isTimerEnd = false;
AnimationSpeed = _speed;
speed *=2;
yield return new WaitForSeconds(_timeLength);
AnimationSpeed = 1;
speed /= 2;
isTimerEnd = true;
}
IEnumerator animationSpeedDown(float _timeLength,float _speed)
{
if(!isTimerEnd)yield break;
Color temp = color2;
color2 = beEatenColor;
isTimerEnd = false;
updownSpeed = 5;
if(bodyList.Count > minBodyNunber )
RemoveBody();
animationState = AnimationState.start;
AnimationSpeed = _speed;
//speed *= 0.5f;
yield return new WaitForSeconds(_timeLength);
AnimationSpeed = 1;
//speed *= 2;
updownSpeed = 1;
isTimerEnd = true;
m_head.beEaten = false;
color2 = temp;
}
void UpdateCycleStageSelector()
{
EventManagement();
switch (m_updateStage)
{
case SnakeMotionStage.Idle:
SnakeMove();
break;
case SnakeMotionStage.Hunting:
Hunter();
break;
case SnakeMotionStage.Eating:
GrowUp();
m_updateStage = SnakeMotionStage.Idle;
break;
case SnakeMotionStage.BeEaten:
SnakeMove();
StartCoroutine(animationSpeedDown(1,0.5f));
break;
}
if (timer > 5) CheckEachBodyIffStayInBoundary();
}
void GrowUp()
{
StartCoroutine(animationSpeedUp(1f,3));
//StartCoroutine(animationSpeedDown(1,0.5f));
eatNumber += 1;
//Debug.Log("HowMuchNumberForEatingToGrowUp" + HowMuchNumberForEatingToGrowUp + "||Eat Number" + eatNumber);
if (eatNumber > HowMuchNumberForEatingToGrowUp)
{
if (snakeAddingMaxNumber == 0)
{
m_updateStage = SnakeMotionStage.Idle;
return;
}
snakeAddingMaxNumber -= 1;
eatNumber = 0;
//Debug.Log("grow");
AddBody();
}
m_updateStage = SnakeMotionStage.Idle;
}
//define what stage should be
void EventManagement()
{
SnakeHead m_head = head.GetComponent<SnakeHead>();
if (m_head.HuntingList.Count > 1 && !m_head.beEaten)
{
m_updateStage = SnakeMotionStage.Hunting;
}
else if (m_head.HuntingList.Count == 0 && !m_head.beEaten)
{
m_updateStage = SnakeMotionStage.Idle;
}
else if (m_head.beEaten)
{
m_updateStage = SnakeMotionStage.BeEaten;
}
else if (m_head.getIfEating)
{
m_updateStage = SnakeMotionStage.Eating;
}
}
public bool ifHaveTarget = false;
public GameObject mostCloseTarget = null;
public GameObject currentTarget
{
get
{
return m_head._currentTarget;
}
set
{
m_head._currentTarget = value;
}
}
void Hunter()
{
if (!ifHaveTarget)
{
ChooseTarget();
}
TracingTarget();
}
void ChooseTarget()
{
if (m_head.HuntingList.Count > 0)
{
float mostCloseDistance = 0;
for (int i = 0; i < m_head.HuntingList.Count; i++)
{
float distanceToTarget = Vector3.Distance(m_head.transform.position, m_head.HuntingList[i].transform.position);
if (mostCloseTarget == null)
{
currentTarget = m_head.HuntingList[i];
mostCloseDistance = Vector3.Distance(m_head.transform.position, currentTarget.transform.position);
}
else if (distanceToTarget < mostCloseDistance)
{
currentTarget = m_head.HuntingList[i];
mostCloseDistance = distanceToTarget;
}
}
}
else if (m_head.HuntingList.Count == 0)
{
//Debug.Log("lost target");
m_updateStage = SnakeMotionStage.Idle;
}
}
void TracingTarget()
{
float distanceToTarget = Vector3.Distance(m_head.transform.position, currentTarget.transform.position);
for (int i = 0; i < bodyList.Count; i++)
{
if (i == 0)
TracingMove(bodyList[i]);
else
CheckDistanceWithForward(bodyList[i - 1], bodyList[i]);
}
if (distanceToTarget < 1.39f)
{
m_updateStage = SnakeMotionStage.Eating;
GrowUp();
}
}
void TracingMove(GameObject _head)
{
//Vector3 velocity = (currentTarget.transform.position - _head.transform.position ).normalized* speed * 1.5f * Time.deltaTime;
//_head.GetComponent<Rigidbody>().MovePosition(_head.transform.position + velocity);
float _distance = Vector3.Distance(currentTarget.transform.position, _head.transform.position);
Vector3 dir = (currentTarget.transform.position - _head.transform.position).normalized;
float t = Time.deltaTime * _distance / 2 * speed * 0.35f;
if (t > 0.5) t = 0.5f;
_head.GetComponent<Rigidbody>().MovePosition(
Vector3.Slerp(_head.transform.position, currentTarget.transform.position, t));
}
void PositionInitialize()
{
this.transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, 0);
}
void AttributeIniate()
{
index = UnityEngine.Random.Range(12345, 823231);
//stage initialize
m_stage = SnakeLifeStage.RebornDelay;
m_updateStage = SnakeMotionStage.Idle;
m_Boundary = transform.parent.GetComponent<ScreenSpaceBoundary>();
rebbornDelayTime = UnityEngine.Random.Range(rebornDelay.x, rebornDelay.y);
deathParticleEffect.Stop();
}
void SnakeInitializer()
{
//Head and body position random setting
direction = UnityEngine.Random.Range(0, 100) > 50 ? 1 : -1;
transform.localPosition = RegenerateStartPosition(direction);
PositionInitialize();
if (direction == 1)
{
for (int i = 0; i < bodyList.Count; i++)
{
if(i>=bodyList.Count)return;
//head setting
if (i == 0)
{
bodyList[0].transform.localPosition = Vector3.zero;
bodyList[0].GetComponent<Rigidbody>().Sleep();
bodyList[0].GetComponent<SnakeHead>().beEaten = false;
}
//body setting
else
{
bodyList[i].transform.localPosition = bodyList[0].transform.localPosition;
bodyList[i].GetComponent<Rigidbody>().Sleep();
}
//bodyList[i].GetComponent<ParticleBase>().isBeaten = false;
}
}
else
{
for (int i = 0; i < bodyList.Count; i++)
{
if(i>=bodyList.Count)return;
//head setting
if (i == 0)
{
bodyList[0].transform.localPosition = Vector3.zero;
}
//body setting
else
{
bodyList[i].transform.localPosition = bodyList[0].transform.localPosition; ;
}
}
}
}
void CheckEachBodyIffStayInBoundary()
{
//bool[] checklist = new bool[bodyList.Count];
for (int i = 0; i < bodyList.Count; i++)
{
if(i>=bodyList.Count)return;
if (m_Boundary.isPointInside(bodyList[i].transform))
{
//Debug.Log("stay");
return;
}
}
timerAtEnd += Time.deltaTime;
if (timerAtEnd > endingDelay)
{
timer = 0;
timerAtEnd = 0;
m_stage = SnakeLifeStage.End;
//Debug.Log("exit");
}
return;
}
Vector3 RegenerateStartPosition(int direction)
{
float newPositionX = (direction == 1 ? m_Boundary.minX : m_Boundary.maxX) - 5f * direction;
float newPositionY = (m_Boundary.maxY + m_Boundary.minY) / 2 + ((m_Boundary.maxY - m_Boundary.minY) / 4) * Mathf.Sin(Time.time * 0.5f);
Vector3 newPosition = new Vector3(newPositionX, newPositionY, 0);
return newPosition;
}
void SnakeGenerator()
{
HeadGenerator();
BodyGenerator();
}
void HeadGenerator()
{
GameObject Head = (Instantiate(headPrefab) as GameObject);
Head.transform.parent = this.transform;
Head.transform.localPosition = new Vector3(0, 0, 0);
Head.GetComponent<Renderer>().material.SetColor("_TintColor", headColor);
Head.GetComponent<ParticleBase>().maxMoveSpeed = maxMoveSpeed;
Head.GetComponent<SphereCollider>().radius = SensorTriggerRadius;
//Snake layer
Head.layer = 13;
bodyList.Add(Head);
head = Head;
}
void BodyGenerator()
{
for (int i = 1; i <= numberOfBody; i++)
{
GameObject body = (Instantiate(bodyPrefab) as GameObject);
body.transform.parent = this.transform;
body.transform.position = bodyList[0].transform.position;
body.GetComponent<Renderer>().material.SetColor("_TintColor", bodyColor);
body.layer = 13;
body.GetComponent<Rigidbody>().isKinematic = true;
if (i % 3 == 0)
{
body.GetComponent<Rigidbody>().isKinematic = false;
}
if (bodyList[i - 1] == null)
{
HeadGenerator();
}
bodyList.Add(body);
}
}
void SnakeMove()
{
//Debug.Log("StageControl");
for (int i = 0; i < bodyList.Count; i++)
{
if (i == 0)
{
HeadMove(bodyList[i]);
}
else
{
CheckDistanceWithForward(bodyList[i - 1], bodyList[i]);
}
}
}
void CheckDistanceWithForward(GameObject forward, GameObject current)
{
current.GetComponent<Rigidbody>().Sleep();
float _distance = Vector3.Distance(forward.transform.position, current.transform.position);
Vector3 dir = (forward.transform.position - current.transform.position).normalized;
float t = Time.deltaTime * _distance / bodyDistance * speed;
if (t > 0.5) t = 0.5f;
current.GetComponent<Rigidbody>().MovePosition(
Vector3.Slerp(current.transform.position, forward.transform.position, t));
}
float updownSpeed = 1;
void HeadMove(GameObject _head)
{
_head.GetComponent<Rigidbody>().Sleep();
if (direction == 0) direction = 1;
float moveX = (Mathf.PerlinNoise(Time.time + index, index) - 0.1f) * 2 * speed * Time.deltaTime * direction;
float moveY = Mathf.Sin((Time.time)+ index) * 3 * Time.deltaTime *(1/updownSpeed);
Vector3 velocity = new Vector3(moveX, moveY, 0);
_head.GetComponent<Rigidbody>().MovePosition(_head.transform.position + velocity);
//Debug.Log(velocity);
//if(!m_Boundary.isPointInside(_head.transform) && timer > 5)
//{
// _head.GetComponent<Rigidbody>().MovePosition(_head.transform.position - velocity * 2);
//}
}
void AddBody()
{
GameObject body = (Instantiate(bodyPrefab) as GameObject);
body.transform.parent = this.transform;
body.transform.position = bodyList[bodyList.Count - 1].transform.position;
body.layer = 13;
body.GetComponent<Renderer>().material.SetColor("_TintColor", bodyColor);
bodyList.Add(body);
}
void RemoveBody()
{
GameObject removeTarget = bodyList[bodyList.Count - 1];
snakeAddingMaxNumber ++;
bodyList.Remove(removeTarget);
removeTarget.transform.parent = GameObject.Find("TrashLayer").transform ;
removeTarget.tag = "LittleParticle";
removeTarget.layer = 9;
deathParticleEffect.transform.position = bodyList[bodyList.Count-1].transform.position;
deathParticleEffect.Play();
removeTarget.AddComponent<MainParticleLifeCycle>().fisrtColor = color1;
removeTarget.GetComponent<MainParticleLifeCycle>().finalColor = color2;
removeTarget.GetComponent<MainParticleLifeCycle>().localMoveSpeed = 0;
removeTarget.GetComponent<MainParticleLifeCycle>().m_stage = mainParticleStage.update;
removeTarget.GetComponent<MainParticleLifeCycle>().lifeTime = 60f;
}
#region bodyAnimation
bool isLoop = true;
bool[] states;
float animationTimer;
IEnumerator SnakeColorLerpAnimation()
{
//if(!isUseSnakeBodyAnimation)isLoop = false;
while (isLoop)
{
stateSelector();
AnimationStateSelector();
//Debug.Log("Refresh animation");
yield return new WaitForSeconds(1/animationFreshRate);
}
}
public bool isPlaying
{
get
{
if ((int)animationTimer / animationClipTime <= 0 || (int)animationTimer / animationClipTime >= 1)
{
return false;
}
else
{
return true;
}
}
}
void AnimationStateSelector()
{
switch(animationState)
{
case AnimationState.start:
InitializeAnimation(ref states);
break;
case AnimationState.update:
UpdateAnimation(ref states);
break;
case AnimationState.end:
EndAnimation(ref states);
break;
}
}
public virtual void InitializeAnimation(ref bool[] _states)
{
states = new bool[bodyList.Count];
animationTimer += Time.deltaTime * Mathf.Abs(AnimationSpeed);
}
public virtual void UpdateAnimation(ref bool[] _states) {
animationTimer += Time.deltaTime * Mathf.Abs(AnimationSpeed);
AnimatiionLogic_1(isUseAntiOrder,maxIntervalNumber,ref states);
}
public virtual void EndAnimation(ref bool[] _states)
{
animationTimer = 0;
}
public void stateSelector(){
if (animationTimer == 0)
animationState = AnimationState.start;
else if (animationTimer > 0 && animationTimer < animationClipTime)
animationState = AnimationState.update;
else if (animationTimer > animationClipTime)
animationState = AnimationState.end;
}
void AnimatiionLogic_1(bool _isUseAntiOrder, int maxDarkNumber, ref bool[] _states)
{
int dir = _isUseAntiOrder ? -1 : 1;
int timeIndex = (int)Mathf.Lerp(0, _states.Length + (maxDarkNumber), animationTimer / animationClipTime) * dir;
int min = (_isUseAntiOrder ? (_states.Length - 1) + maxDarkNumber : 0 - maxDarkNumber) + timeIndex;
int max = (_isUseAntiOrder ? min - (maxDarkNumber - 1) : min + (maxDarkNumber - 1));
//Debug.Log("min : " + min + " max : " + max);
for (int i = 0; i < _states.Length; i++)
{
float i_min = Mathf.Abs(i - min);
float i_max = Mathf.Abs(i - max);
//Debug.Log("min : " + min + " max : " + max + " i : " + i + " i-max : " + i_max + " i-min : " + i_min);
if (i_min + i_max < maxDarkNumber)
{
_states[i] = LogicStateSetting.State1 ;
//Debug.Log("Lighting up");
}
else
{
_states[i] = LogicStateSetting.State2;
//Debug.Log("Lighting off");
}
}
if(!isUseSnakeBodyAnimation) return;
Color[] listColor = new Color[_states.Length];
float center = (max + min)/2 ;
for (int i = 0; i < listColor.Length; i++)
{
//Debug.Log(_states[i]);
//Debug.Log("min : " + min + " max : " + max + " i : " + i + " i-max : " + i_max + " i-min : " + i_min);
if (_states[i])
{
float index = i >= center ? i - center : center - i;
float length = i >= center ? max - center : center - min;
listColor[i] = Color.Lerp(color2, color1, index / length);
}
else
{
listColor[i] = color1;
}
if(i<bodyList.Count)
bodyList[i].GetComponent<MeshRenderer>().material.SetColor("_TintColor", listColor[i]);
}
}
#endregion
}
public static class LogicStateSetting
{
//default true
public static bool State1 = true;
//default false
public static bool State2 = false;
//public bool isUseAntiLogic = false;
}
public class SnakeParticleBoundaryEvent : BoundaryEvent
{
public override void StayBoundary()
{
throw new NotImplementedException();
}
public override void ExitBoundary()
{
throw new NotImplementedException();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InteractiveSystemWithMainParticle : MonoBehaviour {
[Header("Force")]
public float RepulsiveForce = 100f;
public float AttrativeForce = 10f;
[Header("VisualizerObject")]
public GameObject ExplosionVisualizer;
public GameObject TirggerVidsualizer;
public GameObject ColliderObject;
bool UseDebugVisualizer = false;
[Header("Radius")]
[Range(0.5f, 20f)] public float attractiveRadius = 10f;
[Range(0.5f, 20f)] public float triggerRadius = 2f;
[Range(0.5f, 20f)] public float explosionRadius = 5f;
//[Range(0.5f, 20f)]public float deathRadius = 0.5f;
[Header("Time Setting")]
public float explosionTime = 0.3f;
public float attractiveTime = 10f;
private float timer;
//計算吸收數量
public int substractNumber = 0;
public int HowManyToGrow = 20;
Rigidbody m_rigidbody;
SphereCollider m_collider;
public PlayerStage m_stage = PlayerStage.Beginning;
public enum PlayerStage
{
Beginning,
update,
end
}
// Use this for initialization
void Start () {
GetComponent<Star>().frequency += 1;
StartCoroutine(StageControl());
}
// Update is called once per frame
void Update () {
if(substractNumber>HowManyToGrow)
{
GetComponent<Star>().frequency += 1;
GetComponent<Star>().Reset();
substractNumber = 0;
//Debug.Log(GetComponent<Star>().frequency);
}
}
private void Initialize()
{
//component setting
m_collider = this.GetComponent<SphereCollider>();
m_rigidbody = this.GetComponent<Rigidbody>();
//game object setting
if (ExplosionVisualizer == null)
{
GameObject _ExplosionVisualizer = new GameObject();
_ExplosionVisualizer.name = "_ExplosionVisualizer";
_ExplosionVisualizer.AddComponent<MeshFilter>();
_ExplosionVisualizer.AddComponent<MeshRenderer>();
_ExplosionVisualizer.transform.localScale = Vector3.one * explosionRadius;
ExplosionVisualizer = _ExplosionVisualizer;
}
else
{
ExplosionVisualizer.transform.localScale = Vector3.one * explosionRadius;
}
if (TirggerVidsualizer == null)
{
GameObject _TirggerVidsualizer = new GameObject();
_TirggerVidsualizer.name = "_ExplosionVisualizer";
_TirggerVidsualizer.AddComponent<MeshFilter>();
_TirggerVidsualizer.AddComponent<MeshRenderer>();
_TirggerVidsualizer.transform.localScale = Vector3.one * triggerRadius / 2;
TirggerVidsualizer = _TirggerVidsualizer;
}
else
{
TirggerVidsualizer.transform.localScale = Vector3.one * triggerRadius;
}
if (ColliderObject == null)
{
GameObject _ColliderObject = new GameObject();
_ColliderObject.name = "_ExplosionVisualizer";
_ColliderObject.AddComponent<MeshFilter>();
_ColliderObject.AddComponent<MeshRenderer>();
_ColliderObject.transform.localScale = Vector3.one * triggerRadius;
ColliderObject = _ColliderObject;
}
else
{
ColliderObject.transform.localScale = this.transform.localScale;
}
if(!UseDebugVisualizer)
{
TirggerVidsualizer.SetActive(false);
ExplosionVisualizer.SetActive(false);
}
}
void AttributeInitialize()
{
switch (m_stage)
{
//explosion stage
case PlayerStage.Beginning:
m_collider.radius = explosionRadius/2;
substractNumber = 0;
if(UseDebugVisualizer)
{
ExplosionVisualizer.SetActive(true);
TirggerVidsualizer.SetActive(false);
ExplosionVisualizer.transform.localScale = new Vector3(explosionRadius, explosionRadius, explosionRadius);
}
break;
//Attractive stage
case PlayerStage.update:
m_collider.radius = attractiveRadius/2;
//substractNumber = 0;
if(UseDebugVisualizer)
{
ExplosionVisualizer.SetActive(false);
TirggerVidsualizer.SetActive(true);
TirggerVidsualizer.transform.localScale = new Vector3(attractiveRadius, attractiveRadius, attractiveRadius);
}
break;
case PlayerStage.end:
break;
}
}
IEnumerator StageControl()
{
Initialize();
while(true)
{
timer = 0;
switch(m_stage)
{
case PlayerStage.Beginning:
AttributeInitialize();
while(timer/explosionTime<1)
{
timer += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
m_stage = PlayerStage.update;
break;
case PlayerStage.update:
AttributeInitialize();
while (timer / attractiveTime < 1)
{
timer += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
m_stage = PlayerStage.Beginning;
break;
case PlayerStage.end:
break;
}
}
}
//debug use function
private void OnMouseEnter()
{
m_stage = PlayerStage.Beginning;
Debug.Log("On Mouse Enter");
}
private void OnTriggerStay(Collider other)
{
if (other.tag == "LittleParticle" && (other.gameObject.GetComponent<MainParticleLifeCycle>().m_stage == mainParticleStage.update ||
other.gameObject.GetComponent<MainParticleLifeCycle>().m_stage == mainParticleStage.end))
{
Rigidbody pRigbody = other.GetComponent<Rigidbody>();
Vector3 Force;
float distance = Vector3.Distance(other.transform.position, this.transform.position);
switch (m_stage)
{
case PlayerStage.Beginning:
if(other.gameObject.GetComponent<MainParticleLifeCycle>().m_stage == mainParticleStage.end)
{
other.gameObject.GetComponent<MainParticleLifeCycle>().m_stage = mainParticleStage.update;
}
Force = (other.transform.position - this.transform.position).normalized *
Mathf.Lerp(0,RepulsiveForce,distance/triggerRadius);
pRigbody.AddForce(Force);
break;
case PlayerStage.update:
if(other.gameObject.GetComponent<MainParticleLifeCycle>().m_stage == mainParticleStage.update)
{
Color firstColor = other.GetComponent<MainParticleLifeCycle>().fisrtColor;
Color finalColor = other.GetComponent<MainParticleLifeCycle>().finalColor;
Color newColor = Color.Lerp(firstColor, finalColor, 1 - distance / triggerRadius);
//Debug.Log(1 - distance / triggerRadius);
other.GetComponent<MeshRenderer>().material.SetColor("_TintColor", newColor);
}
Force = (this.transform.position - other.transform.position).normalized *
Mathf.Lerp(AttrativeForce,AttrativeForce/2 ,distance / triggerRadius);
if(pRigbody.GetComponent<Rigidbody>().velocity.magnitude < pRigbody.GetComponent<MainParticleLifeCycle>().maxMoveSpeed)
pRigbody.AddForce(Force);
break;
case PlayerStage.end:
break;
}
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "LittleParticle" && (collision.gameObject.GetComponent<MainParticleLifeCycle>().m_stage == mainParticleStage.end))
{
//Rigidbody pRigbody = collision.gameObject.GetComponent<Rigidbody>();
switch (m_stage)
{
case PlayerStage.Beginning:
break;
case PlayerStage.update:
substractNumber += 1;
collision.gameObject.GetComponent<MainParticleLifeCycle>().m_stage = mainParticleStage.beEaten;
break;
case PlayerStage.end:
break;
}
}
}
private void OnTriggerExit(Collider other)
{
if (other.tag == "LittleParticle")
{
other.GetComponent<MeshRenderer>().material.SetColor("_TintColor", other.GetComponent<MainParticleLifeCycle>().fisrtColor);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ParticleMouse : MonoBehaviour {
public int EatingNumber;
public float EatingTimeInterval = 0.5f;
public bool isEating = false;
public bool isBeEaten = false;
[HideInInspector] public Collider MouseCollider;
[HideInInspector] public float timer;
public LayerManager[] HuntingTargets;
//ParticleSystem m_particleEffect;
// Use this for initialization
void Start () {
MouseCollider = GetComponent<SphereCollider>();
}
// Update is called once per frame
void Update () {
}
public void setHunigTarget(LayerManager[] _HuntingTargets)
{
HuntingTargets = _HuntingTargets;
}
public void Reset()
{
EatingNumber = 0;
timer = 0;
isEating = false;
}
void OnTriggerEnter(Collider other)
{
//Debug.Log(other.gameObject.layer);
if (!isEating)
{
EatingEvent(other.gameObject);
}
}
private void OnTriggerStay(Collider other)
{
if (!isEating)
{
EatingEvent(other.gameObject);
}
}
public void BeEaten()
{
isBeEaten = true;
}
//call event
void EatingEvent(GameObject beEatenGameObject)
{
if(HuntingTargets == null)return;
//Debug.Log(beEatenGameObject.layer);
for(int i = 0;i<HuntingTargets.Length;i++)
{
if(beEatenGameObject.layer == (int)HuntingTargets[i])
{
switch(beEatenGameObject.layer)
{
case 9:
beEatenGameObject.GetComponent<MainParticleLifeCycle>().BeEaten();
isEating = true;
break;
//player layer
case 10:
break;
//spring worm layer
case 12:
beEatenGameObject.GetComponent<ParticleBase>().BeEaten();
isEating = true;
break;
case 13:
if(beEatenGameObject.GetComponent<SnakeHead>() != true)return;
beEatenGameObject.GetComponent<SnakeHead>().beEaten = true;
isEating = true;
break;
case 14:
if (beEatenGameObject.GetComponent<ParticleMouse>() == null || beEatenGameObject.layer == gameObject.layer) return;
if (!beEatenGameObject.GetComponent<ParticleMouse>().isBeEaten)
beEatenGameObject.GetComponent<ParticleMouse>().BeEaten();
else Debug.Log("Emitter has already be eaten");
break;
case 16:
break;
}
break;
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class ParticleBase : MonoBehaviour{
[HideInInspector]public float mass;
public float lifeTime;
[HideInInspector]public Vector3 direction;
//[HideInInspector]public Vector3 position;
[HideInInspector]public Vector3 velocity;
[Range(0, 100)] public float maxMoveSpeed = 100;
private float _lerpTime = 2;
public bool isBeaten = false;
[HideInInspector]public Vector3 angVelocity;
//public float lerpTime = 1f;
private void Update()
{
if(GetComponent<Rigidbody>().velocity.magnitude > maxMoveSpeed)
{
GetComponent<Rigidbody>().velocity = GetComponent<Rigidbody>().velocity.normalized * maxMoveSpeed;
}
}
//spring joint worm use
public void BeEaten()
{
isBeaten = true;
Color now = GetComponent<MeshRenderer>().material.GetColor("_TintColor");
GetComponent<Collider>().enabled = false;
GetComponent<MeshRenderer>().material.SetColor("_TintColor", new Vector4(now.r, now.g, now.b, 0));
}
// spring joint worm use
public void FadeIn()
{
isBeaten = false;
Debug.Log("start fade in ");
StartCoroutine(fadein());
}
public IEnumerator fadein()
{
Color nowTransparent = GetComponent<Renderer>().material.GetColor("_TintColor");
Color now = new Vector4(nowTransparent.r, nowTransparent.g, nowTransparent.b, 1f);
GetComponent<MeshRenderer>().material.SetColor("_TintColor", nowTransparent);
for (float i = 0; i < _lerpTime; i+=Time.deltaTime)
{
Color _c = Color.Lerp(nowTransparent,now , i / _lerpTime);
//Debug.Log("fade in" + _c);
GetComponent<MeshRenderer>().material.SetColor("_TintColor", _c);
yield return new WaitForFixedUpdate();
}
GetComponent<Collider>().enabled = true;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Hunter
{
public LayerManager m_Layer;
public LayerManager[] HuntingTargets;
public ParticleMouse mouse;
[HideInInspector] public bool ifHasTarget
{
get{
return HuntingList.Count > 0;
}
}
public List<GameObject> HuntingList;
public bool getIsEating{get { return mouse.isEating; }}
public virtual void SelectTracingTarget()
{
}
public virtual void TracingTarget()
{
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.CompilerServices;
using System.Timers;
//using NUnit.Framework.Internal.Commands;
[System.Serializable]
public class WaveParticleHunter : Hunter
{
public ParticleMouse[] mice;
public void setHuntingTargetToMice()
{
for (int i = 0; i < mice.Length;i++)
{
mice[i].HuntingTargets = HuntingTargets;
}
}
public bool getIsMiceEating {
get {
for (int i = 0; i < mice.Length;i++)
{
if (mice[i].isEating) return true;
}
return false;
}
}
public bool getIsMiceBeEaten{
get {
for (int i = 0; i < mice.Length;i++)
{
if (mice[i].isBeEaten) return true;
}
return false;
}
}
}
public class WaveParticleBehaviour : ParticleBehaiour
{
public WaveParticleHunter m_hunter;
[Header("Move motion setting")]
[Tooltip("multiply")] public float globalMoveSpeed = 1;
public float moveSpeed = 1;
public int direction = 1;
[Header("Color setting")]
public Color firstColor;
public Color secondColor;
[Header("Time setting")]
public float shiningIntervalTime = 0.15f;
public float shiningTotalTime = 2f;
public float eatingInterval = 2f;
public float lerpTime = 2f;
[Header("Animation speed")]
public float defaultAnimationSpeed = 1;
public float EatingAnimationSpeed = 3;
public float BeEatenAnimationSpeed = 5;
private int index;
private float timer;
private float timerAtFirst;
float nextTimeToEatOrBeEaten;
public AudioClip waveOST;
public AudioSource m_audioPlayer;
private void Start()
{
m_hunter.setHuntingTargetToMice();
InitializeComponent();
}
private void FixedUpdate()
{
LifeCycleStateSelector();
}
#region state setting function
//state setting function
//life state funtion region
public override void LifeCycleStateSelector()
{
timer += Time.deltaTime;
switch (stateNow)
{
case ParticleLifeState.Start:
Initialize();
break;
case ParticleLifeState.Update:
UpdateCycleStateSelector();
break;
case ParticleLifeState.End:
EndBehaviour();
break;
}
}
public override void Initialize()
{
direction = m_Boundary.worldCenter.x - transform.position.x > 0 ? 1 : -1;
RegenerateStartPosition(direction);
GetComponent<SpriteRenderer>().color = firstColor;
stateNow = ParticleLifeState.Update;
timer = 0;
}
public void EndBehaviour()
{
stateNow = ParticleLifeState.Start;
}
public override void UpdateCycleStateSelector()
{
EventManager();
switch (motionStateNow)
{
case ParticleMotionState.FirstUpdate:
FirstUpdateEventHandler();
break;
case ParticleMotionState.Idle:
GetComponent<Animator>().speed = defaultAnimationSpeed;
IdldeEventHandler();
break;
case ParticleMotionState.Eating:
break;
case ParticleMotionState.BeEaten:
break;
case ParticleMotionState.EndOfUpdate:
EndOfUpdateEventHandler();
break;
}
}
public void EventManager()
{
//Debug.Log("isEating" + m_hunter.getIsMiceEating);
if (!m_Boundary.isPointInside(transform) && timer > 5)
{
stateNow = ParticleLifeState.End;
}
else if(!inAnimation &&
Time.time > nextTimeToEatOrBeEaten &&
m_hunter.getIsMiceBeEaten &&
motionStateNow != ParticleMotionState.BeEaten)
{
GetComponent<Animator>().speed = BeEatenAnimationSpeed;
StartCoroutine(ColorShining(firstColor, secondColor, shiningTotalTime, shiningIntervalTime));
motionStateNow = ParticleMotionState.BeEaten;
}
else if (!inAnimation &&
Time.time > nextTimeToEatOrBeEaten &&
m_hunter.getIsMiceEating &&
motionStateNow != ParticleMotionState.Eating)
{
GetComponent<Animator>().speed = EatingAnimationSpeed;
StartCoroutine(ColorLerpChanging(firstColor, secondColor, lerpTime));
motionStateNow = ParticleMotionState.Eating;
}
//else
//{
// motionStateNow = ParticleMotionState.Idle;
//}
}
void FirstUpdateEventHandler()
{
timerAtFirst += Time.deltaTime;
}
void IdldeEventHandler() { Run(); }
void EndOfUpdateEventHandler(){}
#endregion
#region behaviour function
//behaviour function
void Run()
{
float velocity = Mathf.PerlinNoise(Time.time + index, index) * direction * moveSpeed * Time.deltaTime;
m_rigidbody.MovePosition(transform.position + velocity * Vector3.right);
}
bool inAnimation = false;
IEnumerator ColorShining(Color _firstColor, Color _secondColor, float _shiningTotalTime, float _shiningIntervalTime)
{
inAnimation = true;
int counter = 0;
float endingTime = Time.time + _shiningTotalTime;
Color nowColor = GetComponent<SpriteRenderer>().color;
while (Time.time < endingTime)
{
counter += 1;
switch (counter % 2)
{
case 1:
nowColor = _firstColor;
break;
case 0:
nowColor = _secondColor;
break;
}
GetComponent<SpriteRenderer>().color = nowColor;
yield return new WaitForSeconds(_shiningIntervalTime);
}
inAnimation = false;
GetComponent<SpriteRenderer>().color = _firstColor;
motionStateNow = ParticleMotionState.Idle;
nextTimeToEatOrBeEaten = eatingInterval+ Time.time;
foreach (ParticleMouse mouse in m_hunter.mice) mouse.isBeEaten = false;
}
IEnumerator ColorLerpChanging(Color _firstColor, Color _finalColor, float _lerpTotalTime)
{
inAnimation = true;
float endingTime = Time.time + _lerpTotalTime;
Color nowColor = GetComponent<SpriteRenderer>().color;
//avoid blink
if(nowColor != _firstColor || nowColor == _finalColor)
{
Color temp = _firstColor;
_firstColor = _finalColor;
_finalColor = temp;
}
m_audioPlayer.clip = waveOST;
m_audioPlayer.Play();
while (Time.time < endingTime)
{
nowColor = Color.Lerp(_finalColor, _firstColor, (endingTime - Time.time) / _lerpTotalTime);
GetComponent<SpriteRenderer>().color = nowColor;
yield return new WaitForEndOfFrame();
}
inAnimation = false;
GetComponent<SpriteRenderer>().color = _finalColor;
motionStateNow = ParticleMotionState.Idle;
nextTimeToEatOrBeEaten = eatingInterval + Time.time;
foreach (ParticleMouse mouse in m_hunter.mice) mouse.isBeEaten = false;
//GetComponent<SpriteRenderer>().material.SetColor("_TintColor", _firstColor);
}
#endregion
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum GameState{
Start,
Update,
end
}
public class GameStageManager : MonoBehaviour
{
public GameState m_GameState;
[Header("Time setting")]
[Tooltip("it means update time length")]
public float stageTimeLength = 60f;
float timer;
// Start is called before the first frame update
void Start()
{
}
IEnumerator GameStageControl()
{
yield return new WaitForEndOfFrame();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[ExecuteInEditMode]
public class ScreenSpaceBoundary : BoundaryBase
{
[Header("塞入相機物件")]
public GameObject cameraObject ;
[Header("到相機的距離")]
[Range(0f,100f)]public float distanceToCamera = 10;
public Color debugColor = Color.white;
[HideInInspector]public float minX, maxX, minY, maxY = 0;
[HideInInspector]public Vector3 worldCenter;
private void Update()
{
SetDistanceToCamera();
GetBoundaryConrner();
BoundaryVisualizer();
}
void SetDistanceToCamera()
{
//check camera gameObject
if(cameraObject == null)
cameraObject = GameObject.FindWithTag("MainCamera");
this.transform.position = new Vector3(0, cameraObject.transform.position.y, distanceToCamera);
worldCenter = this.transform.position;
}
void GetBoundaryConrner()
{
Vector3 bottomCorner = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, distanceToCamera));
Vector3 TopCorner = Camera.main.ViewportToWorldPoint(new Vector3(1, 1, distanceToCamera));
maxX = TopCorner.x;
minX = bottomCorner.x;
maxY = TopCorner.y;
minY = bottomCorner.y;
}
void BoundaryVisualizer()
{
Vector3 TopCornerRight = new Vector3(maxX,maxY,transform.position.z);
Vector3 TopCornerLeft = new Vector3(minX, maxY, transform.position.z);
Vector3 BottomCornerRight = new Vector3(maxX, minY, transform.position.z);
Vector3 BottomCornerLeft = new Vector3(minX, minY, transform.position.z);
Debug.DrawRay(TopCornerRight, TopCornerLeft - TopCornerRight , debugColor);
Debug.DrawRay(TopCornerRight, BottomCornerRight - TopCornerRight , debugColor);
Debug.DrawRay(BottomCornerLeft, TopCornerLeft - BottomCornerLeft , debugColor);
Debug.DrawRay(BottomCornerLeft, BottomCornerRight - BottomCornerLeft , debugColor);
}
public override bool isPointInside(Transform _point)
{
bool checkPositionX = (_point.position.x < maxX && _point.position.x > minX);
bool checkPositionY = (_point.position.y < maxY && _point.position.y > minY);
bool pointChecker = checkPositionX && checkPositionY;
return pointChecker;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerManager : MonoBehaviour, KinectGestures.GestureListenerInterface
{
KinectManager manager;
private static ModelGestureListener instance = null;
public static ModelGestureListener Instance
{
get
{
return instance;
}
}
public List<GameObject> PlayerList;
public List<KinectSkeletonTracker> PlayerParticleEffect;
public int usersSaved = 0;
public GameObject flashLight ;
void Update()
{
if(manager == null)manager = KinectManager.Instance;
// switch( manager.GetUsersCount())
// {
// case 0:
// for(int i = 1;i<PlayerList.Count;i++)
// {
// PlayerList[i].SetActive(false);
// //PlayerParticleEffect[i].enabled = false;
// }
// break;
// case 1:
// for(int i = 1;i<PlayerList.Count;i++)
// {
// PlayerList[i].SetActive(false);
// //PlayerParticleEffect[i].enabled = false;
// }
// break;
// case 2:
// break;
// case 3:
// break;
// }
// if(manager && manager.IsInitialized())
// {
// int usersNow = manager.GetUsersCount();
// if(usersNow > usersSaved)
// {
// OndetectUser();
// }
// if(usersNow < usersSaved)
// {
// OnLostUser();
// }
// usersSaved = usersNow;
// }
if(manager.GetUsersCount() == 0 && flashLight.activeSelf != true)
{
flashLight.SetActive(true);
}
else if(manager.GetUsersCount() != 0 && flashLight.activeSelf != false)
{
flashLight.SetActive(false);
}
}
void OndetectUser(){
}
void OnLostUser(){
}
public void UserDetected(long userId, int userIndex){
Debug.Log("User detect");
PlayerParticleEffect[userIndex].enabled = (true);
PlayerParticleEffect[userIndex].PlayerIndex = userIndex;
PlayerParticleEffect[userIndex].Idle = false;
StartCoroutine(PlayerParticleEffect[userIndex].Timer());
PlayerList[userIndex].SetActive(true);
PlayerList[userIndex].GetComponent<PlayerData>().userID = userId;
PlayerList[userIndex].GetComponent<PlayerData>().userIndex = userIndex;
PlayerList[userIndex].GetComponent<PlayerData>().ResetPalayerParticlePosition();
manager.DetectGesture(userId, KinectGestures.Gestures.Jump);
manager.DetectGesture(userId,KinectGestures.Gestures.Tpose);
manager.DetectGesture(userId,KinectGestures.Gestures.SwipeRight);
manager.DetectGesture(userId,KinectGestures.Gestures.SwipeLeft);
}
public void UserLost(long userId, int userIndex){
Debug.Log("user lost");
foreach(GameObject user in PlayerList)
{
long _userId = user.GetComponent<PlayerData>().userID;
int _userIndex = user.GetComponent<PlayerData>().userIndex;
if(_userId == userId)
{
//Debug.Log(userIndex);
if((manager.GetUsersCount() == 1 ))
{
user.GetComponent<PlayerData>().userID = -1;
PlayerParticleEffect[userIndex].enabled = false;
PlayerList.Insert(0,user);
return;
}
else if((manager.GetUsersCount() > 1 ))
{
PlayerList.Remove(user);
PlayerList.Add(user);
user.GetComponent<PlayerData>().userID = -1;
user.GetComponent<PlayerData>().userIndex = PlayerList.Count - 1;
PlayerParticleEffect[userIndex].enabled = false;
user.SetActive(false);
break;
}
}
}
}
public void PlayerGestureDetect(int userIndex, KinectGestures.Gestures gesture){}
public void GestureInProgress(long userId, int userIndex, KinectGestures.Gestures gesture,
float progress, KinectInterop.JointType joint, Vector3 screenPos){
if(progress >0.5f &&(gesture == KinectGestures.Gestures.Tpose ||
gesture == KinectGestures.Gestures.Jump
||gesture == KinectGestures.Gestures.SwipeRight ||
gesture == KinectGestures.Gestures.SwipeLeft ||
gesture == KinectGestures.Gestures.RaiseRightHand
))
{
KinectSkeletonTracker vfx = PlayerParticleEffect[userIndex];
Color m_color = vfx.m_Color;
Color _color = new Color(m_color.r, m_color.g, m_color.b, 1);
vfx.changeColor(_color);
vfx.Idle = false;
StartCoroutine(vfx.Timer());
PlayerList[userIndex].GetComponent<PlayerData>().ResetPalayerParticlePosition();
Debug.Log("Get complete gesture id : " + userId);
return;
}
}
public bool GestureCompleted(long userId, int userIndex, KinectGestures.Gestures gesture,
KinectInterop.JointType joint, Vector3 screenPos)
{
if((gesture == KinectGestures.Gestures.Tpose ||
gesture == KinectGestures.Gestures.Jump
||gesture == KinectGestures.Gestures.SwipeRight
))
{
KinectSkeletonTracker vfx = PlayerParticleEffect[userIndex];
Color m_color = vfx.m_Color;
Color _color = new Color(m_color.r, m_color.g, m_color.b, 1);
vfx.changeColor(_color);
vfx.Idle = false;
StartCoroutine(vfx.Timer());
Debug.Log("Get complete gesture id : " + userId);
PlayerList[userIndex].GetComponent<PlayerData>().ResetPalayerParticlePosition();
return true;
}
else if(gesture == KinectGestures.Gestures.SwipeLeft)
{
}
else if( gesture == KinectGestures.Gestures.RaiseRightHand)
{
}
return false;
}
public bool GestureCancelled(long userId, int userIndex, KinectGestures.Gestures gesture,
KinectInterop.JointType joint)
{
return true;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseControllMove : MonoBehaviour
{
public GameObject controllObject;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
MouseControlMove();
}
public void MouseControlMove()
{
//Vector3 point = new Vector3();
Event currentEvent = Event.current;
//Vector2 mousePos = new Vector2();
ScreenSpaceBoundary m_Boundary = GetComponent<ScreenSpaceBoundary>();
Vector3 mousePointToPlayerLayer = Camera.main.ScreenToWorldPoint(
new Vector3(Input.mousePosition.x,
Input.mousePosition.y,
m_Boundary.distanceToCamera));
controllObject.transform.position = mousePointToPlayerLayer;
//m_rigidbody.MovePosition(mousePointToPlayerLayer);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class BoundaryBase : MonoBehaviour {
public void CollisionBoundary(Transform particleTransform,ref BoundaryEvent @event){
if(isPointInside(particleTransform))
{
@event.StayBoundary();
}
else
{
@event.ExitBoundary();
}
}
public virtual bool isPointInside(Transform _point){
return false;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml.Schema;
using System.Runtime.CompilerServices;
public enum mainParticleStage
{
rebornDelay,
start,
update,
beEaten,
end
}
public class MainParticleLifeCycle : ParticleBase
{
[HideInInspector] public int index;
[Range(0, 10)] public float rebornDelayTimeRange = 5f;
float rebornDelayTime = 5f;
[Range(0, 20)] public float localMoveSpeed = 2;
//private Color m_color;
public Color fisrtColor;
public Color finalColor;
ScreenSpaceBoundary m_Boundary;
Rigidbody m_rigidbody;
Renderer m_renderer;
#region time comtrol
public float lerpTime = 1f;
#endregion
public mainParticleStage m_stage = mainParticleStage.rebornDelay;
//[HideInInspector]public MainParticleMove m_move = new MainParticleMove();
[HideInInspector]public MainParticleMove m_move;
public BoundaryEvent m_event;
//ParticleSystem m_particleEffect;
private void Start()
{
Initialized();
RebornPositionSetting();
StartCoroutine(StageControl());
}
private void Update()
{
if (GetComponent<Rigidbody>().velocity.magnitude > maxMoveSpeed)
{
GetComponent<Rigidbody>().velocity = GetComponent<Rigidbody>().velocity.normalized * maxMoveSpeed;
}
}
private void FixedUpdate()
{
OutputValue();
}
public new void BeEaten()
{
//Debug.Log("number" + index + "be eaten");
//m_particleEffect.Play();
m_stage = mainParticleStage.beEaten;
GetComponent<MeshRenderer>().enabled = false;
}
public void Run()
{
direction += new Vector3(
Mathf.Sin(Mathf.Rad2Deg * Random.Range(-Mathf.PI, Mathf.PI) * Mathf.PerlinNoise(Time.time + index, index)),
Mathf.Cos(Mathf.Rad2Deg * Random.Range(-Mathf.PI, Mathf.PI) * Mathf.PerlinNoise(Time.time + index, index)), 0);
direction = direction.normalized;
direction.Set(direction.x, direction.y, 0);
//Debug.Log("Run");
velocity = Mathf.PerlinNoise( Time.time + index, index ) * direction * localMoveSpeed * Time.deltaTime;
}
void OutputValue()
{
if(m_move.index % 2 != 0)
{
m_rigidbody.AddForce(m_move.velocity * 150);
}
else{
m_rigidbody.MovePosition(transform.position + m_move.velocity);
//Debug.Log("Move position"+m_move.index);
}
//m_rigidbody.AddForce(velocity);
m_rigidbody.angularVelocity = m_move.angVelocity;
//Debug.Log("m_move" + m_move.velocity);
}
public void Initialized()
{
rebornDelayTime = Random.Range(rebornDelayTimeRange*0.3f, rebornDelayTimeRange);
m_Boundary = transform.parent.GetComponent<ScreenSpaceBoundary>();
m_rigidbody = GetComponent<Rigidbody>();
m_renderer = GetComponent<Renderer>();
m_event = new MainParticleBoundaryEvent(GetComponent<MainParticleLifeCycle>());
//m_move = new MainParticleMove();
m_move = gameObject.AddComponent<MainParticleMove>();
//m_color = fisrtColor ;
m_renderer.material.SetColor("_TintColor", new Color(fisrtColor.a,fisrtColor.g,fisrtColor.b,0));
}
public void AttributeInitialze()
{
RebornPositionSetting();
m_move.velocity = Vector3.zero;
m_move.angVelocity = Vector3.zero;
m_move.index = Random.Range(12345, 823231);
m_move.localMoveSpeed = localMoveSpeed;
rebornDelayTime = Random.Range(0, rebornDelayTimeRange);
}
void RebornPositionSetting()
{
transform.localPosition = new Vector3(
Random.Range(m_Boundary.minX, m_Boundary.maxX),
Random.Range(m_Boundary.minY, m_Boundary.maxY), 0);
}
public void ExitBoundary()
{
//AttributeInitialze();
//m_renderer.material.SetColor("_TintColor", new Color(fisrtColor.r, fisrtColor.g, fisrtColor.b, 0));
m_stage = mainParticleStage.end;
}
IEnumerator StageControl()
{
while (true)
{
float timer = 0;
Color nowColor;
Color lerpColor = new Color(fisrtColor.r, fisrtColor.g, fisrtColor.b, 0);
Color m_color = m_renderer.material.GetColor("_TintColor");
switch(m_stage)
{
case mainParticleStage.rebornDelay:
//velocity = Vector3.zero;
angVelocity = Vector3.zero;
//GetComponent<Rigidbody>().
GetComponent<MeshRenderer>().enabled = true;
GetComponent<Collider>().enabled = false;
m_renderer.material.SetColor("_TintColor", lerpColor);
while (timer / rebornDelayTime < 1)
{
timer += Time.deltaTime;
//Debug.Log("Timer"+timer);
if(m_stage != mainParticleStage.rebornDelay)
{
break;
}
yield return new WaitForEndOfFrame();
}
m_stage = mainParticleStage.start;
break;
case mainParticleStage.start:
AttributeInitialze();
GetComponent<Collider>().enabled = true;
GetComponent<Rigidbody>().isKinematic = false;
//m_rigidbody.constraints = RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY;
while (timer / lerpTime < 1)
{
timer += Time.deltaTime;
nowColor = Color.Lerp(m_color, fisrtColor, timer / lerpTime);
m_renderer.material.SetColor("_TintColor", nowColor);
m_Boundary.CollisionBoundary(transform, ref m_event);
//CollisionBoundary();
//m_Boundary.CollisionBoundary(transform,ref m_event);
// if (m_stage != mainParticleStage.start)
// {
// break;
// }
yield return new WaitForEndOfFrame();
}
m_stage = mainParticleStage.update;
break;
case mainParticleStage.update:
while (timer / lifeTime < 1)
{
timer += Time.deltaTime;
m_Boundary.CollisionBoundary(transform, ref m_event);
if (m_stage != mainParticleStage.update)
{
break;
}
yield return new WaitForEndOfFrame();
}
m_stage = mainParticleStage.end;
break;
case mainParticleStage.beEaten:
m_stage = mainParticleStage.rebornDelay;
break;
case mainParticleStage.end:
while (timer / lerpTime < 1)
{
timer += Time.deltaTime;
nowColor = Color.Lerp(m_color, lerpColor, timer / lerpTime);
m_renderer.material.SetColor("_TintColor", nowColor);
//CollisionBoundary();
m_Boundary.CollisionBoundary(transform, ref m_event);
if(m_Boundary.isPointInside(transform))
{
m_move.Run();
}
if (m_stage != mainParticleStage.end)
{
break;
}
yield return new WaitForEndOfFrame();
}
m_stage = mainParticleStage.rebornDelay;
break;
}
}
}
}
public class MainParticleBoundaryEvent : BoundaryEvent
{
public MainParticleLifeCycle _particle;
public MainParticleBoundaryEvent(MainParticleLifeCycle particle)
{
_particle = particle;
//Debug.Log(_particle);
}
public override void StayBoundary()
{
_particle.m_move.Run();
//Debug.Log("Stay boundary");
}
public override void ExitBoundary()
{
_particle.m_stage = mainParticleStage.end;
_particle.velocity = Vector3.zero;
//Debug.Log("Exit boundary");
}
}
public class MainParticleMove : ParticleBase
{
public int index;
public float localMoveSpeed = 100;
public void Run()
{
direction += new Vector3(
Mathf.Sin(Mathf.Rad2Deg * Random.Range(-Mathf.PI, Mathf.PI) * Mathf.PerlinNoise(Time.time + index, index)),
Mathf.Cos(Mathf.Rad2Deg * Random.Range(-Mathf.PI, Mathf.PI) * Mathf.PerlinNoise(Time.time + index, index)), 0);
direction = direction.normalized;
direction.Set(direction.x, direction.y, 0);
velocity = Mathf.PerlinNoise(Time.time + index, index) * direction * localMoveSpeed * Time.deltaTime;
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
//using Boo.Lang;
[System.Serializable]
public class PlayerHunter : Hunter
{
}
public enum ForceType
{
attractive,
explosition
}
public class PlayerParticleBehaviour : ParticleBehaiour{
private static PlayerParticleBehaviour _instance;
public PlayerParticleBehaviour instance{
get
{
if (_instance == null) _instance = this;
return _instance;
}
}
int index;
int eatNumberCounter;
float timer;
float timerAtIdle;
float timerAtEnd;
float timerAtFirst;
/* 參考用
public ApearenceStructure apearence;
public PhysicMotionSetting physicMotion;
public bool isUseRandomReborn;
//public Hunter hunter;
[Header("State setting")]
public bool isHunter = false;
public ParticleLifeState stateNow;
public ParticleMotionState motionStateNow;
[Header("Growing Up attribute")]
public bool canItGrowUp = false;
public int HowMuchNumberForEatingToGrowUp;
[HideInInspector] public bool beEaten = false;
//int index;
[HideInInspector]public ScreenSpaceBoundary m_Boundary;
[HideInInspector]public Rigidbody m_rigidbody;
[HideInInspector]public SphereCollider m_collider;
*/
public PlayerHunter m_hunter;
[Header("Force effect Radius")]
[Range(0.5f, 10f)] public float attractiveRadius = 7.5f;
[Range(0.5f, 10f)] public float collisionRadius = 2f;
[Range(0.5f, 10f)] public float explosionRadius = 7.5f;
[Header("Force")]
public float RepulsiveForce = 100f;
public float AttrativeForce = 10f;
[Header("Time Setting")]
public float lifeTime = 20f;
public float explosionTime = 0.3f;
public float attractiveTime = 10f;
[Header("Move motion setting")]
public Vector2 stepRandomMoveDistance = new Vector2(1, 2);
public Vector2 maxMoveAngle = new Vector2(60, 120);
[Header("Interactive target")]
[Tooltip("the particle who will affected by player particle")]
public LayerManager[] InteractTarget;
public LayerManager[] HuntingTarget;
public bool isUseMouseToControl = true;
public int MaxCorner = 18;
public float stage1Scale = 2.8f;
public float stage2Scale = 5;
public float stage1ColliderTrigger = 5;
public float stage2ColliderTrigger = 1;
[Header("Audio Sound Effect")]
public AudioClip EatingSnakeOST;
public AudioClip EatingLittleParticleOST;
public AudioClip EatingEmitterParticleOST;
public AudioClip EatingWaveOST;
public AudioSource m_audioPlayer;
private GameObject stage2;
// Use this for initialization
void Start () {
stage2 = GameObject.Find("Stage2");
GetComponent<SphereCollider>().radius = stage1ColliderTrigger;
HowMuchNumberForEatingToGrowUp = 15;
}
// Update is called once per frame
void Update () {
if(stage2 == null)
{
stage2 = GameObject.Find("Stage2");
return;
}
if(stage2.activeSelf && transform.localScale.x != stage2Scale)
{
transform.localScale = Vector3.one * stage2Scale;
}
else if(!stage2.activeSelf && transform.localScale.x != stage1Scale)
{
transform.localScale = Vector3.one * stage1Scale;
}
if(!stage2.activeSelf && GetComponent<SphereCollider>().radius != stage1ColliderTrigger)
{
GetComponent<SphereCollider>().radius = stage1ColliderTrigger;
}
else if(stage2.activeSelf && GetComponent<SphereCollider>().radius != stage2ColliderTrigger)
{
GetComponent<SphereCollider>().radius = stage2ColliderTrigger;
}
}
private void FixedUpdate()
{
LifeCycleStateSelector();
}
public void Inititalize()
{
m_Boundary = transform.parent.GetComponent<ScreenSpaceBoundary>();
m_collider = this.GetComponent<SphereCollider>();
m_rigidbody = this.GetComponent<Rigidbody>();
m_hunter.HuntingTargets = HuntingTarget;
m_hunter.mouse.HuntingTargets = HuntingTarget;
timer = 0;
stateNow = ParticleLifeState.Update;
}
public override void LifeCycleStateSelector()
{
timer += Time.deltaTime;
switch (stateNow)
{
case ParticleLifeState.Start:
Inititalize();
if (isUseMouseToControl) MouseControlMove();
else { IdleMove(); }
stateNow = ParticleLifeState.Update;
break;
case ParticleLifeState.Update:
UpdateCycleStateSelector();
break;
case ParticleLifeState.End:
stateNow = ParticleLifeState.Start;
break;
}
}
public override void UpdateCycleStateSelector()
{
EventManager();
switch (motionStateNow)
{
case ParticleMotionState.FirstUpdate:
FirstUpdateEventHandler();
break;
case ParticleMotionState.Idle:
IdldeEventHandler();
if (isUseMouseToControl) MouseControlMove();
break;
case ParticleMotionState.Hunting:
break;
case ParticleMotionState.Eating:
m_hunter.mouse.isEating = false;
break;
case ParticleMotionState.interactive:
if (isUseMouseToControl) MouseControlMove();
break;
case ParticleMotionState.BeEaten:
break;
case ParticleMotionState.EndOfUpdate:
EndOfUpdateEventHandler();
break;
}
}
public bool interaciveStateTrigger = false;
void EventManager()
{
if(timerAtFirst / explosionTime < 1)
{
motionStateNow = ParticleMotionState.FirstUpdate;
}
else if(timerAtIdle/lifeTime < 1)
{
if(interaciveStateTrigger)
{
motionStateNow = ParticleMotionState.interactive;
}
else if (m_hunter.getIsEating)
{
motionStateNow = ParticleMotionState.Eating;
}
else if(m_hunter.ifHasTarget)
{
motionStateNow = ParticleMotionState.Hunting;
}
else if(beEaten)
{
motionStateNow = ParticleMotionState.BeEaten;
}
else
{
motionStateNow = ParticleMotionState.Idle;
}
}
else
{
motionStateNow = ParticleMotionState.EndOfUpdate;
}
}
void FirstUpdateEventHandler()
{
timerAtFirst += Time.deltaTime;
}
void IdldeEventHandler()
{
timerAtIdle += Time.deltaTime;
}
void EndOfUpdateEventHandler()
{
timerAtEnd += Time.deltaTime;
if (timerAtEnd / explosionTime > 1)
{
stateNow = ParticleLifeState.End;
timerAtEnd = 0;
timerAtIdle = 0;
timerAtFirst = 0;
}
}
private void OnTriggerStay(Collider other)
{
InteractiveStateSelector(other.gameObject);
}
void OnTriggerEnter(Collider other)
{
EatingEvent(other.gameObject);
}
public void InteractiveStateSelector(GameObject collisionObject)
{
if (!checkIfInTargetList(InteractTarget, collisionObject))
return;
if(stateNow == ParticleLifeState.Update)
{
switch (motionStateNow)
{
case ParticleMotionState.FirstUpdate:
ForceSelector(collisionObject,ForceType.explosition);
break;
case ParticleMotionState.Idle:
ForceSelector(collisionObject, ForceType.attractive);
break;
case ParticleMotionState.Hunting:
break;
case ParticleMotionState.Eating:
Grow();
break;
case ParticleMotionState.interactive:
if(collisionObject.GetComponent<Rigidbody>() != null)
ForceSelector(collisionObject, ForceType.explosition);
if(m_hunter.getIsEating)Grow();
break;
case ParticleMotionState.BeEaten:
break;
case ParticleMotionState.EndOfUpdate:
ForceSelector(collisionObject, ForceType.explosition);
break;
}
}
}
void EatingEvent(GameObject beEatenGameObject)
{
switch (beEatenGameObject.layer)
{
//object
case 9:
break;
//snake
case 13:
if(beEatenGameObject.GetComponent<SnakeHead>() == null)return;
m_audioPlayer.clip = EatingSnakeOST;
m_audioPlayer.Play();
break;
//emitter partcle
case 14:
m_audioPlayer.clip = EatingEmitterParticleOST;
m_audioPlayer.Play();
break;
//wave
case 16:
m_audioPlayer.clip = EatingWaveOST;
m_audioPlayer.Play();
break;
}
}
/// <summary>
/// direct add force to input game object
/// </summary>
/// <param name="_collisionObject">.</param>
/// <param name="type">Type.</param>
public void ForceSelector(GameObject _collisionObject,ForceType type)
{
Vector3 Force = Vector3.zero;
Rigidbody pRigidbody = _collisionObject.GetComponent<Rigidbody>();
float distance = Vector3.Distance(transform.position, _collisionObject.transform.position);
switch(type)
{
case ForceType.attractive:
Force = (this.transform.position - _collisionObject.transform.position).normalized *
Mathf.Lerp(AttrativeForce, AttrativeForce / 2, distance / attractiveRadius);
break;
case ForceType.explosition:
Force = (_collisionObject.transform.position - this.transform.position).normalized *
Mathf.Lerp(0, RepulsiveForce, distance / explosionRadius);
break;
}
pRigidbody.AddForce(Force);
}
int direction = 1;
void IdleMove()
{
direction = Random.Range(0, 100) > 50 ? 1 : -1;
float mediumAngle = direction == 1 ? (maxMoveAngle.x + maxMoveAngle.y) * Mathf.Deg2Rad * 0.5f : (maxMoveAngle.x + maxMoveAngle.y) * Mathf.Deg2Rad * 0.5f + 180f * Mathf.Deg2Rad;
float moveAngle = Random.Range(maxMoveAngle.x * Mathf.Deg2Rad - mediumAngle, maxMoveAngle.y * Mathf.Deg2Rad - mediumAngle);
float moveDistance = Random.Range(stepRandomMoveDistance.x, stepRandomMoveDistance.y);
float newX = (float)(moveDistance * Mathf.Cos(moveAngle));
float newY = (float)(moveDistance * Mathf.Sin(moveAngle));
m_rigidbody.MovePosition(transform.position + new Vector3(newX, newY, 0).normalized * Time.deltaTime * physicMotion.speed);
}
public void MouseControlMove()
{
//Vector3 point = new Vector3();
Event currentEvent = Event.current;
//Vector2 mousePos = new Vector2();
Vector3 mousePointToPlayerLayer = Camera.main.ScreenToWorldPoint(
new Vector3(Input.mousePosition.x,
Input.mousePosition.y,
m_Boundary.distanceToCamera));
m_rigidbody.MovePosition(mousePointToPlayerLayer);
}
public bool checkIfInTargetList(LayerManager[] list, GameObject checkThisObject)
{
if(list.Length == 0)
{
Debug.Log("the list dont have any target");
return false;
}
for (int i = 0; i < list.Length;i++)
{
if(checkThisObject.layer == (int)list[i])
{
return true;
}
}
return false;
}
private void OnMouseDown()
{
m_hunter.mouse.MouseCollider.isTrigger = true;
interaciveStateTrigger = true;
}
private void OnMouseUp()
{
m_hunter.mouse.MouseCollider.isTrigger = false;
interaciveStateTrigger = false;
}
float timerToEat;
void Grow()
{
eatNumberCounter += 1;
m_hunter.mouse.Reset();
if (eatNumberCounter % HowMuchNumberForEatingToGrowUp == 0 && canItGrowUp)
{
Star m_shape = GetComponent<Star>();
if (m_shape.frequency < MaxCorner && Time.time > timerToEat)
{
timerToEat = Time.time + 6f;
transform.localScale *=1.1f;
m_shape.frequency++;
m_shape.Reset();
eatNumberCounter = 0;
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpinAround : MonoBehaviour {
// Use this for initialization
void Start () {
StartCoroutine(spinAround());
}
public float frequency = 0.5f;
public int direction = 1;
public float minSpeed = 50;
public float maxSpeed = 150;
public bool isUsePhysicWayToRotate = false;
IEnumerator spinAround()
{
while(true)
{
float angle = (minSpeed + (maxSpeed - minSpeed) *
Mathf.PerlinNoise(Time.deltaTime *
Mathf.Sin(minSpeed + maxSpeed) *
Mathf.Cos((maxSpeed - minSpeed)),
1)) *
Time.deltaTime * direction * Mathf.Sin((minSpeed + Time.time) * frequency);
if(!isUsePhysicWayToRotate)
transform.Rotate(0,0,angle);
else
GetComponent<Rigidbody>().angularVelocity += new Vector3(0, 0, angle);
//Debug.Log(angle);
yield return new WaitForEndOfFrame();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class StageTransferTool : MonoBehaviour
{
[Header("Game Object setting")]
public Camera MainCamera;
public PostProcessVolume postProcessing;
public Text TimerText;
public GameObject Stage1;
public GameObject Stage2;
public bool isUseKinect;
public GameObject noKinectPLayer;
public GameObject kinectPlayer;
private float timer;
[Header("Time setting")]
public float fadeInTime = 0.3f;
public float fadeOutTime = 1f;
public float Stage1TimeLength = 60;
public float Stage2TimeLength = 60;
public float EndingStageTimeLength = 30;
public gameStage gameStageNow = gameStage.Stage1;
[Header("[Start]Vignette Animation setting (Blink)")]
public Color vignetteColor = new Color(0,19,67,255);
public Color vignetteColor2 = new Color(0,19,67,255);
public AnimationCurve vignetteIntensity = AnimationCurve.EaseInOut(0,0.5f,1,0.3f);
public AnimationCurve vignetteRoundness = AnimationCurve.EaseInOut(0,1f,1,0.9f);
[Header("[Start]Color grading Attribte setting (Blink)")]
public AnimationCurve ColorGrading_ColorFilter_Intensity = AnimationCurve.EaseInOut(0,0,1,1);
[Header("[Transfer]Vignette Animation setting")]
public float cameraMotionTimeLength = 2f;
public AnimationCurve cameraMotionTime1 = AnimationCurve.EaseInOut(0,0.5f,1,-0.1f);
public AnimationCurve cameraMotionTime2 = AnimationCurve.EaseInOut(0,1.1f,1,0.5f);
public GameObject EndingCanvas;
public enum gameStage{
Stage1,
Stage2
}
// Start is called before the first frame update
void Start()
{
//if(isFullScreen) Screen.fullScreen = true;
if (!isUseKinect)
{
//switch to mouse
noKinectPLayer.SetActive(true);
kinectPlayer.SetActive(false);
MainCamera = noKinectPLayer.GetComponent<PlayerObjectManager>().MainCamera;
postProcessing = MainCamera.GetComponent<PostProcessVolume>();
}
else
{
//switch to kinect
noKinectPLayer.SetActive(false);
kinectPlayer.SetActive(true);
MainCamera = kinectPlayer.GetComponent<PlayerObjectManager>().MainCamera;
postProcessing = MainCamera.GetComponent<PostProcessVolume>();
}
ChangeBoundaryLayerCamera();
attributeInitate();
StartCoroutine( GameStageManager());
}
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
TimerText.text = "Time : " + (int)timer;
if(Input.GetKeyDown(KeyCode.Space))
{
SceneManager.LoadSceneAsync(0);
}
}
IEnumerator GameStageManager()
{
BlinkEffect();
yield return new WaitForSeconds(Stage1TimeLength);
if(gameStageNow == gameStage.Stage1)
TransferEffect();
yield return new WaitForSeconds(Stage2TimeLength);
EndingCanvas.SetActive(true);
Stage1.SetActive(false);
Stage2.SetActive(false);
yield return new WaitForSeconds(EndingStageTimeLength);
SceneManager.LoadSceneAsync(0);
}
void attributeInitate()
{
if(MainCamera == null)
{
MainCamera = Camera.main;
}
if(postProcessing == null)
{
postProcessing = MainCamera.GetComponent<PostProcessVolume>();
}
timer = 0;
}
public void SwitchPlayerControll()
{
isUseKinect = !isUseKinect;
if(!isUseKinect)
{
//switch to mouse
noKinectPLayer.SetActive(true);
kinectPlayer.SetActive(false);
MainCamera = noKinectPLayer.GetComponent<PlayerObjectManager>().MainCamera;
postProcessing = MainCamera.GetComponent<PostProcessVolume>();
}
else
{
//switch to kinect
noKinectPLayer.SetActive(false);
kinectPlayer.SetActive(true);
MainCamera = kinectPlayer.GetComponent<PlayerObjectManager>().MainCamera;
postProcessing = MainCamera.GetComponent<PostProcessVolume>();
}
ChangeBoundaryLayerCamera();
}
public void ChangeBoundaryLayerCamera()
{
switch(gameStageNow)
{
case gameStage.Stage1:
foreach(ScreenSpaceBoundary layerBoundary in Stage1.GetComponentsInChildren<ScreenSpaceBoundary>())
{
layerBoundary.cameraObject = MainCamera.gameObject;
}
break;
case gameStage.Stage2:
foreach(ScreenSpaceBoundary layerBoundary in Stage2.GetComponentsInChildren<ScreenSpaceBoundary>())
{
layerBoundary.cameraObject = MainCamera.gameObject;
}
break;
}
}
public void BlinkEffect()
{
gameStageNow = gameStage.Stage1;
StartCoroutine(Blink());
}
public void TransferEffect()
{
gameStageNow = gameStage.Stage2;
StartCoroutine(camerMotion());
}
public void TimeMachine()
{
Time.timeScale = 10;
}
void stageObjectManager()
{
switch(gameStageNow)
{
case gameStage.Stage1:
Stage1.SetActive(true);
Stage2.SetActive(false);
break;
case gameStage.Stage2:
Stage1.SetActive(false);
Stage2.SetActive(true);
break;
}
}
IEnumerator Blink()
{
Vignette vignette = null;
ColorGrading colorGrading = null;
postProcessing.profile.TryGetSettings(out vignette);
postProcessing.profile.TryGetSettings(out colorGrading);
vignette.color.value = vignetteColor;
stageObjectManager();
for (float i = 0; i < fadeInTime; i+=Time.deltaTime)
{
vignette.intensity.value = vignetteIntensity.Evaluate(i/fadeInTime);
vignette.roundness.value = vignetteRoundness.Evaluate(i/fadeInTime);
colorGrading.colorFilter.value = new Color(
ColorGrading_ColorFilter_Intensity.Evaluate(i/fadeInTime),
ColorGrading_ColorFilter_Intensity.Evaluate(i/fadeInTime),
ColorGrading_ColorFilter_Intensity.Evaluate(i/fadeInTime),0);
yield return new WaitForEndOfFrame();
}
}
IEnumerator camerMotion()
{
Vignette vignette = null;
postProcessing.profile.TryGetSettings(out vignette);
fadeInTime = 0.15f;
// for (float i = 0; i < fadeInTime; i+=Time.deltaTime)
// {
// vignette.intensity.value = vignetteIntensity.Evaluate(1 - i/fadeInTime);
// vignette.roundness.value = vignetteRoundness.Evaluate(1- i/fadeInTime);
// yield return new WaitForEndOfFrame();
// }
// vignette.rounded.value = true;
vignette.color.value = vignetteColor2;
for (float i = 0; i <cameraMotionTimeLength; i+=Time.deltaTime)
{
float x = cameraMotionTime1.Evaluate(i/cameraMotionTimeLength);
vignette.center.value =new Vector2(x,vignette.center.value.y);
yield return new WaitForEndOfFrame();
}
stageObjectManager();
for (float i = 0; i < cameraMotionTimeLength; i+=Time.deltaTime)
{
float x = cameraMotionTime2.Evaluate(i/cameraMotionTimeLength);
vignette.center.value =new Vector2(x,vignette.center.value.y);
yield return new WaitForEndOfFrame();
}
// vignette.rounded.value = false;
// for (float i = 0; i < fadeInTime; i+=Time.deltaTime)
// {
// vignette.intensity.value = vignetteIntensity.Evaluate(i/fadeInTime);
// vignette.roundness.value = vignetteRoundness.Evaluate(i/fadeInTime);
// yield return new WaitForEndOfFrame();
// }
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FlashTool : MonoBehaviour
{
public float flashInterval = 0.5f;
Image m_img;
// Start is called before the first frame update
void Start()
{
StartCoroutine(Flash());
}
IEnumerator Flash()
{
Image m_img = GetComponent<Image>();
Color m_color = new Color( m_img.color.r,m_img.color.g,m_img.color.b,m_img.color.a);
Color m_Color_transparent = new Color(m_color.r,m_color.g,m_color.b,0);
while(true)
{
//alpha now to 0
for(float i = 0;i<flashInterval;i+=Time.deltaTime)
{
m_img.color = Color.Lerp(m_color,m_Color_transparent,i/flashInterval);
yield return new WaitForEndOfFrame();
}
//alpha 0 to now
for(float i = 0;i<flashInterval;i+=Time.deltaTime)
{
m_img.color = Color.Lerp(m_Color_transparent,m_color,i/flashInterval);
yield return new WaitForEndOfFrame();
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
[System.Serializable]
public struct ApearenceStructure
{
public Gradient randomRebbornColor;
}
[System.Serializable]
public struct PhysicMotionSetting
{
public float speed;
public float maxMoveSpeed;
}
public enum ParticleLifeState
{
RebornDelay,
Start,
Update,
End
}
public enum ParticleMotionState
{
Idle,
Hunting,
Eating,
BeEaten,
interactive,
grow,
FirstUpdate,
EndOfUpdate
}
public enum LayerManager
{
Object = 9,
Player = 10,
SpringJointWorm = 12,
Snake = 13,
EmitterParticle = 14,
Wave = 15,
Trash = 16
}
public class ParticleBehaiour : MonoBehaviour {
//public Hunter hunter;
[Header("State setting")]
public bool isHunter = false;
public ParticleLifeState stateNow;
public ParticleMotionState motionStateNow;
[Header("Growing Up attribute")]
public bool isUseRandomReborn;
public bool canItGrowUp = false;
public int HowMuchNumberForEatingToGrowUp;
[HideInInspector] public bool beEaten = false;
[Header("struct data setting")]
public PhysicMotionSetting physicMotion;
//int index;
[HideInInspector]public ScreenSpaceBoundary m_Boundary;
[HideInInspector]public Rigidbody m_rigidbody;
[HideInInspector]public SphereCollider m_collider;
public void InitializeComponent()
{
m_Boundary = transform.parent.GetComponent<ScreenSpaceBoundary>();
m_rigidbody = GetComponent<Rigidbody>();
m_collider = GetComponent<SphereCollider>();
}
public virtual void RandomReborn(){}
public virtual void Initialize(){}
public virtual void LifeCycleStateSelector(){}
public virtual void UpdateCycleStateSelector(){}
//public virtual void EventManagement(){}
public virtual void GrowUp()
{
if(canItGrowUp)
{
}
}
public Vector3 RegenerateStartPosition(int direction)
{
float newPositionX = (direction == 1 ? m_Boundary.minX : m_Boundary.maxX) - 5f * direction;
float newPositionY = (m_Boundary.maxY + m_Boundary.minY) / 2 + ((m_Boundary.maxY - m_Boundary.minY) / 4) * Mathf.Sin(Time.time * 0.5f);
Vector3 newPosition = new Vector3(newPositionX, newPositionY, 0);
return newPosition;
}
public void PositionInitialize()
{
this.transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, 0);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class SnakeHead : MonoBehaviour {
//public LayerManager HuntingTarget;
public bool beEaten = false;
public LayerManager[] HuntingTargets;
public List<GameObject> HuntingList = new List<GameObject>();
public GameObject snakeMouse;
public bool getIfEating
{
get{
return snakeMouse.GetComponent<SnakeMouse>().isEating;
}
}
[HideInInspector]public GameObject _currentTarget;
// Use this for initialization
void Start () {
snakeMouse.GetComponent<SnakeMouse>().HuntingTargets = HuntingTargets;
}
// Update is called once per frame
void Update () {
}
private void FixedUpdate()
{
checkEveryTarget();
}
void checkEveryTarget()
{
if (HuntingList.Count == 0) return;
for (int i = 0; i < HuntingList.Count;i++)
{
if(HuntingList[i] == null)
{
HuntingList.Remove(HuntingList[i]);
break;
}
switch (HuntingList[i].layer)
{
//object layer
case 9:
if (HuntingList[i].GetComponent<MainParticleLifeCycle>().m_stage != mainParticleStage.update)
{
if(_currentTarget == HuntingList[i].gameObject)
{
_currentTarget = null;
}
HuntingList.Remove(HuntingList[i].gameObject);
}
break;
//player layer
case 10:
break;
//spring worm layer
case 12:
break;
case 13:
break;
case 14:
if(Vector3.Distance(transform.position,HuntingList[i].transform.position)>10)
{
if (_currentTarget == HuntingList[i].gameObject)
{
_currentTarget = null;
}
HuntingList.Remove(HuntingList[i].gameObject);
}
else if(HuntingList[i].GetComponent<ParticleMouse>().isBeEaten)
{
HuntingList.Remove(HuntingList[i].gameObject);
}
break;
}
}
}
private void OnTriggerEnter(Collider other)
{
for (int i = 0; i < HuntingTargets.Length;i++)
{
//Debug.Log(other.gameObject.layer + " " + (int)HuntingTargets[i]);
if(other.gameObject.layer == (int)HuntingTargets[i])
{
switch(other.gameObject.layer)
{
//object layer
case 9:
if (other.gameObject.GetComponent<MainParticleLifeCycle>() == false) return;
if(other.gameObject.GetComponent<MainParticleLifeCycle>().m_stage == mainParticleStage.update)
{
HuntingList.Add(other.gameObject);
}
break;
//player layer
case 10:
break;
//spring worm layer
case 12:
break;
case 13:
break;
case 14:
if (other.GetComponent<ParticleMouse>() == null) return;
if (!other.GetComponent<ParticleMouse>().isBeEaten)
HuntingList.Add(other.gameObject);
else Debug.Log("Emitter has already be eaten");
break;
case 16:
HuntingList.Add(other.gameObject);
break;
}
}
}
}
private void OnTriggerExit(Collider other)
{
//if (other.gameObject.layer == huntingTarget)
for (int i = 0; i < HuntingTargets.Length; i++)
{
if (other.gameObject.layer == (int)HuntingTargets[i])
{
HuntingList.Remove(other.gameObject);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class BoundaryEvent
{
public abstract void StayBoundary();
public abstract void ExitBoundary();
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.Rendering.PostProcessing;
public class FocusDistanceControlWithPlayerLayer : MonoBehaviour {
public ScreenSpaceBoundary playerLayerBoundary;
public float changingFrequency = 5f;
PostProcessVolume volume;
// Use this for initialization
void Start () {
StartCoroutine(changeFocusDistance());
}
// Update is called once per frame
void Update () {
}
IEnumerator changeFocusDistance()
{
while(true)
{
ControlFocusDistance();
yield return new WaitForSeconds(changingFrequency);
}
}
void ControlFocusDistance()
{
volume = gameObject.GetComponent<PostProcessVolume>();
DepthOfField depthOfField = null;
volume.profile.TryGetSettings(out depthOfField);
depthOfField.focusDistance.value = ReadPlayerLayerDistance();
}
float ReadPlayerLayerDistance()
{
float distanceOfPlayerLayer = 0;
distanceOfPlayerLayer = playerLayerBoundary.distanceToCamera;
return distanceOfPlayerLayer;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Security.Cryptography.X509Certificates;
[RequireComponent(typeof(SphereCollider))]
public class TrackingTargetBehaviour : MonoBehaviour
{
[Header("Motion setting")]
public float circleAroundRadius=5;
public float trackingSpeed = 1;
public float circcleAroundSpeed = 1;
[Header("Trigger setting")]
public float triggerRadius;
public bool isUseVisualizer = true;
public Color nowTargetColor = Color.white;
public Color otherTargetColor = Color.red;
[Header("Target list")]
public List<GameObject> allTargets;
public GameObject NowTarget;
Rigidbody m_rigidbody;
MotionState m_state = MotionState.Idle;
enum MotionState
{
Idle,
Tracking,
CircleArdound
}
// Start is called before the first frame update
void Start()
{
triggerRadius = GetComponent<SphereCollider>().radius;
m_rigidbody = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
//checkEveryObject();
Moving();
}
void Moving()
{
MovingEventSelector();
SwitchState();
}
void MovingEventSelector()
{
if(NowTarget == null)
{
m_state = MotionState.Idle;
}
else
{
float distanceToTarget = Vector3.Distance(NowTarget.transform.position, transform.position);
if(distanceToTarget > circleAroundRadius)
{
m_state = MotionState.Tracking;
}
else if(distanceToTarget <= circleAroundRadius)
{
m_state = MotionState.CircleArdound;
}
}
}
void SwitchState()
{
switch(m_state)
{
case MotionState.Idle:
IdleMove();
break;
case MotionState.Tracking:
TrackingMove();
break;
case MotionState.CircleArdound:
CircleAroundMove();
break;
}
}
void IdleMove()
{
//Debug.Log("Idle Move");
}
void TrackingMove()
{
//Debug.Log("TrackingMove");
//Vector3 moveStep = (NowTarget.transform.position - transform.position).normalized;
//m_rigidbody.MovePosition(transform.position + moveStep * trackingSpeed * Time.deltaTime);
LerpMove(NowTarget.transform.position, transform.position, 5f);
}
void CircleAroundMove()
{
//Debug.Log("CircleAround");
Vector3 towardDir = Vector3.Cross(transform.position - NowTarget.transform.position, Vector3.forward).normalized;
m_rigidbody.MovePosition(transform.position + towardDir * circcleAroundSpeed * Time.deltaTime);
}
void LerpMove(Vector3 forwardPosition, Vector3 currentPosition, float minCloseDistance)
{
float _distance = Vector3.Distance(forwardPosition, currentPosition);
Vector3 dir = (forwardPosition - currentPosition).normalized;
float t = Time.deltaTime * _distance / minCloseDistance * trackingSpeed;
if (t > 0.5) t = 0.5f;
m_rigidbody.MovePosition(
Vector3.Slerp(currentPosition, forwardPosition, t));
}
void checkEveryObject()
{
if (allTargets.Count == 0) return;
float mostCloseDistance = 10;
foreach(GameObject gb in allTargets.ToArray())
{
bool active = gb.active;
float distanceToTarget = Vector3.Distance(gb.transform.position, transform.position);
bool ifOutOfRange = ( distanceToTarget > triggerRadius * transform.localScale.x);
Debug.Log("Distance to target : " + distanceToTarget + " most close distance : " + mostCloseDistance);
//if (NowTarget == null && mostCloseDistance > distanceToTarget)
//{
// mostCloseDistance = distanceToTarget;
// NowTarget = gb;
//}
if (!active || ifOutOfRange)
{
if (NowTarget == gb)
NowTarget = null;
allTargets.Remove(gb);
}
Color color = gb == NowTarget ? nowTargetColor : otherTargetColor;
if(isUseVisualizer)
Debug.DrawRay(transform.position, gb.transform.position - transform.position, color);
}
}
private void OnTriggerEnter(Collider other)
{
addListObject(other.gameObject);
}
//use to check every object is existing
private void OnTriggerStay(Collider other)
{
addListObject(other.gameObject);
}
private void OnTriggerExit(Collider other)
{
removeListObject(other.gameObject);
}
void addListObject(GameObject _gb)
{
GameObject enterGameObject = _gb;
if (enterGameObject.tag != "TrackingTarget") return;
if (!allTargets.Contains(enterGameObject))
{
allTargets.Add(enterGameObject);
NowTarget = enterGameObject;
}
}
void removeListObject(GameObject _gb)
{
GameObject enterGameObject = _gb;
if (enterGameObject.tag != "TrackingTarget") return;
if (allTargets.Contains(enterGameObject))
allTargets.Remove(enterGameObject);
if (NowTarget == enterGameObject)
{
NowTarget = null;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerData : MonoBehaviour
{
public long userID;
public int userIndex;
public GameObject playerHand;
public GameObject playerParticle;
private KinectManager manager;
public void ResetPalayerParticlePosition()
{
if(manager == null)
{
manager = KinectManager.Instance;
}
if(manager && manager.IsInitialized())
{
playerHand.GetComponent<PlayerKinectManager>().OverlayJoint(
userID,
(int)KinectInterop.JointType.Head,
playerParticle.transform);
}
}
}
| 933bf55b41bc7a2d0b36803f5d5fe5293584c744 | [
"Markdown",
"C#"
] | 33 | C# | doremi31618/Unity3D_RealTimeEffect_AIParticleSystem | 891e63c30d5cd19fc816a3544d6c9c3b634b6097 | e9cd792fa98f96eb13f23a8f768711705c87e80a | |
refs/heads/master | <file_sep>//
// MathModel.swift
// TrueFalseStarter
//
// Created by <NAME> on 6/28/16.
// Copyright © 2016 Treehouse. All rights reserved.
//
import GameKit
struct MathModel {
static func randomMathEquationDict() -> [String : String] {
let maxOperand = 10
var maxAnswer: Int
var operator_: String
var correctAnswer: Int
let op1 = GKRandomSource.sharedRandom().nextIntWithUpperBound(maxOperand)
let op2 = GKRandomSource.sharedRandom().nextIntWithUpperBound(maxOperand)
if GKRandomSource.sharedRandom().nextIntWithUpperBound(2) == 0 {
// addition
maxAnswer = maxOperand + maxOperand
operator_ = "+"
correctAnswer = op1 + op2
} else {
// multiplication
maxAnswer = maxOperand * maxOperand
operator_ = "*"
correctAnswer = op1 * op2
}
var answerOptions: [Int] = []
while answerOptions.count < 3 { // TODO: get rid of magic number
let randNum = GKRandomSource.sharedRandom().nextIntWithUpperBound(maxAnswer)
if randNum != correctAnswer && !(answerOptions.contains(randNum)) { // we don't want duplicate answers
answerOptions.append(randNum)
}
}
answerOptions = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(answerOptions) as! [Int]
return QuestionModel.questionModel(question: "\(op1) \(operator_) \(op2)", correctAnswer: "\(correctAnswer)", incorrectAnswer1: "\(answerOptions[0])", incorrectAnswer2: "\(answerOptions[1])", incorrectAnswer3: "\(answerOptions[2])")
}
}<file_sep>//
// ViewController.swift
// TrueFalseStarter
//
// Created by <NAME> on 3/9/16.
// Copyright © 2016 Treehouse. All rights reserved.
//
import UIKit
import GameKit
import AudioToolbox
class ViewController: UIViewController {
let questionsPerRound = 4
var questionsAsked = 0
var correctQuestions = 0
var correctAnswer: String = ""
var triviaModel = TriviaModel()
var mathMode: Bool = true
var timer = NSTimer()
let secondsPerQuestion: NSTimeInterval = 15
var gameSound: SystemSoundID = 0
var correctAnswerSound: SystemSoundID = 0
var incorrectAnswerSound: SystemSoundID = 0
@IBOutlet weak var questionField: UILabel!
@IBOutlet weak var option1Button: UIButton!
@IBOutlet weak var option2Button: UIButton!
@IBOutlet weak var option3Button: UIButton!
@IBOutlet weak var option4Button: UIButton!
@IBOutlet weak var playMathButton: UIButton!
@IBOutlet weak var playTriviaButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
loadGameSounds()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func displayQuestionAndOptions() {
if mathMode {
let qD = MathModel.randomMathEquationDict()
displayQuestionAndOptions(questionDictionary: qD)
} else if let qD = triviaModel.randomTrivia() {
displayQuestionAndOptions(questionDictionary: qD)
} else {
nextRound(true)
}
}
func displayQuestionAndOptions(questionDictionary qD: [String : String]) {
// begin countdown
timer = NSTimer.scheduledTimerWithTimeInterval(secondsPerQuestion, target: self, selector: #selector(ViewController.timesUp), userInfo: nil, repeats: false)
// reset buttons
removeBoardersFromButtons()
enableButtons()
questionField.text = qD[questionKey]
option1Button.setTitle(qD[option1Key], forState: .Normal)
option2Button.setTitle(qD[option2Key], forState: .Normal)
option3Button.setTitle(qD[option3Key], forState: .Normal)
option4Button.setTitle(qD[option4Key], forState: .Normal)
correctAnswer = qD["Answer"]!
}
func displayScore() {
hideAnswerButtons()
showPlayButtons()
questionField.text = "Way to go!\nYou got \(correctQuestions) out of \(questionsAsked) correct!"
}
@IBAction func checkAnswer(sender: UIButton? = nil) {
timer.invalidate()
// Increment the questions asked counter
questionsAsked += 1
disableButtons()
showCorrectAnswer(correctAnswer)
if let button = sender {
if (button.currentTitle == correctAnswer) {
correctQuestions += 1
questionField.text = "Correct!"
playCorrectAnswerSound()
} else {
highlightOptionButton(button, correctAnswer: false)
questionField.text = "Sorry, wrong answer!"
playIncorrectAnswerSound()
}
} else {
questionField.text = "Sorry, time is up!"
playIncorrectAnswerSound()
}
loadNextRoundWithDelay(seconds: 2)
}
func timesUp() {
checkAnswer()
}
func nextRound(noMoreQuestionsLeft: Bool = false) {
if questionsAsked == questionsPerRound || noMoreQuestionsLeft {
// Game is over
displayScore()
// Get trivia model with question that were already asked
triviaModel = TriviaModel()
} else {
// Continue game
displayQuestionAndOptions()
}
}
@IBAction func playAgain(sender: UIButton) {
mathMode = sender === playMathButton
playGameStartSound()
hidePlayButtons()
showAnswerButtons()
questionsAsked = 0
correctQuestions = 0
nextRound()
}
// MARK: Helper Methods
func hidePlayButtons(hide: Bool = true) {
playMathButton.hidden = hide
playTriviaButton.hidden = hide
}
func showPlayButtons() {
hidePlayButtons(false)
}
func showCorrectAnswer(answer: String) {
if option1Button.currentTitle == answer {
highlightOptionButton(option1Button, correctAnswer: true)
} else if option2Button.currentTitle == answer {
highlightOptionButton(option2Button, correctAnswer: true)
} else if option3Button.currentTitle == answer {
highlightOptionButton(option3Button, correctAnswer: true)
} else if option4Button.currentTitle == answer {
highlightOptionButton(option4Button, correctAnswer: true)
}
}
func hideAnswerButtons(hide: Bool = true) {
option1Button.hidden = hide
option2Button.hidden = hide
option3Button.hidden = hide
option4Button.hidden = hide
}
func showAnswerButtons() {
hideAnswerButtons(false)
}
func enableButtons(enable: Bool = true) {
option1Button.enabled = enable
option2Button.enabled = enable
option3Button.enabled = enable
option4Button.enabled = enable
}
func disableButtons() {
enableButtons(false)
}
func removeBoardersFromButtons() {
option1Button.layer.borderWidth = 0.0
option2Button.layer.borderWidth = 0.0
option3Button.layer.borderWidth = 0.0
option4Button.layer.borderWidth = 0.0
}
func highlightOptionButton(sender: UIButton, correctAnswer: Bool) {
if correctAnswer {
sender.layer.borderColor = UIColor.greenColor().CGColor
} else {
sender.layer.borderColor = UIColor.redColor().CGColor
}
sender.layer.borderWidth = 2.0
}
func loadNextRoundWithDelay(seconds seconds: Int) {
// Converts a delay in seconds to nanoseconds as signed 64 bit integer
let delay = Int64(NSEC_PER_SEC * UInt64(seconds))
// Calculates a time value to execute the method given current time and delay
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, delay)
// Executes the nextRound method at the dispatch time on the main queue
dispatch_after(dispatchTime, dispatch_get_main_queue()) {
self.nextRound()
}
}
func loadGameSounds() {
let pathToSoundFile1 = NSBundle.mainBundle().pathForResource("GameSound", ofType: "wav")
let soundURL1 = NSURL(fileURLWithPath: pathToSoundFile1!)
AudioServicesCreateSystemSoundID(soundURL1, &gameSound)
let pathToSoundFile2 = NSBundle.mainBundle().pathForResource("doh1", ofType: "wav")
let soundURL2 = NSURL(fileURLWithPath: pathToSoundFile2!)
AudioServicesCreateSystemSoundID(soundURL2, &incorrectAnswerSound)
let pathToSoundFile3 = NSBundle.mainBundle().pathForResource("roger-doger", ofType: "wav")
let soundURL3 = NSURL(fileURLWithPath: pathToSoundFile3!)
AudioServicesCreateSystemSoundID(soundURL3, &correctAnswerSound)
}
func playGameStartSound() {
AudioServicesPlaySystemSound(gameSound)
}
func playCorrectAnswerSound() {
AudioServicesPlaySystemSound(correctAnswerSound)
}
func playIncorrectAnswerSound() {
AudioServicesPlaySystemSound(incorrectAnswerSound)
}
}
<file_sep>//
// TriviaModel.swift
// TrueFalseStarter
//
// Created by <NAME> on 6/26/16.
// Copyright © 2016 Treehouse. All rights reserved.
//
import GameKit
let questionKey = "Question"
let option1Key = "Option 1"
let option2Key = "Option 2"
let option3Key = "Option 3"
let option4Key = "Option 4"
let answerKey = "Answer"
struct TriviaModel {
var trivia: [[String : String]]
let unshuffledTrivia: [[String : String]] = [
QuestionModel.questionModel(question: "This was the only US President to serve more than two consecutive terms.", correctAnswer: "<NAME>", incorrectAnswer1: "<NAME>", incorrectAnswer2: "<NAME>", incorrectAnswer3: "<NAME>"),
QuestionModel.questionModel(question: "Which of the following countries has the most residents?", correctAnswer: "Nigeria", incorrectAnswer1: "Russia", incorrectAnswer2: "Iran", incorrectAnswer3: "Vietnam"),
QuestionModel.questionModel(question: "In what year was the United Nations founded?", correctAnswer: "1945", incorrectAnswer1: "1918", incorrectAnswer2: "1919", incorrectAnswer3: "1954"),
QuestionModel.questionModel(question: "The Titanic departed from the United Kingdom, where was it supposed to arrive?", correctAnswer: "New York City", incorrectAnswer1: "Paris", incorrectAnswer2: "Washington D.C.", incorrectAnswer3: "Boston"),
QuestionModel.questionModel(question: "What nation produces the most oil?", correctAnswer: "Canada", incorrectAnswer1: "Iran", incorrectAnswer2: "Iraq", incorrectAnswer3: "Brazil"),
QuestionModel.questionModel(question: "Which country has most recently won consecutive World Cups in Soccer?", correctAnswer: "Italy", incorrectAnswer1: "Brazil", incorrectAnswer2: "Argentina", incorrectAnswer3: "Spain"),
QuestionModel.questionModel(question: "Which of the following rivers is longest?", correctAnswer: "Yangtze", incorrectAnswer1: "Mississippi", incorrectAnswer2: "Congo", incorrectAnswer3: "Mekong"),
QuestionModel.questionModel(question: "Which city is oldest?", correctAnswer: "Mexico City", incorrectAnswer1: "Cape Town", incorrectAnswer2: "San Juan", incorrectAnswer3: "Sydney"),
QuestionModel.questionModel(question: "Which country was the first to allow women to vote in national elections?", correctAnswer: "Poland", incorrectAnswer1: "United States", incorrectAnswer2: "Sweden", incorrectAnswer3: "Senegal"),
QuestionModel.questionModel(question: "Which of these countries won the most medals in the 2012 Summer Games?", correctAnswer: "Great Britian", incorrectAnswer1: "France", incorrectAnswer2: "Germany", incorrectAnswer3: "Japan")
]
init() {
trivia = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(unshuffledTrivia) as! [[String : String]]
}
mutating func randomTrivia() -> [String : String]? {
return self.trivia.popLast()
}
}
<file_sep>//
// QuestionModel.swift
// TrueFalseStarter
//
// Created by <NAME> on 6/30/16.
// Copyright © 2016 Treehouse. All rights reserved.
//
import GameKit
struct QuestionModel {
static func questionModel(question question: String, correctAnswer: String, incorrectAnswer1: String,
incorrectAnswer2: String, incorrectAnswer3: String) -> [String : String] {
let unshuffledOptions: [String] = [correctAnswer, incorrectAnswer1, incorrectAnswer2, incorrectAnswer3]
let options = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(unshuffledOptions) as! [String]
return [ questionKey: question, option1Key: options[0], option2Key: options[1], option3Key: options[2], option4Key: options[3], answerKey: correctAnswer ]
}
} | 5b385686fd696938dc8d56eb28a7a3314a0f0a95 | [
"Swift"
] | 4 | Swift | bonuelc/Enhancing-a-Quiz-App-in-iOS | 51730811ab4aff26802672a88b44f47a92ac4026 | 465249467b5d5d40f72569611fb36de8488a11ab | |
refs/heads/master | <file_sep>pitchup
=======
REQUIREMENT:
Write a program to find a pitch based on this clue:
"Join us at pitch x. x is a number between 1 and 553 such that the sum of x's divisors
(not including x) is greater than x but no subset of x's divisors add up to exactly x."*
IMPLEMENTATION NOTES:
This project is implemented using Python 2.7
There have been few rafactoring iterations - that gradually improved program's performance,
ultimately leading to the given, quite well performing implementation.
If interested in details (to see how each refactoring iteration led to performance improvements) -
contact developer at <EMAIL>. Notes below correspond to the latest (most current)
implementation:
1. Number class (number.py) is used as helper. It implements methods that load number's divisors
set (__loadDivisors()) and a generator method powerset() that returns POWERSET of number's
divisors.
2. Main program (pitchup.py) uses "threading" to evaluate all individual numbers (in the range
1 .. 553) in parallel. This is very primitive use of threading - as this program does not
involve resource sharing that would require use of locking (Lock or RLock), notifications, etc.
3. All "heavy lifting" is done within number._powerset() procedure - which implements GENERATOR
design pattern. Instead of loading entire POWERSET (a set of all subsets) of number's divisors
into memory (which proved to be highly resource-bound and time consuming process), this procedure
allows getting POWERSET items iteratively, one at a time. This results in really *huge*
performance improvements - due to the fact that instead of generating entire POWERSET (as I had
in previous iterations) and evaluating individual subsets after that, we now evaluate each
individual subset as it gets fetched by generator, and stop processing as soon as we find one
subset that does not pass validation. This saves time, memory, and avoids generating
(potentially large number of) subsets that are not needed for our evaluation
RESULT:
Program (pitchup.py) finds (quite quickly) following solution to the given problem: 70
<file_sep>'''
Created on May 3, 2012
@author: valeriy
'''
import time
import threading
from number import Number
pitches = []
def checkNum( num ):
"""Check if given <num.value> satisfies following requirements:
1. sum(num.divisors) > num.value
2. No subset from powerset of <num.divisors> adds up to exactly <num.value>
"""
global pitches
num = Number( num )
isOfInterest = True
if sum( num.divisors ) > num.value:
subsets = num.powerset()
for subset in subsets:
if sum( subset ) == num.value:
isOfInterest = False
break
else:
isOfInterest = False
if isOfInterest:
pitches.append( num.value )
def pitchup():
"Find all numbers in the range 1 .. 553 that pass requirements"
# Start all the threads - one for each number in range 1 ... 553
for num in range( 1, 553 ):
thread = threading.Thread( target = checkNum, name = "checkNum_%i" % num, args = ( num, ) )
thread.start()
# Wait for all threads to terminate
while threading.activeCount() > 1:
time.sleep( 1 )
return
if __name__ == '__main__':
pitchup()
if pitches != []:
for pitch in pitches:
print "Selected pitch: %i" % pitch
else:
print "No pitch selected"
<file_sep>'''
Created on May 3, 2012
@author: valeriy
'''
def _powerset( seq ):
"""
Returns all the subsets of this set. This is a generator.
"""
if len( seq ) <= 1:
yield seq
yield []
else:
for item in _powerset( seq[1:] ):
yield [seq[0]] + item
yield item
class Number:
def __init__( self, value ):
self.value = value
self.divisors = None
self.__loadDivisors()
def __loadDivisors( self ):
"Get a list of all divisors of <self.value> - excluding <self.value> itself"
self.divisors = [1]
for num in range( 2, ( self.value / 2 + 1 ) ):
if ( self.value % num ) == 0:
if num in self.divisors:
break
i = self.value / num
if i == num:
self.divisors.append( num )
else:
self.divisors.extend( [num, self.value / num] )
def powerset( self ):
"""
Returns all the subsets of this set. This is a generator.
"""
return _powerset( self.divisors )
| aee11ada2fd0b1dcda417b00f45f637eea3cecdd | [
"Markdown",
"Python"
] | 3 | Markdown | vpogrebi/pitchup | dfee522ae61eee622dcb18d1d26b98a78817463d | c3603ecb0b93badff5e5059b3c6ecc623aa702d0 | |
refs/heads/main | <file_sep>import React from 'react';
import { StyleSheet, Text, View, Image, TouchableNativeFeedback } from 'react-native';
function BottomMenu(props) {
const heightMenu = 100
return (
<View style={styles.wrapperMenu}>
{/* <View style={{
position: 'absolute',
top: 5,
width: '100%',
height: 30,
alignItems: 'center'
}}>
<TouchableNativeFeedback>
<View style={{
width: '30%',
height: 30,
alignItems: 'center'
}}>
<Image source={require('../assets/icon/stripes.png')} style={{
width: '50%',
height: 5
}} />
</View>
</TouchableNativeFeedback>
</View> */}
<TouchableNativeFeedback>
<View style={styles.wrapperButton}>
<View style={styles.buttonMenuImg}>
<Image source={require('../assets/icon/ride.png')} style={{
width: 35,
height: 35
}} />
</View>
<Text style={{
fontSize: 12,
color: "#ffffff"
}}>Let's Ride</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback>
<View style={styles.wrapperButton}>
<View style={styles.buttonMenuImg}>
<Image source={require('../assets/icon/food.png')} style={{
width: 35,
height: 35
}} />
</View>
<Text style={{
fontSize: 12,
color: "#ffffff"
}}>Let's Eat</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback>
<View style={styles.wrapperButton}>
<View style={styles.buttonMenuImg}>
<Image source={require('../assets/icon/shop.png')} style={{
width: 35,
height: 35
}} />
</View>
<Text style={{
fontSize: 12,
color: "#ffffff"
}}>Let's Shop</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback>
<View style={styles.wrapperButton}>
<View style={styles.buttonMenuImg}>
<Image source={require('../assets/icon/play.png')} style={{
width: 35,
height: 35
}} />
</View>
<Text style={{
fontSize: 12,
color: "#ffffff"
}}>Let's play</Text>
</View>
</TouchableNativeFeedback>
</View>
);
}
const styles = StyleSheet.create({
wrapperMenu: {
flex: 1,
flexDirection: 'row',
position:'absolute',
bottom: 0,
width: '100%',
height: 100,
backgroundColor: '#70A143',
justifyContent: 'space-evenly',
paddingLeft: "10%",
paddingRight: "10%",
paddingTop: 20,
paddingBottom: 10,
zIndex: 101
},
wrapperButton:{
height: "100%",
alignItems: 'center',
},
buttonMenuImg:{
width: 50,
height: 50,
backgroundColor: "#ffffff",
borderRadius: 25,
alignItems: 'center',
justifyContent: 'center'
}
});
export default BottomMenu;<file_sep>import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, Platform, ScrollView } from 'react-native';
import BottomMenu from './app/menu/BottomMenu'
import HeaderPage from './app/header/HeaderPage'
import ContentSlider from './app/slider/ContentSlider'
import Category from './app/category/Category'
import AdditionalReview from "./app/content/AdditionalReview";
import MainContent from './app/content/MainContent'
export default function App() {
return (
<View style={styles.wrapper}>
<View style={styles.container}>
<HeaderPage />
<ScrollView style={styles.content}>
<ContentSlider />
<Category />
<AdditionalReview />
<MainContent />
</ScrollView>
<BottomMenu />
</View>
</View>
);
}
const styles = StyleSheet.create({
wrapper: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
alignItems: 'center'
},
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
width: Platform.OS === "web" ? 700 : "100%"
},
content: {
flex: 1,
backgroundColor: '#fff',
top: 170,
zIndex: 100,
width: Platform.OS === "web" ? 700 : "100%"
}
});
<file_sep>import React, {useState} from 'react';
import { StyleSheet, Text, View, Image, StatusBar, Dimensions, TextComponent, TouchableOpacity, TouchableNativeFeedback, } from 'react-native';
function AdditionalReview(props) {
const [defaultRating, setDefaultRating] = useState(0)
const [maxRating, setmaxRating] = useState([1,2,3,4,5])
const starImgFilled = 'https://rizkymalm.com/assets/images/test/star_filled.png'
const starImgCorner = 'https://rizkymalm.com/assets/images/test/star_corner.png'
const CustomRatingBar = () => {
return(
<View style={styles.CustomRatingBarStyle}>
{
maxRating.map((item, key) => {
return(
<TouchableOpacity
activeOpacity = {0.7}
key={item}
onPress={() => setDefaultRating(item)}
>
<Image
style={styles.starImgStyle}
source={
item <= defaultRating
? {uri: starImgFilled}
: {uri: starImgCorner}
}
/>
</TouchableOpacity>
)
})
}
</View>
)
}
return (
<View style={styles.wrapperAddtionalReview}>
<TouchableNativeFeedback>
<View style={styles.contentAdditionalReview}>
<Image source={require('../assets/icon/rating.png')} style={{
width: 100,
height: 100
}} />
<View style={{
flex: 1,
paddingLeft: 10,
paddingRight: 10
}}>
<Text style={{
fontSize: 18,
fontWeight: 'bold'
}}>How was your food</Text>
<Text style={{
fontSize: 12
}}><NAME> Sederhana</Text>
<View style={{
width: "100%",
paddingTop: 10,
paddingBottom: 10,
}}>
<CustomRatingBar />
</View>
</View>
</View>
</TouchableNativeFeedback>
</View>
);
}
const styles = StyleSheet.create({
wrapperAddtionalReview: {
width: "100%",
paddingLeft: "5%",
paddingRight: "5%"
},
contentAdditionalReview: {
flexDirection: 'row',
width: "100%",
shadowColor: "#000",
padding: 15,
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.39,
shadowRadius: 8.30,
elevation: 13,
borderRadius: 10,
backgroundColor: "white"
},
CustomRatingBarStyle: {
justifyContent: 'center',
flexDirection: 'row'
},
starImgStyle: {
width: 30,
height: 30,
resizeMode: 'cover'
}
})
export default AdditionalReview;<file_sep>import React from 'react';
import { StyleSheet, Text, View, Image, StatusBar, ScrollView, Dimensions, TouchableNativeFeedback } from 'react-native';
function Category(props) {
return (
<View style={styles.wrapperCategory}>
<TouchableNativeFeedback>
<View style={styles.contentCategory}>
<Image source={require('../assets/icon/bestseller.png')} style={{
width: "80%",
}} />
<Text style={{fontSize: 14}}>Best Seller</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback>
<View style={styles.contentCategory}>
<Image source={require('../assets/icon/nearme.png')} style={{
width: "80%",
}} />
<Text style={{fontSize: 14}}>Near Me</Text>
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback>
<View style={styles.contentCategory}>
<Image source={require('../assets/icon/sale.png')} style={{
width: "80%",
}} />
<Text style={{fontSize: 14}}>Big Deals</Text>
</View>
</TouchableNativeFeedback>
</View>
);
}
const styles = StyleSheet.create({
wrapperCategory: {
flexDirection: 'row',
flexWrap: 'wrap',
width: '100%',
paddingTop: 15,
paddingBottom: 10,
paddingLeft: 20,
paddingRight: 20
},
contentCategory:{
flex: 1,
width: "30%",
margin: "3%",
borderColor: "#CCCCCC",
borderWidth: StyleSheet.hairlineWidth,
borderRadius: 10,
alignItems: 'center',
justifyContent: 'center',
paddingBottom: 10
}
});
export default Category; | 269be4e0bb18d3521d178747a360747721f3f641 | [
"JavaScript"
] | 4 | JavaScript | rizkymalm/frontend_rm | e097c5df6360cb2525c318ad55211af268914f43 | 6ddc579586d7e69456eb429f2fc602794b301e45 | |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: pavel
*
* Created on September 13, 2016, 8:01 PM
*/
#include <cstdlib>
#include <cstdio>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <linux/in.h>
#include <errno.h>
#include <pthread.h>
#include <vector>
#include <map>
#include <stdexcept>
#define PSIZE 32
#define FILLER 126
#define PORT 10501
using namespace std;
struct t_arg {
int sock_d;
int q_len;
};
struct handle_sockets_t {
int *sd;
pthread_t *thread;
int closed;
};
// basic currency measure
typedef int step_t;
typedef struct currency_t{
char *name;
step_t rate;
step_t change;
vector<step_t> hist;
} currency_t;
struct cmp_str
{
bool operator()(char const *a, char const *b)
{
return strcmp(a, b) < 0;
}
};
map<char*, currency_t, cmp_str> curr_map;
vector<currency_t> curr_list;
vector<handle_sockets_t> clients;
pthread_mutex_t client_lock, currency_lock;
void *t_listen(void* arg);
int error(int fd, char* mes);
int sendall(int s, char *buf, int len, int flags);
int recvall(int sockfd, void *buf, int len, int flags);
void *t_handle(void* arg);
void print_list(void);
void disconnect(int socket);
void list(int socket);
void addcurr(int socket, char *pckg);
void rmcurr(int socket, char *pckg);
void setrate(int socket, char *pckg);
void history(int socket, char *pckg);
void senderr(int socket);
void sendok(int socket);
char *get_sum(char *pckg, int size, int offset);
char* get_code(char* package);
char* get_name(char* package);
char* get_rate(char* package);
char* get_change(char* package);
char *make_package(char type, currency_t c);
int error(int fd, char* mes) {
printf("%s\n%s\n", mes, strerror(errno));
if (fd) close(fd);
//int *code = new int;
// *code = -1;
//return code;
return -1;
}
int sendall(int s, char *buf, int len, int flags) {
int total = 0;
int n;
while (total < len) {
n = send(s, buf + total, len - total, flags);
if (n < 1) {
break;
}
total += n;
}
return (n < 1 ? -1 : total);
}
int recvall(int sockfd, void *buf, int len, int flags) {
int total = 0;
int n;
while (total < len) {
n = recv(sockfd, buf + total, len - total, flags);
if (n < 1) {
break;
}
total += n;
}
return (n < 1 ? -1 : total);
}
void sendok(int socket){
char *pckg = new char[PSIZE];
pckg[0]='1';
for(int i = 1; i < PSIZE; i++)
pckg[i] = (char)FILLER;
if (sendall(socket, pckg, PSIZE, 0) < 0)
error(0, "Send error.\n");
delete[] pckg;
}
void senderr(int socket){
char *pckg = new char[PSIZE];
pckg[0]='0';
for(int i = 1; i < PSIZE; i++)
pckg[i] = (char)FILLER;
if (sendall(socket, pckg, PSIZE, 0) < 0)
error(0, "Send error.\n");
delete[] pckg;
}
void disconnect(int socket){
vector<handle_sockets_t>::iterator it;
pthread_mutex_lock(&client_lock);
for (it = clients.begin(); it < clients.end(); it++) {
if (*(it->sd) == socket && it->closed == 0) {
printf("Kicked client %d with status %d.\n", socket,
shutdown(*(it->sd), SHUT_RDWR));
printf("Listening socket is closed with status %i\n",
close(*(it->sd)));
it->closed = 1;
break;
}
}
pthread_mutex_unlock(&client_lock);
}
void addcurr(int socket, char *pckg){
if (strcmp(get_code(pckg),"2")!=0){
senderr(socket);
return;
}
currency_t new_c;
new_c.name=get_name(pckg);
new_c.rate=0;
new_c.change=INT32_MIN;
pthread_mutex_lock(¤cy_lock);
if(curr_map.insert(make_pair(new_c.name,new_c)).second)
sendok(socket);
else
senderr(socket);
pthread_mutex_unlock(¤cy_lock);
}
void list(int socket){
map<char*,currency_t>::iterator it;
char *pckg = new char[PSIZE];
pthread_mutex_lock(¤cy_lock);
for(it = curr_map.begin(); it != curr_map.end(); it++){
pckg = make_package('3',it->second);
if (sendall(socket, pckg, PSIZE, 0) < 0)
error(0, "Send error.\n");
}
pthread_mutex_unlock(¤cy_lock);
sendok(socket);
delete[] pckg;
}
void rmcurr(int socket, char *pckg){
if (strcmp(get_code(pckg),"3")!=0){
senderr(socket);
return;
}
char *name = get_name(pckg);
pthread_mutex_lock(¤cy_lock);
if(curr_map.erase(name))
sendok(socket);
else
senderr(socket);
pthread_mutex_unlock(¤cy_lock);
delete[] name;
}
void setrate(int socket, char *pckg){
if (strcmp(get_code(pckg),"4")!=0){
senderr(socket);
return;
}
char *name = get_name(pckg);
step_t rate = atoi(get_rate(pckg));
if (rate < 0){
senderr(socket);
delete[] name;
return;
}
currency_t *curr;
try{
pthread_mutex_lock(¤cy_lock);
curr = &(curr_map.at(name));
}
catch (out_of_range& e){
pthread_mutex_unlock(¤cy_lock);
senderr(socket);
delete[] name;
return;
}
curr->hist.push_back(curr->rate);
curr->change = rate - curr->rate;
curr->rate = rate;
pthread_mutex_unlock(¤cy_lock);
sendok(socket);
delete[] name;
}
void history(int socket, char *pckg){
if (strcmp(get_code(pckg),"5")!=0){
senderr(socket);
return;
}
char *name = get_name(pckg);
currency_t curr;
pthread_mutex_lock(¤cy_lock);
try{
curr = curr_map.at(name);
}
catch(out_of_range){
pthread_mutex_unlock(¤cy_lock);
senderr(socket);
return;
}
currency_t record;
char *response;
if(!curr.hist.empty()){
vector<step_t>::iterator it;
int counter=0;
for(it = curr.hist.begin(); it < curr.hist.end(); it++){
record.name = name;
record.rate = *it;
record.change = counter;
counter++;
response = make_package('2', record);
if (sendall(socket, response, PSIZE, NULL) < 0)
error(0, "Send error.\n");
delete[] response;
}
}
response = make_package('2', curr);
if (sendall(socket, response, PSIZE, NULL) < 0)
error(0, "Send error.\n");
delete[] response;
pthread_mutex_unlock(¤cy_lock);
sendok(socket);
delete[] name;
}
void *t_listen(void* arg) {
struct t_arg *sock_par = (struct t_arg*) arg;
// client address length
socklen_t *cl_addr_len = new socklen_t;
struct sockaddr_in client_addr;
int handle_socket, err;
struct handle_sockets_t *new_rec;
pthread_t created_thread, *new_thread;
// set socket to listening mode
if (listen((*sock_par).sock_d, (*sock_par).q_len) < 0){
int status = error((*sock_par).sock_d, "Listen error.\n");
return (void *)&status;
}
*cl_addr_len = sizeof (struct sockaddr_in);
while (1) {
handle_socket = accept(
(*sock_par).sock_d, (struct sockaddr *) &client_addr, cl_addr_len);
if (handle_socket <= 0) {
error((*sock_par).sock_d, "Connection accept error.\n");
break;
}
struct t_arg *arg = (struct t_arg*) malloc(sizeof (struct t_arg));
arg -> sock_d = handle_socket;
//arg -> status = sock_par -> status;
pthread_create(&created_thread, NULL, t_handle, arg);
new_thread = new pthread_t;
*new_thread = created_thread;
new_rec = new handle_sockets_t;
new_rec->sd = &(arg->sock_d);
new_rec->thread = new_thread;
new_rec->closed = 0;
pthread_mutex_lock(&client_lock);
clients.push_back(*new_rec);
pthread_mutex_unlock(&client_lock);
}
pthread_mutex_lock(&client_lock);
for (int i = 0; i < clients.size(); i++) {
if (clients[i].closed == 0) {
printf("Shutting up thread %d...\n", i);
shutdown(*(clients[i].sd), SHUT_RDWR);
printf("Thread %d is shut.\n", i);
printf("Handling socket is closed with status %i\n",
close(*(clients[i].sd)));
clients[i].closed = 1;
} else
printf("Skipped closing kicked socket %d.\n", i);
}
for (int i = 0; i < clients.size(); i++) {
printf("Waiting thread %d to join...\n", i);
pthread_join(*(clients[i].thread), NULL);
printf("Thread %d is joined.\n", i);
}
pthread_mutex_unlock(&client_lock);
printf("All threads are joined\n");
delete cl_addr_len;
//delete sock_par;
return NULL;
}
void *t_handle(void* arg) {
struct t_arg* _arg = (t_arg*) arg;
int *pconnected_socket = &(_arg-> sock_d);
int size = 0;
char *pckg = new char[PSIZE];
sendok(*pconnected_socket);
while (1) {
if (recvall(*pconnected_socket, pckg, PSIZE, NULL) < 0) {
error(0, "Receive error.\n");
break;
}
switch(pckg[0]){
case '0': disconnect(*pconnected_socket); break;
case '1': list(*pconnected_socket); break;
case '2': addcurr(*pconnected_socket, pckg); break;
case '3': rmcurr(*pconnected_socket, pckg); break;
case '4': setrate(*pconnected_socket, pckg); break;
case '5': history(*pconnected_socket, pckg); break;
default: senderr(*pconnected_socket);
}
}
delete[] pckg;
return NULL;
}
/*
*
*/
int main(int argc, char** argv) {
// listening socket descriptor, handling socket descriptor
// and error variable
int server_socket, err, stat;
pthread_t thr_listen;
// server port
unsigned short int port = (unsigned short int) PORT;
// socket address struct for server and client
struct sockaddr_in server_addr;
// length of client request queue
int len = 10;
// fill server address structure
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = INADDR_ANY;
// create server socket descriptor
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if ((pthread_mutex_init(&client_lock, NULL) != 0)
|| (pthread_mutex_init(¤cy_lock, NULL) != 0)) {
return error(0, "Mutex init error.\n");
}
if (server_socket < 0) {
printf("Server socket init error.\n");
close(server_socket);
return -1;
}
// assign ip:port pair to the socket descriptor
if ((err = bind(server_socket, (struct sockaddr *) &server_addr,
sizeof (server_addr))) < 0) {
return error(server_socket, "Bind error.\n");
}
struct t_arg arg;
arg.q_len = len;
arg.sock_d = server_socket;
stat = pthread_create(&thr_listen, NULL, t_listen, &arg);
char *command = new char[10];
while (1 > 0) {
printf("command: ");
scanf("%s", command);
if (strcmp(command, "quit") == 0) {
printf("Exiting...\n");
printf("Listening stopped with status %d.\n",
shutdown(server_socket, SHUT_RDWR));
printf("Listening socket is closed with status %i\n",
close(server_socket));
break;
} else if (strcmp(command, "list") == 0) {
print_list();
} else if (strcmp(command, "kick") == 0) {
int descr = -1;
printf("Enter socket descriptor.\n");
scanf("%d", &descr);
if (descr >= 0){
disconnect(descr);
}
} else
printf("Unknown command.\n");
}
pthread_join(thr_listen, NULL);
printf("Exited.\n");
pthread_mutex_destroy(&client_lock);
pthread_mutex_destroy(¤cy_lock);
delete[] command;
vector<handle_sockets_t>::iterator it;
for (it = clients.begin(); it!= clients.end(); it++){
delete it->sd;
//delete it->thread;
}
return 0;
}
void print_list(void) {
printf("#### Connections list ####\n");
pthread_mutex_lock(&client_lock);
for (int i = 0; i < clients.size(); i++) {
printf("SD[%d]: descriptor %d; closed %d\n", i, *clients[i].sd, clients[i].closed);
}
pthread_mutex_unlock(&client_lock);
}
char *get_sum(char *pckg, int size, int offset){
char *_ret = new char[size+1];
//bzero(_ret, size+1);
int i;
for (i=0; i<size; i++){
if(pckg[i+offset] == FILLER) break;
_ret[i] = pckg[i+offset];
}
_ret[i]='\0';
return _ret;
}
char *get_code(char *pckg){
return get_sum(pckg, 1, 0);
}
char *get_name(char *pckg){
return get_sum(pckg, 10, 1);
}
char *get_rate(char *pckg){
return get_sum(pckg, 10, 11);
}
char *get_change(char *pckg){
return get_sum(pckg, 11, 21);
}
char *make_package(char type, currency_t c){
char *package = new char[PSIZE];
package[0] = type;
for(int i=0; i<10; i++){
if(c.name[i]!= 0)
package[i+1]=c.name[i];
else
package[i+1]=FILLER;
}
char* rate = new char[10];
sprintf(rate, "%d", c.rate);
for(int i=0; i<10; i++){
if(rate[i]!= 0)
package[i+11]=rate[i];
else
package[i+11]=FILLER;
}
char* change = new char[11];
sprintf(change, "%d", c.change);
for(int i=0; i<11; i++){
if(change[i] != 0)
package[i+21]=change[i];
else
package[i+21]=FILLER;
}
return package;
} | 95953da929a0c740992c853a362ea340f6acaf86 | [
"C++"
] | 1 | C++ | KirpichenkovPavel/tcp_server | 5fce0bb03fdd5e8979f2273d0ac1f0b7f2bef62c | f4c3d4f9debbd6b735e070d77052aacf46cfe97b | |
refs/heads/master | <repo_name>gdbinit/lldbinit<file_sep>/README.md
<p align="center">
<img src="images/logo.png">
</p>
### About
A gdbinit clone for LLDB aka how to make LLDB a bit more useful and less crappy.
https://github.com/gdbinit/lldbinit
Original lldbinit code by Deroko @ https://github.com/deroko/lldbinit
gdbinit available @ https://github.com/gdbinit/Gdbinit
(c) Deroko 2014, 2015, 2016
(c) fG! 2017-2023 - <EMAIL> - https://reverse.put.as
No original license by Deroko.
All my modifications are under MIT license.
Huge thanks to Deroko for his original effort! Without it this would not exist.
Most of gdbinit functions are converted, and a bunch of new functions added.
Some of the commands that were passed to lldb command line were converted to internal API.
While it's almost 5k lines of text and a bit annoying to manage and edit, I don't intend to modularize this version because I like to just copy a single file where I need it. Extra features could be added as plugins (for example [lisa.py](https://github.com/ant4g0nist/lisa.py/tree/dev/resources/archs) databases of x86 and ARM instructions).
Intel syntax is used for x86. Switching to AT&T (yuk!) is a configurable option.
### Forks and other lldbinit scripts
<NAME> maintains a [forked version](https://github.com/peternguyen93/lldbinit) with other features and improvements. Requires Python 3.x.
[lisa.py](https://github.com/ant4g0nist/lisa.py) is also another good contender although focused on exploit dev.
### What's new in version 3.x
* Full arm64 (AArch64) support for most commands and displays.
* Add new `bm` command to break when specific images/modules are loaded. Super useful to break on dynamic libraries for malware analysis and other reversing tasks. This could be done manually with stop on shared library events setting but this command automates and simplifies the process.
* Cleaned up, simplified, improved and updated code.
* Bug fixes.
* Small changes and improvements to UI.
* Dark theme support. Not really a dark theme for now other than fixing basic colors to look ok. Pull requests?
### The future
* Add the remaining features I want.
* Test suite would be a nice to have.
* Keep improving code (Python not my cup of tea).
* Import/add useful features from other scripts.
### Support & Requirements
Supports x86_64, i386, and arm64 targets. The i386 target as long been deprecated in macOS but supporting for now isn't a lot extra work and I hate when tools don't work when you need them (such as reversing old malware or cracking old stuff).
Tested with Xcode 9.4.1, 10.x, 12.x, 14.x (x86_64 and arm64). Python 2.x and 3.x compatible.
Optional Keystone Engine (https://www.keystone-engine.org) can be installed for assembler support.
### How to install
```
cp lldbinit.py ~
echo "command script import ~/lldbinit.py" >>~/.lldbinit
```
or
just copy it somewhere and use `command script import path_to_script` when you want to load it.
### How to use
List all implemented commands with 'lldbinitcmds'.
### Configuration
There are some user configurable options in the header. You can also use the enable/disable commands to dynamically configure some options.
### Features
* Display the destination of (indirect) calls, jmps, returns, and also Objective-C class and selectors.
<p align="center">
<img src="images/indirectarm64.png">
</p>
* Display the result of conditional jumps and instructions.
<p align="center">
<img src="images/conditionalx86.png">
</p>
<p align="center">
<img src="images/conditionalarm64.png">
</p>
### Helpful commands and shortcuts
The `bpm` command allows to set a breakpoint when a specific module (library/framework) is loaded.
The `stepo` command alows to step over branches and calls (they are still executed) so you can easily trace one function without stepping into any calls or branches it might have.
The `skip` command allows you to skip exactly one instruction to next instruction (ignoring control flow!).
The `bpn` command breakpoints the next instruction (ignoring control flow!). It's useful to get out of a loop (when you are at the loop conditional jump tester and you breakpoint the next instruction to let the loop execute without stepping every iteration).
The crack family of commands allow you to automate return from functions with a value and skip code (for all your cracking isRegistered: and malware reversing needs) or breakpoint an address and set a given register to a value (also for all your cracking needs).
You can set the value of any register using its name, which is basically a shortcut for `register write` LLDB command.
The data window allows you to display the data of a certain memory location that you set with `datawin` command. Useful if you want to observe the contents of a string decryption routine for example.
<file_sep>/lldbinit.py
'''
_ _ _ _ _ _ _
| | |_| | |_|_|___|_| |_
| | | . | . | | | | _|
|_|_|___|___|_|_|_|_|_|
lldbinit v3.0
A gdbinit clone for LLDB aka how to make LLDB a bit more useful and less crappy
Available at https://github.com/gdbinit/lldbinit
Original lldbinit code by Deroko @ https://github.com/deroko/lldbinit
gdbinit available @ https://github.com/gdbinit/Gdbinit
(c) Deroko 2014, 2015, 2016
(c) fG! 2017-2023 - <EMAIL> - https://reverse.put.as
No original license by Deroko.
All my modifications are under MIT license:
Copyright 2017-2023 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
Huge thanks to Deroko for his original effort!
To list all implemented commands use 'lldbinitcmds' command.
How to install it:
------------------
$ cp lldbinit.py ~
$ echo "command script import ~/lldbinit.py" >>$HOME/.lldbinit
or
just copy it somewhere and use "command script import path_to_script" when you want to load it.
Notes:
------
Version 3.0+ drops support for ARM32 and assumes ARM64 instead
TODO:
-----
- shortcut to dump memory to file
- check sbthread class: stepoveruntil for example
- help for aliases
- add source window?
- add threads window?
- command to search for symbol and display image address (image lookup -s symbol -v) (address is the range)
- command to update breakpoints with new ASLR
- solve addresses like lea rsi, [rip + 0x38cf] (lldb does solve some stuff that it has symbols for and adds the info as comment)
- swift support?
- window for floating point/neon registers? off by default - they are huge in length so it might look crappy
- exception state registers window?
BUGS:
-----
LLDB design:
------------
lldb -> debugger -> target -> process -> thread -> frame(s)
-> thread -> frame(s)
'''
if __name__ == "__main__":
print("Run only as script from LLDB... Not as standalone program!")
import lldb
import sys
import re
import os
import time
import struct
import argparse
import subprocess
import tempfile
import termios
import fcntl
try:
import keystone
CONFIG_KEYSTONE_AVAILABLE = 1
except ImportError:
CONFIG_KEYSTONE_AVAILABLE = 0
pass
VERSION = "3.0"
BUILD = "347"
#
# User configurable options
#
CONFIG_ENABLE_COLOR = 1
# light or dark mode
CONFIG_APPEARANCE = "light"
# display the instruction bytes in disassembler output
CONFIG_DISPLAY_DISASSEMBLY_BYTES = 1
# the maximum number of lines to display in disassembler output
CONFIG_DISASSEMBLY_LINE_COUNT = 8
# x/i and disas output customization - doesn't affect context disassembler output
CONFIG_USE_CUSTOM_DISASSEMBLY_FORMAT = 1
# enable all the register command shortcuts
CONFIG_ENABLE_REGISTER_SHORTCUTS = 1
# display stack contents on context stop
CONFIG_DISPLAY_STACK_WINDOW = 0
CONFIG_DISPLAY_FLOW_WINDOW = 0
# display data contents on context stop - an address for the data must be set with "datawin" command
CONFIG_DISPLAY_DATA_WINDOW = 0
# disassembly flavor 'intel' or 'att' - default is Intel unless AT&T syntax is your cup of tea
CONFIG_FLAVOR = "intel"
# setup the logging level, which is a bitmask of any of the following possible values (don't use spaces, doesn't seem to work)
#
# LOG_VERBOSE LOG_PROCESS LOG_THREAD LOG_EXCEPTIONS LOG_SHLIB LOG_MEMORY LOG_MEMORY_DATA_SHORT LOG_MEMORY_DATA_LONG LOG_MEMORY_PROTECTIONS LOG_BREAKPOINTS LOG_EVENTS LOG_WATCHPOINTS
# LOG_STEP LOG_TASK LOG_ALL LOG_DEFAULT LOG_NONE LOG_RNB_MINIMAL LOG_RNB_MEDIUM LOG_RNB_MAX LOG_RNB_COMM LOG_RNB_REMOTE LOG_RNB_EVENTS LOG_RNB_PROC LOG_RNB_PACKETS LOG_RNB_ALL LOG_RNB_DEFAULT
# LOG_DARWIN_LOG LOG_RNB_NONE
#
# to see log (at least in macOS)
# $ log stream --process debugserver --style compact
# (or whatever style you like)
CONFIG_LOG_LEVEL = "LOG_NONE"
# removes the offsets and modifies the module name position
# reference: https://lldb.llvm.org/formats.html
CUSTOM_DISASSEMBLY_FORMAT = "\"{${function.initial-function}{${function.name-without-args}} @ {${module.file.basename}}:\n}{${function.changed}\n{${function.name-without-args}} @ {${module.file.basename}}:\n}{${current-pc-arrow} }${addr-file-or-load}: \""
# the colors definitions - don't mess with this
if CONFIG_ENABLE_COLOR:
RESET = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
REVERSE = "\033[7m"
BLACK = "\033[30m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
else:
RESET = ""
BOLD = ""
UNDERLINE = ""
REVERSE = ""
BLACK = ""
RED = ""
GREEN = ""
YELLOW = ""
BLUE = ""
MAGENTA = ""
CYAN = ""
WHITE = ""
# default colors - modify as you wish
# since these are just strings modes can be combined
if CONFIG_APPEARANCE == "light":
COLOR_REGVAL = BLACK
COLOR_REGNAME = GREEN
COLOR_CPUFLAGS = BOLD + UNDERLINE + MAGENTA
COLOR_SEPARATOR = BOLD + BLUE
COLOR_HIGHLIGHT_LINE = RED
COLOR_REGVAL_MODIFIED = RED
COLOR_SYMBOL_NAME = BLUE
COLOR_CURRENT_PC = RED
COLOR_CONDITIONAL_YES = REVERSE + GREEN
COLOR_CONDITIONAL_NO = REVERSE + RED
COLOR_HEXDUMP_HEADER = BLUE
COLOR_HEXDUMP_ADDR = BLACK
COLOR_HEXDUMP_DATA = BLACK
COLOR_HEXDUMP_ASCII = BLACK
elif CONFIG_APPEARANCE == "dark":
COLOR_REGVAL = WHITE
COLOR_REGNAME = GREEN
COLOR_CPUFLAGS = BOLD + UNDERLINE + MAGENTA
COLOR_SEPARATOR = CYAN
COLOR_HIGHLIGHT_LINE = RED
COLOR_REGVAL_MODIFIED = RED
COLOR_SYMBOL_NAME = BLUE
COLOR_CURRENT_PC = RED
COLOR_CONDITIONAL_YES = REVERSE + GREEN
COLOR_CONDITIONAL_NO = REVERSE + RED
COLOR_HEXDUMP_HEADER = BLUE
COLOR_HEXDUMP_ADDR = WHITE
COLOR_HEXDUMP_DATA = WHITE
COLOR_HEXDUMP_ASCII = WHITE
else:
print("[-] Invalid CONFIG_APPEARANCE value.")
# configure the separator character between the "windows" and their size
SEPARATOR = "-"
# minimum terminal width 120 chars
I386_TOP_SIZE = 81
I386_STACK_SIZE = I386_TOP_SIZE - 1
I386_BOTTOM_SIZE = 87
# minimum terminal width 125 chars
X64_TOP_SIZE = 119
X64_STACK_SIZE = X64_TOP_SIZE - 1
X64_BOTTOM_SIZE = 125
# minimum terminal width 108 chars
ARM_TOP_SIZE = 102
ARM_STACK_SIZE = ARM_TOP_SIZE - 1
ARM_BOTTOM_SIZE = 108
#
# Don't mess after here unless you know what you are doing!
#
DATA_WINDOW_ADDRESS = 0
POINTER_SIZE = 8
old_x86 = { "eax": 0, "ecx": 0, "edx": 0, "ebx": 0, "esp": 0, "ebp": 0, "esi": 0, "edi": 0, "eip": 0,
"eflags": 0, "cs": 0, "ds": 0, "fs": 0, "gs": 0, "ss": 0, "es": 0 }
old_x64 = { "rax": 0, "rcx": 0, "rdx": 0, "rbx": 0, "rsp": 0, "rbp": 0, "rsi": 0, "rdi": 0, "rip": 0,
"r8": 0, "r9": 0, "r10": 0, "r11": 0, "r12": 0, "r13": 0, "r14": 0, "r15": 0,
"rflags": 0, "cs": 0, "fs": 0, "gs": 0 }
old_arm64 = { "x0": 0, "x1": 0, "x2": 0, "x3": 0, "x4": 0, "x5": 0, "x6": 0, "x7": 0, "x8": 0, "x9": 0, "x10": 0,
"x11": 0, "x12": 0, "x13": 0, "x14": 0, "x15": 0, "x16": 0, "x17": 0, "x18": 0, "x19": 0, "x20": 0,
"x21": 0, "x22": 0, "x23": 0, "x24": 0, "x25": 0, "x26": 0, "x27": 0, "x28": 0, "fp": 0, "lr": 0,
"sp": 0, "pc": 0, "cpsr": 0 }
GlobalListOutput = []
int3patches = {}
crack_cmds = []
crack_cmds_noret = []
modules_list = []
# dyld modes
dyld_mode_dict = {
0: "dyld_image_adding",
1: "dyld_image_removing",
2: "dyld_image_info_change",
3: "dyld_image_dyld_moved"
}
MIN_COLUMNS = 125
MIN_ROWS = 25
# test terminal - idea from https://github.com/ant4g0nist/lisa.py/
try:
tty_rows, tty_columns = struct.unpack("hh", fcntl.ioctl(1, termios.TIOCGWINSZ, "1234"))
# i386 is fine with 87x21
# x64 is fine with 125x23
# aarch64 is fine with 108x26
if tty_columns < MIN_COLUMNS or tty_rows < MIN_ROWS:
print("\033[1m\033[31m[!] current terminal size is {:d}x{:d}".format(tty_columns, tty_rows))
print("[!] lldbinit is best experienced with a terminal size at least {}x{}\033[0m".format(MIN_COLUMNS, MIN_ROWS))
except Exception as e:
print("\033[1m\033[31m[-] failed to find out terminal size.")
print("[!] lldbinit is best experienced with a terminal size at least {}x{}\033[0m".format(MIN_COLUMNS, MIN_ROWS))
def __lldb_init_module(debugger, internal_dict):
''' we can execute lldb commands using debugger.HandleCommand() which makes all output to default
lldb console. With SBDebugger.GetCommandinterpreter().HandleCommand() we can consume all output
with SBCommandReturnObject and parse data before we send it to output (eg. modify it);
in practice there is nothing here in initialization or anywhere else that we want to modify
'''
# don't load if we are in Xcode since it is not compatible and will block Xcode
if os.getenv('PATH').startswith('/Applications/Xcode'):
return
res = lldb.SBCommandReturnObject()
ci = debugger.GetCommandInterpreter()
# settings
ci.HandleCommand("settings set target.x86-disassembly-flavor " + CONFIG_FLAVOR, res)
ci.HandleCommand("settings set prompt \"(lldbinit) \"", res)
ci.HandleCommand("settings set stop-disassembly-count 0", res)
# set the log level - must be done on startup?
ci.HandleCommand("settings set target.process.extra-startup-command QSetLogging:bitmask=" + CONFIG_LOG_LEVEL + ";", res)
if CONFIG_USE_CUSTOM_DISASSEMBLY_FORMAT == 1:
ci.HandleCommand("settings set disassembly-format " + CUSTOM_DISASSEMBLY_FORMAT, res)
# the hook that makes everything possible :-)
ci.HandleCommand("command script add -f lldbinit.HandleHookStopOnTarget HandleHookStopOnTarget", res)
ci.HandleCommand("command script add -f lldbinit.HandleHookStopOnTarget context", res)
ci.HandleCommand("command alias ctx HandleHookStopOnTarget", res)
# commands
ci.HandleCommand("command script add -f lldbinit.cmd_lldbinitcmds lldbinitcmds", res)
ci.HandleCommand("command script add -f lldbinit.cmd_IphoneConnect iphone", res)
#
# dump memory commands
#
ci.HandleCommand("command script add -f lldbinit.cmd_db db", res)
ci.HandleCommand("command script add -f lldbinit.cmd_dw dw", res)
ci.HandleCommand("command script add -f lldbinit.cmd_dd dd", res)
ci.HandleCommand("command script add -f lldbinit.cmd_dq dq", res)
ci.HandleCommand("command script add -f lldbinit.cmd_DumpInstructions u", res)
ci.HandleCommand("command script add -f lldbinit.cmd_findmem findmem", res)
ci.HandleCommand("command script add -f lldbinit.cmd_showregions showregions", res)
#
# Settings related commands
#
ci.HandleCommand("command script add -f lldbinit.cmd_enable enable", res)
ci.HandleCommand("command script add -f lldbinit.cmd_disable disable", res)
ci.HandleCommand("command script add -f lldbinit.cmd_contextcodesize contextcodesize", res)
# a few settings aliases
ci.HandleCommand("command alias enablesolib enable solib", res)
ci.HandleCommand("command alias disablesolib disable solib", res)
ci.HandleCommand("command alias enableaslr enable aslr", res)
ci.HandleCommand("command alias disableaslr disable aslr", res)
#
# Breakpoint related commands
#
ci.HandleCommand("command script add -f lldbinit.cmd_bhb bhb", res)
ci.HandleCommand("command script add -f lldbinit.cmd_bht bht", res)
ci.HandleCommand("command script add -f lldbinit.cmd_bpt bpt", res)
ci.HandleCommand("command script add -f lldbinit.cmd_bpn bpn", res)
ci.HandleCommand("command script add -f lldbinit.cmd_bm bm", res)
ci.HandleCommand("command script add -f lldbinit.cmd_bmc bmc", res)
ci.HandleCommand("command script add -f lldbinit.cmd_antidebug antidebug", res)
ci.HandleCommand("command script add -f lldbinit.cmd_print_notifier_images print_images", res)
# disable a breakpoint or all
ci.HandleCommand("command script add -f lldbinit.cmd_bpd bpd", res)
ci.HandleCommand("command script add -f lldbinit.cmd_bpda bpda", res)
# clear a breakpoint or all
ci.HandleCommand("command script add -f lldbinit.cmd_bpc bpc", res)
ci.HandleCommand("command alias bpca breakpoint delete", res)
# enable a breakpoint or all
ci.HandleCommand("command script add -f lldbinit.cmd_bpe bpe", res)
ci.HandleCommand("command script add -f lldbinit.cmd_bpea bpea", res)
# commands to set temporary int3 patches and restore original bytes
ci.HandleCommand("command script add -f lldbinit.cmd_int3 int3", res)
ci.HandleCommand("command script add -f lldbinit.cmd_rint3 rint3", res)
ci.HandleCommand("command script add -f lldbinit.cmd_listint3 listint3", res)
ci.HandleCommand("command script add -f lldbinit.cmd_nop nop", res)
ci.HandleCommand("command script add -f lldbinit.cmd_null null", res)
# change eflags commands
ci.HandleCommand("command script add -f lldbinit.cmd_cfa cfa", res)
ci.HandleCommand("command script add -f lldbinit.cmd_cfc cfc", res)
ci.HandleCommand("command script add -f lldbinit.cmd_cfd cfd", res)
ci.HandleCommand("command script add -f lldbinit.cmd_cfi cfi", res)
ci.HandleCommand("command script add -f lldbinit.cmd_cfo cfo", res)
ci.HandleCommand("command script add -f lldbinit.cmd_cfp cfp", res)
ci.HandleCommand("command script add -f lldbinit.cmd_cfs cfs", res)
ci.HandleCommand("command script add -f lldbinit.cmd_cft cft", res)
ci.HandleCommand("command script add -f lldbinit.cmd_cfz cfz", res)
# change NZCV flags - exclusive commands to AArch64 (Z, C are common)
ci.HandleCommand("command script add -f lldbinit.cmd_cfn cfn", res)
ci.HandleCommand("command script add -f lldbinit.cmd_cfv cfv", res)
# skip/step current instruction commands
ci.HandleCommand("command script add -f lldbinit.cmd_skip skip", res)
ci.HandleCommand("command script add -f lldbinit.cmd_stepo stepo", res)
# load breakpoints from file
ci.HandleCommand("command script add -f lldbinit.cmd_LoadBreakPoints lb", res)
ci.HandleCommand("command script add -f lldbinit.cmd_LoadBreakPointsRva lbrva", res)
# cracking friends
ci.HandleCommand("command script add -f lldbinit.cmd_crack crack", res)
ci.HandleCommand("command script add -f lldbinit.cmd_crackcmd crackcmd", res)
ci.HandleCommand("command script add -f lldbinit.cmd_crackcmd_noret crackcmd_noret", res)
# alias for existing breakpoint commands
# list all breakpoints
ci.HandleCommand("command alias bpl breakpoint list", res)
# alias "bp" command that exists in gdbinit - lldb also has alias for "b"
ci.HandleCommand("command alias bp _regexp-break", res)
# to set breakpoint commands - I hate typing too much
ci.HandleCommand("command alias bcmd breakpoint command add", res)
# launch process and stop at entrypoint (not exactly as gdb command that just inserts breakpoint)
# usually it will be inside dyld and not the target main()
ci.HandleCommand("command alias break_entrypoint process launch --stop-at-entry", res)
ci.HandleCommand("command script add -f lldbinit.cmd_show_loadcmds show_loadcmds", res)
ci.HandleCommand("command script add -f lldbinit.cmd_show_header show_header", res)
ci.HandleCommand("command script add -f lldbinit.cmd_tester tester", res)
ci.HandleCommand("command script add -f lldbinit.cmd_datawin datawin", res)
# used mostly for aliases below but can be called as other commands
ci.HandleCommand("command script add -f lldbinit.cmd_update_register update_register", res)
# shortcut command to modify registers content
if CONFIG_ENABLE_REGISTER_SHORTCUTS == 1:
# x64
ci.HandleCommand("command alias rip update_register rip", res)
ci.HandleCommand("command alias rax update_register rax", res)
ci.HandleCommand("command alias rbx update_register rbx", res)
ci.HandleCommand("command alias rbp update_register rbp", res)
ci.HandleCommand("command alias rsp update_register rsp", res)
ci.HandleCommand("command alias rdi update_register rdi", res)
ci.HandleCommand("command alias rsi update_register rsi", res)
ci.HandleCommand("command alias rdx update_register rdx", res)
ci.HandleCommand("command alias rcx update_register rcx", res)
ci.HandleCommand("command alias r8 update_register r8", res)
ci.HandleCommand("command alias r9 update_register r9", res)
ci.HandleCommand("command alias r10 update_register r10", res)
ci.HandleCommand("command alias r11 update_register r11", res)
ci.HandleCommand("command alias r12 update_register r12", res)
ci.HandleCommand("command alias r13 update_register r13", res)
ci.HandleCommand("command alias r14 update_register r14", res)
ci.HandleCommand("command alias r15 update_register r15", res)
# x86
ci.HandleCommand("command alias eip update_register eip", res)
ci.HandleCommand("command alias eax update_register eax", res)
ci.HandleCommand("command alias ebx update_register ebx", res)
ci.HandleCommand("command alias ebp update_register ebp", res)
ci.HandleCommand("command alias esp update_register esp", res)
ci.HandleCommand("command alias edi update_register edi", res)
ci.HandleCommand("command alias esi update_register esi", res)
ci.HandleCommand("command alias edx update_register edx", res)
ci.HandleCommand("command alias ecx update_register ecx", res)
# ARM64
ci.HandleCommand("command alias x0 update_register x0", res)
ci.HandleCommand("command alias x1 update_register x1", res)
ci.HandleCommand("command alias x2 update_register x2", res)
ci.HandleCommand("command alias x3 update_register x3", res)
ci.HandleCommand("command alias x4 update_register x4", res)
ci.HandleCommand("command alias x5 update_register x5", res)
ci.HandleCommand("command alias x6 update_register x6", res)
ci.HandleCommand("command alias x7 update_register x7", res)
ci.HandleCommand("command alias x8 update_register x8", res)
ci.HandleCommand("command alias x9 update_register x9", res)
ci.HandleCommand("command alias x10 update_register x10", res)
ci.HandleCommand("command alias x11 update_register x11", res)
ci.HandleCommand("command alias x12 update_register x12", res)
ci.HandleCommand("command alias x13 update_register x13", res)
ci.HandleCommand("command alias x14 update_register x14", res)
ci.HandleCommand("command alias x15 update_register x15", res)
ci.HandleCommand("command alias x16 update_register x16", res)
ci.HandleCommand("command alias x17 update_register x17", res)
ci.HandleCommand("command alias x18 update_register x18", res)
ci.HandleCommand("command alias x19 update_register x19", res)
ci.HandleCommand("command alias x20 update_register x20", res)
ci.HandleCommand("command alias x21 update_register x21", res)
ci.HandleCommand("command alias x22 update_register x22", res)
ci.HandleCommand("command alias x23 update_register x23", res)
ci.HandleCommand("command alias x24 update_register x24", res)
ci.HandleCommand("command alias x25 update_register x25", res)
ci.HandleCommand("command alias x26 update_register x26", res)
ci.HandleCommand("command alias x27 update_register x27", res)
ci.HandleCommand("command alias x28 update_register x28", res)
if CONFIG_KEYSTONE_AVAILABLE == 1:
ci.HandleCommand("command script add -f lldbinit.cmd_asm32 asm32", res)
ci.HandleCommand("command script add -f lldbinit.cmd_asm64 asm64", res)
ci.HandleCommand("command script add -f lldbinit.cmd_arm32 arm32", res)
ci.HandleCommand("command script add -f lldbinit.cmd_arm64 arm64", res)
ci.HandleCommand("command script add -f lldbinit.cmd_armthumb armthumb", res)
# add the hook - we don't need to wait for a target to be loaded
# Note: since I removed the original stop-disassembly-count trick to allegedly avoid
# double loading it had a side effect to keep adding multiple copies of the hook
# when doing multiple imports of the script (for testing mostly)
# a check is now implemented where the hook is only added if no previous hook exist
ci.HandleCommand("target stop-hook list", res)
if res.Succeeded():
if "HandleHookStopOnTarget" not in res.GetOutput():
ci.HandleCommand("target stop-hook add -o 'HandleHookStopOnTarget'", res)
else:
print("[-] error: failed to list stop hooks and our hook isn't loaded")
ci.HandleCommand("command script add --function lldbinit.cmd_banner banner", res)
# custom commands
ci.HandleCommand("command script add -f lldbinit.cmd_fixret fixret", res)
# displays the version banner when lldb is loaded
debugger.HandleCommand("banner")
return
def cmd_banner(debugger,command,result,dict):
print(GREEN + "[+] Loaded lldbinit version " + VERSION + "." + BUILD + RESET)
def cmd_lldbinitcmds(debugger, command, result, dict):
'''Display all available lldbinit commands.'''
help_table = [
[ "lldbinitcmds", "this command" ],
[ "----[ Settings ]----", ""],
[ "enable", "configure lldb and lldbinit options" ],
[ "disable", "configure lldb and lldbinit options" ],
[ "contextcodesize", "set number of instruction lines in code window" ],
[ "enablesolib/disablesolib", "enable/disable the stop on library load events" ],
[ "enableaslr/disableaslr", "enable/disable process ASLR" ],
[ "datawin", "set start address to display on data window" ],
[ "----[ Breakpoints ]----", ""],
[ "b", "breakpoint address" ],
[ "bpt", "set a temporary software breakpoint" ],
[ "bhb", "set an hardware breakpoint" ],
[ "bpc", "clear breakpoint" ],
[ "bpca", "clear all breakpoints" ],
[ "bpd", "disable breakpoint" ],
[ "bpda", "disable all breakpoints" ],
[ "bpe", "enable a breakpoint" ],
[ "bpea", "enable all breakpoints" ],
[ "bcmd", "alias to breakpoint command add"],
[ "bpl", "list all breakpoints"],
[ "bpn", "temporarly breakpoint next instruction" ],
[ "bm", "breakpoint on specific module load" ],
[ "bmc", "clear all module load breakpoints" ],
[ "break_entrypoint", "launch target and stop at entrypoint" ],
[ "skip", "skip current instruction" ],
[ "int3", "patch memory address with INT3" ],
[ "rint3", "restore original byte at address patched with INT3" ],
[ "listint3", "list all INT3 patched addresses" ],
[ "lb", "load breakpoints from file and apply them (currently only func names are applied)" ],
[ "lbrva", "load breakpoints from file and apply to main executable, only RVA in this case" ],
[ "print_images", "print all images available at gdb_image_notifier() breakpoint"],
[ "----[ Memory ]----", ""],
[ "nop", "patch memory address with NOP" ],
[ "null", "patch memory address with NULL" ],
[ "db/dw/dd/dq", "memory hex dump in different formats" ],
[ "findmem", "search memory" ],
[ "showregions", "display process memory regions" ],
[ "----[ Disassembly ]----", ""],
[ "u", "dump instructions" ],
[ "ctx/context", "show current instruction pointer CPU context" ],
[ "stepo", "step over calls and loop instructions" ],
[ "----[ Registers and CPU Flags ]----", ""],
[ "rip/rax/rbx/etc", "shortcuts to modify x64 registers" ],
[ "eip/eax/ebx/etc", "shortcuts to modify x86 registers" ],
[ "x{0..28}", "shortcuts to modify ARM64 registers" ],
[ "cfa/cfc/cfd/cfi/cfo/cfp/cfs/cft/cfz", "change x86/x64 CPU flags" ],
[ "cfn/cfz/cfc/cfv", "change AArch64 CPU flags (NZCV register)"],
[ "----[ File headers ]----", ""],
[ "show_loadcmds", "show otool output of Mach-O load commands" ],
[ "show_header", "show otool output of Mach-O header" ],
[ "----[ Cracking ]----", ""],
[ "crack", "return from current function" ],
[ "crackcmd", "set a breakpoint and return from that function" ],
[ "crackcmd_noret", "set a breakpoint and set a register value. doesn't return from function" ],
[ "----[ Misc ]----", ""],
[ "iphone", "connect to debugserver running on iPhone" ],
[ "----[ Assembler ]----", ""],
[ "asm32/asm64", "x86/x64 assembler using keystone" ],
[ "arm32/arm64/armthumb", "ARM assembler using keystone" ]
]
print("lldbinit available commands:")
for row in help_table:
if not row[1]:
print(" {: <20} {: <30}".format(*row))
else:
print(" {: <20} - {: <30}".format(*row))
print("\nUse \'cmdname help\' for extended command help.")
# placeholder to make tests
def cmd_tester(debugger, command, result, dict):
print("test")
return
# -------------------------
# Settings related commands
# -------------------------
def cmd_enable(debugger, command, result, dict):
'''Enable certain lldb and lldbinit options. Use \'enable help\' for more information.'''
help = """
Enable certain lldb and lldbinit configuration options.
Syntax: enable <setting>
Available settings:
solib: enable stop on library events trick.
aslr: enable process aslr.
stack: enable stack window in context display.
data: enable data window in context display, configure address with datawin.
flow: enable call targets and objective-c class/methods window in context display.
"""
global CONFIG_DISPLAY_STACK_WINDOW
global CONFIG_DISPLAY_FLOW_WINDOW
global CONFIG_DISPLAY_DATA_WINDOW
cmd = command.split()
if len(cmd) == 0:
print("[-] error: command requires argument.")
print("")
print(help)
return
if cmd[0] == "solib":
debugger.HandleCommand("settings set target.process.stop-on-sharedlibrary-events true")
print("[+] Enabled stop on library events trick.")
elif cmd[0] == "aslr":
debugger.HandleCommand("settings set target.disable-aslr false")
print("[+] Enabled ASLR.")
elif cmd[0] == "stack":
CONFIG_DISPLAY_STACK_WINDOW = 1
print("[+] Enabled stack window in context display.")
elif cmd[0] == "flow":
CONFIG_DISPLAY_FLOW_WINDOW = 1
print("[+] Enabled indirect control flow window in context display.")
elif cmd[0] == "data":
CONFIG_DISPLAY_DATA_WINDOW = 1
print("[+] Enabled data window in context display. Configure address with \'datawin\' cmd.")
elif cmd[0] == "help":
print(help)
else:
print("[-] error: unrecognized command.")
print(help)
return
def cmd_disable(debugger, command, result, dict):
'''Disable certain lldb and lldbinit options. Use \'disable help\' for more information.'''
help = """
Disable certain lldb and lldbinit configuration options.
Syntax: disable <setting>
Available settings:
solib: disable stop on library events trick.
aslr: disable process aslr.
stack: disable stack window in context display.
data: disable data window in context display.
flow: disable call targets and objective-c class/methods window in context display.
"""
global CONFIG_DISPLAY_STACK_WINDOW
global CONFIG_DISPLAY_FLOW_WINDOW
global CONFIG_DISPLAY_DATA_WINDOW
cmd = command.split()
if len(cmd) == 0:
print("[-] error: command requires argument.")
print("")
print(help)
return
if cmd[0] == "solib":
debugger.HandleCommand("settings set target.process.stop-on-sharedlibrary-events false")
print("[+] Disabled stop on library events trick.")
elif cmd[0] == "aslr":
debugger.HandleCommand("settings set target.disable-aslr true")
print("[+] Disabled ASLR.")
elif cmd[0] == "stack":
CONFIG_DISPLAY_STACK_WINDOW = 0
print("[+] Disabled stack window in context display.")
elif cmd[0] == "flow":
CONFIG_DISPLAY_FLOW_WINDOW = 0
print("[+] Disabled indirect control flow window in context display.")
elif cmd[0] == "data":
CONFIG_DISPLAY_DATA_WINDOW = 0
print("[+] Disabled data window in context display.")
elif cmd[0] == "help":
print(help)
else:
print("[-] error: unrecognized command.")
print(help)
return
def cmd_contextcodesize(debugger, command, result, dict):
'''Set the number of disassembly lines in code window. Use \'contextcodesize help\' for more information.'''
help = """
Configures the number of disassembly lines displayed in code window. Default is 8.
Syntax: contextcodesize <line_count>
Note: expressions supported, do not use spaces between operators.
"""
global CONFIG_DISASSEMBLY_LINE_COUNT
cmd = command.split()
if len(cmd) != 1:
print("[-] error: please insert the number of disassembly lines to display.")
print("")
print(help)
return
if cmd[0] == "help":
print(help)
print("\nCurrent configuration value is: {:d}".format(CONFIG_DISASSEMBLY_LINE_COUNT))
return
value = evaluate(cmd[0])
if value is None:
print("[-] error: invalid input value.")
print("")
print(help)
return
CONFIG_DISASSEMBLY_LINE_COUNT = value
return
# ---------------------------------
# Color and output related commands
# ---------------------------------
# append data to the output that we display at the end of the hook-stop
def output(x):
global GlobalListOutput
GlobalListOutput.append(x)
# ---------------------------
# Breakpoint related commands
# ---------------------------
ANTIDEBUG_SYSCTL_OBJS = []
# the second step breakpoint callback of the sysctl antidebug bypass
# we are at the return address of sysctl symbol
# and we simply remove the P_TRACED flag if it exists
def antidebug_callback_step2(frame, bp_loc, dict):
global ANTIDEBUG_SYSCTL_OBJS
for i in ANTIDEBUG_SYSCTL_OBJS:
#print(hex(i))
ANTIDEBUG_SYSCTL_OBJS.remove(i)
# offset to kp_proc.p_flag - this should be stable
offset = 0x20
target = get_target()
error = lldb.SBError()
# read the current value so we can modify and write again
# we could probably use an expression via cmdline to make it easier
value = get_process().ReadUnsignedFromMemory(i+offset, 4, error)
#print("before {}".format(hex(value)))
# remve P_TRACED flag if exists
value = value ^ 0x800
# WriteMemory accepts a string so we need to pack this
patch = struct.pack("I", value)
result = target.GetProcess().WriteMemory(i+offset, patch, error)
if not error.Success():
print("[-] error: Failed to write memory at 0x{:x}.".format(i+offset))
return
#value = get_process().ReadUnsignedFromMemory(i+offset, 4, error)
#print("after {}".format(hex(value)))
get_process().Continue()
# the first step breakpoint callback of the sysctl antidebug bypass
# this deals with the breakpoint at sysctl symbol
# the purpose is to verify the request and set a second stage on return address
# where the debug flag is removed
def antidebug_callback_step1(frame, bp_loc, dict):
global ANTIDEBUG_SYSCTL_OBJS
if frame is None:
return 0
target = get_target()
rdi = int(frame.FindRegister('rdi').GetValue(), 16)
error = lldb.SBError()
mib0 = get_process().ReadUnsignedFromMemory(rdi, 4, error)
if not error.Success():
print("[-] error: failed to read mib0")
return
mib1 = get_process().ReadUnsignedFromMemory(rdi+4, 4, error)
if not error.Success():
print("[-] error: failed to read mib1")
return
mib2 = get_process().ReadUnsignedFromMemory(rdi+8, 4, error)
if not error.Success():
print("[-] error: failed to read mib2")
return
# check if it's a potential AmIBeingDebugged request
# it's a common request from some apps
# so we need to verify on the return and remove the flag
if mib0 == 1 and mib1 == 14 and mib2 == 1:
print("[+] Hit sysctl antidebug request")
rdx = int(frame.FindRegister('rdx').GetValue(), 16)
if rdx == 0:
print("[!] warning: rdx == 0")
get_process().Continue()
ANTIDEBUG_SYSCTL_OBJS.append(rdx)
# set a temporary breakpoint on the ret
# temporary because we can't sync this with other sysctl calls
mem_sbaddr = lldb.SBAddress(int(frame.FindRegister('pc').GetValue(), 16), target)
instructions_mem = target.ReadInstructions(mem_sbaddr, 64, "intel")
for mem_inst in instructions_mem:
#print(hex(mem_inst.addr.GetLoadAddress(target)), mem_inst.mnemonic)
if mem_inst.GetMnemonic(target) == 'ret':
breakpoint = target.BreakpointCreateByAddress(mem_inst.addr.GetLoadAddress(target))
breakpoint.SetOneShot(True)
breakpoint.SetThreadID(get_frame().GetThread().GetThreadID())
breakpoint.SetScriptCallbackFunction('lldbinit.antidebug_callback_step2')
# everything automatic here so continue in any case
get_process().Continue()
def taskexception_callback(frame, bp_loc, dict):
if frame is None:
return 0
print("[+] Hit task_set_exception_ports request")
target = get_target()
thread = frame.GetThread()
# the SBValue to ReturnFromFrame must be eValueTypeRegister type
# if we do a lldb.SBValue() we can't set to that type
# so we need to make a copy
# can we use FindRegister() from frame?
return_value = frame.reg["rax"]
return_value.value = str(0)
thread.ReturnFromFrame(frame, return_value)
#get_process().Continue()
def cmd_antidebug(debugger, command, result, dict):
'''Enable anti-anti-debugging. Use \'antidebug help\' for more information.'''
help = """
Enable anti-anti-debugging measures.
Bypasses sysctl AmIBeingDebugged debugger detection.
Syntax: antidebug
"""
global modules_list
cmd = command.split()
if len(cmd) > 0 and cmd[0] == "help":
print(help)
return
if is_arm():
print("[-] error: unsupported architecture for this command.")
return
target = get_target()
for m in target.module_iter():
# print(m.file.fullpath)
if m.file.fullpath == "/usr/lib/dyld":
breakpoint = target.BreakpointCreateByName("sysctl", '/usr/lib/system/libsystem_c.dylib')
breakpoint.SetScriptCallbackFunction('lldbinit.antidebug_callback_step1')
#breakpoint2 = target.BreakpointCreateByName("task_set_exception_ports", '/usr/lib/system/libsystem_kernel.dylib')
#breakpoint2.SetScriptCallbackFunction('lldbinit.taskexception_callback')
break
# the callback for the specific module loaded breakpoint
# supports x64, i386, arm64
def module_breakpoint_callback(frame, bp_loc, dict):
global modules_list
# rdx contains the module address
# rdx+8 contains pointer to the module name string
if frame is None:
return 0
error = lldb.SBError()
i386 = is_i386()
x64 = is_x64()
arm = is_arm()
if not i386 and not x64 and not arm:
print("[-] error: unsupported architecture.")
# for i386 we need the stack pointer to retrieve arguments
if i386:
sp = frame.FindRegister("esp")
sp = int(sp.GetValue(), 16)
# static void gdb_image_notifier(enum dyld_image_mode mode, uint32_t infoCount, const dyld_image_info info[])
# static void lldb_image_notifier(enum dyld_image_mode mode, uint32_t infoCount, const dyld_image_info info[])
if x64:
pc = frame.FindRegister("rdi")
mode = int(pc.GetValue(), 16)
elif arm:
# argument registers from x0 to x7
pc = frame.FindRegister("x0")
mode = int(pc.GetValue(), 16)
elif i386:
mode = get_process().ReadUnsignedFromMemory(sp+4, 4, error)
if not error.Success():
print("[-] error: failed to read mode from stack.")
return
# only interested in new images
# enum dyld_image_mode { dyld_image_adding=0, dyld_image_removing=1, dyld_image_info_change=2, dyld_image_dyld_moved=3 };
if mode != 0:
get_process().Continue()
return
# infoCount argument
if x64:
pc = frame.FindRegister("rsi")
infoCount = int(pc.GetValue(), 16)
elif arm:
pc = frame.FindRegister("x1")
infoCount = int(pc.GetValue(), 16)
elif i386:
infoCount = get_process().ReadUnsignedFromMemory(sp+8, 4, error)
if not error.Success():
print("[-] error: failed to read infoCount from stack.")
return
# info argument
if x64:
pc = frame.FindRegister("rdx")
info = int(pc.GetValue(), 16)
elif arm:
pc = frame.FindRegister("x2")
info = int(pc.GetValue(), 16)
elif i386:
info = get_process().ReadUnsignedFromMemory(sp+12, 4, error)
if not error.Success():
print("[-] error: failed to read address from rdx.")
return
# set values according to target platform
if i386:
readSize = 4
# sizeof(struct dyld_image_info) - this should be constant?
dyld_image_info_size = 4 * 3
else:
readSize = 8
dyld_image_info_size = 8 * 3
hit = 0
# go over all the images being added and try to found the ones we are interested in
for x in range(infoCount):
address = get_process().ReadUnsignedFromMemory(info, readSize, error)
if not error.Success():
print("[-] error: failed to read address from info structure" + error)
return
string_ptr = get_process().ReadUnsignedFromMemory(info+readSize, readSize, error)
if not error.Success():
print("[-] error: failed to read string pointer from info structure.")
return
string = get_process().ReadCStringFromMemory(string_ptr, 1024, error)
if not error.Success():
print("[-] error: failed to read module name string.")
return
for i in modules_list:
if i == string:
hit = 1
print("[+] Hit module loading: {0} @ {1}".format(string, hex(address)))
break
# we found the module so no point continuing
# lldb stays at the gdb_image_notifier() breakpoint
# so that user can do something
if hit == 1:
return
# advance to next one
info += dyld_image_info_size
# nothing found so we resume execution
if hit == 0:
get_process().Continue()
# breakpoint on specific module
def cmd_bm(debugger, command, result, dict):
'''Set breakpoint on specific module load. Use \'bm help\' for more information.'''
help = """
Set gdb_image_notifier() or lldb_image_notifier() breakpoint on module load.
Similar to stop on shared library events feature but stops only on configured modules.
Issue the command multiple times to add different modules.
If no module path specified it will just be a shortcut to set breakpoint
at beginning of image notifier. Use \'print_images\' to show all images there.
Note: the gdb_image_notifier() was removed in Monterey.
Syntax: bm [<module full path>]
Example:
bm /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation
"""
global modules_list
cmd = command.split()
if len(cmd) > 0 and cmd[0] == "help":
print(help)
return
# cmd is a list so we have problems in paths with spaces
# convert everything to a single string
# and hope the user doesn't make an error such as: bm path with spaces junk
modpath = command.split(" ", 0)
found = 0
target = get_target()
for m in target.module_iter():
# print(m.file.fullpath)
if m.file.fullpath == "/usr/lib/dyld":
for symbol in m:
# mangled is easier because the other symbol commands will retrieve with prototype info in the name
name = symbol.GetMangledName()
# XXX: improve this because we are doubling the amount of work?
# the lldb symbol isn't mangled
name2 = symbol.GetName()
if name == "_ZL18gdb_image_notifier15dyld_image_modejPK15dyld_image_info" or name2 == "lldb_image_notifier":
saddr = symbol.GetStartAddress()
# process needs to be loaded before we can execute this command...
if saddr.GetLoadAddress(target) == 0xffffffffffffffff:
print("[-] error: failed to retrieve address of gdb_image_notifier. use 'break_entrypoint' or 'process launch -s' command first and then this one.")
return
bpt_addr = saddr.GetLoadAddress(target)
# check if it's a duplicate breakpoint
# just add to the module list if the callback is already set
for bpt in target.breakpoint_iter():
# we need to iterate all locations of each breakpoint... geezzzzzz
for bl in bpt:
if bl.GetLoadAddress() == bpt_addr:
modules_list.append(modpath[0])
return
print("[+] setting breakpoint on gdb_image_notifier located at address {0}".format(hex(saddr.GetLoadAddress(target))))
breakpoint = target.BreakpointCreateByAddress(bpt_addr)
# append the module name to the list if set
if len(cmd) > 0:
breakpoint.SetScriptCallbackFunction('lldbinit.module_breakpoint_callback')
modules_list.append(modpath[0])
found = 1
break
if found:
break
def cmd_bmc(debugger, command, result, dict):
'''Clear all breakpoints on specific module load. Use \'bmc help\' for more information.'''
help = """
Clear all breakpoints on specific module load.
Syntax: bmc
"""
global modules_list
cmd = command.split()
if len(cmd) > 0 and cmd[0] == "help":
print(help)
return
modules_list = []
def cmd_print_notifier_images(debugger, command, result, dict):
'''Print all images available at gdb_image_notifier/lldb_image_notifier breakpoint'''
help = """
Print all images available at gdb_image_notifier() or lldb_image_notifier() breakpoint.
Only valid when breakpoint set at beginning of the image notifier.
Note: the gdb_image_notifier() was removed in Monterey.
Syntax: print_images
"""
cmd = command.split()
if len(cmd) > 0 and cmd[0] == "help":
print(help)
return
frame = get_frame()
if frame is None:
return 0
error = lldb.SBError()
# XXX: check that we are effectively at gdb_image_notifier address
i386 = is_i386()
x64 = is_x64()
arm = is_arm()
if not i386 and not x64 and not arm:
print("[-] error: unsupported architecture.")
# for i386 we need the stack pointer to retrieve arguments
if i386:
sp = frame.FindRegister("esp")
sp = int(sp.GetValue(), 16)
# static void gdb_image_notifier(enum dyld_image_mode mode, uint32_t infoCount, const dyld_image_info info[])
# static void lldb_image_notifier(enum dyld_image_mode mode, uint32_t infoCount, const dyld_image_info info[])
# mode argument
if x64:
pc = frame.FindRegister("rdi")
mode = int(pc.GetValue(), 16)
elif arm:
# argument registers from x0 to x7
pc = frame.FindRegister("x0")
mode = int(pc.GetValue(), 16)
elif i386:
mode = get_process().ReadUnsignedFromMemory(sp+4, 4, error)
if not error.Success():
print("[-] error: failed to read mode from stack.")
return
# infoCount argument
if x64:
pc = frame.FindRegister("rsi")
infoCount = int(pc.GetValue(), 16)
elif arm:
pc = frame.FindRegister("x1")
infoCount = int(pc.GetValue(), 16)
elif i386:
infoCount = get_process().ReadUnsignedFromMemory(sp+8, 4, error)
if not error.Success():
print("[-] error: failed to read infoCount from stack.")
return
# info argument
if x64:
pc = frame.FindRegister("rdx")
info = int(pc.GetValue(), 16)
elif arm:
pc = frame.FindRegister("x2")
info = int(pc.GetValue(), 16)
elif i386:
info = get_process().ReadUnsignedFromMemory(sp+12, 4, error)
if not error.Success():
print("[-] error: failed to read address from rdx.")
return
# set values according to target platform
if i386:
readSize = 4
dyld_image_info_size = 4 * 3
else:
readSize = 8
dyld_image_info_size = 8 * 3
print("[+] gdb_image_notifier total dyld_image_info images: {0}".format(infoCount))
print("[+] mode: {0} ({1})".format(mode, dyld_mode_dict[mode]))
print("[+] Loaded modules:")
for x in range(infoCount):
address = get_process().ReadUnsignedFromMemory(info, readSize, error)
if not error.Success():
print("[-] error: failed to read address from info structure.")
return
string_ptr = get_process().ReadUnsignedFromMemory(info+readSize, readSize, error)
if not error.Success():
print("[-] error: failed to read string pointer from info structure.")
return
string = get_process().ReadCStringFromMemory(string_ptr, 1024, error)
if not error.Success():
print("[-] error: failed to read module name string.")
return
print("{0} @ {1}".format(string, hex(address)))
# advance to next one sizeof(struct dyld_image_info)
info += dyld_image_info_size
# temporary software breakpoint
def cmd_bpt(debugger, command, result, dict):
'''Set a temporary software breakpoint. Use \'bpt help\' for more information.'''
help = """
Set a temporary software breakpoint.
Syntax: bpt <address>
Note: expressions are supported, do not use spaces between operators.
"""
cmd = command.split()
if len(cmd) != 1:
print("[-] error: please insert a breakpoint address.")
print("")
print(help)
return
if cmd[0] == "help":
print(help)
return
value = evaluate(cmd[0])
if value is None:
print("[-] error: invalid input value.")
print("")
print(help)
return
target = get_target()
breakpoint = target.BreakpointCreateByAddress(value)
breakpoint.SetOneShot(True)
breakpoint.SetThreadID(get_frame().GetThread().GetThreadID())
print("[+] Set temporary breakpoint at 0x{:x}".format(value))
# hardware breakpoint
def cmd_bhb(debugger, command, result, dict):
'''Set an hardware breakpoint'''
help = """
Set an hardware breakpoint.
Syntax: bhb <address>
Note: expressions are supported, do not use spaces between operators.
"""
cmd = command.split()
if len(cmd) != 1:
print("[-] error: please insert a breakpoint address.")
print("")
print(help)
return
if cmd[0] == "help":
print(help)
return
value = evaluate(cmd[0])
if value is None:
print("[-] error: invalid input value.")
print("")
print(help)
return
# the python API doesn't seem to support hardware breakpoints
# so we set it via command line interpreter
res = lldb.SBCommandReturnObject()
lldb.debugger.GetCommandInterpreter().HandleCommand("breakpoint set -H -a " + hex(value), res)
print("[+] Hardware breakpoint set at 0x{:x}".format(value))
return
# temporary hardware breakpoint
def cmd_bht(debugger, command, result, dict):
'''Set a temporary hardware breakpoint'''
print("[-] error: lldb has no x86/x64 temporary hardware breakpoints implementation.")
return
# clear breakpoint number
def cmd_bpc(debugger, command, result, dict):
'''Clear a breakpoint. Use \'bpc help\' for more information.'''
help = """
Clear a breakpoint.
Syntax: bpc <breakpoint_number>
Notes:
- Only breakpoint numbers are valid, not addresses. Use \'bpl\' to list breakpoints.
- Expressions are supported, do not use spaces between operators.
"""
cmd = command.split()
if len(cmd) != 1:
print("[-] error: please insert a breakpoint number.")
print("")
print(help)
return
if cmd[0] == "help":
print(help)
return
# breakpoint disable only accepts breakpoint numbers not addresses
value = evaluate(cmd[0])
if value is None:
print("[-] error: invalid input value - only a breakpoint number is valid.")
print("")
print(help)
return
target = get_target()
for bpt in target.breakpoint_iter():
if bpt.id == value:
if target.BreakpointDelete(bpt.id) is False:
print("[-] error: failed to delete breakpoint #{:d}".format(value))
return
print("[+] Deleted breakpoint #{:d}".format(value))
return
print("[-] error: breakpoint #{:d} not found".format(value))
return
# disable breakpoint number
# XXX: we could support addresses, not sure it's worth the trouble
def cmd_bpd(debugger, command, result, dict):
'''Disable a breakpoint. Use \'bpd help\' for more information.'''
help = """
Disable a breakpoint.
Syntax: bpd <breakpoint_number>
Notes:
- Only breakpoint numbers are valid, not addresses. Use \'bpl\' to list breakpoints.
- Expressions are supported, do not use spaces between operators.
"""
cmd = command.split()
if len(cmd) != 1:
print("[-] error: please insert a breakpoint number.")
print("")
print(help)
return
if cmd[0] == "help":
print(help)
return
# breakpoint disable only accepts breakpoint numbers not addresses
value = evaluate(cmd[0])
if value is None:
print("[-] error: invalid input value - only a breakpoint number is valid.")
print("")
print(help)
return
target = get_target()
for bpt in target.breakpoint_iter():
if bpt.id == value and bpt.IsEnabled():
bpt.SetEnabled(False)
print("[+] Disabled breakpoint #{:d}".format(value))
# disable all breakpoints
def cmd_bpda(debugger, command, result, dict):
'''Disable all breakpoints. Use \'bpda help\' for more information.'''
help = """
Disable all breakpoints.
Syntax: bpda
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
target = get_target()
if target.DisableAllBreakpoints() is False:
print("[-] error: failed to disable all breakpoints.")
print("[+] Disabled all breakpoints.")
# enable breakpoint number
def cmd_bpe(debugger, command, result, dict):
'''Enable a breakpoint. Use \'bpe help\' for more information.'''
help = """
Enable a breakpoint.
Syntax: bpe <breakpoint_number>
Notes:
- Only breakpoint numbers are valid, not addresses. Use \'bpl\' to list breakpoints.
- Expressions are supported, do not use spaces between operators.
"""
cmd = command.split()
if len(cmd) != 1:
print("[-] error: please insert a breakpoint number.")
print("")
print(help)
return
if cmd[0] == "help":
print(help)
return
# breakpoint enable only accepts breakpoint numbers not addresses
value = evaluate(cmd[0])
if value is None:
print("[-] error: invalid input value - only a breakpoint number is valid.")
print("")
print(help)
return
target = get_target()
for bpt in target.breakpoint_iter():
if bpt.id == value and not bpt.IsEnabled():
bpt.SetEnabled(True)
print("[+] Enabled breakpoint #{:d}".format(value))
# enable all breakpoints
def cmd_bpea(debugger, command, result, dict):
'''Enable all breakpoints. Use \'bpea help\' for more information.'''
help = """
Enable all breakpoints.
Syntax: bpea
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
target = get_target()
if not target.EnableAllBreakpoints():
print("[-] error: failed to enable all breakpoints.")
print("[+] Enabled all breakpoints.")
# skip current instruction - just advances PC to next instruction but doesn't execute it
def cmd_skip(debugger, command, result, dict):
'''Advance PC to instruction at next address. Use \'skip help\' for more information.'''
help = """
Advance current instruction pointer to next instruction.
Syntax: skip
Note: control flow is not respected, it advances to next instruction in memory.
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
start_addr = get_current_pc()
next_addr = start_addr + get_inst_size(start_addr)
if is_x64():
get_frame().reg["rip"].value = format(next_addr, '#x')
elif is_i386():
get_frame().reg["eip"].value = format(next_addr, '#x')
elif is_arm():
get_frame().reg["pc"].value = format(next_addr, '#x')
# show the updated context
lldb.debugger.HandleCommand("context")
def cmd_int3(debugger, command, result, dict):
'''Patch at address to a breakpoint instruction (INT3 for x86, BRK #0 for AArch64) . Use \'int3 help\' for more information.'''
help = """
Patch process memory with a breakpoint instruction at given address.
Syntax: int3 [<address>]
Notes:
- Useful in cases where the debugger breakpoints aren't respected but an INT3/BRK will always trigger the debugger.
- Expressions are supported, do not use spaces between operators. Example: int3 $pc+0x10
"""
global int3patches
error = lldb.SBError()
target = get_target()
cmd = command.split()
# if empty insert a int3 at current PC
if len(cmd) == 0:
int3_addr = get_current_pc()
if int3_addr == 0:
print("[-] error: invalid current address.")
return
elif len(cmd) == 1:
if cmd[0] == "help":
print(help)
return
int3_addr = evaluate(cmd[0])
if int3_addr is None:
print("[-] error: invalid input address value.")
print("")
print(help)
return
else:
print("[-] error: please insert a breakpoint address.")
print("")
print(help)
return
bpt_size = 1
if is_arm():
bpt_size = 4
bytes_string = target.GetProcess().ReadMemory(int3_addr, bpt_size, error)
if not error.Success():
print("[-] error: Failed to read memory at 0x{:x}.".format(int3_addr))
return
bytes_read = bytearray(bytes_string)
if is_python2():
patch_bytes = str('\xCC')
if is_arm():
# brk #0
patch_bytes = str("\x00\x00\x20\xd4")
else:
patch_bytes = bytearray(b'\xCC')
if is_arm():
patch_bytes = bytearray(b'\x00\x00\x20\xd4')
# insert the patch
result = target.GetProcess().WriteMemory(int3_addr, patch_bytes, error)
# XXX: compare len(patch) with result
if not error.Success():
print("[-] error: Failed to write memory at 0x{:x}.".format(int3_addr))
return
# save original bytes for later restore
int3patches[str(int3_addr)] = bytes_read
print("[+] Patched breakpoint at 0x{:x}".format(int3_addr))
return
def cmd_rint3(debugger, command, result, dict):
'''Restore byte at address from a previously patched breakpoint instruction. Use \'rint3 help\' for more information.'''
help = """
Restore the original byte at a previously patched address using \'int3\' command.
Syntax: rint3 [<address>]
Note: expressions are supported, do not use spaces between operators.
"""
global int3patches
error = lldb.SBError()
target = get_target()
cmd = command.split()
# if empty insert a int3 at current PC
if len(cmd) == 0:
int3_addr = get_current_pc()
if int3_addr == 0:
print("[-] error: invalid current address.")
return
elif len(cmd) == 1:
if cmd[0] == "help":
print(help)
return
int3_addr = evaluate(cmd[0])
if int3_addr is None:
print("[-] error: invalid input address value.")
print("")
print(help)
return
else:
print("[-] error: please insert a breakpoint patched address.")
print("")
print(help)
return
if len(int3patches) == 0:
print("[-] error: No breakpoint patched addresses to restore available.")
return
if str(int3_addr) not in int3patches:
print("[-] error: No breakpoint patch found at address 0x{:x}.".format(int3_addr))
return
original_bytes = int3patches[str(int3_addr)]
bpt_size = 1
if is_arm():
bpt_size = 4
bytes_string = target.GetProcess().ReadMemory(int3_addr, bpt_size, error)
if not error.Success():
print("[-] error: Failed to read memory at 0x{:x}.".format(int3_addr))
return
bytes_read = bytearray(bytes_string)
# validate what's in memory
if len(bytes_read) == 1 and bytes_read[0] != 0xCC:
print("[-] error: no INT3 patch found in memory at address 0x{:x}".format(int3_addr))
return
elif len(bytes_read) == 4 and bytes_read[3] != 0xd4:
print("[-] error: no BRK patch found in memory at address 0x{:x}".format(int3_addr))
return
if is_python2():
patch_bytes = str(original_bytes)
else:
patch_bytes = original_bytes
# restore original bytes
result = target.GetProcess().WriteMemory(int3_addr, patch_bytes, error)
if not error.Success():
print("[-] error: failed to write memory at 0x{:x}.".format(int3_addr))
return
# remove element from original bytes list
del int3patches[str(int3_addr)]
return
def cmd_listint3(debugger, command, result, dict):
'''List all patched addresses with breakpoint instructions. Use \'listint3 help\' for more information.'''
help = """
List all addresses patched with \'int3\' command.
Syntax: listint3
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
if len(int3patches) == 0:
print("[-] No breakpoint patched addresses available.")
return
print("Current breakpoint patched addresses:")
for address, byte in int3patches.items():
print("[*] {:s}".format(hex(int(address, 10))))
return
def cmd_nop(debugger, command, result, dict):
'''NOP byte(s) at address. Use \'nop help\' for more information.'''
help = """
Patch process memory with NOP instruction(s) at given address.
Syntax: nop <address> [<amount>]
Notes:
- Default is one instruction if amount not specified.
- Expressions are supported, do not use spaces between operators. Example: nop $pc+10
"""
error = lldb.SBError()
target = get_target()
cmd = command.split()
if len(cmd) == 1:
if cmd[0] == "help":
print(help)
return
nop_addr = evaluate(cmd[0])
patch_size = 1
if nop_addr is None:
print("[-] error: invalid address value.")
print("")
print(help)
return
elif len(cmd) == 2:
nop_addr = evaluate(cmd[0])
if nop_addr is None:
print("[-] error: invalid address value.")
print("")
print(help)
return
patch_size = evaluate(cmd[1])
if patch_size is None:
print("[-] error: invalid size value.")
print("")
print(help)
return
else:
print("[-] error: please insert a target address.")
print("")
print(help)
return
current_patch_addr = nop_addr
# format for WriteMemory()
# Python 2
if is_python2():
patch_len = 1
patch_bytes = str('\x90')
if is_arm():
patch_bytes = str('\x1f\x20\x03\xd5')
patch_len = 4
else:
patch_len = 1
patch_bytes = bytearray(b'\x90')
if is_arm():
patch_bytes = bytearray(b'\x1f\x20\x03\xd5')
patch_len = 4
for i in range(patch_size):
result = target.GetProcess().WriteMemory(current_patch_addr, patch_bytes, error)
if not error.Success():
print("[-] error: Failed to write memory at 0x{:x}.".format(current_patch_addr))
return
current_patch_addr = current_patch_addr + patch_len
return
def cmd_null(debugger, command, result, dict):
'''Patch byte(s) at address to NULL (0x00). Use \'null help\' for more information.'''
help = """
Patch process memory with NULL (0x00) byte(s) at given address.
Syntax: null <address> [<size>]
Notes:
- Default size is one byte if size not specified.
- Expressions are supported, do not use spaces between operators. Example: null $pc+0x10
"""
error = lldb.SBError()
target = get_target()
cmd = command.split()
if len(cmd) == 1:
if cmd[0] == "help":
print(help)
return
null_addr = evaluate(cmd[0])
patch_size = 1
if null_addr is None:
print("[-] error: invalid address value.")
print("")
print(help)
return
elif len(cmd) == 2:
null_addr = evaluate(cmd[0])
if null_addr is None:
print("[-] error: invalid address value.")
print("")
print(help)
return
patch_size = evaluate(cmd[1])
if patch_size is None:
print("[-] error: invalid size value.")
print("")
print(help)
return
else:
print("[-] error: please insert a breakpoint address.")
print("")
print(help)
return
current_patch_addr = null_addr
# format for WriteMemory()
patch_bytes = str('\x00')
# can we do better here? WriteMemory takes an input string... weird
for i in range(patch_size):
result = target.GetProcess().WriteMemory(current_patch_addr, patch_bytes, error)
if not error.Success():
print("[-] error: failed to write memory at 0x{:x}.".format(current_patch_addr))
return
current_patch_addr = current_patch_addr + 1
return
'''
Implements stepover instruction.
'''
def cmd_stepo(debugger, command, result, dict):
'''Step over calls and some other instructions so we don't need to step into them. Use \'stepo help\' for more information.'''
help = """
Step over calls and loops that we want executed but not step into.
Affected instructions:
- x86: call, movs, stos, cmps, loop.
- arm64: bl, blr, blraa, blraaz, blrab, blrabz.
Syntax: stepo
"""
cmd = command.split()
if len(cmd) != 0 and cmd[0] == "help":
print(help)
return
debugger.SetAsync(True)
target = get_target()
# compute the next address where to breakpoint
pc_addr = get_current_pc()
if pc_addr == 0:
print("[-] error: invalid current address.")
return
next_addr = pc_addr + get_inst_size(pc_addr)
# much easier to use the mnemonic output instead of disassembling via cmd line and parse
mnemonic = get_mnemonic(pc_addr)
if is_arm():
# the a versions are with pointer authentication
branch_mnemo = [ "bl", "blr", "blraa", "blraaz", "blrab", "blrabz" ]
if mnemonic in branch_mnemo:
breakpoint = target.BreakpointCreateByAddress(next_addr)
breakpoint.SetThreadID(get_frame().GetThread().GetThreadID())
breakpoint.SetOneShot(True)
breakpoint.SetThreadID(get_frame().GetThread().GetThreadID())
target.GetProcess().Continue()
return
else:
get_process().selected_thread.StepInstruction(False)
return
# XXX: make the other instructions besides call user configurable?
# calls can be call, callq, so use wider matching for those
step_list = [ "call", "callq", "movs", "stos", "loop", "cmps" ]
if mnemonic in step_list:
breakpoint = target.BreakpointCreateByAddress(next_addr)
breakpoint.SetOneShot(True)
breakpoint.SetThreadID(get_frame().GetThread().GetThreadID())
target.GetProcess().Continue()
else:
get_process().selected_thread.StepInstruction(False)
# XXX: help
def cmd_LoadBreakPointsRva(debugger, command, result, dict):
global GlobalOutputList
GlobalOutputList = []
'''
frame = get_frame();
target = lldb.debugger.GetSelectedTarget();
nummods = target.GetNumModules();
#for x in range (0, nummods):
# mod = target.GetModuleAtIndex(x);
# #print(dir(mod));
# print(target.GetModuleAtIndex(x));
# for sec in mod.section_iter():
# addr = sec.GetLoadAddress(target);
# name = sec.GetName();
# print(hex(addr));
#1st module is executable
mod = target.GetModuleAtIndex(0);
sec = mod.GetSectionAtIndex(0);
loadaddr = sec.GetLoadAddress(target);
if loadaddr == lldb.LLDB_INVALID_ADDRESS:
sec = mod.GetSectionAtIndex(1);
loadaddr = sec.GetLoadAddress(target);
print(hex(loadaddr));
'''
target = get_target()
mod = target.GetModuleAtIndex(0)
sec = mod.GetSectionAtIndex(0)
loadaddr = sec.GetLoadAddress(target)
if loadaddr == lldb.LLDB_INVALID_ADDRESS:
sec = mod.GetSectionAtIndex(1)
loadaddr = sec.GetLoadAddress(target)
try:
f = open(command, "r")
except OSError:
return
while True:
line = f.readline()
if not line:
break
line = line.rstrip()
if not line:
break
# XXX: long() doesn't exist in p3
debugger.HandleCommand("breakpoint set -a " + hex(loadaddr + long(line, 16)))
f.close()
# XXX: help
def cmd_LoadBreakPoints(debugger, command, result, dict):
global GlobalOutputList
GlobalOutputList = []
try:
f = open(command, "r")
except OSError:
return
while True:
line = f.readline()
if not line:
break
line = line.rstrip()
if not line:
break
debugger.HandleCommand("breakpoint set --name " + line)
f.close()
# Temporarily breakpoint next instruction - this is useful to skip loops (don't want to use stepo for this purpose)
def cmd_bpn(debugger, command, result, dict):
'''Temporarily breakpoint instruction at next address. Use \'bpn help\' for more information.'''
help = """
Temporarily breakpoint instruction at next address
Syntax: bpn
Note: control flow is not respected, it breakpoints next instruction in memory.
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
target = get_target()
start_addr = get_current_pc()
next_addr = start_addr + get_inst_size(start_addr)
breakpoint = target.BreakpointCreateByAddress(next_addr)
breakpoint.SetOneShot(True)
breakpoint.SetThreadID(get_frame().GetThread().GetThreadID())
print("[+] Set temporary breakpoint at 0x{:x}".format(next_addr))
# command that sets rax/eax/x0 to 1 or 0 and returns right away from current function
# technically just a shortcut to "thread return"
def cmd_crack(debugger, command, result, dict):
'''Return from current function and set return value. Use \'crack help\' for more information.'''
help = """
Return from current function and set return value
Syntax: crack <return value>
Sets rax/eax/x0 to return value and returns immediately from current function.
You probably want to use this at the top of the function you want to return from.
"""
cmd = command.split()
if len(cmd) != 1:
print("[-] error: please insert a return value.")
print("")
print(help)
return
if cmd[0] == "help":
print(help)
return
# breakpoint disable only accepts breakpoint numbers not addresses
value = evaluate(cmd[0])
if value is None:
print("[-] error: invalid return value.")
print("")
print(help)
return
frame = get_frame()
# if we copy the SBValue from any register and use that copy
# for return value we will get that register and rax/eax set
# on return
# the SBValue to ReturnFromFrame must be eValueTypeRegister type
# if we do a lldb.SBValue() we can't set to that type
# so we need to make a copy
# can we use FindRegister() from frame?
if is_x64():
return_value = frame.reg["rax"]
elif is_arm():
return_value = frame.reg["x0"]
elif is_i386():
return_value = frame.reg["eax"]
else:
print("[-] error: unsupported architecture.")
return
return_value.value = str(value)
# XXX: should check the frame count and validate if there is something to return to
get_thread().ReturnFromFrame(frame, return_value)
# set a breakpoint with return command associated when hit
def cmd_crackcmd(debugger, command, result, dict):
'''Breakpoint an address, when breakpoint is hit return from function and set return value. Use \'crackcmd help\' for more information.'''
help = """
Breakpoint an address, when breakpoint is hit return from function and set return value.
Syntax: crackcmd <address> <return value>
Sets rax/eax/x0 to return value and returns immediately from current function where breakpoint was set.
"""
global crack_cmds
cmd = command.split()
if len(cmd) == 0:
print("[-] error: please check required arguments.")
print("")
print(help)
return
elif len(cmd) > 0 and cmd[0] == "help":
print(help)
return
elif len(cmd) < 2:
print("[-] error: please check required arguments.")
print("")
print(help)
return
# XXX: is there a way to verify if address is valid? or just let lldb error when setting the breakpoint
address = evaluate(cmd[0])
if address is None:
print("[-] error: invalid address value.")
print("")
print(help)
return
return_value = evaluate(cmd[1])
if return_value is None:
print("[-] error: invalid return value.")
print("")
print(help)
return
for tmp_entry in crack_cmds:
if tmp_entry['address'] == address:
print("[-] error: address already contains a crack command.")
return
# set a new entry so we can deal with it in the callback
new_crack_entry = {}
new_crack_entry['address'] = address
new_crack_entry['return_value'] = return_value
crack_cmds.append(new_crack_entry)
target = get_target()
# we want a global breakpoint
breakpoint = target.BreakpointCreateByAddress(address)
# when the breakpoint is hit we get this callback executed
breakpoint.SetScriptCallbackFunction('lldbinit.crackcmd_callback')
def crackcmd_callback(frame, bp_loc, internal_dict):
global crack_cmds
# retrieve address we just hit
current_bp = bp_loc.GetLoadAddress()
print("[+] warning: hit crack command breakpoint at 0x{:x}".format(current_bp))
crack_entry = None
for tmp_entry in crack_cmds:
if tmp_entry['address'] == current_bp:
crack_entry = tmp_entry
break
if crack_entry is None:
print("[-] error: current breakpoint not found in list.")
return
# we can just set the register in the frame and return empty SBValue
if is_x64():
frame.reg["rax"].value = str(crack_entry['return_value']).rstrip('L')
elif is_arm():
frame.reg["x0"].value = str(crack_entry['return_value']).rstrip('L')
elif is_i386():
frame.reg["eax"].value = str(crack_entry['return_value']).rstrip('L')
else:
print("[-] error: unsupported architecture.")
return
get_thread().ReturnFromFrame(frame, lldb.SBValue())
get_process().Continue()
# set a breakpoint with a command that doesn't return, just sets the specified register to a value
def cmd_crackcmd_noret(debugger, command, result, dict):
'''Set a breakpoint and a register to a value when hit. Use \'crackcmd_noret help\' for more information.'''
help = """
Sets the specified register to a value when the breakpoint at specified address is hit, and resumes execution.
Syntax: crackcmd_noret <address> <register> <value>
"""
global crack_cmds_noret
cmd = command.split()
if len(cmd) == 0:
print("[-] error: please check required arguments.")
print("")
print(help)
return
if len(cmd) > 0 and cmd[0] == "help":
print(help)
return
if len(cmd) < 3:
print("[-] error: please check required arguments.")
print("")
print(help)
return
address = evaluate(cmd[0])
register = cmd[1]
value = evaluate(cmd[2])
if address is None:
print("[-] error: invalid address.")
print("")
print(help)
return
# check if register is set and valid
if is_x64():
valid = [ "rip","rax","rbx","rbp","rsp","rdi","rsi","rdx","rcx","r8","r9","r10","r11","r12","r13","r14","r15" ]
if register not in valid:
print("[-] error: invalid register for x64 architecture.")
print(help)
return
elif is_arm():
valid = [ "x0","x1","x2","x3","x4","x5","x6","x7","x8","x9","x10","x11","x12","x13","x14","x15","x16","x17","x18","x19","x20","x21","x22","x23","x24","x25","x26","x27","x28","fp","lr","sp","pc","cpsr" ]
if register not in valid:
print("[-] error: invalid register for arm64 architecture.")
print(help)
return
elif is_i386():
valid = [ "eip", "eax", "ebx", "ebp", "esp", "edi", "esi", "edx", "ecx" ]
if register not in valid:
print("[-] error: invalid register for i386 architecture.")
print(help)
return
if value is None:
print("[-] error: invalid value.")
print("")
print(help)
return
for tmp_entry in crack_cmds_noret:
if tmp_entry['address'] == address:
print("[-] error: address already contains a crack command.")
return
# set a new entry so we can deal with it in the callback
new_crack_entry = {}
new_crack_entry['address'] = address
new_crack_entry['register'] = register
new_crack_entry['value'] = value
crack_cmds_noret.append(new_crack_entry)
target = get_target()
# we want a global breakpoint
breakpoint = target.BreakpointCreateByAddress(address)
# when the breakpoint is hit we get this callback executed
breakpoint.SetScriptCallbackFunction('lldbinit.crackcmd_noret_callback')
def crackcmd_noret_callback(frame, bp_loc, internal_dict):
global crack_cmds_noret
# retrieve address we just hit
current_bp = bp_loc.GetLoadAddress()
print("[+] warning: hit crack command no ret breakpoint at 0x{:x}".format(current_bp))
crack_entry = None
for tmp_entry in crack_cmds_noret:
if tmp_entry['address'] == current_bp:
crack_entry = tmp_entry
break
if crack_entry is None:
print("[-] error: current breakpoint not found in list.")
return
# must be a string!
frame.reg[crack_entry['register']].value = str(crack_entry['value']).rstrip('L')
get_process().Continue()
# -----------------------
# Memory related commands
# -----------------------
'''
Output nice memory hexdumps...
'''
# display byte values and ASCII characters
def cmd_db(debugger, command, result, dict):
'''Display hex dump in byte values and ASCII characters. Use \'db help\' for more information.'''
help = """
Display memory hex dump in byte length and ASCII representation.
Syntax: db [<address>] [<size>]
Notes:
- If no address specified it will dump current instruction pointer address.
- Default size is 256 bytes.
- Expressions are supported, do not use spaces between operators.
"""
global GlobalListOutput
GlobalListOutput = []
size = 0x100
cmd = command.split()
if len(cmd) == 0:
dump_addr = get_current_pc()
if dump_addr == 0:
print("[-] error: invalid current address.")
return
elif len(cmd) == 1:
if cmd[0] == "help":
print(help)
return
dump_addr = evaluate(cmd[0])
if dump_addr is None:
print("[-] error: invalid address value.")
print("")
print(help)
return
elif len(cmd) == 2:
if cmd[0] == "help":
print(help)
return
dump_addr = evaluate(cmd[0])
if dump_addr is None:
print("[-] error: invalid address value.")
print("")
print(help)
return
size = evaluate(cmd[1])
if size is None:
print("[-] error: invalid size value.")
print("")
print(help)
return
else:
print("[-] error: please insert a start address.")
print("")
print(help)
return
err = lldb.SBError()
membuf = get_process().ReadMemory(dump_addr, size, err)
if not err.Success():
print("[-] error: failed to read memory from address 0x{:x}".format(dump_addr))
result.PutCString("".join(GlobalListOutput))
result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
return
if POINTER_SIZE == 4:
output(COLOR_HEXDUMP_HEADER + "[0x0000:0x%.08X]" % dump_addr + RESET)
else:
output(COLOR_HEXDUMP_HEADER + "[0x0000:0x%.016lX]" % dump_addr + RESET)
output(COLOR_HEXDUMP_HEADER + "------------------------------------------------------" + RESET)
output(BOLD + COLOR_HEXDUMP_HEADER + "[data]" + RESET + "\n")
offset = 0
hex_str = ""
ascii_str = ""
while offset < len(membuf):
hex_str += BOLD + COLOR_HEXDUMP_ADDR
hex_str += "0x{0:08x} ".format(offset+dump_addr) if POINTER_SIZE == 4 else "0x{0:016x} ".format(offset+dump_addr)
hex_str += RESET
for i in range(16):
if offset + i < len(membuf):
byte = membuf[offset + i]
# python 2
if is_python2():
hex_str += "{0:02x} ".format(ord(byte))
ascii_str += byte if 32 <= ord(byte) <= 126 else "."
else:
hex_str += "{0:02x} ".format(byte)
ascii_str += chr(byte) if 32 <= byte <= 126 else "."
else:
# no data so just print empty space
hex_str += " "
ascii_str += " "
# split hexdump at 8 bytes
if i % 8 == 7:
hex_str += " "
hex_str += " " + BOLD + COLOR_HEXDUMP_ASCII + ascii_str + RESET + "\n"
ascii_str = ""
offset += 16
# put output into the print buffer
output(hex_str)
result.PutCString("".join(GlobalListOutput))
result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
# display word values and ASCII characters
def cmd_dw(debugger, command, result, dict):
''' Display hex dump in word values and ASCII characters. Use \'dw help\' for more information.'''
help = """
Display memory hex dump in word length and ASCII representation.
Syntax: dw [<address>] [<size>]
Notes:
- If no address specified it will dump current instruction pointer address.
- Default size is 256 bytes. Must be multiple of 16 bytes.
- Expressions are supported, do not use spaces between operators.
"""
global GlobalListOutput
GlobalListOutput = []
size = 0x100
cmd = command.split()
if len(cmd) == 0:
dump_addr = get_current_pc()
if dump_addr == 0:
print("[-] error: invalid current address.")
return
elif len(cmd) == 1:
if cmd[0] == "help":
print(help)
return
dump_addr = evaluate(cmd[0])
if dump_addr is None:
print("[-] error: invalid address value.")
print("")
print(help)
return
elif len(cmd) == 2:
if cmd[0] == "help":
print(help)
return
dump_addr = evaluate(cmd[0])
if dump_addr is None:
print("[-] error: invalid address value.")
print("")
print(help)
return
size = evaluate(cmd[1])
if size is None:
print("[-] error: invalid size value.")
print("")
print(help)
return
else:
print("[-] error: please insert a start address.")
print("")
print(help)
return
if size % 16:
print("[-] size must be multiple of 16 bytes.")
return
err = lldb.SBError()
membuf = get_process().ReadMemory(dump_addr, size, err)
if not err.Success():
print("[-] error: failed to read memory from address 0x{:x}".format(dump_addr))
result.PutCString("".join(GlobalListOutput))
result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
return
if POINTER_SIZE == 4:
output(COLOR_HEXDUMP_HEADER + "[0x0000:0x%.08X]" % dump_addr + RESET)
else:
output(COLOR_HEXDUMP_HEADER + "[0x0000:0x%.016lX]" % dump_addr + RESET)
output(COLOR_HEXDUMP_HEADER + "--------------------------------------------" + RESET)
output(BOLD + COLOR_HEXDUMP_HEADER + "[data]" + RESET + "\n")
index = 0
while index < size:
data = struct.unpack("HHHHHHHH", membuf[index:index+0x10])
szaddr = "0x%.016lX" % dump_addr
if POINTER_SIZE == 4:
szaddr = "0x%.08X" % dump_addr
data_str = COLOR_HEXDUMP_DATA + " {:04x} {:04x} {:04x} {:04x} {:04x} {:04x} {:04x} {:04x} ".format(
data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]) + RESET
output(BOLD + COLOR_HEXDUMP_ADDR + "{:s} :".format(szaddr) + RESET + data_str + BOLD + COLOR_HEXDUMP_ASCII + "{:s}".format(quotechars(membuf[index:index+0x10])) + RESET)
if index + 0x10 != size:
output("\n")
index += 0x10
dump_addr += 0x10
result.PutCString("".join(GlobalListOutput))
result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
# display dword values and ASCII characters
def cmd_dd(debugger, command, result, dict):
''' Display hex dump in double word values and ASCII characters. Use \'dd help\' for more information.'''
help = """
Display memory hex dump in double word length and ASCII representation.
Syntax: dd [<address>] [<size>]
Notes:
- If no address specified it will dump current instruction pointer address.
- Default size is 256 bytes. Must be multiple of 16 bytes.
- Expressions are supported, do not use spaces between operators.
"""
global GlobalListOutput
GlobalListOutput = []
size = 0x100
cmd = command.split()
if len(cmd) == 0:
dump_addr = get_current_pc()
if dump_addr == 0:
print("[-] error: invalid current address.")
return
elif len(cmd) == 1:
if cmd[0] == "help":
print(help)
return
dump_addr = evaluate(cmd[0])
if dump_addr is None:
print("[-] error: invalid address value.")
print("")
print(help)
return
elif len(cmd) == 2:
if cmd[0] == "help":
print(help)
return
dump_addr = evaluate(cmd[0])
if dump_addr is None:
print("[-] error: invalid address value.")
print("")
print(help)
return
size = evaluate(cmd[1])
if size is None:
print("[-] error: invalid size value.")
print("")
print(help)
return
else:
print("[-] error: please insert a start address.")
print("")
print(help)
return
if size % 16:
print("[-] size must be multiple of 16 bytes.")
return
err = lldb.SBError()
membuf = get_process().ReadMemory(dump_addr, size, err)
if not err.Success():
print("[-] error: failed to read memory from address 0x{:x}".format(dump_addr))
result.PutCString("".join(GlobalListOutput))
result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
return
if POINTER_SIZE == 4:
output(COLOR_HEXDUMP_HEADER + "[0x0000:0x%.08X]" % dump_addr + RESET)
else:
output(COLOR_HEXDUMP_HEADER + "[0x0000:0x%.016lX]" % dump_addr + RESET)
output(COLOR_HEXDUMP_HEADER + "----------------------------------------" + RESET)
output(BOLD + COLOR_HEXDUMP_HEADER + "[data]" + RESET + "\n")
index = 0
while index < size:
(mem0, mem1, mem2, mem3) = struct.unpack("IIII", membuf[index:index+0x10])
szaddr = "0x%.016lX" % dump_addr
if POINTER_SIZE == 4:
szaddr = "0x%.08X" % dump_addr
data_str = COLOR_HEXDUMP_DATA + " {:08x} {:08x} {:08x} {:08x} ".format(mem0, mem1, mem2, mem3) + RESET
output(BOLD + COLOR_HEXDUMP_ADDR + "{:s} :".format(szaddr) + RESET + data_str + BOLD + COLOR_HEXDUMP_ASCII + "{:s}".format(quotechars(membuf[index:index+0x10])) + RESET)
if index + 0x10 != size:
output("\n")
index += 0x10
dump_addr += 0x10
result.PutCString("".join(GlobalListOutput))
result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
# display quad values
def cmd_dq(debugger, command, result, dict):
''' Display hex dump in quad values. Use \'dq help\' for more information.'''
help = """
Display memory hex dump in quad word length.
Syntax: dq [<address>] [<size>]
Notes:
- If no address specified it will dump current instruction pointer address.
- Default size is 256 bytes. Must be multiple of 16 bytes.
- Expressions are supported, do not use spaces between operators.
"""
global GlobalListOutput
GlobalListOutput = []
size = 0x100
cmd = command.split()
if len(cmd) == 0:
dump_addr = get_current_pc()
if dump_addr == 0:
print("[-] error: invalid current address.")
return
elif len(cmd) == 1:
if cmd[0] == "help":
print(help)
return
dump_addr = evaluate(cmd[0])
if dump_addr is None:
print("[-] error: invalid address value.")
print("")
print(help)
return
elif len(cmd) == 2:
if cmd[0] == "help":
print(help)
return
dump_addr = evaluate(cmd[0])
if dump_addr is None:
print("[-] error: invalid address value.")
print("")
print(help)
return
size = evaluate(cmd[1])
if size is None:
print("[-] error: invalid size value.")
print("")
print(help)
return
else:
print("[-] error: please insert a start address.")
print("")
print(help)
return
if size % 16:
print("[-] size must be multiple of 16 bytes.")
return
err = lldb.SBError()
membuf = get_process().ReadMemory(dump_addr, size, err)
if not err.Success():
print("[-] error: failed to read memory from address 0x{:x}".format(dump_addr))
result.PutCString("".join(GlobalListOutput))
result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
return
if POINTER_SIZE == 4:
output(COLOR_HEXDUMP_HEADER + "[0x0000:0x%.08X]" % dump_addr + RESET)
else:
output(COLOR_HEXDUMP_HEADER + "[0x0000:0x%.016lX]" % dump_addr + RESET)
output(COLOR_HEXDUMP_HEADER + "----------------------------------------------------------------------------------------" + RESET)
output(BOLD + COLOR_HEXDUMP_HEADER + "[data]" + RESET + "\n")
index = 0
while index < size:
(mem0, mem1, mem2, mem3) = struct.unpack("QQQQ", membuf[index:index+0x20])
szaddr = "0x%.016lX" % dump_addr
if POINTER_SIZE == 4:
szaddr = "0x%.08X" % dump_addr
data_str = COLOR_HEXDUMP_DATA + " {:016x} {:016x} {:016x} {:016x} ".format(mem0, mem1, mem2, mem3) + RESET
output(BOLD + COLOR_HEXDUMP_ADDR + "{:s} :".format(szaddr) + RESET + data_str + BOLD + COLOR_HEXDUMP_ASCII + "{:s}".format(quotechars(membuf[index:index+0x20])) + RESET)
if index + 0x20 != size:
output("\n")
index += 0x20
dump_addr += 0x20
result.PutCString("".join(GlobalListOutput))
result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
# thx poupas :-)
def byte_to_int(b):
if isinstance(b, int):
return b
return ord(b)
def hexdump(addr, chars, sep, width, lines=5):
l = []
line_count = 0
while chars:
if line_count >= lines:
break
line = chars[:width]
chars = chars[width:]
line = line.ljust(width, b'\000')
szaddr = "0x%.016lX" % addr
if POINTER_SIZE == 4:
szaddr = "0x%.08X" % addr
out = BOLD + COLOR_HEXDUMP_ADDR + "{:s} :".format(szaddr) + RESET + COLOR_HEXDUMP_DATA + " {:s}{:s} ".format(sep.join( "%02X" % byte_to_int(c) for c in line ), sep) + RESET + BOLD + COLOR_HEXDUMP_ASCII + "{:s}".format(quotechars(line)) + RESET
l.append(out)
addr += 0x10
line_count = line_count + 1
return "\n".join(l)
def quotechars( chars ):
data = ""
for x in bytearray(chars):
if x >= 0x20 and x <= 0x7E:
data += chr(x)
else:
data += "."
return data
# XXX: help
# find memory command - lldb has 'memory find' but requires a start and end address where to search
# this version will seek in all available process memory regions
def cmd_findmem(debugger, command, result, dict):
'''Search memory'''
help = """
[options]
-s searches for specified string
-b searches binary (eg. -b 4142434445 will find ABCDE anywhere in mem)
-d searches dword (eg. -d 0x41414141)
-q searches qword (eg. -d 0x4141414141414141)
-f loads patern from file if it's tooooo big to fit into any of specified options
-c specify if you want to find N occurances (default is all)
-v verbose output
"""
global GlobalListOutput
GlobalListOutput = []
arg = str(command)
parser = argparse.ArgumentParser(prog="findmem")
parser.add_argument("-s", "--string", help="Search unicode string")
parser.add_argument("-b", "--binary", help="Search binary string")
parser.add_argument("-d", "--dword", help="Find dword (native packing)")
parser.add_argument("-q", "--qword", help="Find qword (native packing)")
parser.add_argument("-f", "--file" , help="Load find pattern from file")
parser.add_argument("-c", "--count", help="How many occurances to find, default is all")
parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output such as current memory region being searched")
# XXX: problem with strings with spaces
parser = parser.parse_args(arg.split())
if parser.string is not None:
search_string = parser.string.encode('utf-8')
elif parser.binary is not None:
if parser.binary[0:2] == "0x":
parser.binary = parser.binary[2:]
if is_python2():
search_string = parser.binary.decode("hex")
else:
search_string = bytes.fromhex(parser.binary)
elif parser.dword is not None:
dword = evaluate(parser.dword)
if dword is None:
print("[-] error evaluating : " + parser.dword)
return
search_string = struct.pack("I", dword & 0xffffffff)
elif parser.qword is not None:
qword = evaluate(parser.qword)
if qword is None:
print("[-] error evaluating : " + parser.qword)
return
search_string = struct.pack("Q", qword & 0xffffffffffffffff)
elif parser.file is not None:
f = 0
try:
f = open(parser.file, "rb")
except OSError:
return
search_string = f.read()
f.close()
else:
print("[-] Wrong option... use findmem --help")
return
count = -1
if parser.count is not None:
count = evaluate(parser.count)
if count is None:
print("[-] error evaluating count : " + parser.count)
return
process = get_process()
target = get_target()
# retrieve SBMemoryRegionInfoList list
regions = process.GetMemoryRegions()
# iterate list of SBMemoryRegionInfo
scan_list = []
for i in range(0, regions.GetSize()):
reg = lldb.SBMemoryRegionInfo()
t = regions.GetMemoryRegionAtIndex(i, reg)
isexec = reg.IsExecutable()
isread = reg.IsReadable()
iswrite = reg.IsWritable()
tmp = []
tmp.append(reg.GetRegionBase())
tmp.append(reg.GetRegionEnd())
scan_list.append(tmp)
for x in scan_list:
mem_name = ""
mem_start = x[0]
mem_end = x[1]
mem_size = mem_end - mem_start
if parser.verbose:
print("[+] Searching 0x{:x} to 0x{:x} size:0x{:x}".format(mem_start, mem_end, mem_size))
err = lldb.SBError()
# XXX: this is going to use a lot of memory for large zones
# we should split reading?
membuf = process.ReadMemory(mem_start, mem_size, err)
if not err.Success():
#output(str(err));
#result.PutCString("".join(GlobalListOutput));
continue
off = 0
base_displayed = 0
# slice indexing starts at 0
start_search = 0
while True:
if count == 0:
return
# we can pass slice notation here
# the original would slice the buffer - that seems to create a new copy in Python?
idx = membuf.find(search_string, start_search)
if idx == -1:
break
if count != -1:
count = count - 1
# the offset is relative to the slice start
off = idx
GlobalListOutput = []
if POINTER_SIZE == 4:
ptrformat = "0x%.08X"
else:
ptrformat = "0x%.016lX"
output(RESET + "Found at : ")
output(GREEN + ptrformat % (mem_start + off) + RESET)
if base_displayed == 0:
output(" base : ")
output(YELLOW + ptrformat % mem_start + RESET)
base_displayed = 1
else:
output(" ")
if POINTER_SIZE == 4:
output(" " * 8)
else:
output(" " * 16)
# try to find where this match address belongs to
# this has a problem when searching the dyld cache memory area
# the libraries that are mapped in the process do have a file path available
# but the others that are part of it can trigger match but no file path is available
# since they aren't linked to the target
file_sbaddr = lldb.SBAddress(mem_start + off, target)
module = file_sbaddr.module
module_name = module.file.fullpath
output(" off : 0x%.08X %s (%s)" % (off, mem_name, module_name))
print("".join(GlobalListOutput))
# set the slice pointer for next search
start_search = idx+len(search_string)
return
# display information about process memory regions similar to vmmap
# contains less information in particular the type of memory region
def cmd_showregions(debugger, command, result, dict):
'''Display memory regions information'''
help = """
Display memory regions similar to vmmap (but with less information)
Syntax: showregions
"""
cmd = command.split()
if len(cmd) > 0 and cmd[0] == "help":
print(help)
return
process = get_process()
target = get_target()
regions = process.GetMemoryRegions()
if POINTER_SIZE == 4:
ptrformat = "0x{:08x} 0x{:08x} 0x{:08x} {:s}{:s}{:s} {:^16s} {:<s}"
hdrformat = "{:^10s} {:^10s} {:^10s} {:^4s} {:^16s} {:^12s}\n-------------------------------------------------------------------------"
else:
ptrformat = "0x{:016x} 0x{:016x} 0x{:016x} {:s}{:s}{:s} {:^16s} {:<s}"
hdrformat = "{:^18s} {:^18s} {:^18s} {:^4s} {:^16s} {:>12s}\n--------------------------------------------------------------------------------------------------"
print(hdrformat.format("START", "END", "SIZE", "PROT", "TYPE", "PATH"))
for i in range(0, regions.GetSize()):
reg = lldb.SBMemoryRegionInfo()
t = regions.GetMemoryRegionAtIndex(i, reg)
r = '-'
w = '-'
x = '-'
if reg.IsReadable():
r = 'r'
if reg.IsWritable():
w = 'w'
if reg.IsExecutable():
x = 'x'
start = reg.GetRegionBase()
end = reg.GetRegionEnd()
size = end - start
err = lldb.SBError()
# try to find the type of region by reading some bytes
# and matching magic values
# XXX: we should read more bytes here?
membuf = process.ReadMemory(start, 4, err)
if not err.Success():
continue
data = struct.unpack("I", membuf)
hdr_name = ""
# XXX: add more magic
if data[0] == 0xfeedfacf:
hdr_name = "mach-o"
elif data[0] == 0x646c7964:
hdr_name = "dyld cache"
elif data[0] == 0xfeedface:
hdr_name = "mach-o"
# try to find if addresses belong to files
file_sbaddr = lldb.SBAddress(start, target)
module = file_sbaddr.module
module_name = module.file.fullpath
if module_name is None:
module_name = ""
try:
# older LLDB versions don't have this API available
# this doesn't seem to work anyway, returning None for all regions
name = reg.GetName()
if name is None:
print(ptrformat.format(start, end, size, r,w,x, hdr_name, module_name))
else:
print(ptrformat.format(start, end, size, r,w,x, name, module_name))
except Exception as e:
print(ptrformat.format(start, end, size, r,w,x, hdr_name, module_name))
return
def cmd_datawin(debugger, command, result, dict):
'''Configure address to display in data window. Use \'datawin help\' for more information.'''
help = """
Configure address to display in data window.
The data window display will be fixed to the address you set. Useful to observe strings being decrypted, etc.
Syntax: datawin <address>
Note: expressions are supported, do not use spaces between operators.
"""
global DATA_WINDOW_ADDRESS
cmd = command.split()
if len(cmd) == 0:
print("[-] error: please insert an address.")
print("")
print(help)
return
if cmd[0] == "help":
print(help)
return
dump_addr = evaluate(cmd[0])
if dump_addr is None:
print("[-] error: invalid address value.")
print("")
print(help)
DATA_WINDOW_ADDRESS = 0
return
DATA_WINDOW_ADDRESS = dump_addr
# ----------------------------------------------------------
# Functions to extract internal and process lldb information
# ----------------------------------------------------------
def is_python2():
if sys.version_info[0] < 3:
return True
return False
def get_arch():
target = get_target()
return target.triple.split('-')[0]
#return frame for stopped thread... there should be one at least...
def get_frame():
frame = None
# SBProcess supports thread iteration -> SBThread
for thread in get_process():
if thread.GetStopReason() != lldb.eStopReasonNone and thread.GetStopReason() != lldb.eStopReasonInvalid:
frame = thread.GetFrameAtIndex(0)
break
# this will generate a false positive when we start the target the first time because there's no context yet.
if frame is None:
raise Exception("[!] warning: get_frame() failed. Is the target binary started?")
return frame
def get_thread():
ret = None
# SBProcess supports thread iteration -> SBThread
for thread in get_process():
if thread.GetStopReason() != lldb.eStopReasonNone and thread.GetStopReason() != lldb.eStopReasonInvalid:
ret = thread
# XXX: bug? should break?
if ret is None:
print("[!] warning: get_thread() failed. Is the target binary started?")
return ret
def get_target():
target = lldb.debugger.GetSelectedTarget()
if not target:
raise Exception("[-] error: no target available. please add a target to lldb.")
return target
def get_process():
# process
# A read only property that returns an lldb object that represents the process (lldb.SBProcess) that this target owns.
return get_target().process
# evaluate an expression and return the value it represents
def evaluate(command):
frame = get_frame()
if frame is not None:
value = frame.EvaluateExpression(command)
if not value.IsValid():
return None
try:
value = int(value.GetValue(), base=10)
return value
except Exception as e:
print("[-] error: exception on evaluate: " + str(e))
return None
# use the target version - if no target exists we can't do anything about it
else:
target = get_target()
if target is None:
return None
value = target.EvaluateExpression(command)
if not value.IsValid():
return None
try:
value = int(value.GetValue(), base=10)
return value
except Exception as e:
print("[-] error: exception on evaluate: " + str(e))
return None
def is_i386():
arch = get_arch()
return arch == "i386"
def is_x64():
arch = get_arch()
return arch.startswith("x86_64")
def is_arm():
arch = get_arch()
# Linux returns aarch64 instead of arm64* for macOS/iOS
return arch.startswith("arm64") or arch == "aarch64"
def get_pointer_size():
poisz = evaluate("sizeof(long)")
return poisz
# from https://github.com/facebook/chisel/blob/main/fbchisellldbobjcruntimehelpers.py
# returns a string with an expression to evaluate to retrieve the target object
def get_instance_object():
instanceObject = None
if is_i386():
# at the call to objc_msgSend esp contains object, esp+4 the selector
instanceObject = '*(id*)($esp)'
elif is_x64():
instanceObject = '(id)$rdi'
elif is_arm():
instanceObject = '(id)$x0'
return instanceObject
# -------------------------
# Register related commands
# -------------------------
# return the int value of a general purpose register
def get_gp_register(reg_name):
regs = get_registers("general purpose")
if regs is None:
return 0
for reg in regs:
if reg_name == reg.GetName():
#return int(reg.GetValue(), 16)
return reg.unsigned
return 0
def get_gp_registers():
regs = get_registers("general purpose")
if regs is None:
return 0
registers = {}
for reg in regs:
reg_name = reg.GetName()
registers[reg_name] = reg.unsigned
return registers
def get_register(reg_name):
regs = get_registers("general purpose")
if regs is None:
return "0"
for reg in regs:
if reg_name == reg.GetName():
return reg.GetValue()
return "0"
def get_registers(kind):
"""Returns the registers given the frame and the kind of registers desired.
Returns None if there's no such kind.
"""
frame = get_frame()
if frame is None:
return None
registerSet = frame.GetRegisters() # Return type of SBValueList.
for value in registerSet:
if kind.lower() in value.GetName().lower():
return value
return None
# retrieve current instruction pointer via platform independent $pc register
def get_current_pc():
frame = get_frame()
if frame is None:
return 0
pc = frame.FindRegister("pc")
return int(pc.GetValue(), 16)
# retrieve current stack pointer via registers information
def get_current_sp():
if is_i386():
sp_addr = get_gp_register("esp")
elif is_x64():
sp_addr = get_gp_register("rsp")
elif is_arm():
sp_addr = get_gp_register("sp")
else:
print("[-] error: wrong architecture.")
return 0
return sp_addr
# function that updates given register
# used for register aliases to replace individual commands per register
def cmd_update_register(debugger, command, result, dict):
help = """
Update given register with a new value.
Syntax: update_register <register name> <value>
Where value can be a single value or an expression.
Note: if using the register aliases only the value is required for those commands
"""
cmd = command.split()
if len(cmd) == 0:
print("[-] error: command requires arguments.")
print("")
print(help)
return
if cmd[0] == "help":
print(help)
return
if len(cmd) != 2:
print("[-] error: missing arguments.")
print(help)
return
register = cmd[0]
value = evaluate(cmd[1])
if value is None:
print("[-] error: invalid input value.")
print("")
print(help)
return
# test if register exists for current arch being debugged
valid_reg = get_frame().reg[register]
if valid_reg is None:
arch = get_arch()
print("[-] error: invalid register - trying to set register for wrong arch? current target arch: {:s}".format(arch))
return
# we need to format because hex() will return string with an L and that will fail to update register
get_frame().reg[register].value = format(value, '#x')
# -----------------------------
# modify eflags/rflags commands
# -----------------------------
def modify_eflags(flag):
# read the current value so we can modify it
if is_x64():
eflags = get_gp_register("rflags")
elif is_i386():
eflags = get_gp_register("eflags")
else:
print("[-] error: unsupported architecture for this command.")
return
masks = { "CF":0, "PF":2, "AF":4, "ZF":6, "SF":7, "TF":8, "IF":9, "DF":10, "OF":11 }
if flag not in masks.keys():
print("[-] error: requested flag not available")
return
# we invert whatever value is set
if bool(eflags & (1 << masks[flag])):
eflags = eflags & ~(1 << masks[flag])
else:
eflags = eflags | (1 << masks[flag])
# finally update the value
if is_x64():
get_frame().reg["rflags"].value = format(eflags, '#x')
elif is_i386():
get_frame().reg["eflags"].value = format(eflags, '#x')
def modify_cpsr(flag):
if is_x64() or is_i386():
print("[-] error: unsupported architecture for this command.")
return
masks = { 'N': 31, 'Z': 30, 'C': 29, 'V': 28 }
if flag not in masks.keys():
print("[-] error: requested flag not available")
return
cpsr = get_gp_register("cpsr")
# we invert whatever value is set
if bool(cpsr & (1 << masks[flag])):
cpsr = cpsr & ~(1 << masks[flag])
else:
cpsr = cpsr | (1 << masks[flag])
get_frame().reg["cpsr"].value = format(cpsr, '#x')
# AArch64 NZCV register negative bit
def cmd_cfn(debugger, command, result, dict):
'''Change negative flag. Use \'cfn help\' for more information.'''
help = """
Flip current negative flag.
Syntax: cfn
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
modify_cpsr("N")
# AArch NZCV registger overflow bit
def cmd_cfv(debugger, command, result, dict):
'''Change overflow flag. Use \'cfv help\' for more information.'''
help = """
Flip current overflow flag.
Syntax: cfv
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
modify_cpsr("V")
def cmd_cfa(debugger, command, result, dict):
'''Change adjust flag. Use \'cfa help\' for more information.'''
help = """
Flip current adjust flag.
Syntax: cfa
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
modify_eflags("AF")
def cmd_cfc(debugger, command, result, dict):
'''Change carry flag. Use \'cfc help\' for more information.'''
help = """
Flip current carry flag.
Syntax: cfc
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
if is_arm():
modify_cpsr("C")
else:
modify_eflags("CF")
def cmd_cfd(debugger, command, result, dict):
'''Change direction flag. Use \'cfd help\' for more information.'''
help = """
Flip current direction flag.
Syntax: cfd
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
modify_eflags("DF")
def cmd_cfi(debugger, command, result, dict):
'''Change interrupt flag. Use \'cfi help\' for more information.'''
help = """
Flip current interrupt flag.
Syntax: cfi
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
modify_eflags("IF")
def cmd_cfo(debugger, command, result, dict):
'''Change overflow flag. Use \'cfo help\' for more information.'''
help = """
Flip current overflow flag.
Syntax: cfo
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
modify_eflags("OF")
def cmd_cfp(debugger, command, result, dict):
'''Change parity flag. Use \'cfp help\' for more information.'''
help = """
Flip current parity flag.
Syntax: cfp
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
modify_eflags("PF")
def cmd_cfs(debugger, command, result, dict):
'''Change sign flag. Use \'cfs help\' for more information.'''
help = """
Flip current sign flag.
Syntax: cfs
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
modify_eflags("SF")
def cmd_cft(debugger, command, result, dict):
'''Change trap flag. Use \'cft help\' for more information.'''
help = """
Flip current trap flag.
Syntax: cft
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
modify_eflags("TF")
def cmd_cfz(debugger, command, result, dict):
'''Change zero flag. Use \'cfz help\' for more information.'''
help = """
Flip current zero flag.
Syntax: cfz
"""
cmd = command.split()
if len(cmd) != 0:
if cmd[0] == "help":
print(help)
return
print("[-] error: command doesn't take any arguments.")
print("")
print(help)
return
if is_arm():
modify_cpsr("Z")
else:
modify_eflags("ZF")
def dump_eflags(eflags):
eflagsTuples = [('OF', 11), ('DF', 10), ('IF', 9), ('TF', 8), ('SF', 7), ('ZF', 6), ('AF', 4), ('PF', 2), ('CF', 0)]
# use the first character of each register key to output, lowercase if bit not set
out = ""
for flag, bitfield in eflagsTuples :
last = " "
# don't print a space on last bit
if bitfield == 0:
last = ""
if bool(eflags & (1 << bitfield)):
out += flag[0] + last
else:
out += flag[0].lower() + last
return out
# returns the result of a conditional AArch64 instruction and the flags condition text
# adapted from https://github.com/ant4g0nist/lisa.py/blob/dev/lisa.py
def dump_conditionalaarch64(cpsr):
# In AArch64 state, the NZCV register holds copies of the N, Z, C, and V condition flags.
# The processor uses them to determine whether or not to execute conditional instructions.
# The NZCV register contains the flags in bits[31:28].
# N: Set to 1 when the result of the operation is negative, cleared to 0 otherwise.
# Z: Set to 1 when the result of the operation is zero, cleared to 0 otherwise.
# C: Set to 1 when the operation results in a carry, cleared to 0 otherwise.
# V: Set to 1 when the operation causes overflow, cleared to 0 otherwise.
# LLDB contains this information in the CPSR register (which doesn't really exist in AArch64)
flags_table = {
31: "negative",
30: "zero",
29: "carry",
28: "overflow",
7: "interrupt",
6: "fast"
}
reason_dict = {
"eq": {True: "Z == 1", False: "Z == 0"},
"ne": {True: "Z == 0", False: "Z == 1"},
"hs": {True: "C == 1", False: "C == 0"},
"lo": {True: "C == 0", False: "C == 1"},
"lt": {True: "N != V", False: "N == V"},
"le": {True: "Z == 1 || N != V", False: "Z == 0 && N == V"},
"gt": {True: "Z == 0 && N == V", False: "Z == 1 || N != V"},
"ge": {True: "N == V", False: "N != V"},
"vs": {True: "V == 1", False: "V == 0"},
"vc": {True: "V == 0", False: "V == 1"},
"mi": {True: "N == 1", False: "N == 0"},
"pl": {True: "N == 0", False: "N == 1"},
"hi": {True: "C == 1 && Z == 0", False: "C == 0 || Z == 1"},
"ls": {True: "C == 0 || Z == 1", False: "C == 1 && Z == 0"},
}
branch_mnemos = {"cbnz", "cbz", "tbnz", "tbz"}
pc_addr = get_gp_register("pc")
mnemo = get_mnemonic(pc_addr)
operands = get_operands(pc_addr)
insn = get_instruction(pc_addr)
# failed to retrieve instruction
if insn.size == 0:
return False, ""
# we can test insn.is_branch property to check if it's a branch instruction
taken, reason = False, ""
# skip all processing if not a branch
if not mnemo.startswith("b.") and mnemo not in branch_mnemos is True:
return taken, reason
flags = dict((flags_table[k], k) for k in flags_table)
# compare/test and branch versions
if mnemo in branch_mnemos:
# x are 64 bit registers, w are 32 bit
if operands.startswith('x') or operands.startswith('w'):
# x = re.search('([a-z0-9]{2,3})', operands)
# extract each operand - they are comma separated
# cb have two, tb three operands
x = re.findall('[^,\s]+', operands)
# if we can't read the operands it's an error
if x is None:
return taken, reason
# retrieve the first operand register name
reg = x[0]
# and its value
op = get_gp_register(reg)
# now we can deal with the instructions and their conditional results
if mnemo=="cbnz":
if op != 0: taken, reason = True, "{} != 0".format(reg)
else: taken, reason = False, "{} == 0".format(reg)
elif mnemo=="cbz":
if op == 0: taken, reason = True, "{} == 0".format(reg)
else: taken, reason = False, "{} != 0".format(reg)
elif mnemo=="tbnz":
# retrieve the immediate value - 2nd operand from tb* instruction
# the imm is preceded by a # so we remove it
i = int(x[1][1:], 16)
if (op & 1<<i) != 0: taken, reason = True, "{} & 1 << {} != 0".format(reg,i)
else: taken, reason = False, "{} & 1 << {} == 0".format(reg,i)
elif mnemo=="tbz":
i = int(x[1][1:], 16)
if (op & 1<<i) == 0: taken, reason = True, "{} & 1 << {} == 0".format(reg,i)
else: taken, reason = False, "{} & 1 << {} != 0".format(reg,i)
return taken, reason
# process conditional branches
if mnemo.endswith("eq"):
taken = bool(cpsr&(1<<flags["zero"]))
reason = reason_dict["eq"][taken]
elif mnemo.endswith("ne"):
taken = not cpsr&(1<<flags["zero"])
reason = reason_dict["ne"][taken]
elif mnemo.endswith("hs"):
taken = bool(cpsr & (1<<flags["carry"]))
elif mnemo.endswith("lo"):
taken = not cpsr & (1<<flags["carry"])
reason = reason_dict["lo"][taken]
elif mnemo.endswith("lt"):
taken = bool(cpsr&(1<<flags["negative"])) != bool(cpsr&(1<<flags["overflow"]))
reason = reason_dict["lt"][taken]
elif mnemo.endswith("le"):
taken = bool(cpsr&(1<<flags["zero"])) or \
bool(cpsr&(1<<flags["negative"])) != bool(cpsr&(1<<flags["overflow"]))
reason = reason_dict["le"][taken]
elif mnemo.endswith("gt"):
taken = bool(cpsr&(1<<flags["zero"])) == 0 and \
bool(cpsr&(1<<flags["negative"])) == bool(cpsr&(1<<flags["overflow"]))
reason = reason_dict["gt"][taken]
elif mnemo.endswith("ge"):
taken = bool(cpsr&(1<<flags["negative"])) == bool(cpsr&(1<<flags["overflow"]))
reason = reason_dict["ge"][taken]
elif mnemo.endswith("vs"):
taken = bool(cpsr&(1<<flags["overflow"]))
reason = reason_dict["vs"][taken]
elif mnemo.endswith("vc"):
taken = not cpsr&(1<<flags["overflow"])
reason = reason_dict["vc"][taken]
elif mnemo.endswith("mi"):
taken = bool(cpsr&(1<<flags["negative"]))
reason = reason_dict["mi"][taken]
elif mnemo.endswith("pl"):
taken = not cpsr&(1<<flags["negative"])
reason = reason_dict["pl"][taken]
elif mnemo.endswith("hi"):
taken = bool(cpsr&(1<<flags["carry"])) and not cpsr&(1<<flags["zero"])
reason = reason_dict["hi"][taken]
elif mnemo.endswith("ls"):
taken = not cpsr&(1<<flags["carry"]) or bool(cpsr&(1<<flags["zero"]))
reason = reason_dict["ls"][taken]
return taken, reason
# function to dump the conditional jumps results
def dump_jumpx86(eflags):
# masks and flags from https://github.com/ant4g0nist/lisa.py
masks = { "CF":0, "PF":2, "AF":4, "ZF":6, "SF":7, "TF":8, "IF":9, "DF":10, "OF":11 }
flags = { key: bool(eflags & (1 << value)) for key, value in masks.items() }
error = lldb.SBError()
target = get_target()
if is_i386():
pc_addr = get_gp_register("eip")
elif is_x64():
pc_addr = get_gp_register("rip")
else:
print("[-] error: wrong architecture.")
return
mnemonic = get_mnemonic(pc_addr)
output_string=""
## opcode 0x77: JA, JNBE (jump if CF=0 and ZF=0)
## opcode 0x0F87: JNBE, JA
if "ja" == mnemonic or "jnbe" == mnemonic:
if not flags["CF"] and not flags["ZF"]:
output_string="Jump is taken (c = 0 and z = 0)"
else:
output_string="Jump is NOT taken (c = 0 and z = 0)"
## opcode 0x73: JAE, JNB, JNC (jump if CF=0)
## opcode 0x0F83: JNC, JNB, JAE (jump if CF=0)
elif "jae" == mnemonic or "jnb" == mnemonic or "jnc" == mnemonic:
if not flags["CF"]:
output_string="Jump is taken (c = 0)"
else:
output_string="Jump is NOT taken (c != 0)"
## opcode 0x72: JB, JC, JNAE (jump if CF=1)
## opcode 0x0F82: JNAE, JB, JC
elif "jb" == mnemonic or "jc" == mnemonic or "jnae" == mnemonic:
if flags["CF"]:
output_string="Jump is taken (c = 1)"
else:
output_string="Jump is NOT taken (c != 1)"
## opcode 0x76: JBE, JNA (jump if CF=1 or ZF=1)
## opcode 0x0F86: JBE, JNA
elif "jbe" == mnemonic or "jna" == mnemonic:
if flags["CF"] or flags["ZF"] == 1:
output_string="Jump is taken (c = 1 or z = 1)"
else:
output_string="Jump is NOT taken (c != 1 or z != 1)"
## opcode 0xE3: JCXZ, JECXZ, JRCXZ (jump if CX=0 or ECX=0 or RCX=0)
# XXX: we just need cx output...
elif "jcxz" == mnemonic or "jecxz" == mnemonic or "jrcxz" == mnemonic:
rcx = get_gp_register("rcx")
ecx = get_gp_register("ecx")
cx = get_gp_register("cx")
if ecx == 0 or cx == 0 or rcx == 0:
output_string="Jump is taken (cx = 0 or ecx = 0 or rcx = 0)"
else:
output_string="Jump is NOT taken (cx != 0 or ecx != 0 or rcx != 0)"
## opcode 0x74: JE, JZ (jump if ZF=1)
## opcode 0x0F84: JZ, JE, JZ (jump if ZF=1)
elif "je" == mnemonic or "jz" == mnemonic:
if flags["ZF"] == 1:
output_string="Jump is taken (z = 1)"
else:
output_string="Jump is NOT taken (z != 1)"
## opcode 0x7F: JG, JNLE (jump if ZF=0 and SF=OF)
## opcode 0x0F8F: JNLE, JG (jump if ZF=0 and SF=OF)
elif "jg" == mnemonic or "jnle" == mnemonic:
if flags["ZF"] == 0 and flags["SF"] == flags["OF"]:
output_string="Jump is taken (z = 0 and s = o)"
else:
output_string="Jump is NOT taken (z != 0 or s != o)"
## opcode 0x7D: JGE, JNL (jump if SF=OF)
## opcode 0x0F8D: JNL, JGE (jump if SF=OF)
elif "jge" == mnemonic or "jnl" == mnemonic:
if flags["SF"] == flags["OF"]:
output_string="Jump is taken (s = o)"
else:
output_string="Jump is NOT taken (s != o)"
## opcode: 0x7C: JL, JNGE (jump if SF != OF)
## opcode: 0x0F8C: JNGE, JL (jump if SF != OF)
elif "jl" == mnemonic or "jnge" == mnemonic:
if flags["SF"] != flags["OF"]:
output_string="Jump is taken (s != o)"
else:
output_string="Jump is NOT taken (s = o)"
## opcode 0x7E: JLE, JNG (jump if ZF = 1 or SF != OF)
## opcode 0x0F8E: JNG, JLE (jump if ZF = 1 or SF != OF)
elif "jle" == mnemonic or "jng" == mnemonic:
if flags["ZF"] == 1 or flags["SF"] != flags["OF"]:
output_string="Jump is taken (z = 1 or s != o)"
else:
output_string="Jump is NOT taken (z != 1 or s = o)"
## opcode 0x75: JNE, JNZ (jump if ZF = 0)
## opcode 0x0F85: JNE, JNZ (jump if ZF = 0)
elif "jne" == mnemonic or "jnz" == mnemonic:
if flags["ZF"] == 0:
output_string="Jump is taken (z = 0)"
else:
output_string="Jump is NOT taken (z != 0)"
## opcode 0x71: JNO (OF = 0)
## opcode 0x0F81: JNO (OF = 0)
elif "jno" == mnemonic:
if flags["OF"] == 0:
output_string="Jump is taken (o = 0)"
else:
output_string="Jump is NOT taken (o != 0)"
## opcode 0x7B: JNP, JPO (jump if PF = 0)
## opcode 0x0F8B: JPO (jump if PF = 0)
elif "jnp" == mnemonic or "jpo" == mnemonic:
if flags["PF"] == 0:
output_string="Jump is NOT taken (p = 0)"
else:
output_string="Jump is taken (p != 0)"
## opcode 0x79: JNS (jump if SF = 0)
## opcode 0x0F89: JNS (jump if SF = 0)
elif "jns" == mnemonic:
if flags["SF"] == 0:
output_string="Jump is taken (s = 0)"
else:
output_string="Jump is NOT taken (s != 0)"
## opcode 0x70: JO (jump if OF=1)
## opcode 0x0F80: JO (jump if OF=1)
elif "jo" == mnemonic:
if flags["OF"] == 1:
output_string="Jump is taken (o = 1)"
else:
output_string="Jump is NOT taken (o != 1)"
## opcode 0x7A: JP, JPE (jump if PF=1)
## opcode 0x0F8A: JP, JPE (jump if PF=1)
elif "jp" == mnemonic or "jpe" == mnemonic:
if flags["PF"] == 1:
output_string="Jump is taken (p = 1)"
else:
output_string="Jump is NOT taken (p != 1)"
## opcode 0x78: JS (jump if SF=1)
## opcode 0x0F88: JS (jump if SF=1)
elif "js" == mnemonic:
if flags["SF"] == 1:
output_string="Jump is taken (s = 1)"
else:
output_string="Jump is NOT taken (s != 1)"
# XXX: we should just return a string and the caller should do this work instead
if output_string:
if is_i386():
if "NOT" in output_string:
output(" " + COLOR_CONDITIONAL_NO + "=> {:s}".format(output_string) + RESET)
else:
output(" " + COLOR_CONDITIONAL_YES + "=> {:s}".format(output_string) + RESET)
elif is_x64():
if "NOT" in output_string:
output(" " + COLOR_CONDITIONAL_NO + "=> {:s}".format(output_string) + RESET)
else:
output(" " + COLOR_CONDITIONAL_YES + "=> {:s}".format(output_string) + RESET)
def showreg64(reg, val):
output(COLOR_REGNAME + " {:>3s}: ".format(reg.upper()) + RESET)
c = COLOR_REGVAL_MODIFIED
if val == old_x64[reg]:
c = COLOR_REGVAL
output(c + "0x%.016lX" % (val) + RESET)
old_x64[reg] = val
def reg64():
current = get_gp_registers()
# first register line + rflags
line = [ "rax", "rbx", "rbp", "rsp" ]
for reg in line:
r = current[reg]
showreg64(reg, r)
output(" ")
# align flags right side
output(" ")
rflags = current["rflags"]
f = dump_eflags(rflags)
output(COLOR_CPUFLAGS + f + RESET)
output("\n")
# second register line
line = [ "rdi", "rsi", "rdx", "rcx", "rip" ]
for reg in line:
r = current[reg]
showreg64(reg, r)
output("\n")
# third register line
line = [ "r8", "r9", "r10", "r11", "r12" ]
for reg in line:
r = current[reg]
showreg64(reg, r)
output("\n")
# fourth register line + jump decision if exists
line = [ "r13", "r14", "r15" ]
for reg in line:
r = current[reg]
showreg64(reg, r)
rflags = current["rflags"]
dump_jumpx86(rflags)
output("\n")
# last register line
line = [ "cs", "fs", "gs" ]
for reg in line:
r = current[reg]
output(COLOR_REGNAME + " {:>3s}: ".format(reg.upper()))
c = COLOR_REGVAL_MODIFIED
if r == old_x64[reg]:
c = COLOR_REGVAL
output(c + "%.04X" % (r) + RESET)
old_x64[reg] = r
output("\n")
def showreg32(reg, val):
output(COLOR_REGNAME + " {:>3s}: ".format(reg.upper()) + RESET)
c = COLOR_REGVAL_MODIFIED
if val == old_x86[reg]:
c = COLOR_REGVAL
output(c + "0x%.08X" % (val) + RESET)
old_x86[reg] = val
def reg32():
current = get_gp_registers()
# first register line + eflags
line = [ "eax", "ebx", "ecx", "edx" ]
for reg in line:
r = current[reg]
showreg32(reg, r)
output(" ")
eflags = current["eflags"]
f = dump_eflags(eflags)
output(COLOR_CPUFLAGS + f + RESET)
output("\n")
# second register line
line = [ "esi", "edi", "ebp", "esp", "eip" ]
for reg in line:
r = current[reg]
showreg32(reg, r)
output("\n")
# last register line + jump decision if exists
line = [ "cs", "ds", "es", "fs", "gs", "ss" ]
for reg in line:
r = current[reg]
output(COLOR_REGNAME + " {:>3s}: ".format(reg.upper()))
c = COLOR_REGVAL_MODIFIED
if r == old_x86[reg]:
c = COLOR_REGVAL
output(c + "%.04X" % (r) + RESET)
old_x86[reg] = r
eflags = current["eflags"]
dump_jumpx86(eflags)
output("\n")
def dump_cpsr(cpsr):
# XXX: some fields reserved in recent ARM specs so we should revise and set to latest?
# AArch32 - unused
cpsrTuples32 = [ ('N', 31), ('Z', 30), ('C', 29), ('V', 28), ('Q', 27), ('SSBS', 23),
('PAN', 22), ('DIT', 21), ('E', 9), ('A', 8), ('I', 7), ('F', 6) ]
# AArch64 - CPSR doesn't exist here
# https://developer.arm.com/documentation/den0024/a/Fundamentals-of-ARMv8
# https://medium.com/@deryugin.denis/poring-os-to-aarch64-a0a5dfa38c5d
# DAIF register holds A (SError interrupt mask), I (IRQ mask), F (FIQ mask) bits of old CPSR
# NZCV register holds N Z C V bits
# LLDB keeps the same information in the "emulated" cpsr register
cpsrTuples64 = [ ('N', 31), ('Z', 30), ('C', 29), ('V', 28), ('A', 8), ('I', 7), ('F', 6) ]
# use the first character of each register key to output, lowercase if bit not set
allFlags = ""
for flag, bitfield in cpsrTuples64 :
last = " "
# don't print space on last bit
if bitfield == 6:
last = ""
if bool(cpsr & (1 << bitfield)):
allFlags += flag + last
else:
allFlags += flag.lower() + last
return allFlags
def regarm64():
current = get_gp_registers()
# register display order (4 columns)
display = [
['x0', 'x8', 'x16', 'x24'],
['x1', 'x9', 'x17', 'x25'],
['x2', 'x10', 'x18', 'x26'],
['x3', 'x11', 'x19', 'x27'],
['x4', 'x12', 'x20', 'x28'],
['x5', 'x13', 'x21', 'fp' ],
['x6', 'x14', 'x22', 'lr' ],
['x7', 'x15', 'x23', 'sp' ]
]
for row in display:
for col in row:
reg_name = col
output(COLOR_REGNAME + " {:>3s}: ".format(reg_name.upper()) + RESET)
reg_value = current[reg_name]
if reg_value == old_arm64[reg_name]:
c = COLOR_REGVAL
else:
c = COLOR_REGVAL_MODIFIED
output(c + "0x%.016X" % (reg_value) + RESET)
old_arm64[reg_name] = reg_value
output("\n")
output(COLOR_REGNAME + " PC: ")
pc = current["pc"]
if pc == old_arm64["pc"]:
c = COLOR_REGVAL
else:
c = COLOR_REGVAL_MODIFIED
output(c + "0x%.016X" % (pc) + RESET)
old_arm64["pc"] = pc
output(" ")
cpsr = current["cpsr"]
taken, reason = dump_conditionalaarch64(cpsr)
# add the () between the reason message
if reason != "":
reason = "({:s})".format(reason)
# format the rest of the line according to conditional or lack of
if taken:
linefmt = " " + COLOR_CPUFLAGS + "{:s}" + RESET + " " + COLOR_CONDITIONAL_YES + "=> Taken " + "{:s}" + RESET
elif reason != "":
linefmt = " " + COLOR_CPUFLAGS + "{:s}" + RESET + " " + COLOR_CONDITIONAL_NO + "=> Not taken " + "{:s}" + RESET
else:
linefmt = " " + COLOR_CPUFLAGS + "{:s}" + RESET + "{:s}"
flags = dump_cpsr(cpsr)
# XXX: should flags be always red? red in registers means they changed
output(linefmt.format(flags, reason) + "\n")
def print_registers():
if is_i386():
reg32()
elif is_x64():
reg64()
elif is_arm():
regarm64()
# ------------------------------
# Disassembler related functions
# ------------------------------
'''
Handles 'u' command which displays instructions. Also handles output of
'disassemble' command ...
'''
# XXX: help
def cmd_DumpInstructions(debugger, command, result, dict):
'''Dump instructions at certain address (SoftICE like u command style)'''
help = """ """
global GlobalListOutput
GlobalListOutput = []
target = get_target()
cmd = command.split()
if len(cmd) == 0 or len(cmd) > 2:
disassemble(get_current_pc(), CONFIG_DISASSEMBLY_LINE_COUNT)
elif len(cmd) == 1:
address = evaluate(cmd[0])
if address is None:
return
disassemble(address, CONFIG_DISASSEMBLY_LINE_COUNT)
else:
address = evaluate(cmd[0])
if address is None:
return
count = evaluate(cmd[1])
if count is None:
return
disassemble(address, count)
result.PutCString("".join(GlobalListOutput))
result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
# return the SBInstruction at input address
def get_instruction(target_addr):
err = lldb.SBError()
target = get_target()
# flavor argument only relevant to x86 targets - seems to work with ARM anyway
instruction_list = target.ReadInstructions(lldb.SBAddress(target_addr, target), 1, 'intel')
if instruction_list.GetSize() == 0:
print("[-] error: not enough instructions disassembled.")
return lldb.SBInstruction()
return instruction_list.GetInstructionAtIndex(0)
# return the instruction mnemonic at input address
def get_mnemonic(target_addr):
err = lldb.SBError()
target = get_target()
# flavor argument only relevant to x86 targets - seems to work with ARM anyway
instruction_list = target.ReadInstructions(lldb.SBAddress(target_addr, target), 1, 'intel')
if instruction_list.GetSize() == 0:
print("[-] error: not enough instructions disassembled.")
return ""
cur_instruction = instruction_list.GetInstructionAtIndex(0)
# much easier to use the mnemonic output instead of disassembling via cmd line and parse
mnemonic = cur_instruction.GetMnemonic(target)
return mnemonic
# returns the instruction operands
def get_operands(src_address):
err = lldb.SBError()
target = get_target()
# use current memory address
# needs to be this way to workaround SBAddress init bug
src_sbaddr = lldb.SBAddress()
src_sbaddr.SetLoadAddress(src_address, target)
instruction_list = target.ReadInstructions(src_sbaddr, 1, 'intel')
if instruction_list.GetSize() == 0:
print("[-] error: not enough instructions disassembled.")
return ""
cur_instruction = instruction_list[0]
return cur_instruction.GetOperands(target)
# find out the size of an instruction using internal disassembler
def get_inst_size(target_addr):
err = lldb.SBError()
target = get_target()
instruction_list = target.ReadInstructions(lldb.SBAddress(target_addr, target), 1, 'intel')
if instruction_list.GetSize() == 0:
print("[-] error: not enough instructions disassembled.")
return 0
cur_instruction = instruction_list.GetInstructionAtIndex(0)
return cur_instruction.size
# the disassembler we use on stop context
# we can customize output here instead of using the cmdline as before and grabbing its output
def disassemble(start_address, nrlines):
target = get_target()
if target is None:
return
# this init will set a file_addr instead of expected load_addr
# and so the disassembler output will be referenced to the file address
# instead of the current loaded memory address
# this is annoying because all RIP references will be related to file addresses
file_sbaddr = lldb.SBAddress(start_address, target)
# create a SBAddress object with the load_addr set so we can disassemble with
# current memory addresses and what is happening right now
# we use the empty init and then set the property which is read/write for load_addr
# this whole thing seems like a bug?
mem_sbaddr = lldb.SBAddress()
mem_sbaddr.SetLoadAddress(start_address, target)
# disassemble to get the file and memory version
# we could compute this by finding sections etc but this way it seems
# much simpler and faster
# this seems to be a bug or missing feature because there is no way
# to distinguish between the load and file addresses in the disassembler
# the reason might be because we can't create a SBAddress that has
# load_addr and file_addr set so that the disassembler can distinguish them
# somehow when we use file_sbaddr object the SBAddress GetLoadAddress()
# retrieves the correct memory address for the instruction while the
# SBAddress GetFileAddress() retrives the correct file address
# but the branch instructions addresses are the file addresses
# bug on SBAddress init implementation???
# this also has problems with symbols - the memory version doesn't have them
# flavor argument only relevant to x86 targets - works fine with ARM like this
instructions_mem = target.ReadInstructions(mem_sbaddr, nrlines, CONFIG_FLAVOR)
instructions_file = target.ReadInstructions(file_sbaddr, nrlines, CONFIG_FLAVOR)
if instructions_mem.GetSize() != instructions_file.GetSize():
print("[-] error: instructions arrays sizes are different.")
return
# find out the biggest instruction length and mnemonic length
# so we can have a uniform output
max_size = 0
max_mnem_size = 0
for i in instructions_mem:
if i.size > max_size:
max_size = i.size
mnem_len = len(i.GetMnemonic(target))
if mnem_len > max_mnem_size:
max_mnem_size = mnem_len
current_pc = get_current_pc()
# get info about module if there is a symbol
module = file_sbaddr.module
#module_name = module.file.GetFilename()
module_name = module.file.fullpath
count = 0
blockstart_symaddr = None
blockend_symaddr = None
for mem_inst in instructions_mem:
# get the same instruction but from the file version because we need some info from it
file_inst = instructions_file[count]
# try to extract the symbol (function) name from this location if it exists
# needs to be referenced to file because memory it doesn't work
symbol_name = instructions_file[count].addr.GetSymbol().GetName()
# if there is no symbol just display module where current instruction is
# also get rid of unnamed symbols since they are useless
if symbol_name is None or "___lldb_unnamed_symbol" in symbol_name:
if count == 0:
if CONFIG_ENABLE_COLOR == 1:
output(COLOR_SYMBOL_NAME + "@ {}:".format(module_name) + "\n" + RESET)
else:
output("@ {}:".format(module_name) + "\n")
elif symbol_name is not None:
# print the first time there is a symbol name and save its interval
# so we don't print again until there is a different symbol
file_symaddr = file_inst.GetAddress().GetFileAddress()
if blockstart_symaddr is None or (file_symaddr < blockstart_symaddr) or (file_symaddr >= blockend_symaddr):
if CONFIG_ENABLE_COLOR == 1:
output(COLOR_SYMBOL_NAME + "{} @ {}:".format(symbol_name, module_name) + "\n" + RESET)
else:
output("{} @ {}:".format(symbol_name, module_name) + "\n")
blockstart_symaddr = file_inst.GetAddress().GetSymbol().GetStartAddress().GetFileAddress()
blockend_symaddr = file_inst.GetAddress().GetSymbol().GetEndAddress().GetFileAddress()
# get the instruction bytes formatted as uint8
inst_data = mem_inst.GetData(target).uint8
mnem = mem_inst.GetMnemonic(target)
operands = mem_inst.GetOperands(target)
bytes_string = ""
if CONFIG_DISPLAY_DISASSEMBLY_BYTES == 1:
total_fill = max_size - mem_inst.size
total_spaces = mem_inst.size - 1
for x in inst_data:
bytes_string += "{:02x}".format(x)
if total_spaces > 0:
bytes_string += " "
total_spaces -= 1
if total_fill > 0:
# we need one more space because the last byte doesn't have space
# and if we are smaller than max size we are one space short
bytes_string += " " * total_fill
bytes_string += " " * total_fill
mnem_len = len(mem_inst.GetMnemonic(target))
if mnem_len < max_mnem_size:
missing_spaces = max_mnem_size - mnem_len
mnem += " " * missing_spaces
# the address the current instruction is loaded at
# we need to extract the address of the instruction and then find its loaded address
memory_addr = mem_inst.addr.GetLoadAddress(target)
# the address of the instruction in the current module
# for main exe it will be the address before ASLR if enabled, otherwise the same as current
# for modules it will be the address in the module code, not the address it's loaded at
# so we can use this address to quickly get to current instruction in module loaded at a disassembler
# without having to rebase everything etc
#file_addr = mem_inst.addr.GetFileAddress()
file_addr = file_inst.addr.GetFileAddress()
comment = ""
if file_inst.GetComment(target) != "":
comment = " ; " + file_inst.GetComment(target)
if current_pc == memory_addr:
# try to retrieve extra information if it's a branch instruction
# used to resolve indirect branches and try to extract Objective-C selectors
if mem_inst.DoesBranch():
flow_addr = get_indirect_flow_address(mem_inst.GetAddress().GetLoadAddress(target))
if flow_addr > 0:
flow_module_name = get_module_name(flow_addr)
symbol_info = ""
# try to solve the symbol for the target address
target_symbol_name = lldb.SBAddress(flow_addr,target).GetSymbol().GetName()
# if there is a symbol append to the string otherwise
# it will be empty and have no impact in output
if target_symbol_name is not None:
symbol_info = target_symbol_name + " @ "
if comment == "":
# remove space for instructions without operands
if mem_inst.GetOperands(target) == "":
comment = "; " + symbol_info + hex(flow_addr) + " @ " + flow_module_name
else:
comment = " ; " + symbol_info + hex(flow_addr) + " @ " + flow_module_name
else:
comment = comment + " " + hex(flow_addr) + " @ " + flow_module_name
# for arm64 targets there is a branch to a subroutine that does the real call to the objc_msgSend
# and the selector string is there - the symbol name does contain the name
# so we can either extract it from here or read the information from the subroutine
# or not worth the trouble since the symbol name always has lots of info
className, selectorName = get_objectivec_selector(current_pc)
if className != "":
if selectorName != "":
comment += " -> " + "[" + className + " " + selectorName + "]"
else:
comment += " -> " + "[" + className + "]"
output(COLOR_CURRENT_PC + "-> 0x{:x} (0x{:x}): {} {} {}{}".format(memory_addr, file_addr, bytes_string, mnem, operands, comment) + "\n" + RESET)
else:
output(" 0x{:x} (0x{:x}): {} {} {}{}".format(memory_addr, file_addr, bytes_string, mnem, operands, comment) + "\n")
count += 1
return
# ------------------------------------
# Commands that use external utilities
# ------------------------------------
def cmd_show_loadcmds(debugger, command, result, dict):
'''Show otool output of Mach-O load commands. Use \'show_loadcmds\' for more information.'''
help = """
Show otool output of Mach-O load commands.
Syntax: show_loadcmds <address>
Where address is start of Mach-O header in memory.
Note: expressions supported, do not use spaces between operators.
"""
error = lldb.SBError()
cmd = command.split()
if len(cmd) == 1:
if cmd[0] == "help":
print(help)
return
header_addr = evaluate(cmd[0])
if header_addr is None:
print("[-] error: invalid header address value.")
print("")
print(help)
return
else:
print("[-] error: please insert a valid Mach-O header address.")
print("")
print(help)
return
if not os.path.isfile("/usr/bin/otool"):
print("[-] error: /usr/bin/otool not found. Please install Xcode or Xcode command line tools.")
return
bytes_string = get_process().ReadMemory(header_addr, 4096*10, error)
if not error.Success():
print("[-] error: failed to read memory at 0x{:x}.".format(header_addr))
return
# open a temporary filename and set it to delete on close
f = tempfile.NamedTemporaryFile(delete=True)
f.write(bytes_string)
# pass output to otool
output_data = subprocess.check_output(["/usr/bin/otool", "-l", f.name])
# show the data
print(output_data)
# close file - it will be automatically deleted
f.close()
return
def cmd_show_header(debugger, command, result, dict):
'''Show otool output of Mach-O header. Use \'show_header\' for more information.'''
help = """
Show otool output of Mach-O header.
Syntax: show_header <address>
Where address is start of Mach-O header in memory.
Note: expressions supported, do not use spaces between operators.
"""
error = lldb.SBError()
cmd = command.split()
if len(cmd) == 1:
if cmd[0] == "help":
print(help)
return
header_addr = evaluate(cmd[0])
if header_addr is None:
print("[-] error: invalid header address value.")
print("")
print(help)
return
else:
print("[-] error: please insert a valid Mach-O header address.")
print("")
print(help)
return
if not os.path.isfile("/usr/bin/otool"):
print("[-] error: /usr/bin/otool not found. Please install Xcode or Xcode command line tools.")
return
# recent otool versions will fail so we need to read a reasonable amount of memory
# even just for the mach-o header
bytes_string = get_process().ReadMemory(header_addr, 4096*10, error)
if not error.Success():
print("[-] error: failed to read memory at 0x{:x}.".format(header_addr))
return
# open a temporary filename and set it to delete on close
f = tempfile.NamedTemporaryFile(delete=True)
f.write(bytes_string)
# pass output to otool
output_data = subprocess.check_output(["/usr/bin/otool", "-hv", f.name])
# show the data
print(output_data)
# close file - it will be automatically deleted
f.close()
return
# use keystone-engine.org to assemble
def assemble_keystone(arch, mode, code, syntax=0):
ks = keystone.Ks(arch, mode)
if syntax != 0:
ks.syntax = syntax
print("\nKeystone output:\n----------")
for inst in code:
try:
encoding, count = ks.asm(inst)
except keystone.KsError as e:
print("[-] error: keystone failed to assemble: {:s}".format(e))
return
output = []
output.append(inst)
output.append('->')
for i in encoding:
output.append("{:02x}".format(i))
print(" ".join(output))
def cmd_asm32(debugger, command, result, dict):
'''32 bit x86 interactive Keystone based assembler. Use \'asm32 help\' for more information.'''
help = """
32 bit x86 interactive Keystone based assembler.
Syntax: asm32
Type one instruction per line. Finish with \'end\' or \'stop\'.
Keystone set to KS_ARCH_X86 and KS_MODE_32.
Requires Keystone and Python bindings from www.keystone-engine.org.
"""
cmd = command.split()
if len(cmd) != 0 and cmd[0] == "help":
print(help)
return
if CONFIG_KEYSTONE_AVAILABLE == 0:
print("[-] error: keystone python bindings not available. Please install from www.keystone-engine.org.")
return
inst_list = []
while True:
try:
line = raw_input('Assemble ("stop" or "end" to finish): ')
except NameError:
line = input('Assemble ("stop" or "end" to finish): ')
if line == 'stop' or line == 'end':
break
inst_list.append(line)
assemble_keystone(keystone.KS_ARCH_X86, keystone.KS_MODE_32, inst_list)
def cmd_asm64(debugger, command, result, dict):
'''64 bit x86 interactive Keystone based assembler. Use \'asm64 help\' for more information.'''
help = """
64 bit x86 interactive Keystone based assembler
Syntax: asm64
Type one instruction per line. Finish with \'end\' or \'stop\'.
Keystone set to KS_ARCH_X86 and KS_MODE_64.
Requires Keystone and Python bindings from www.keystone-engine.org.
"""
cmd = command.split()
if len(cmd) != 0 and cmd[0] == "help":
print(help)
return
if CONFIG_KEYSTONE_AVAILABLE == 0:
print("[-] error: keystone python bindings not available. Please install from www.keystone-engine.org.")
return
inst_list = []
while True:
try:
line = raw_input('Assemble ("stop" or "end" to finish): ')
except NameError:
line = input('Assemble ("stop" or "end" to finish): ')
if line == 'stop' or line == 'end':
break
inst_list.append(line)
assemble_keystone(keystone.KS_ARCH_X86, keystone.KS_MODE_64, inst_list)
def cmd_arm32(debugger, command, result, dict):
'''32 bit ARM interactive Keystone based assembler. Use \'arm32 help\' for more information.'''
help = """
32 bit ARM interactive Keystone based assembler
Syntax: arm32
Type one instruction per line. Finish with \'end\' or \'stop\'.
Keystone set to KS_ARCH_ARM and KS_MODE_ARM.
Requires Keystone and Python bindings from www.keystone-engine.org.
"""
cmd = command.split()
if len(cmd) != 0 and cmd[0] == "help":
print(help)
return
if CONFIG_KEYSTONE_AVAILABLE == 0:
print("[-] error: keystone python bindings not available. Please install from www.keystone-engine.org.")
return
inst_list = []
while True:
try:
line = raw_input('Assemble ("stop" or "end" to finish): ')
except NameError:
line = input('Assemble ("stop" or "end" to finish): ')
if line == 'stop' or line == 'end':
break
inst_list.append(line)
assemble_keystone(keystone.KS_ARCH_ARM, keystone.KS_MODE_ARM, inst_list)
def cmd_armthumb(debugger, command, result, dict):
'''32 bit ARM Thumb interactive Keystone based assembler. Use \'armthumb help\' for more information.'''
help = """
32 bit ARM Thumb interactive Keystone based assembler
Syntax: armthumb
Type one instruction per line. Finish with \'end\' or \'stop\'.
Keystone set to KS_ARCH_ARM and KS_MODE_THUMB.
Requires Keystone and Python bindings from www.keystone-engine.org.
"""
cmd = command.split()
if len(cmd) != 0 and cmd[0] == "help":
print(help)
return
if CONFIG_KEYSTONE_AVAILABLE == 0:
print("[-] error: keystone python bindings not available. Please install from www.keystone-engine.org.")
return
inst_list = []
while True:
try:
line = raw_input('Assemble ("stop" or "end" to finish): ')
except NameError:
line = input('Assemble ("stop" or "end" to finish): ')
if line == 'stop' or line == 'end':
break
inst_list.append(line)
assemble_keystone(keystone.KS_ARCH_ARM, keystone.KS_MODE_THUMB, inst_list)
def cmd_arm64(debugger, command, result, dict):
'''64 bit ARM interactive Keystone based assembler. Use \'arm64 help\' for more information.'''
help = """
64 bit ARM interactive Keystone based assembler
Syntax: arm64
Type one instruction per line. Finish with \'end\' or \'stop\'.
Keystone set to KS_ARCH_ARM64 and KS_MODE_ARM.
Requires Keystone and Python bindings from www.keystone-engine.org.
"""
cmd = command.split()
if len(cmd) != 0 and cmd[0] == "help":
print(help)
return
if CONFIG_KEYSTONE_AVAILABLE == 0:
print("[-] error: keystone python bindings not available. Please install from www.keystone-engine.org.")
return
inst_list = []
while True:
try:
line = raw_input('Assemble ("stop" or "end" to finish): ')
except NameError:
line = input('Assemble ("stop" or "end" to finish): ')
if line == 'stop' or line == 'end':
break
inst_list.append(line)
assemble_keystone(keystone.KS_ARCH_ARM64, keystone.KS_MODE_ARM, inst_list)
# XXX: help
def cmd_IphoneConnect(debugger, command, result, dict):
'''Connect to debugserver running on iPhone'''
help = """ """
global GlobalListOutput
GlobalListOutput = []
if len(command) == 0 or ":" not in command:
output("Connect to remote iPhone debug server")
output("\n")
output("iphone <ipaddress:port>")
output("\n")
output("iphone 192.168.0.2:5555")
result.PutCString("".join(GlobalListOutput))
result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
return
res = lldb.SBCommandReturnObject()
lldb.debugger.GetCommandInterpreter().HandleCommand("platform select remote-ios", res)
if res.Succeeded():
output(res.GetOutput())
else:
output("[-] Error running platform select remote-ios")
result.PutCString("".join(GlobalListOutput))
result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
return
lldb.debugger.GetCommandInterpreter().HandleCommand("process connect connect://" + command, res)
if res.Succeeded():
output("[+] Connected to iphone at : " + command)
else:
output(res.GetOutput())
result.PutCString("".join(GlobalListOutput))
result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
def display_stack():
'''Hex dump current stack pointer'''
stack_addr = get_current_sp()
if stack_addr == 0:
return
err = lldb.SBError()
target = get_target()
membuf = get_process().ReadMemory(stack_addr, 0x100, err)
if not err.Success():
print("[-] error: failed to read memory at 0x{:x}.".format(stack_addr))
return
if len(membuf) == 0:
print("[-] error: not enough bytes read.")
return
output(hexdump(stack_addr, membuf, " ", 16, 4))
def display_data():
'''Hex dump current data window pointer'''
data_addr = DATA_WINDOW_ADDRESS
print(data_addr)
if data_addr == 0:
return
err = lldb.SBError()
target = get_target()
membuf = get_process().ReadMemory(data_addr, 0x100, err)
if not err.Success():
print("[-] error: failed to read memory at 0x{:x}.".format(data_addr))
return
if len(membuf) == 0:
print("[-] error: not enough bytes read.")
return
output(hexdump(data_addr, membuf, " ", 16, 4))
# workaround for lldb bug regarding RIP addressing outside main executable
def get_rip_relative_addr(src_address):
err = lldb.SBError()
target = get_target()
inst_size = get_inst_size(src_address)
if inst_size <= 1:
print("[-] error: instruction size too small.")
return 0
# XXX: problem because it's not just 2 and 5 bytes
# 0x7fff53fa2180 (0x1180): 0f 85 84 01 00 00 jne 0x7fff53fa230a ; stack_not_16_byte_aligned_error
offset_bytes = get_process().ReadMemory(src_address+1, inst_size-1, err)
if not err.Success():
print("[-] error: failed to read memory at 0x{:x}.".format(src_address))
return 0
if inst_size == 2:
data = struct.unpack("b", offset_bytes)
elif inst_size == 5:
data = struct.unpack("i", offset_bytes)
rip_call_addr = src_address + inst_size + data[0]
#output("source {:x} rip call offset {:x} {:x}\n".format(src_address, data[0], rip_call_addr))
return rip_call_addr
# find out the target address of an indirect instruction
# such as memory references and registers but also RIP relative calls
def get_indirect_flow_target(src_address):
err = lldb.SBError()
operand = get_operands(src_address).lower()
mnemonic = get_mnemonic(src_address)
# XXX: check allowed instructions here ?
# calls into a deferenced memory address (intel only)
if "word" in operand:
#output("dereferenced call\n")
deref_addr = 0
# first we need to find the address to dereference
# we can simplify by extracting just the contents and sending for evaluation
# we can have three cases
# reg + offset
# reg - offset
# reg
z = re.search(r'\[(.*?)\]', operand)
# we need to transform the register into a variable
# register + offset cases
if z.group(1).startswith("r") or z.group(1).startswith("e"):
value = get_frame().EvaluateExpression("$" + z.group(1))
# only offset
else:
value = get_frame().EvaluateExpression(z.group(1))
if not value.IsValid():
return 0
deref_addr = int(value.GetValue(), 10)
if "rip" in operand:
deref_addr = deref_addr + get_inst_size(src_address)
# simpler than using ReadUnsignedFromMemory()
call_target_addr = get_process().ReadPointerFromMemory(deref_addr, err)
if err.Success():
return call_target_addr
else:
return 0
# calls into a register - x86_64, i386, aarch64 (register or blr/br*)
# aarch64:
# BRAA Xn, Xm/SP : 30 08 1F D7 BRAA X1, X16
# BRAAZ Xn : 3F 08 1F D6 BRAAZ X1
# BRAB Xn, Xm/SP
# BRABZ Xn
# BLRAA Xn, Xm/SP : 28 09 3F D7 BLRAA X9, X8
# BLRAAZ Xn : 1F 0A 3F D6 BLRAAZ X16
# BLRAB Xn, Xm/SP
# BLRABZ Xn
elif operand.startswith('r') or operand.startswith('e') or operand.startswith('x'):
# these are PAC instructions that contain a modifier in a second register
# the modifier is zero for Z terminated functions so we only see one operand
if mnemonic in ('braa', 'brab', 'blraa', 'blrab'):
operand = operand.split(',')[0].strip(' ')
# remove the PAC
# XXX: what is really the number of bits? can't find good documentation on this :(
# https://github.com/lelegard/arm-cpusysregs/blob/main/docs/arm64e-on-macos.md
# says it's 47 bits for macOS
# https://googleprojectzero.blogspot.com/2019/02/examining-pointer-authentication-on.html
# talks about higher number of bits for iOS
value = get_frame().EvaluateExpression("$" + operand)
if not value.IsValid():
return 0
ret = int(value.GetValue(), 10)
if mnemonic in ('braa', 'braaz', 'brab', 'brabz', 'blraa', 'blraaz', 'blrab', 'blrabz'):
# let's go with 47 bits for now...
ret &= 0xFFFFFFFFFFFF
return ret
# RIP relative calls
# the disassembly output already contains the target address so we just need to extract it
# and don't need to compute anything ourselves
elif operand.startswith('0x'):
# the disassembler already did the dirty work for us
# so we just extract the address
x = re.search('(0x[0-9a-z]+)', operand)
if x is not None:
return int(x.group(1), 16)
return 0
def get_ret_address(pc_addr):
if is_arm():
target = get_target()
instruction = get_instruction(pc_addr)
mnemonic = instruction.GetMnemonic(target)
operands = instruction.GetOperands(target)
lr = get_gp_register("lr")
if lr == 0:
print("[-] error: failed to retrieve LR register.")
return -1
if mnemonic == 'ret':
# ret - x30 (LR) is default, register can be specified
if len(operands) == 0:
return lr
# 20 00 5f d6 - ret x1
elif operands.startswith('x') and len(operands) <= 3:
ret = get_gp_register(operands)
return ret
else:
print("[-] error: more than one operand in ret instruction.")
return -1
elif mnemonic in ( 'retaa', 'retab' ):
# PAC versions: retaa and retab - use LR
# https://developer.arm.com/documentation/dui0801/h/A64-General-Instructions/RETAA--RETAB
return lr
else:
err = lldb.SBError()
stack_addr = get_current_sp()
if stack_addr == 0:
return -1
ret_addr = get_process().ReadPointerFromMemory(stack_addr, err)
if not err.Success():
print("[-] error: failed to read memory at 0x{:x}.".format(stack_addr))
return -1
return ret_addr
def is_sending_objc_msg():
err = lldb.SBError()
target = get_target()
call_addr = get_indirect_flow_target(get_current_pc())
sym_addr = lldb.SBAddress(call_addr, target)
symbol = sym_addr.GetSymbol()
# XXX: add others?
return symbol.name in ('objc_msgSend')
# displays the contents of the flow window (disabled by default)
# pretty much information about indirect references and objective-c where available
def display_indirect_flow():
target = get_target()
pc_addr = get_current_pc()
mnemonic = get_mnemonic(pc_addr)
# x86 and arm64 (including pac versions)
if mnemonic.startswith("ret"):
indirect_addr = get_ret_address(pc_addr)
output("0x%x -> %s" % (indirect_addr, lldb.SBAddress(indirect_addr, target).GetSymbol().name))
output("\n")
return
if mnemonic in ('call', 'callq', 'jmp', 'br', 'bl', 'b', 'braa', 'braaz', 'brab', 'brabz', 'blraa', 'blraaz', 'blrab', 'blrabz'):
# we need to identify the indirect target address
indirect_addr = get_indirect_flow_target(pc_addr)
output("0x%x -> %s" % (indirect_addr, lldb.SBAddress(indirect_addr, target).GetSymbol().name))
if is_sending_objc_msg():
output("\n")
className, selectorName = get_objectivec_selector(pc_addr)
if className != "":
output(RED + 'Class: ' + RESET)
output(className)
if selectorName != "":
output(RED + ' Selector: ' + RESET)
output(selectorName)
output("\n")
return
# find out the target address of ret, and indirect call and jmp
def get_indirect_flow_address(src_addr):
target = get_target()
instruction_list = target.ReadInstructions(lldb.SBAddress(src_addr, target), 1, 'intel')
if instruction_list.GetSize() == 0:
print("[-] error: not enough instructions disassembled.")
return -1
cur_instruction = instruction_list.GetInstructionAtIndex(0)
if not cur_instruction.DoesBranch():
return -1
if cur_instruction.GetMnemonic(target).startswith("ret"):
ret_addr = get_ret_address(src_addr)
return ret_addr
elif cur_instruction.GetMnemonic(target) in ( 'call', 'jmp' ):
# don't care about RIP relative jumps
if cur_instruction.GetOperands(target).startswith('0x'):
return -1
indirect_addr = get_indirect_flow_target(src_addr)
return indirect_addr
elif cur_instruction.GetMnemonic(target) in ('br', 'blr', 'braa', 'braaz', 'brab', 'brabz', 'blraa', 'blraaz', 'blrab', 'blrabz'):
indirect_addr = get_indirect_flow_target(src_addr)
return indirect_addr
# all other branches just return -1
return -1
# retrieve the module full path name an address belongs to
def get_module_name(src_addr):
target = get_target()
src_module = lldb.SBAddress(src_addr, target).module
module_name = src_module.file.fullpath
if module_name is None:
return ""
else:
return module_name
# tries to retrieve the class name of object being sent a message and the selector
def get_objectivec_selector(src_addr):
options = lldb.SBExpressionOptions()
options.SetLanguage(lldb.eLanguageTypeObjC)
options.SetTrapExceptions(False)
err = lldb.SBError()
target = get_target()
process = get_process()
call_addr = get_indirect_flow_target(src_addr)
if call_addr == 0:
return "", ""
# first verify if it's the right symbol
sym_addr = lldb.SBAddress(call_addr, target)
symbol = sym_addr.GetSymbol()
if not symbol.IsValid():
return "", ""
# XXX: add others?
if not symbol.name.startswith("objc_msgSend"):
return "", ""
# expr -- (void)printf("[%s, %s]\n",(char *) object_getClassName(*(long*)($rdi)), (char *) *(long *)($rsi) )
# if the target isn't compiled with obj-c information we get this error and crash (-ObjC option to the compiler)
# warning: could not execute support code to read Objective-C class data in the process. This may reduce the quality of type information available.
classname_command = '(const char *)object_getClassName((id){})'.format(get_instance_object())
classname_value = get_frame().EvaluateExpression(classname_command)
# IsValid() doesn't seem that useful because if there is an error it still returns true
# we can check the error property or the size of the data for example
# https://lldb.llvm.org/python_api/lldb.SBValue.html?highlight=sbvalue
if not classname_value.IsValid() or classname_value.size == 0:
return "", ""
className = classname_value.GetSummary().strip('"')
# get pointer to selector string
if is_x64():
selector_addr = get_gp_register("rsi")
elif is_arm():
selector_addr = get_gp_register("x1")
elif is_i386:
# selector pointer is at esp+4
src = get_gp_register("esp")
src += 4
selector_addr = process.ReadPointerFromMemory(src, err)
if not err.Success():
print("[-] error: failed to read selector address from 0x{:x}".format(src))
return className, ""
# XXX: verify that address makes some sense?
# read selector string
methodName = process.ReadCStringFromMemory(selector_addr, 0x100, err)
if not err.Success():
print("[-] error: failed to read selector string from 0x{:x}".format(selector_addr))
# XXX: do we need to return here or methodName is empty?
if len(methodName) != 0:
return className, methodName
else:
return className, ""
#----------------
# CUSTOM COMMANDS
#----------------
def cmd_fixret(debugger, command, result, dict):
'''Fix return breakpoint. Use \'fixret help\' for more information.'''
help = """
Fix return breakpoint anti-debugging.
Syntax: fixret
"""
cmd = command.split()
if len(cmd) > 0 and cmd[0] == "help":
print(help)
return
target = get_target()
frame = get_frame()
if frame is None:
return
thread = frame.GetThread()
rsp = int(frame.FindRegister('rsp').GetValue(), 16)
#print(hex(rsp))
error = lldb.SBError()
ret_addr = get_process().ReadUnsignedFromMemory(rsp, 8, error)
if not error.Success():
print("[-] error: failed to read RSP.")
return
#print("[DEBUG] return address is {0}".format(hex(ret_addr)))
get_frame().reg["rip"].value = format(ret_addr, '#x')
rsp = rsp + 0x8
get_frame().reg["rsp"].value = format(rsp, '#x')
if len(cmd) == 0:
get_process().Continue()
#------------------------------------------------------------
# The heart of lldbinit - when lldb stop this is where we land
#------------------------------------------------------------
def HandleHookStopOnTarget(debugger, command, result, dict):
'''Display current code context.'''
# Don't display anything if we're inside Xcode
if os.getenv('PATH').startswith('/Applications/Xcode'):
return
# the separator strings based on configuration and target arch
if is_i386():
top_sep = SEPARATOR * I386_TOP_SIZE
stack_sep = SEPARATOR * I386_STACK_SIZE
bottom_sep = SEPARATOR * I386_BOTTOM_SIZE
elif is_x64():
top_sep = SEPARATOR * X64_TOP_SIZE
stack_sep = SEPARATOR * X64_STACK_SIZE
bottom_sep = SEPARATOR * X64_BOTTOM_SIZE
elif is_arm():
top_sep = SEPARATOR * ARM_TOP_SIZE
stack_sep = SEPARATOR * ARM_STACK_SIZE
bottom_sep = SEPARATOR * ARM_BOTTOM_SIZE
else:
arch = get_arch()
print("[-] error: unknown and unsupported architecture : " + arch)
return
global GlobalListOutput
global CONFIG_DISPLAY_STACK_WINDOW
global CONFIG_DISPLAY_FLOW_WINDOW
global POINTER_SIZE
debugger.SetAsync(True)
# when we start the thread is still not valid and get_frame() will always generate a warning
# this way we avoid displaying it in this particular case
if get_process().GetNumThreads() == 1:
thread = get_process().GetThreadAtIndex(0)
if not thread.IsValid():
return
frame = get_frame()
if not frame:
return
# XXX: this has a small bug - if we reload the script and try commands that depend on POINTER_SIZE
# they will use the default value instead of the target until the context command is issued
# or this hook is called
POINTER_SIZE = get_pointer_size()
while True:
frame = get_frame()
thread = frame.GetThread()
if thread.GetStopReason() == lldb.eStopReasonNone or thread.GetStopReason() == lldb.eStopReasonInvalid:
time.sleep(0.001)
else:
break
GlobalListOutput = []
output(COLOR_SEPARATOR + top_sep)
output(BOLD + "[regs]\n" + RESET)
print_registers()
if CONFIG_DISPLAY_STACK_WINDOW == 1:
output(COLOR_SEPARATOR + stack_sep)
output(BOLD + "[stack]\n" + RESET)
display_stack()
output("\n")
if CONFIG_DISPLAY_DATA_WINDOW == 1:
output(COLOR_SEPARATOR + top_sep)
output(BOLD + "[data]\n" + RESET)
display_data()
output("\n")
if CONFIG_DISPLAY_FLOW_WINDOW == 1:
output(COLOR_SEPARATOR + top_sep)
output(BOLD + "[flow]\n" + RESET)
display_indirect_flow()
output(COLOR_SEPARATOR + top_sep)
output(BOLD + "[code]\n" + RESET)
# disassemble and add its contents to output inside
disassemble(get_current_pc(), CONFIG_DISASSEMBLY_LINE_COUNT)
output(COLOR_SEPARATOR + bottom_sep + RESET)
# XXX: do we really need to output all data into the array and then print it in a single go? faster to just print directly?
# was it done this way because previously disassembly was capturing the output and modifying it?
data = "".join(GlobalListOutput)
result.PutCString(data)
result.SetStatus(lldb.eReturnStatusSuccessFinishResult)
return 0
| 40fc618131f3f7a152489a1a53d70cc3d1351b83 | [
"Markdown",
"Python"
] | 2 | Markdown | gdbinit/lldbinit | 1fe8df74ccd80836ddae73da4207dc63fcaf388a | 15e1634f6c54db78b7882c379bd98fa1d9679702 | |
refs/heads/master | <repo_name>u5-03/mac-setup<file_sep>/Setting/terminal.sh
# 環境変数export LANG=ja_JP.UTF-8
export KCODE=u # KCODEにUTF-8を設定
## 色を使用出来るようにする
autoload -Uz colors
colors
## 補完機能を有効にする
autoload -Uz compinit
compinit
## cdを使わずにディレクトリを移動できる
setopt auto_cd
## $ cd - でTabを押すと、ディレクトリの履歴が見れる
setopt auto_pushd
## タブ補完時に大文字小文字を区別しない
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}'
# Options
# 日本語ファイル名を表示可能にする
setopt print_eight_bit
# コマンドラインでも # 以降をコメントと見なす
setopt interactive_comments
# beep を無効にする
setopt no_beep
# rm *で確認を求める機能を無効化する
setopt RM_STAR_SILENT
# # Terminalのユーザー名を非表示にする
# PROMPT=$'%n [%*] -> %% '
# # 現在のパスを表示(文字を青色に設定)
# RPROMPT="%{${fg[blue]}%}[%~]%{${reset_color}%}"
# https://qiita.com/tocomi/items/c0127c44eded54b43c11
function powerline_precmd() {
PS1="$(powerline-shell --shell zsh $?)
$"
}
function install_powerline_precmd() {
for s in "${precmd_functions[@]}"; do
if [ "$s" = "powerline_precmd" ]; then
return
fi
done
precmd_functions+=(powerline_precmd)
}
if [ "$TERM" != "linux" ]; then
install_powerline_precmd
fi
# PROMPT変数内で変数参照する
# setopt prompt_subst
# RPROMPT=$RPROMPT'${vcs_info_msg_0_}'
# vcsの表示
## vcs_infoロード
autoload -Uz vcs_info
# zstyle ':vcs_info:*' enable git svn hg bzr
# zstyle ':vcs_info:*' check-for-changes true
# zstyle ':vcs_info:*' stagedstr "%F{yellow}!"
# zstyle ':vcs_info:*' unstagedstr "%F{red}+"
# zstyle ':vcs_info:*' formats "%F{green}%c%u[%b]%f"
# zstyle ':vcs_info:*' actionformats '[%b|%a]'
# プロンプト表示直前にvcs_info呼び出し(プロンプトが表示されるたびに、実行される関数)
# precmd () {
# psvar=()
# LANG=en_US.UTF-8 vcs_info
# [[ -n "$vcs_info_msg_0_" ]] && psvar[1]="$vcs_info_msg_0_"
# }
export SHELL="/otp/homebrew/bin/zsh"<file_sep>/InitSettings/Dev/flutter-init.sh
# Flutter
flutter doctor
#JAVA
# Ref: https://zenn.dev/satokazur222/articles/66568417b291d8
sudo ln -sfn $(brew --prefix)/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk<file_sep>/Alias/dev-alias.sh
alias carthage='mint run carthage carthage'
alias cu='carthage update --platform iOS --cache-builds --no-use-binaries'
alias cb='carthage bootstrap --platform iOS --cache-builds'
alias xcodegen='mint run xcodegen xcodegen'
alias xg='xcodegen'
alias swiftgen='mint run swiftgen swiftgen'
alias xcconfigextractor-='mint run xcconfig-extractor xcconfig-extractor'
alias xe='xcconfig-extractor'
alias mb='mint bootstrap'
alias py='python'
alias fl='flutter'
alias fs='bundle exec fastlane'
alias swiftymocky='mint run SwiftyMocky swiftyMocky'
alias sm='swiftymocky'
alias sml='xcrun simctl list'
alias spg='swift package generate-xcodeproj'
<file_sep>/InitSettings/Dev/index.sh
sh $HOME/mac-setup/InitSettings/Dev/fastlane-init.sh
sh $HOME/mac-setup/InitSettings/Dev/flutter-init.sh
# sh $HOME/mac-setup/InitSettings/Dev/ionic-init.sh
sh $HOME/mac-setup/InitSettings/Dev/node-init.sh
sh $HOME/mac-setup/InitSettings/Dev/pod-init.sh
sh $HOME/mac-setup/InitSettings/Dev/python-init.sh
sh $HOME/mac-setup/InitSettings/Dev/terminal-init.sh
sh $HOME/mac-setup/InitSettings/Dev/xcode-init.sh
<file_sep>/InitSettings/Dev/terminal-init.sh
# Powerline-shell
# https://qiita.com/tocomi/items/c0127c44eded54b43c11
## Install Powerline-shell
git clone https://github.com/b-ryan/powerline-shell $HOME/dev-tool/powerline-shell
cd $HOME/dev-tool/powerline-shell
sudo python setup.py install
## Install fonts
git clone https://github.com/powerline/fonts.gszit --depth=1 $HOME/dev-tool/fonts
$HOME/dev-tool/fonts/install.sh
cd $HOME/dev-tool
cd $HOME
mkdir $HOME/.config/powerline
cp $HOME/SettingFiles/Powerline-shell/config.json $HOME/.config/powerline/config.json
cp $HOME/SettingFiles/Powerline-shell/mytheme.pyc $HOME/dev-tool/powerline-shell/powerline_shell/themes/mytheme.pyc
<file_sep>/InitSettings/Dev/gem-init.sh
# Bundler
sudo gem install bundler<file_sep>/InitSettings/Brewfile
tap "homebrew/bundle"
tap "homebrew/cask"
tap "homebrew/core"
tap "leoafarias/fvm"
brew "1password-cli"
brew "arp-scan"
brew "cloc"
brew "discord"
brew "cmake"
brew "colordiff"
brew "curl"
brew "lame"
brew "fvm"
brew "gh"
brew "goenv"
brew "gnu-sed"
brew "jq"
brew "kela"
brew "mas"
brew "mint"
brew "nodebrew"
brew "pyenv"
brew "rbenv"
brew "tcptraceroute"
brew "tfenv"
brew "tmux"
brew "translate-shell"
brew "wget"
brew "zplug"
brew "zsh-autosuggestions"
brew "zsh-completions"
brew "zsh-syntax-highlighting"
cask "1password", args: { appdir: "/Applications" }
cask "alfred", args: { appdir: "/Applications" }
cask "android-studio", args: { appdir: "/Applications" }
cask "appcleaner", args: { appdir: "/Applications" }
cask "balenaetcher"
cask "bettertouchtool", args: { appdir: "/Applications" }
cask "cheatsheet", args: { appdir: "/Applications" }
cask "dash", args: { appdir: "/Applications" }
cask "docker", args: { appdir: "/Applications" }
cask "finicky", args: { appdir: "/Applications" }
cask "google-japanese-ime", args: { appdir: "/Applications" }
cask "handbrake", args: { appdir: "/Applications" }
cask "imageoptim", args: { appdir: "/Applications" }
cask "iterm2", args: { appdir: "/Applications" }
cask "keyboardcleantool", args: { appdir: "/Applications" }
cask "menumeters", args: { appdir: "/Applications" }
cask "notion", args: { appdir: "/Applications" }
cask "postman", args: { appdir: "/Applications" }
cask "provisionql", args: { appdir: "/Applications" }
cask "sdformatter", args: { appdir: "/Applications" }
cask "sf-symbols", args: { appdir: "/Applications" }
cask "shiftit", args: { appdir: "/Applications" }
cask "sourcetree", args: { appdir: "/Applications" }
cask "svnx", args: { appdir: "/Applications" }
cask "the-unarchiver", args: { appdir: "/Applications" }
cask "visual-studio-code", args: { appdir: "/Applications" }
cask "vivaldi", args: { appdir: "/Applications" }
cask "vlc", args: { appdir: "/Applications" }
cask "wkhtmltopdf", args: { appdir: "/Applications" }
cask "xcodes", args: { appdir: "/Applications" }
mas "iMovie", id: 408981434
mas "Keynote", id: 409183694
mas "Numbers", id: 409203825
mas "Slack", id: 803453959
<file_sep>/Alias/git-alias.sh
# git Aliases
alias ga='git add'
alias gaa='git add -A'
alias gap='git add -p'
alias gaproj='git aproj'
alias gb='git branch'
alias gc='git commit'
alias gcl='git clone'
alias gca='git commit --amend'
alias gco='git checkout'
alias gcp='git cherry-pick'
alias gd='git diff'
alias gdt='git difftool'
alias gdc='git diff --cached'
alias gf='git fetch'
alias gfa='git fetch --all'
alias gfp='git fetch -p'
alias gl='git log'
alias gmnf='git merge --no-ff'
alias grb='git rebase'
alias grba='git rebase --abort'
alias grbc='git rebase --continue'
alias grbi='git rebase -i'
alias grbo='git rebase --onto'
alias grhe='git reset HEAD'
alias grha='git reset --hard'
alias grhs='git reset HEAD\^ --soft'
alias gst='git stash -u'
alias gstp='git stash pop'
alias gstpf='git stash pop #'
alias gstl='git stash list'
alias grbdev='git rebase origin/develop'
alias grbidev='git rebase -i origin/develop'
alias gcd='git reset HEAD .; git checkout .; git clean -df .'
alias gra='git remote add origin'
alias gpl='git pull origin'
alias gps='git push origin'
alias gpsf='git push -f origin'
alias gs='git status'
alias gsu='git submodule update --init --recursive'
alias gsuf='git submodule update --init --force --remote'
alias grc='git rm --cached'
function grh() {
if [ ! -n "$1" ] && [ -e $1 ]; then
echo "arg1: branch name is required!"
return
else
git reset --hard origin/$1
fi
}
function grb() {
git rebase origin/$1
}
function grbi() {
git rebase -i origin/$1
}
function gc() {
git checkout $1
}
<file_sep>/InitSettings/init-download.sh
function command_exists {
command -v "$1" > /dev/null;
}
#
# Install homebrew.
#
if ! command_exists brew ; then
echo " --------- Homebrew ----------"
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> /Users/$USER/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"
brew doctor
brew -v
echo " ------------ Homebrew END ------------"
fi
#
# Install git
#
if ! command_exists git ; then
echo " ------------ Git ------------"
brew install git
git --version
echo " ------------ Git END ------------"
fi
#
# mac-auto-setup.git
#
echo " ---- mac-setup -----"
git clone https://github.com/u5-03/mac-setup.git
echo " ------------ mac-setup END ------------"
<file_sep>/Setting/dowload.sh
function isPrivateConfigSet() {
if [ -e $HOME/SettingFiles/PrivateSettings/private-config.sh ]; then
return 0
else
return 1
fi
}
# GoogleDriveに保存したBetterTouchToolのライセンスファイルを指定ディレクトリに保存する。
function dlBtt() {
if ! isPrivateConfigSet; then
echo Could not load private config file!
return
fi
savePath=$HOME/SettingFiles/BetterTouchToolsLicenceFile
if [[ ! -e $savePath/$filename ]]; then
mkdir -p $savePath
curl -c ./cookie -s -L "https://drive.google.com/uc?export=download&id=${fileid}" > /dev/null
curl -Lb ./cookie "https://drive.google.com/uc?export=download&confirm=`awk '/download/ {print $NF}' ./cookie`&id=${fileid}" -o $savePath/${filename}
echo Downloading licence file is complete!
else
echo Licence file already exist!
fi
}<file_sep>/Alias/xcode-alias.sh
# Xcode関連のalias
alias deletederiveddata='rm -rf ~/Library/Developer/Xcode/DerivedData/*'
alias ddd='deletederiveddata'
alias xcv='xcversion'
alias xo='xcodeOpen'
alias rkb='replaceKeybindingFile'
alias sds='setDeviceSupport'
alias xsl='xcrun simctl list'
alias spg='swift package generate-xcodeproj'
## xcodeのバージョンを指定して、プロジェクトを開く($1: Xcodeのバージョン, $2: .xcodeproj/xcworkspace のパス)
function xcodeOpen() {
# arg1/arg2のnullチェック
if [ ! -n "$1" -o -z "$2" ]; then
echo "arg1(xcode version number) and arg2(xcodeproj file path) are required!"; return
fi
# arg1の数値判定
expr "$1 + 1" > /dev/null 2>&1
if [ ! $? -lt 2 ]; then
echo arg1 must be xcode version number!; return
fi
#arg1のバージョンのXcodeがアプリケーションフォルダにあるかどうかの判定
XcodePath=/Applications/Xcode$1.app
if [ ! -e $XcodePath ]; then
echo Xcode$1.app does not exist in Applications directory!; return
fi
#arg2のパスに.xcodeproj/xcworkspaceがあるかどうかの判定
if [ ! -e $2 ]; then
echo "The path: $2 is not valid!"; return
fi
FileExtension=${2##*.}
#拡張子がXcodeで開くことができるものかの判定
if [ $FileExtension = "xcodeproj" -o $FileExtension = "xcworkspace" ]; then
open -a $XcodePath $2
else
echo "$2 cannot be opend in Xcode!";
fi
}
## xcodeのバージョンを指定して、KeyBindingFileをカスタムのものに置き換える($1: Xcodeのバージョン, $2: IDETextKeyBindingSet.plistのパス)
function replaceKeybindingFile() {
# arg1のnullチェック
if [ ! -n "$1" ]; then
echo "arg1(xcode version number) is required!"; return
fi
# arg1の数値判定
expr "$1 + 1" > /dev/null 2>&1
if [ ! $? -lt 2 ]; then
echo arg1 must be xcode version number!; return
fi
#arg1のバージョンのXcodeがアプリケーションフォルダにあるかどうかの判定
XcodePath=/Applications/Xcode$1.app
if [ ! -e $XcodePath ]; then
echo Xcode$1.app does not exist in Applications directory!; return
fi
KeyBindingFilePath=""
PrivateKeyBindingFilePath=$HOME/SettingFiles/Xcode/XcodekeyBinding/IDETextKeyBindingSet.plist
if [ -n "$2" ] && [ -e $2 ] && [ `basename $2` = IDETextKeyBindingSet.plist ]; then
KeyBindingFilePath=$2
elif [ -e $PrivateKeyBindingFilePath ]; then
KeyBindingFilePath=$PrivateKeyBindingFilePath
echo Default file: $HOME/SettingFiles/Xcode/XcodekeyBinding/IDETextKeyBindingSet.plist will be used!
else
echo "arg2(`$KeyBindingFilePath`) is invalid!"; return
fi
XcodeKeyBindingFilePath="/Applications/Xcode$1.app/Contents/Frameworks/IDEKit.framework/Versions/A/Resources/IDETextKeyBindingSet.plist"
cp -f $KeyBindingFilePath $XcodeKeyBindingFilePath
echo "keybinding file of Xcode$1.app was replaced!"
}
## Specify the iOS and Xcode version, download the DeviceSupport file and set it in the corresponding version Xcode ($1: iOS version, $2: Xcode version path)
function setDeviceSupport() {
# null check of arg1
if [ -z "$1" ]; then
echo "arg1(iOS version number) is required! e.g. 14.6"; return
fi
# null check of arg2
if [ -z "$2" ]; then
echo "arg2(xcode version number) is required! e.g. 12.5"; return
fi
which svn
echo "Clone $1 DeviceSupport zip from https://github.com/filsv/iOSDeviceSupport"
svn export https://github.com/filsv/iOSDeviceSupport/trunk/$1.zip
unzip $1.zip
mv -f ./$1 /Applications/Xcode$2.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/
rm -f $1.zip
rm -f -r __MACOSX
echo "Set $1 Device Support file to Xcode$2!"
}
<file_sep>/README.md
# mac-setup
### Run following
①
```
sudo curl -fsSL https://raw.githubusercontent.com/u5-03/mac-setup/master/InitSettings/init-download.sh | sh
```
②
```
cd ./mac-setup
```
③
```
make setup
```<file_sep>/InitSettings/Dev/xcode-init.sh
if ! which xcversion >/dev/null; then
echo xcode-install will be installed!
sudo gem install xcode-install
else
echo xcode-install is already installed!
fi
# cat ./UserSettings/xcode-version.sh | grep -v "#" | while read line || [ -n "${line}" ];
# do
# xcversion install $line
# done
# echo Xcode install complete!<file_sep>/InitSettings/.finicky.js
// Generated by Finicky Kickstart
// Save as ~/.finicky.js
module.exports = {
defaultBrowser: "Vivaldi",
handlers: [
{
match: /^https?:\/\/app\.bitrise\.com\/.*$/,
browser: "Safari"
},
{
match: /^https?:\/\/console\.firebase\.google\.com\/.*$/,
browser: "Safari"
}
]
}<file_sep>/Alias/command-alias.sh
alias ls="ls -G"
alias tree="tree -NC -l"
alias mkdir="mkdir -p"
alias ...="cd ../.."<file_sep>/Setting/dev.sh
# Node
nodebrewPath=".nodebrew"
if [[ ! $PATH =~ $nodebrewPath ]]; then
export PATH=$HOME/.nodebrew/current/bin:$PATH
fi
# Python
pythonPath=".pyenv"
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/shims:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv init --path)"
# Flutter
## Ref: https://zenn.dev/aiiro/articles/6df504554d57ef
flutterPath="$HOME/fvm/default/bin"
if [[ ! $PATH =~ $flutterPath ]]; then
export PATH="$PATH:$flutterPath"
fi
## `Unable to find bundled Java version` => Run command below.
## Ref: https://qiita.com/y-matsumoto/items/74467e528c7b2c745b87
androidSDKPAth="$HOME/Library/Android/sdk/platform-tools"
if [[ ! $PATH =~ $androidSDKPAth ]]; then
export PATH="$androidSDKPAth:$PATH"
fi
rbenv="$HOME/.rvenv/bin"
if [[ ! $PATH =~ $rbenv ]]; then
export PATH="$PATH:$rbenv"
fi
rbenvShims="$HOME/.rvenv/shims"
if [[ ! $PATH =~ $rbenvShims ]]; then
export PATH="$PATH:$rbenvShims"
fi
eval "$(rbenv init -)"
# Android
ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME:$ANDROID_HOME/emulator:$ANDROID_HOME/tools/:$ANDROID_HOME/platform-tools
# Ref: https://qiita.com/uhooi/items/74bdc893c7a7b43f6e94#android-studio%E3%81%AB%E5%90%8C%E6%A2%B1%E3%81%95%E3%82%8C%E3%81%A6%E3%81%84%E3%82%8Bjdk%E3%81%8C%E8%A6%8B%E3%81%A4%E3%81%8B%E3%82%89%E3%81%AA%E3%81%84
export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jbr/Contents/Home
if [ -d "${JAVA_HOME}" ]; then
export PATH="${JAVA_HOME}/bin:$PATH"
fi
# GitHubCLI
eval "$(gh completion -s zsh)"
<file_sep>/Setting/history.sh
# ヒストリの設定
# ヒストリの設定
HISTFILE=~/.sh_history
HISTSIZE=1000000
SAVEHIST=1000000
# 同じコマンドをヒストリに残さない
setopt hist_ignore_all_dups
# 同時に起動したzshの間でヒストリを共有する
setopt share_history
# ヒストリファイルに保存するとき、すでに重複したコマンドがあったら古い方を削除する
setopt hist_save_nodups
# スペースから始まるコマンド行はヒストリに残さない
setopt hist_ignore_space
# ヒストリに保存するときに余分なスペースを削除する
setopt hist_reduce_blanks
# 補完候補が複数あるときに自動的に一覧表示する
setopt auto_menu
# 高機能なワイルドカード展開を使用する
setopt extended_glob<file_sep>/Alias/custom-alias.sh
# custom-alias
alias sz='source ~/.zshrc'
alias opcd='open `pwd`'
alias nb='nodebrew'
alias sed='gsed'
alias paths="echo $PATH | tr ':' '\n'"
# Wifi設定alias
alias wfe='sudo networksetup -setairportpower en0 on'
alias wfd='sudo networksetup -setairportpower en0 off'
alias cwf='connectWifi'
function connectWifi() {
sudo networksetup -setairportnetwork en0 $1 $2
}
##「悪質なソフトウェアかどうかをAppleで確認できないため、このソフトウェアを開けません。」のエラー時に、全てのアプリケーション実行を許可する(application-force-install)
alias afi='sudo spctl --master-disable'
alias afid='sudo spctl --master-enable'
## TerminalからMacをシャットダウンする
alias shutdown='sudo shutdown -h now'
##screenCaptureの保存先の変更
function ccd() {
DIR=$HOME/Pictures/Captures
if [ -n "$1" ] && [ -e $1 ]; then
DIR=$1
else
if [ ! -d $DIR ]; then
mkdir $DIR
fi
fi
defaults write com.apple.screencapture location $DIR
killall SystemUIServer
echo Screen captures will be saved in $DIR!
}<file_sep>/zsh-config.sh
#PrivateConfigの読み込み
if [ -e $HOME/SettingFiles/PrivateSettings/private-config.sh ]; then
source $HOME/SettingFiles/PrivateSettings/private-config.sh
fi
#分割している設定ファイルの読み込み
# DIRECTORY=`dirname $0`
DIRECTORY=$HOME/mac-setup
# ## Aliasの設定
source $DIRECTORY/Alias/index.sh
# ## 設定ファイル系の設定
source $DIRECTORY/Setting/index.sh
## 重複したPATHを削除
typeset -U PATH
<file_sep>/Setting/functions/index.sh
source $DIRECTORY/Setting/functions/function-setting.sh<file_sep>/InitSettings/Dev/ionic-init.sh
npm install ionic -g
npm install cordova -g<file_sep>/InitSettings/Dev/python-init.sh
# https://zenn.dev/kenghaya/articles/9f07914156fab5
version=3.10.6
pyenv install $version
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv init -)"
pyenv global $version
python --version<file_sep>/Setting/index.sh
source $DIRECTORY/Setting/dowload.sh
source $DIRECTORY/Setting/history.sh
source $DIRECTORY/Setting/terminal.sh
source $DIRECTORY/Setting/dev.sh
source $DIRECTORY/Setting/functions/index.sh
<file_sep>/InitSettings/Dev/node-init.sh
# Node
nodebrew setup
nodebrew install-binary stable
nodebrew use stable
export PATH="/usr/local/bin:$PATH"
export PATH=$PATH:$HOME/.nodebrew/current/bin<file_sep>/InitSettings/init-setting.sh
# finickyの設定ファイルをコピーする
# ref: https://github.com/johnste/finicky#installation
cp -f ./InitSettings/.finicky.js $HOME
## Brewfileに書かれたパッケージのインストール
brew bundle --file=./InitSettings/Brewfile
if [ -e ~/.zshrc ]; then
touch ~/.zshrc
fi
# 個人用の設定リポジトリの取得
echo "--Setting of private config repository---------------------"
git clone https://github.com/u5-03/SettingFiles.git $HOME/SettingFiles
# PrivateConfigの読み込み
if [ -e $HOME/SettingFiles/PrivateInitSettings/private-repositories.sh ]; then
source $HOME/SettingFiles/PrivateInitSettings/private-repositories.sh
source $HOME/SettingFiles/PrivateInitSettings/working-repositories.sh
fi
echo source ~/mac-setup/zsh-config.sh > ~/.zshrc
source ~/.zshrc
# zshの設定
echo "--Setting of zsh------------------------------------------"
which -a zsh
sudo -- sh -c 'echo '/usr/local/bin/zsh' >> /etc/shells'
chsh -s /bin/zsh
# Screen captureの保存先を変更
ccd
# 各種開発ツールの設定
sh $HOME/mac-setup/InitSettings/Dev/index.sh
# Terminalでsudo実行時に、生体認証を使用する設定
setBiometricsAuthAsTouchID<file_sep>/Makefile
setup:
sh ./InitSettings/init-setting.sh<file_sep>/InitSettings/Dev/ruby-init.sh
rbenv="$HOME/.rvenv/shims"
if [[ ! $PATH =~ $rbenv ]]; then
export PATH="$PATH:$rbenv"
eval "$(rbenv init -)"
fi
rbenv install<file_sep>/Setting/functions/function-setting.sh
if [ ! -e $HOME/mac-setup/Setting/functions/git-escape-magic ]; then
# zshで^を使用する際に、自動でエスケープする関数
curl https://raw.githubusercontent.com/knu/zsh-git-escape-magic/master/git-escape-magic --output "$HOME/mac-setup/Setting/functions/git-escape-magic"
export FPATH=$HOME/mac-setup/Setting/functions:$FPATH
fi
autoload -Uz git-escape-magic
# git-escape-magic
# Settings to use biometrics when running `sudo` in Terminal
function setBiometricsAuthAsTouchID() {
echo "--Biometrics setting of terminal when use 'sudo'----------------------------"
echo "Insert text below to 2nd line of '/etc/pam.d/sudo'"
echo "auth sufficient pam_tid.so"
while true; do
echo -n "Did you copy ↑ text?(if yes, enter 'yes')"
read ANS
case $ANS in
[Yy]*)
# Enable user write permission
sudo chmod u+w /etc/pam.d/
sudo vi /etc/pam.d/sudo
return 0
;;
*)
echo "Enter yes"
;;
esac
done
}<file_sep>/Alias/index.sh
source $DIRECTORY/Alias/dev-alias.sh
source $DIRECTORY/Alias/git-alias.sh
source $DIRECTORY/Alias/custom-alias.sh
source $DIRECTORY/Alias/command-alias.sh
source $DIRECTORY/Alias/xcode-alias.sh | 979751cc89d8057abe810ccdd3ef542b0292c4e4 | [
"Ruby",
"Markdown",
"JavaScript",
"Makefile",
"Shell"
] | 29 | Shell | u5-03/mac-setup | 46261bcde69f57def421f098338cd95b9099008e | 3918b2c7c4a76b340b5b5a04b8f350cc96b1e1ac | |
refs/heads/main | <repo_name>Lucas-Souza-Santos/Avanade<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/script/Aula04-Parte1/1-array.js
// Criação de um array
const arr1 = [1, 2, 3]
const arr2 = new Array(1, 2, 4);
const arr3 = Array.of(1, 2, 5);
console.log(`Array1 = (${arr1}) Array2 = (${arr2}) Array3 = (${arr3})`)
const arr4 = Array(3);
const arr5 = Array(3, 2);
const divs = document.querySelectorAll('div');
const arr = Array.from(divs);
const cafaDaManha = ['Frutas', 'cafe puro', 'pão', 'mateiga'];
const almoco = ['feijão', 'arroz', 'carne'];
const refeicoes1 = cafaDaManha.concat(almoco);
const refeicoes2 = almoco.concat(cafaDaManha);
arr1.push(4, 5);
// forEach
arr1.forEach((value, index) => {
console.log(`${index + 1}º = ${value}`);
});
// map
console.log(arr1.map(value => value * 2));
console.log(arr1);
// flat
const novo_array = [56, 78, [34, 57], [90, 98, 100]];
console.log(novo_array);
console.log(novo_array.flat());
// flatMap
console.log(novo_array.flatMap(value => [value * 2]));
// keys
const arrIterator = arr1.keys();
console.log("Keys: ")
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
// values
const arrInterator2 = arr1.values();
console.log("valores: ");
console.log(arrInterator2.next());
console.log(arrInterator2.next());
console.log(arrInterator2.next());
console.log(arrInterator2.next());
console.log(arrInterator2.next());
console.log(arrInterator2.next());
// entries
const arrInterator3 = arr1.entries();
console.log("Entries: ");
console.log(arrInterator3.next());
console.log(arrInterator3.next());
console.log(arrInterator3.next());
console.log(arrInterator3.next());
console.log(arrInterator3.next());
console.log(arrInterator3.next());
// find
const firstGreaterThanTwo = arr1.find(value => value > 2);
console.log("Find: ");
console.log(firstGreaterThanTwo);
// findIndex
const firstIndexGreaterThanTwo = arr1.findIndex(value => value > 2);
console.log("Index: ");
console.log(firstIndexGreaterThanTwo + 1);
// filter
const allValuesGreaterThanTwo = arr1.filter(value => value % 2 === 0);
console.log("Retorna Array sobre um condição: ");
console.log(allValuesGreaterThanTwo)
// indexOf
const firstIndexOfItem = arr1.indexOf(3);
console.log("IndexOf: ");
console.log(firstIndexOfItem);
// lastIndexOf
const lastIndexOfItem = arr1.lastIndexOf(3);
console.log("lastIndexOf: ");
console.log(lastIndexOfItem);
// includes
const hasItemOne = arr1.includes(1);
const hasItem1000 = arr1.includes(1000);
console.log("includes: ");
console.log(hasItemOne);
console.log(hasItem1000);
// some
const hasSomeEvenNumber = arr1.some(v => v % 2 === 0)
console.log("some: ");
console.log(hasSomeEvenNumber);
// every
const allEvenNumbers = arr1.every(value => value % 2 === 0);
console.log("every: ");
console.log(allEvenNumbers);
// sort
const sortValues = arr1.sort();
console.log("Sort: ");
console.log(sortValues);
// reverse
const reverteValues = arr1.reverse();
console.log("reverte: ");
console.log(arr1);
// join
const joinValue = arr1.join('-');
console.log("join: ");
console.log(joinValue);
// reduce
const reduceValue = arr1.reduce((total, value) => total += value, 0);
console.log("reduce: ");
console.log(reduceValue);
<file_sep>/Arquitetura_Sistema/Aula04/2-parte.md
## Banco de Dados Relacional
* SGDBR(br) - RDBMS(en) sistema que gerenciam esse tipo
de arquitetura.
* Composto de entidade que agrupa nossas informações
* Tabela
* Linha - Registro - Tupla
* Coluna - Definição o que significa cada informação
* chaves
-> primary keys
-> for in keys cria nosso relacionamento
### Modelo
* Modelo conceitual - MER
* Modelo Lógico - Implementação
O MER pode ser representar por um DER: que é o nosso
diagrama de entidade de relacionamento. Esse diagrama
facilita a compreensão de como o modelo deve se comportar
e também podemos aplicar conceitos de normalização. O DER,
ele é um diagrama grafico, aonde podemos representar as
nossas entidade como o nome, o relacionamento e também
possui cliente que é uma outra entidade. O relacionamento
se dar de uma forma direta ou indireta, nossa entidade
tem um força de existência.
#### Entidade
-> Entidade Forte não dependente de nenhuma outra
informação para existir
-> Entidade fraca que depende de outra informação para
existir
#### Relacionamento
Produto M(1...N) |------ venda -------|N(0...N) Venda
Da direita para esquerda dizemos que Venda possui 1 ou N
Produtos
Da esquerda para a direita dizemos que Produto tem 0 ou N
Venda.
Cliente 1(1...1) |------- Possui -----| N(0...N)
Uma relação do tipo M para N é uma relação associativa.
##### entidade item
Associativa é preciso criar uma nova entidade, que será
chamada de entidade associativa
Vai possuir uma chave estrangeira da entidade Produto e
uma estrangeira da entidade Venda.
Ter uma nova entidade no meio vai resultar em um novo
relacionamento entre eles.
## Normalização
* 1 ... 5 - Forma normal
* 1,2 e 3 - Mais comum
para ajeitar um cadastro que errei é criando uma nova
tabela, ou uma nova coluna.
<file_sep>/Projeto_Netflix/ANOTACOES/Aula.md
# NETFLIX CLONE
- Tudo no html5 é feito com divs
## Tags Semânica
- Header
- Futter
- Aside
Elas são como se fosse divs caixas
Dentro do header vamos definicar nosso menu de
navegação ou navbar, além como nosso navbar
teremos um texto que servirar como log
o html não cuida da formação e sim o css.
cada navegador joga um valor de padding e margin e isso não
pode ser padronizado
resert css vai usar o * e colocar
- margin = 0
- padding = 0
- box-sizing = border-box
pq: Se a gente colocar um contéudo maior que o tamanho da
caixa, esse elemento vai esborrar e não é isso que queremos
Por isso colocamos o box-sizing: border-box, para que tudo
fique no tamanho da caixa.
Como declarar uma variável
- tem que declarada dentro do elemento raiz ou root
displex tipo flex tende a jogar todos os elementos
para a linha
classe wrappe(envelope) ela guarda várias outros
elementos.
- fica mais fácil manipular elementos filhos
-
Para quem deseja continuar
- ter um objetivo claro aonde quer chegar
- Desafios:
-> Dar vida aos botões
-> Criar uma nova página para outro contéudo
-> Colocar algo que não está dentro do projeto
-> linkedin.com/in/felipe-aguiar-047/
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/Anotaçoes/Aula01.md
# Introdução Ao JavaScript
## História e Conceitos
### Historico
* Lançado em setembro de 1995
* Criado por <NAME>
* ECMAScript - É uma especificação da linguagem de programaçao, que é
padronizada pela ECMA62, da ECMA International. Serve como base para
implementação de outras linguagem script.
- JavaScript
- JScript
- ActionScript
* TC39 - Comitê que cuida da evolução da linguagem
- https://github.com/tc39
- https://github.com/tc39/proposals
* Fluxo de Proposta
- Stage 0: strawman -> submeter um formulário com a ideia para
evoluir o ECMAScript, deve ser feita por um membro ou alguém
registrado
- Stage 1: proposal -> surgi a proposta formal, surgi um campeão,
proposta bem definida com exemplo, pode ter varias alterações
- Stage 2: draft -> primeira versão que vai entrar na
especificação, é obrigatório:
-> descrição formal da sintaxe e semâtica da funcionalidade
-> duas implementação são exigida
- Stage 3: candidate -> a proposta tá quase finalizada, precisa
de feed back de implementação, especificação completa nessa etapa
- Stage 4: finished -> tem que passar na suiter de teste,
esperiência prática
* ES.NEXT
-> É uma especificação que possui futura implementações
-> Não está disponivel mas pode ser testada no babel
* BABEL is JavaScript Compiler
->
### Conceitos da Linguagem
* Linguagem interpretada: o código é executado de cima para baixo e
são execultado na msm horas.
* Linguagem de tipagem fraca e dinâmica
* Typescript é um superset da linguagem javascript
- ele consegui adicionar tipos no javascript
- ele adiciona funcionalidade que o javascript não tem por padrão
-> interface
-> enum
-> tipo generic
- https://www.typescriptland.org/
* Flow
- não é considerado um superset javascript
- consegui adicionar tipos
- https://flow.org/en/
* Funções de primeira classe e ordem maior
* Closure a capacidade da variável lembrar aonde foi criada
* Currying -> tecnica para gente transformar uma função com n
paramentro em apenas um parâmetro, e para cada parâmetro agente
retorna uma função.
* Hoisting -> levantar ou suspender algo
* Imutabilidade
Todas vez que passamos um array ou um object ele é passado por
referência.
### Tipos e variáveis
* existe tres escopo dentro do javascript
- Escopo global
- Escopo de função
- Escopo de bloco
* var
Var não respeita o escopo de bloco
* let
* const
- A ideia dele é pra criar constante
- Ele não deixa trocar o valor de tipo primitivo
- Se for criado um objeto, ele permiti mudar as própriedades
- Não pode ser mudado pra aonde o ponteiro dele está apontando
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/script/Aula02-Parte3/1-repeticao.js
// Estrutura de repetição
// for
const array = [1, 2, 3];
for (let index = 0; index < array.length; index++){
console.log(array[index]);
}
// while
var n = 0;
var x = 0;
while (n < 3){
n++;
x += n;
}
console.log(x);
// do - while
let i = 0;
do{
i += 1;
console.log(i);
}while(i < 5);
// for in
for(let i in array){
console.log(i);
}
// for of
for(let i of array){
console.log(i);
}
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/Anotaçoes/Aula04-Parte1.md
# Manipulação e iteração de arrays Parte-1
## criar um array
const arr = [1, 2, 3]
const arr2 = new Array(1, 2, 3);
### Array.of
cria uma nova instância de array a partir do número de
parâmetro informados
### Array
Cria uma nova instância de array de acordo com os
parâmetros informados.
obs.: se for passado um elemento, o vetor é criado com a
quantidade de posições do elemento.
### Array.from
Cria uma nova instância de array a partir de um parâmetro
array-like ou iterable object
#### Array-like
O comando abaixo não é um array e sim um node list. Então
não vou ter funções de array, como: pop, forEach e etc...
const divs = document.querySelectorAll('div');
Se eu quiser ultilizar o node list, é só usar o comando
abaixo, que ele vai me dar um array.
const arr = Array.from(divs)
## Inserir e remover elementos
### push
Adiciona um ou mais elementos no final do array e retorna
o tamanho do novo array.
### pop
Remove o ultimo item
### unshift
Adicionar um ou mais elementos no início do array e
retorna o tamanho do novo array
### shift
Remove o primeiro elemento de um array e retorna o
elemento que ele removeu
### concat
Concatena um ou mais array e retonrnando um novo array.
### slice
Retorna um novo array "fatiando" o array de acordo com
ínicio e fim.
### splice
Altera um array adicionando novos elementos enquanto
remove elementos antigos
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/script/Aula02-Parte1/Aula02-Symbol.js
const symbol1 = Symbol();
const symbol2 = Symbol();
// Symbols são únicos
console.log('symbol1 é igual a symbol2: ', symbol1 === symbol2);
// Previnir conflito entre nomes de propriedades
const nameSymbol1 = Symbol('name');
const nameSymbol2 = symbol2('name');
const user = {
[nameSymbol1]: 'Guilherme',
[nameSymbol2]: 'Outro nome',
lastName: '<NAME>'
};
console.log(user);
// Symbols criam propriedade que não são enumnberables
for (const key in user){
if (user.hasOwnProperty(key)){
console.log(`\nValor da chave ${key}: ${user[key]}`)
}
}
// Acessando todas as propriedades do objeto
console.log('Todas propriedades do objeto user: ', Reflect.ownKeys(user));
// Criar um enum
const directions = {
UP : Symbol( 'UP' ),
DOWN : Symbol( 'DOWN' ),
LEFT : Symbol( 'LEFT' ),
RIGHT : Symbol( 'RIGHT' )
};
<file_sep>/Arquitetura_Sistema/Aula04/4-parte.md
## Transactions
* Um banco de dados deve permitir que várias pessoas deva
acessar ao mesmo tempo.
* cada usuário é tratado como uma transactions diferente.
* impedir que eu altere um transactions e outro depois
altere a mesma transactions e sobreponha a mim... quem
inicio primeiro tem prioridade...
* Inicio, Resolução e Fim
* ACID - Transactions
-> Atomicidade:
Todas operações executadas com sucesso. Commit ou
Rollback
-> Consistência:
Unicidade da chaves, restriçoes de integridade
lógica, etc
-> Isolamento:
Várias transações podem acontecer simultaneamente
o mesmo registro(ou parte do registro)
-> Durabilidade:
Depois do Commit, mesmo com erros, queda de
energia, etc. As alterações devem ser aplicadas.
<file_sep>/Arquitetura_Sistema/Aula01/2-parte.md
## O que é SOAP
* SOAP - Simple Object Access Protocol
* É um protocolo baseado em XML para acessar serviços web
principalmente HTTP.
* Pode-se dizer que SOAP é uma definição de como serviços
web se comunicam
* Foi desenvolvido para facilitar integrações entre
aplicações.
* Permite integrações entre aplicações, independente de
linguagem, pois usa como linguagem comum o XML.
* É independente de plataforma e software.
* Meio de transporte genérico, ou seja, pode ser usado por
outros protocolos além do HTTP
## XML
* XML - Extensible Markup Language
* É uma linguagem de marcação criada na década de 90 pela
W3C.
* Facilita a separação de conteúdo
* Não tem limitação de criação de tags
* Linguagem comum para integrações entre aplicações.
## Estrutura do SOAP
* O "SOAP Message" possui uma estrutura única que deve
sempre ser seguida.
+---------------------------+
| SOAP Envolope |
| +-------------------+ |
| | SOAP Header | |
| +-------------------+ |
| |
| +-------------------+ |
| | SOAP Body | |
| | | |
| | | |
| +-------------------+ |
+---------------------------+
* SOAP Envelope é o primeiro elemento do documento e é
usado para encapsular toda a mensagem SOAP.
* SOAP Header é o elemento onde possui informações de
atributos e metadados da requisição.
* SOAP Body é o elemento que contém os detalhes da
mensagem.
<file_sep>/Arquitetura_Sistema/Aula03/1-parte.md
# Introdução a internet das Coisas
## ARPANET
* começo da internet
* conectar os computadores
Com o objetivo de conectar computadores, a ARPANET cresceu e
hoje ela deu inicio o que chamamos de rede mundial de
computadores
* surgimento dos aplicativos(email, browser e etc)
* chegada dos iphone
* A internet é uma rede de pessoas conectadas e trocando
informações
* A internet das coisas surgiu para conecetar as coisas
### Por que conectar as coisas ?
* Embutir sensores em objetos do dia-a-dia
* COletar dados dos sensores
* Usar o dado para tomar decisão
### Conceitos Báiscos de IoT
* Things
as coisas aonde queremos colocar os sensores, aonde
queremos coletar dados.
* Cloud
aonde a gente quer processar e armazenar os dados
* Intelligence
o processo de usar os dados gerados, se beneficiar do
poder dessa rede e ultilizar esses dados de forma
inteligente.
### Exemplos de onde posso usar o IoT
* Smart Building: é a capacidade de coletar dados e
ultilizar esses dados de forma inteligente para poder
melhorar algo.
um exemplo um prédio
* Smart Home: coletar dados para melhora os processos que
ocorrem dentro da casa.
* Wearables: componentes que colocamos no nosso corpo e
ele acaba coletando dados.
* Agriculture: componente usados na agricultura para
diversos fins.
* Smart Transportation: componente usados no transito
coletando dados.
* RFID Supply Chain: aonde o IoT nasceu
* Energy Efficiency:
### Computação Ubíqua
É quando a computação faz parte da gente que esquecemos
dela.
### Desafios da Internet das Coisas
1. Privacidade e Segurança
2. Quantidade exponencial de dispositivos conectadas na
rede.
3. Ser capaz de precessar e armazenar uma enorme
quantidade de informações
4. Gerar valor a partir dos dados coletados.
<file_sep>/Arquitetura_Sistema/Aula02/1-parte.md
# Conceito de Arquitetura em aplicações para internet
## Tipos de Arquiteturas
### Monolito
* web app ou Mobile app
Ela vai passar por um proxy HTTP, esse proxi vai
redirecionar para qual instância, e essas instâncias
vão está conectadas ao um banco de dados
* A ideia dele é ter uma aplicação, o problema é que com
o aumentou da demanda esse instância teria problema para
aguentar a quantidade de demanda.
* É preciso ter várias instâncias para não ter problemas
com muitas requisições.
* Mais simples
+--------------------------------------------+
| Sevidor |
| +--------------+ +------+ |
| |Aplicação | |Proxi | | +-----+
|+-----+ |(instância #1)| | | | |Web |
||banco| +--------------+ | | | |App |
|| de | +--------------+ |HTTP | | +-----+
||Dados| |Aplicação | | | |
|+-----+ |(instância #2)| | | | +------+
| +--------------+ | | | |Mobile|
| +--------------+ | | | |App |
| |Aplicação | | | | +------+
| |(instância #3)| | | |
| +--------------+ +------+ |
+--------------------------------------------+
### Microserviços #1
* Vantagens de ter microserviços ou serviços menores
* Vantagens de serviços que fazem coisas menores
* Não está preso a uma certa tecnologia
* cada caixa pequena do NODO, serve como servia o
monolito
* Vou ter vários serviços e esses serviços tem que
conversar entre eles.
* cada serviço pode chamar outros serviços, pode ser
por http ou outro tipo de requisição.
### Microserviços #2
* não temos a comunicação entre os NODOS
* temos agora um Message Broker
* A vantagem é que um serviço não vai está conectado
no outro, e tudo vai passar pro um menssage broker
* Se o serviço 1 precisa se comunicar com o serviço 2,
ele vai até o menssage broker e deixa uma mensagem;
se caso o serviço 2 não estiver online, e depois quando
for restabelecida a comunição, e vai até o menssage broker
e verifica as mensagens que tem pra ele.
* fica mais fácil trocar os serviços, se for necessário.
#### desvantage
* Toda plataforma fica refem do message broker, se der
algum problema, toda plataforma sofre com isso.
### Microserviços #3
* Ao invés do proxy http se comunicar com um determinado
serviço, ele vai se comunicar com um gerenciador de
pipeline.
* tem aplicações separadas, cada serviço com sua
dependência diferente, ter o menor código possível,
evitar bugs, melhor perfomace, usar a melhor tecnologia.
<file_sep>/testes/Program.cs
using System;
namespace testes
{
class Program
{
static void Main()
{
nivelTartaruta();
nivelTartaruta();
nivelTartaruta();
}
public void nivelTartaruta()
{
int num = int.Parse(Console.ReadLine());
string[] velocidades = Console.ReadLine().Split(" ");
int maior = 0;
for(int i = 0; i < num; i++){
velocidades[i] = int.Parse(velocidades[i]);
if(i == 0){
maior = velocidades[i];
}
else{
if(velocidades[i] > maior){
maior = velocidades[i];
}
}
Console.WriteLine(maior);
}
}
}<file_sep>/JogoCobra/script.js
/**
* linha 1:
* linha 2: o contexto ele rederizar o desenho que vai
* entrar dentro do canvas, colancando "2d", ele vai passar
* tratar o arquivo em dois d.
*/
/**
* A função criarBG, cria o nosso canvas: desenha e cor
* começando com o contexto e criando a cor
* o fillreact vai desenha o retangulo aonde vai acontecer
* o jogo, trabalhando com 4 parametro
*/
let canvas = document.getElementById("snake"); // linha 1
let context = canvas.getContext("2d"); // linha 2
let box = 32; // linha 3
let snake = []; // linha 4
snake[0] = { // linha 5
x: 8 * box, // linha 6
y: 8 * box // linha 7
} // linha 8
/**
* Precisamos criar uma variável para dominar a direção da
* cobrinha
*
* Nosso próxio passo é criar uma condição que o jogo fique
* sempre atualizado
* setInterval - funçao de tempo
*/
let direction = "right";
let food = {
x: Math.floor(Math.random() * 15 + 1) * box,
y: Math.floor(Math.random() * 15 + 1) * box
}
function criarBG(){
context.fillStyle = "lightgreen";
// fillstyle trabalha com a cor do nosso elemento
context.fillRect(0, 0, 16 * box, 16 * box);
// o fillrect trab 4 param (x, y, altura, largura)
// cada quadrado do canvas vai ter 32 pixes que foi
// definido na variável box
}
// função criarCobra
function criarCobrinha(){
/**
* O for vai percorre todo o tamanho do nosso array e
* vai incrementar. Quando ele tiver a incrementação,
* ele vai pintar o corpo da nossa cobrinha de verde e
* vai setar o tamanho dela certinho.
*/
for(let i = 0; i < snake.length; i++){
/**
* vamos passar o context novamente, só que ele
* estará ligado a nossa cobrinha
*/
context.fillStyle = "green";
context.fillRect(snake[i].x, snake[i].y, box, box);
}
}
function drawFood(){
context.fillStyle = "red";
context.fillRect(food.x, food.y, box, box);
}
document.addEventListener('keydown', update);
function update(event){
if(event.keyCode == 37 && direction != "right") direction = "left";
if(event.keyCode == 38 && direction != "down" ) direction = "up";
if(event.keyCode == 39 && direction != "left" ) direction = "right";
if(event.keyCode == 40 && direction != "up" ) direction = "down";
}
/**
* 1- A cobrinha vai ser um array de coordenadas, agente vai
* 2- Adicionar um elemento e ritrar o ultimo;
* 3- Criar as coordenadas da nossa cobrinha
*/
function iniciarJogo(){
for(let i = 1; i < snake.length; i++){
if(snake[0].x == snake[i].x && snake[0].y == snake[i].y){
clearInterval(jogo);
alert("Game Over");
}
}
if(snake[0].x > 15 * box && direction == "right") snake[0].x = 0;
if(snake[0].x < 0 * box && direction == "left") snake[0].x = 16 * box;
if(snake[0].y > 15 * box && direction == "down") snake[0].y = 0;
if(snake[0].y < 0 * box && direction == "up") snake[0].y = 16 * box;
criarBG();
criarCobrinha();
drawFood();
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if(direction == "right") snakeX += box;
if(direction == "left") snakeX -= box;
if(direction == "up") snakeY -= box;
if(direction == "down") snakeY += box;
if(snakeX != food.x || snakeY != food.y){
snake.pop()
}else{
food.x = Math.floor(Math.random() * 15 + 1) * box;
food.y = Math.floor(Math.random() * 15 + 1) * box;
}
let newHead = {
x: snakeX,
y: snakeY
};
snake.unshift(newHead);
}
let jogo = setInterval(iniciarJogo, 100);
/**
* mexer agora com os controle para a cobrinha não
* desaparecer na tela
*/
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/HTML/index.html
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../CSS/style.css">
<title>JavaScript</title>
</head>
<body>
<div class="body-central">
<div class="corpo-texto">
<p class="texto">Mozila is Cool, Lucas</p>
</div>
<div class="imagem-mozila">
<img src="../image/mozila-foto.png" alt="Logo da Mozila">
</div>
<div class="texto-restante">
<p>At Mozilla, we're global community of</p>
<div class="ordenar">
<ul>
<li>technologists</li>
<li>thinkers</li>
<li>builders</li>
</ul>
</div>
<p>
working together to keep the internet alive ande acessible, so people<br>
worldwide can be informed contributors ande creators of the web. we <br>
believe this act of human collaboration across an open platform is <br>
essential to individual growth and our collective future.
</p>
<p>
Read the <a href="#">Mozilla Manifesto</a> to learn even more about the values and <br>
principles that guide the pursuit of our mission.
</p>
</div>
<div class="btn-click">
<a href="#">Change Useer</a>
</div>
</div>
</body>
</html><file_sep>/Introducao_JavaScript/Programacao-Para-Internet-com-JavaScript/JS/main2.js
/*function soma(n1, n2){
return n1 + n2
}
console.log(soma(5, 3))
function setReplace(frase, nome, novo_nome){
console.log("Frase antiga: \nVai " + nome);
console.log("Frase nova: ");
return frase.replace(nome, novo_nome);
}
console.log(setReplace("Vai Angola", "Angola", "Dinamarca"))
*/
function apertou(){
var texto = document.getElementById("elemento").innerHTML
console.log(texto)
}
function redirecionar1(){
window.open("https://www.google.com");
}
function redirecionar2(){
window.location.href = "https://www.google.com";
}
function mouseMover(elemento){
elemento.style.color = "#00f";
elemento.innerHTML = "Não conseguir fazer o que eu quiz";
}
function voltar(elemento){
elemento.style.color = "#f00";
elemento.innerHTML = "Teste";
}
function load(){
console.log("Página carregada");
}
function pegar(elemento){
var ele = elemento.value
var valor = parseInt(ele)
console.log(valor + 10);
}
<file_sep>/Arquitetura_Sistema/Aula02/3-parte.md
# Gerenciamento de erros e volume de acesso
## Gerenciamento de erros
### Onde é mais complexo:
* Processos assíncronos (Microsserviços #2)
* Pipeline
### Solução:
* Dead letter queue
* Filas de re-tentativas
https://github.com/jeffhsta/fundamentos_arquitetura
<file_sep>/Arquitetura_Sistema/Aula01/3-parte.md
## WSDL
* WSDL - Web Services Description Language.
* Usado para descrever Web Services, funciona como um
contrato do serviço.
* A descrição é feito em um documento XML, onde é
descrito o serviço, especificações de acesso, operações
e métodos.
## XSD
* XSD - XML Schema Definition
* É um shema no formato XML usado para definir a estrutura
de dados que será validade no XML.
* O XSD funciona como uma documentação de como deve ser
motando o SOAP Message (XML) que será envidao através de
Web Service.
VAMOS À PRÁTICA..
www.soapclient.com/xml/soapresponder.wsdl
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/script/Aula02-Parte1/Aula02-Object2.js
const user = {
name: 'Lucas',
lastName: '<NAME>'
};
// Recupera as chaves do objeto
console.log('Propriedade do objeto user: ', Object.keys(user));
// Recupera os valores das chaves do objeto
console.log('\nValores das propriedades do objeto user: ', Object.values(user));
// Retorna um array de arrays contendo [nome_prop, valor_prop]
console.log('\nLista de propriedades e valores: ', Object.entries(user));
// Margear propriedades de objetos
Object.assign(user, {fullName: '<NAME>'});
console.log('\nAdiciona a propriedade fullName no objeto user', user);
// Pensando em imutabilidade o comando de cima não é recomendado
/**
* Não é recomendado alterar o objeto ou array principal, a ideia é que seja gerado um novo.
* Toda vez que formo mergiar um array ou objeto é passar o primeiro parâmetro um objeto ou array
* vázio, ai assim faz o margi. mergi é o comando acima e abaixo está a maneira recomendada,
* que foi descrita nesse texto.
*/
console.log('\nRetorna um novo objeto margeando dois ou mais objetos', Object.assign({}, user, {age: 28}));
/**
* Quando é criado um objeto const, agente não consegui mudar o local
* para aonde ele está apontando; mas suas propriedades podem ser trocadas.
*
*/
// Previne todas as alterações em um objeto
const newObj = {fod: 'bar'};
Object.freeze(newObj);
/**
* Com o comando .freeze não deixa ou não é possivel trocar as
* propriedades do objeto e nem o objeto
*/
newObj.fod = 'changes';
delete newObj.fod;
const person= {name: '<NAME>'};
Object.seal(person);
person.name = '<NAME>';
delete person.name;
person.age = 26;
console.log('\nVariável person após as alterações ', person);
/**
* metodo seal
* Não permite que vc ou delete nenhuma propriedade do objeto
* É possivel trocar o valor de uma propriedade que já existe
* dentro dele.
*/
<file_sep>/Arquitetura_Sistema/Aula03/4-parte.md
#### Arquitetura é escolha
MQTT MQTT
GPS -> Broker -> Worker -> Data store
Eu preciso escolher o vou ultilizar como broker
App -> Eclipse -> Node.js -> Banco de
Android Mosquitto Dados MySQL
#### Mínimo Produto Viável
GPS -> HiveMQ -> Akka -> Banco de
Embarcado Scala Dados noSQL
JVM
#### Solução
GPS -> AWS IoT -> AWS -> AWS S3
Embarcado Core Kinesis
Firehose
#### IoT na prática
GPS Embarcado
AWS IoT Core
AWS Data Stream
AWS Lambda
AWS ElasticCache Redis
AWS EC2
FeathersJS Backend
Dashboard
<file_sep>/Arquitetura_Sistema/Aula03/2-parte.md
# Arquitetura da Internet das Coisas
### Conectando as coisas...
* Como conectar as coisas ?
### Considere esses atributos na escolha
* Baixo consumo de energia
* Rede de dados limitado
* Resiliencia
Armazenar os dados localmente, enquanto eu não tenho
rede(Buffer).
* Segurança
* Customização
o que vc estar desenvolvendo vai sempre encontrar um
ambiente heterogeneo.
* Baixo Custo
### Arduino
* Plataforma de Prototipagem
* Com entradas/saídas
* Desenvolvedor escreve em C/C++
* Interface serial ou USB
* Shields são componentes que vc agrega para poder acessar
a rede
### Embarcados
#### MCUs
* Microcontrolador de chip único
* Sistema operacional real time
* Embarcado
* Uso industrial, médico, militar, transporte
### Minicomputadores
#### Raspberry Pi
* Computador completo
* Hardware inteegrado em uma única placa
* Roda SO Linux ou Windows
* Uso doméstico e comercial
## O protocolo de comunicação
### O protocolo MQTT
Gps Tracker
free RTOS
* Base na pilha do TCP/IP
* Protoolo de mensagem assíncrona (M2M)
* Criado pela IBM para conectar sensores de pipelines de
petróleo a satétiles
* Padrão OASIS suportado pelas linguagens de programação
mais populares.
###### (modelo cliente servidor)
* modelo sincrono
###### (Modelo Pushish/Subscribe)
* Separação de quem manda a mensagem de quem é o receptor
da mensagem
* Capacidade de escalabilidade maior que o client-server
#### Publish
* ter um endereço desse broker
* topico um endereço aonde vai ser entregue a informação
<file_sep>/Arquitetura_Sistema/Aula04/3-parte.md
# SGDBR - SQL
* Linguagem
* DDL - Data Definition Language
* DML - Data Manitulation Language
* DQL - Data Query Language
### DDL
* comando que cria uma tabela
create table Cliente{
Codigo number(10) not null primaty key
Nome varchar(50) not null,
Telefone varchar(15)
}
### DML
insert into Cliente(Codigo, Nome, Telefone)
values (1, "<NAME>", "(88) 999 9999")
delete from cliente where Codigo = 1
Update Cliente set Nome = "<NAME>" where
Codigo = 1
### DQL
Select Codigo, Nome from Cliente
<where> Codigo = 1
<Group by> Profissao
<Having> Count(1) > 0
<Order by> Nome, Codigo
Select Codigo, Nome from Cliente
where Codigo = 1
Union
Select Codigo, Nome from Cliente
where Nome = "<NAME>"
Select Quantidade, valor, Descricao from item_venda
join Produto
on Codigo = Cod_Produto
where valor > 4
### Funções de Conjunto
Select Sum(ven.Quantidade) as QTotal,
Sum(ven.Valor) as VTotal,
pro.Descricao
from Item_venda ven
Join Produto pro
on pro.Codigo = ven.Cod_produto
where ven.Valor > 5
Group by pro.Descricao
Having Sum(ven.Valor) >= 10
### Index
Select ...
where Profissao = 1 and Genero = "M"
index é uma pequena tabela extraida da tabela original
com as coluna que eu desejo
<file_sep>/Linux/Aula02.md
# Instalação e Configuração
<file_sep>/Introducao_JavaScript/Programacao-Para-Internet-com-JavaScript/Aula02.md
# Desenvolva Páginas web
# Maniplando elementos da página
- evento onclick
- pegando elemento atravéz de getElementById
- usando innerHTML
- usando o objeto window com método open, permitindo redirecionar para
uma página html externa, mas abre em outra janela
- window.location.href para redirecionar para uma página html externa,
mas abre na mesma janela
- onmouseover dispara quando o mouse está se movendo em cima do objeto
- onmousemove dispara quando o mouse está se movendo
- onmouseout dispara quando o mouse estar fora do objeto
- this passa o próprio objeto como parâmetro
- onload dispara quando a página é carregada
<file_sep>/Arquitetura_Sistema/Aula04/1-parte.md
### Conceito de Dados
* Dados de uma maneira geral é um conjunto de valores e
ocorrencias que descrevem alguma instância, algumas
ocorrencia ou alguma caracteristica.
### importância
* De DADOS nós podemos extrair: informações, e com a
informação, nós temos o conhecimento; o conhecimento nos
ajuda a tormar decisões, a evoluir sistemas de coisas, a
uma empresa gerenciar e uma infinidade de coisas.
### Dados Digitais
Lorem Ipsum (00)99999-1111 120,19
* Um arquivo texto é um formato de dado digital
* Os dados não tem uma explicação por se só
Velit Esse Cillum (55)99999-2222 1.300,19
### Modelo Sustentável
#### Estruturação
#### Durabilidade
#### Velocidade
#### Controle de Acesso
#### Isolamento
### Exercício Final
1 - O que podemos extrair de dados brutos
a) Apenas atributos
b) Uma descrição de como aconteceram
c) Informações e com ela o conhecimento
d) Nenhuma das anteriores
# O que é um Banco de Dados
* Sistema ou conjunto de sistemas que gerencia esses
dados, permite que nós tenhamos acesso, controle,
redudância e segurança sobre esses dados.
### Abstração
* Pegar os dados que está no meio físico e abstratir
esses dados numa visão que seja pratica que traga
informação.
### SGDBs
* Esses sistemas são chamados de SGDBs ou Sistemas
Gerenciadores de Banco de Dados.
* No nível de abstração foram criados linguagens e
ferramentas que controlam todos esses mecanismo
-> Linguagem de Definição: Aonde posso definir como
é a estrutura dos meus dados.
-> Linguagem de Manipulação: AOnde eu recupera essa
informação ou minipulo esses dados.
-> Dicionário de Dados: que é um banco de dados dentro
do banco de dados que guarda toda essa estrutura.
### Modelos de Banco de Dados
#### Modelo Flat
Nome Telefone Profissão
* Registro 1 Lorem (99) 11111 1111 Vendedor
Ipsum
#### Modelo Hierárquico
Administrativo
/ | \
Vendedor Analista Manutenção
* Armazenado em arvores
* Não mais ultilzado
* tem redudância de informaçõa
#### Modelo Relacional
* Modelo mais ultilizado no momento
#### Modelo Redes - Grafo
#### Modelo Orientado a Objetos
#### Modelo Objeto-Relacional
#### Modelo Big Data
1- O que é um SGDB ?
a) Varios Arquivos com informações
b) Um sistema de Abstração
c) Um sistema que gerencia banco de dados x
d) Uma biblioteca de tabelas
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/Anotaçoes/Aula04-Parte2.md
# Manipulação e iterações de arrays Parte-2
### forEach
Iteração de cada item dentro de um array
### map
Retorna um novo array, de mesmo tamanho, iterando cada
item de um array
### flat
Retorna um novo array com todos os elementos de um sub-
array concatenados de forma recursiva de acordo com a
profundidade especificada(depth)
### flatMap
Retorna um novo array assim como a função map e execulta
um flat de profundidade 1.
### Keys
Retorna um *Array* *Iterator* que contém as chaves para
cada elemento do array.
### values
Retorna um *Array* *Iterator* que contém os valores para
cada elemento do array.
### Entries
Retorna um *Array* *Iterator* que contém os pares chaves/
valor para cada elemento do array.
### Find
Retorna o primeiro item de um array que satisfaz a
condição.
### FindIndex
Retorna o índece do primeiro item de um array que satifaz
a condição.
### filter
Retorna um novo array com todos os elementos que
satisfazem a condição.
### indexOf
Retorna o primeiro índice em que um elemento pode ser
encontrado no array.
### lastIndexOf
Retorna o último índice em que um elemento pode ser
encontrado no array
### includes
Retorna um booleano verificando se determinado elemento
existe no array.
### some
Retorna um booleano verificando se pelo menos um item de
um array satisfaz a condição.
### every
Retorna um booleano verificando se todos os itens de um
array satisfazem a condição.
### sort
Ordena os elementos de um array de acordo com a condição
### reverse
Inverte os elementos de um array
### join
Junta todos os elementos de um array, separados por um
delimitador e retorna uma string
### reduce
Retorna um novo tipo de dado iterando cada posição de um
array
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/script/Aula02-Parte1/Aula02-number.js
const myNumber = 12.4032;
// Transforma número para string
const numberAsString = myNumber.toString();
console.log('Número transformado em String: ', typeof(numberAsString));
// Retorna número com um número de casas decimais
const fixedTwoDecimals = myNumber.toFixed(2);
console.log('\nNúmero com duas casas decimais: ', fixedTwoDecimals);
// transfoma uma string em float
console.log('\nString parseada para float: ', parseFloat('13.20'));
// Transforma uma string em int
console.log('\nString passado para int: ', parseInt('15'));
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/Anotaçoes/Aula03-Parte1.md
# Orientação a objetos
## Herança
-> Baseada em protótipos
-> prototype é uma variável que armazena as definições
do nosso objeto
-> __proto__ aponta para o prototype do tipo que foi
criado.
-> constructor
'use strict'
const myText = 'Hello prototype';
myText.split('');
A declaração de acima é a mesma dessa
const myText = String('Hello prototype!');
console.log(myText.__proto__.split);
Ele está usando a função construtora string; então, a função
construtora já carregada um prototype.
Toda função construtora tem um prototype atrelada a ela e toda
vez que eu crio uma variável, a parti da função construtora, eu vou ter essa referencia do proto atrelada a ela.
__proto__ -> prototype -> constructor
Um proto aponta para um prototype, e esse prototype é criado
apartir de um constructor.
myText.constructor -> String
myText.__proto__ -> String.prototype
function Animal() {}
console.log(Animal.constructor);
f Animal.constructor -> Function -> Function.prototype.
constructor -> Object.prototype = null
O que ocorre ?
1 - Um novo objeto é criado, herdando Foo.prototype
2 - A função construtora Foo é chamad com os argumentos
especificados e com o `this` vinculado ao novo objeto
criado.
3- Caso a função construtora tenha uma retorno explicito,
será respeitado o seu `return`, senão, será retornado o
objeto criado no passo 1.
Classes
-> ES6
-> Simplificação da herança de prototipes
-> palavra chave class
Modificadores de acesso (Atualmente não existe <br>
modificadores de acesso no JS)
-> privado/público
-> criação de atributos privados com o #
Encapsulamento
-. Ocultar detalhe dos funcionamento interno
Static
-> Ele permite que agente acesse métodos ou atributos
sem instanciar determinada classe
<file_sep>/Arquitetura_Sistema/Aula01/4-parte.md
## Rest
* REST - Representational State Tranfer
* É um estilo de arquitetura de software que define a
implementçaõ de um serviço web.
* Podem trabalhar com os formatos XML, JSON ou outros.
Não importa como ele é, mas sim como ele estar.
## Vantagens do REST
* Permite integrações entre aplicações e também entre
cliente e servidor em página web e aplicações.
* Utiliza dos métodos HTTP para definir a operação que
está sendo efetuada.
* Arquitetura de fácil compreensão.
## Estrutura do REST
cliente -> -> -> -> -> -> -> -> -> -> Servidor
O cliente está tentando uma requisão com o servidor usando
HTTP (GET, POST, PUT, DELETE...), o servidor responde com
um código de operação, retorna uma mensagem (Texto, JSON,
XML...);
Quando uma aplicação web disponibiliza um conjuto de
rotinas e padrões através de serviços web podemos chamar esse
conjunto de API.
## API
* API - Application Programming Interface.
* São conjuntos de rotinas documentados e disponibilizados
por uma aplicação para que outras aplicações possam
consumir suas funcionalidades.
* Ficou popular com o aumento dos serviços web.
* As maiores plataformas de tecnologia disponibilizam APIs
para acessos de sua funcionalidades, algumas delas são:
Facebook, Twitter, Telegram, Whatapp, GitHub...
## Principais métodos
* GET - solicita a representação de um recurso.
* POST - solicita a criação de um recurso
* DELETE - Solicita a excluão de um recurso.
* PUT - Solicita a atualizaão de um recurso.
## JSON
* JSON - JavaScript Object Notation.
* Formatação leve utilizada para troca de mensagens entre
sistemas.
* Usa-se de uma estrutra de chave e valor e também de
listas ordenadas.
* um dos formatods mais populares e mais utilizados para
troca de mensagens entre sistemas.
{
"nome": "<NAME>",
"ano_lancamento": "2019",
"personagens":[
{
"nome: "Thanos"
},
{
"nome: "<NAME>"
},
{
"nome: "Thor"
}
]
}
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/script/Aula02-Parte3/1-condicionais.js
const array = [0, 1, 2, 3, 4, 5];
array.forEach( item => {
if(item % 2 === 0){
console.log(`O número ${item} é par.`);
}else{
console.log(`O número ${item} é impar`);
}
});
array.forEach(item => {
if(item % 2 == 0){
console.log("Dividido por 2");
}else if(item % 3 === 0){
console.log("Dividido por 3");
}else{
console.log("Dividido por outro número");
}
})
// switch - case
const fruit = 'banana';
switch(fruit){
case 'banana':
console.log("R$ 3,00/ Kg");
break;
case 'goiaba':
console.log("R$ 4,00/ Kg");
break;
default:
console.log("Não tem sua fruta.");
}
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/script/Aula02-Parte2/1-logicos.js
// ANd logico (&&)
exp1 && epx2
var a1 = true && true; // retorna ture
var a2 = true && false; // retorna false
var a3 = false && true; // retorna false
var a4 = false && (3 == 4); // retorna false
var a5 = "Gato" && "Cao"; // retorna cao
var a6 = false && "Gato"; // retorna false
var a7 = "Gato" && false; // retorna false
// OU logico (||)
exp1 || exp2
var a1 = true && true; // retorna true
var a2 = true && false; // retorna true
var a3 = false && true; // retorna true
var a4 = false && (3 == 4); // retorna false
var a5 = "Gato" && "Cao"; // retorna Gato
var a6 = false && "Gato"; // retorna Gato
var a7 = "Gato" && false; // retorna Gato
// NOT logico (!)
!exp1
var n1 = !true; // retorna false
var n2 = !false; // retorna true
var n3 = !"Gato"; // retorna false
// o que retorna true
" "
1
['teste']
// o que retorna false
""
0
//[]
//!!
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/Anotaçoes/Aula02.md
# Tipos, Variáveis, Operadores, condicionais e repetição
## Tipos e Variáveis
* String
- Para textos
* number
- Numeros
* boolean
- Verdadeiro ou Falso
* null
-
* undefinded
- A variável existe mais não foi definida
* symbol
- Permite criar valores únicos
* Object
-
* Function
- É um objeto que permite que o objeto seja chamado
* Array
## Operadores
* Aritméticos
* Atribuição
* Comparação
* Condicional
* Lógicos
* Spread
<file_sep>/Arquitetura_Sistema/Aula02/2-parte.md
## Pros e contra Monolito
### Pros
* Baixa complexidade
* Monitoramento simplificado
### Contra
* Stack única
* Compartilhamento de recursos
* Acoplamento
* Mais complexo o escalabilidade
## Pros e Contra Microserviços #1
### Pros
* Stack dinâmica
* Simples escalabilidade
### Contra
* Acoplamento
* Monitoramento mais complexo
* Provisionamento mais complexo
## Pros e Contra Microserviços #2
### Pros
* Stack dinâmica
* Simples escalabilidade
* Desacoplamento
### Contra
* Monitoramento mais complexo
* Provisionamento mais complexo
## Pros e Contra Microserviços #3
### Pos
* Stack dinâmica
* Simples escalabilidade
* Desacoplamento
* Menor complexidade
### Contra
* Provisionamento mais complexo
* Plataforma inteira depende do gerenciador de pipeline
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/script/Aula03/1-Parte/exemplo.js
'use strict';
console.log(String.prototype.split);
const myText = String('Hello prototype!');
console.log(myText.__proto__.split);
console.log(myText.__proto__.split === String.prototype.split);
new Foo()
class Animal{
constructor(qtdePatas){
this.qtdePatas = 4;
}
}
<file_sep>/Arquitetura_Sistema/Aula04/5-parte.md
# SGDBs - R
* Oracle
* Microsolt SQL Server
* IBM DB2
* PostgreSQL
* MySQL
* SQLite
https://www.postgresql.org/download/windows/
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/script/Aula02-Parte1/Aula02-booleano.js
/**
*
*/
const isActive = true;
const isAuthenticated = false;
console.log('Tipo da virávlel: ', typeof isActive);
<file_sep>/Introducao_JavaScript/Programacao-Para-Internet-com-JavaScript/Aula01.md
# Introdução ao JavaScript
## JavaScript
* Linguagem de script e multiplataforma
* Client Side - É executado do lado do cliente(usuário)
* Tem capacidade de interagir com elementos de uma página HTML
* Muito usado no desenvolvimento de página e tarefas de aplicativos mobile híbridos
## DOM (Document Objecti Model)
* JavaScript pode alterar todos elementos do HTML
* JavaScript pode alterar todos os atributos e estilos de CSS de uma página
## Como fazer o javascript Interagir com o HTML
- Abrir uma tag scrip e dar comandos javascript
dentro dessa tag
- Ou criar um arquivo externo e usar o tag link
para link o javascript e o Html
## Caracteristicas do JavaScript
- Tipagem dinâmica
## Comandos
- alert -> apresenta uma mensagem na pela quando a página é carregada
- console.log imprimi uma mensagem no console do navegador
- var -> criar uma variável que pode ter qualquer tipo, o navegador
vai traduzir o tipo da variável quando for imprimir
- string.toUperCase -> joga todas as letras da strings para maiusculas
- string.toLowerCase -> joga tudo para minusculas
- pop() -> retira o ultimo elemento da lista
- push() -> acrescenta um elemento na minha lista
- tostring() -> transforma a lista em um string separada por virgula
- .join() -> voce consegue alterar o separador , por outra coisa
<file_sep>/Arquitetura_Sistema/Aula01/1-parte.md
# Fundamentos de Arquitetura de sistemas
## Serviços Web
- Serviços Web ou Web Services são soluções para
aplicações se cominicarem independente de linguagem,software
e hardwares utilizados.
- Inicialmente Serviços Web foram criados para troca de
mensagens utilizando a linguagem XML(Extensible Markup
Languagem) sobre o protocolo HTPP sendo identificado por URI
(Uniform Resource Identifier).
- Podemos dizer que Serviços Web são API's que se
comunicam por meio de redes sobre o protrocolo HTPP.
#### ilustração
- Aplicação x
- Banco de dados x
- Aplicação y
- Banco de dados y
Essas aplicações precisando se comunicar, mas elas são
feitas com tecnologias diferentes: uma usa python, a outra usa
java; o banco de dados, é feita em oracle e o da outra
em postgree: como fazer elas se comunicarem ?
- web service vai ter o acesso a banco de dados, da
aplicação x; a diferença é que ele vai expor uma URI, para que
a aplicação y tenha acesso. O web service vai fazer uma troca
de mensagem, através de:
* XML, JSON e outras linguagens.
Exemplo de XML:
<endereco>
<cep>9999-99</cep>
<bairro>Jardim Paulista</bairro>
<logradouro>Av. Paulista</logradouro>
<cidade>São Paulo</cidade>
<numero>99</numero>
</endereco>
Exemplo:
{
"endereco":{
"cep" : "99999-99",
"logradouro": "Av. Paulista",
"bairro" : "<NAME>",
"cidade" : "São Paulo",
"numero" : 99
}
}
## Vantagens
* Linguagem comum
* Integração
* Reutilização de implementação
* Segurança
* Custos
## Principais Tecnologias
* SOAP
* REST
* XML
* JSON
<file_sep>/Arquitetura_Sistema/Aula01/5-parte.md
## Código de Estado
* Usado pelo servidor para avisar o cliente sobre o
estado da operação solicitada
* 1xx - Informativo
* 2xx - Sucesso
* 3xx - Redirecionamento
* 4xx - Erro do Cliente
* 5xx - Erro do Servidor
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/script/Aula02-Parte2/1-comparacao.js
// Igual (== )
// Retorna verdadeiro caso os opernados sejam iguais. -3 == var1
'3' == var1
3 == '3'
// Não igual (!=)
// Retorna verdadeiro caso os operandos não sejam iguais. -var1 != 4
var2 != '3'
// Estritamente igual (===)
// Retorna verdadeiro caso os oerando sem iguais e do mesmo tipo. Vejam tambem objct. is e igualdade
3 === var1
// Estritamente não igual (!==)
// Retorna verdadeiro aso os operandos não sejam iguais e/ou não sejam do mesmo tipo
var1 !== 3
3 !== '3'
// Maior que (>)
// retorna verdadeiro caso o operando da esquerda seja maior que o da direitia
var2 > var1
"12" > 2
// Maior que ou igual (>=)
// Retorna verdadeiro caso o operando da esquerda seja maior ou igual ao da direita
var2 = var1
var1 >= 3
// Menor que (<)
// Retonra vverdaeiro caso o operando da esquerda seja menor que o da deireita
var1 < var2
'12' < '2'
// Menor que ou igual (<=)
// Retorna verdadeiro caso o operando da esquerda seja menor ou igual ao da direita
var1 <= var2
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/script/Aula03/2-Parte/factory.js
// Exemplo de uma função que não é factory
function FakeUser1(){
this.name = 'Lucas';
this.lastName = 'Santos';
}
const user = new FakeUser1();
// exemplo de factory
function FakeUser2(){
return {
name: 'Lucas',
lastName: 'Santos'
}
}
const user2 = FakeUser2();
<file_sep>/Linux/Aula01.md
# Requisitos Básicos
Processador dual core de 2 GHz ou Superior
2 GB de memória RAM
40 GB de espaço livre no disco rígido
## Parte 1 - Historico
### Fundamentos de Linux
Criado em 1991 por Linux Torvalds
O Linux é o Kernel Ou Núcleo do Sistema Operacional
HardWare --> Kernel(Linux) --> Shell(linha de comandos)
O Linux não é o sistema operacional, ele é o Kernel, quem dá a vida pro sistema operacional
É desenvolvido por diversas pessas e empresas ao
redor do mundo
Multitarefa/Multiusuário
Existe várias versões do kernel linux e existe
vários sistemas operacionais criado no linux
## Fundamentos de Linux Distribuições
O Linux pode ser "distribuído" por empresas
organizações ou mesmo pessoas, que podem colocar
características próprias no S.O, como configurações,
aplicações, sistema de instalação entre outras
peculiaridades, assim damos o nome de distribuição,
sua escolha é pessoal e depende da aplicação.
## Distribuições mais conhecidas:
- Ubuntu
- Debian
- Suse
- fedora
- Red Hat
- Kali
## O Sistema Operacional Ubuntu
O Ubuntu é um S.O de código aberto que é
desenvolvido pela Canonical com base no Kernel Linux,
tem bases non Debian e Hoje é muito aceito por muitas
comunidades de usuários.
<file_sep>/Introducao_JavaScript/JavaScript_ES6_essicial/Anotaçoes/Aula03-Parte2.md
# Design patterns
### Definição
Design Patterns ou padrões de projetos são soluções
generalistas para problemas recorrentes durante o
desenvolvimento de um software. Não se trata de um framework
ou um código pronto, mas de uma definição de alto nível de
como um problema comum pode ser solucionado.
### A Pattern Language
- 1978
- <NAME>, <NAME> e <NAME>
- 253 tipos de problemas/desafios de projetos
### Formato de um pattern
- Nome
- Exemplo
- Contexto
- Problema
- Solução
### Using Pattern Languages for Object-Oriented Programs
- 1987
- <NAME> e <NAME>
- 5 padrões de projetos
### Design Patterns: Elements of Reusable Object-Oriented Software
- 1994
- Gang of Four(GoF)
- <NAME>, <NAME>, <NAME> e <NAME>
### Tipos
- Criação
- Estruturais
- Comportamentais
#### Padrões de criação
Os padrões de criação são aqueles que abstraem e/ou adiam
o processo criação dos objetos. Eles ajudam a tornar um
sistema independente de como seus objetos são criados,
compostos e representados.
- Abstrat Factory
- Builder
- Factory Method
- Prototype
- Singleton
#### Padroes estruturais
Os padrões estruturais se preocupam com a forma como
classes e objetos são compostos para formar estruturas
maiores.
- Adapter
- Bridge
- Composite
- Decorator
- Facade
- Business Delegate
- Flyweight
- Proxy
#### Padrões comportamentais
Os padrões de comportamento se concentram nos algoritmos e
atribuições de responsabilidades entre os objetos. Eles não
descrevem apenas padrões de objetos ou de classses, mas
também os padrões de comunicação entre os objetos.
- Charin of Responsibility
- Command
- Interpreter
- Iterator
- Mediator
- Observer
- State
- Strategy
- Template Method
- Visitor
### Patterns mais utilizados
- Factory
- Singleton
- Decorator
- Observeer
- Module
#### Factory
Todas as funções que retornam um objeto, sem anecessidade
de chamá-las com o new, são consideradas funções Factory
(fabrica).
- Exemplo do que não é uma função factory
function FakeUser(){
this.name: 'Lucas';
this.lastName: 'Santos'
}
const user = new FakeUser();
- Exemplo de factory
Function FakeUser(){
return{
name: 'Lucas',
lastName: 'Santos'
}
}
// Factory
const user = FakeUser();
#### Singleton
O objetivo desse patterns é criar uma única instância de
uma função construtora e retorná-la toda vez em que for
necessário utilizá-la.
Exemplos:
var SETTINGS = {
api: 'http://localhost',
trackJsToken: '<PASSWORD>'
}
function MyApp(){
if(!MyApp.instance){
MyApp.instance = this;
}
return MyApp.instance;
}
#### Decorator
Uma função decorator recebe uma outra função como
parâmetro e estende o seu comportamento sem modificá-la
explicitamente.
#### Observeer
É um pattrn muito popular em aplicações javascript. A
instância(subscriber) mantém uma coleção de objetos
(observers) e notifica todas eles quando ocorrem mudanças
no estado.
#### Module
É um pattern que possibilita organizarmos melhor o nosso
código, sem a necessidade de expor variáveis globais.
<file_sep>/Projeto_Netflix/js/owl/teste.js
let x = 500.0;
let y = 35.0
const precisao = 1000;
let valor = x / y;
console.log(((valor * precisao)/precisao).toFixed(3));
<file_sep>/Arquitetura_Sistema/Aula03/3-parte.md
## A flexibilidade dos tópicos
* protocolo: mqtt
* ://
* broker: broker.io
* /
* user identifier: a6g319
* /
* sensor: gps
* /
* Information Type: position
#### publish
* pub mqtt://broker/a6fb45/gps/position
#### subscribe
* mqtt://broker/user/gps/position
Temos que ter alguns níveis de garantia que esse protocolo vai
funcionar
#### QoS 0
Publish
MQTT Client ---> MQTT Broker
* Nível mínimo de menor esforço
* Sem garantia de entrega
* Mensagem não é retransmitida
#### QoS 1
Publish
MQTT Client ---> MQTT Broker
Puback
* Garante que a mensagem foi entregue no mínimo uma vez
ao recebedor
* Mensagem pode ser retransmitida se não houver
confirmação de entrega
#### QoS 2
+-----------+ Publish -> +-------------+
|MQTT Client| Pubrec <- | MQTT Broker |
+-----------+ Pubrel -> +-------------+
Pubcamp <-
* Garante que a mensagem foi entregue no minimo uma vez
ao recebedor
* Mensagem pode ser retransmitida se não houver
confirmação de entrega.
## Cloud
* Grande e cada vez maior número de devices conectados
* TBs ou PBs de informações
* Potencial de escala global
worker -> Data store
/
broker
\
worker -> cache -> tela
worker é a minha aplicação, meu codigo
| 2e3f248b8d626cdb91f49ed8bfb78ed8d12f17b0 | [
"JavaScript",
"C#",
"HTML",
"Markdown"
] | 44 | JavaScript | Lucas-Souza-Santos/Avanade | e09f1092b47b7fb959715a6ae848201451263ac3 | da2a0e68aff12f41be2fb0bff60bfb455df0bf28 | |
refs/heads/master | <file_sep># LEGIONTDBETA
New Legion TD remake on Dota 2
<file_sep>print ('[LEGION_TD] legionTD.lua' )
-- GameRules Variables
ENABLE_HERO_RESPAWN = true -- Should the heroes automatically respawn on a timer or stay dead until manually respawned
UNIVERSAL_SHOP_MODE = false -- Should the main shop contain Secret Shop items as well as regular items
ALLOW_SAME_HERO_SELECTION = true -- Should we let people select the same hero as each other
HERO_SELECTION_TIME = 1.0 -- How long should we let people select their hero?
PRE_GAME_TIME = 0.0 -- How long after people select their heroes should the horn blow and the game start?
POST_GAME_TIME = 60.0 -- How long should we let people look at the scoreboard before closing the server automatically?
TREE_REGROW_TIME = 60.0 -- How long should it take individual trees to respawn after being cut down/destroyed?
GOLD_PER_TICK = 0 -- How much gold should players get per tick?
GOLD_TICK_TIME = 99 -- How long should we wait in seconds between gold ticks?
RECOMMENDED_BUILDS_DISABLED = true -- Should we disable the recommened builds for heroes (Note: this is not working currently I believe)
CAMERA_DISTANCE_OVERRIDE = 1134.0 -- How far out should we allow the camera to go? 1134 is the default in Dota
MINIMAP_ICON_SIZE = 1 -- What icon size should we use for our heroes?
MINIMAP_CREEP_ICON_SIZE = 1 -- What icon size should we use for creeps?
MINIMAP_RUNE_ICON_SIZE = 1 -- What icon size should we use for runes?
RUNE_SPAWN_TIME = 120 -- How long in seconds should we wait between rune spawns?
CUSTOM_BUYBACK_COST_ENABLED = true -- Should we use a custom buyback cost setting?
CUSTOM_BUYBACK_COOLDOWN_ENABLED = true -- Should we use a custom buyback time?
BUYBACK_ENABLED = false -- Should we allow people to buyback when they die?
DISABLE_FOG_OF_WAR_ENTIRELY = true -- Should we disable fog of war entirely for both teams?
USE_STANDARD_HERO_GOLD_BOUNTY = true -- Should we give gold for hero kills the same as in Dota, or allow those values to be changed?
USE_CUSTOM_TOP_BAR_VALUES = true -- Should we do customized top bar values or use the default kill count per team?
TOP_BAR_VISIBLE = true -- Should we display the top bar score/count at all?
SHOW_KILLS_ON_TOPBAR = true -- Should we display kills only on the top bar? (No denies, suicides, kills by neutrals) Requires USE_CUSTOM_TOP_BAR_VALUES
ENABLE_TOWER_BACKDOOR_PROTECTION = false -- Should we enable backdoor protection for our towers?
REMOVE_ILLUSIONS_ON_DEATH = false -- Should we remove all illusions if the main hero dies?
DISABLE_GOLD_SOUNDS = false -- Should we disable the gold sound when players get gold?
END_GAME_ON_KILLS = true -- Should the game end after a certain number of kills?
KILLS_TO_END_GAME_FOR_TEAM = 50 -- How many kills for a team should signify an end of game?
USE_CUSTOM_HERO_LEVELS = true -- Should we allow heroes to have custom levels?
MAX_LEVEL = 50 -- What level should we let heroes get to?
USE_CUSTOM_XP_VALUES = true -- Should we use custom XP values to level up heroes, or the default Dota numbers?
-- Fill this table up with the required XP per level if you want to change it
XP_PER_LEVEL_TABLE = {}
for i=1,MAX_LEVEL do
XP_PER_LEVEL_TABLE[i] = i * 100
end
-- Generated from template
if GameMode == nil then
print ( '[LEGION_TD] creating legionTD game mode' )
GameMode = class({})
end
-- This function initializes the game mode and is called before anyone loads into the game
-- It can be used to pre-initialize any values/tables that will be needed later
function GameMode:InitGameMode()
GameMode = self
print('[LEGION_TD] Starting to load legionTD gamemode...')
-- Setup rules
GameRules:SetCustomGameTeamMaxPlayers(DOTA_TEAM_GOODGUYS,4)
GameRules:SetCustomGameTeamMaxPlayers(DOTA_TEAM_BADGUYS,4)
GameRules:SetHeroRespawnEnabled( ENABLE_HERO_RESPAWN )
GameRules:SetUseUniversalShopMode( UNIVERSAL_SHOP_MODE )
GameRules:SetSameHeroSelectionEnabled( ALLOW_SAME_HERO_SELECTION )
GameRules:SetHeroSelectionTime( HERO_SELECTION_TIME )
GameRules:SetPreGameTime( PRE_GAME_TIME)
GameRules:SetPostGameTime( POST_GAME_TIME )
GameRules:SetTreeRegrowTime( TREE_REGROW_TIME )
GameRules:SetUseCustomHeroXPValues ( USE_CUSTOM_XP_VALUES )
GameRules:SetGoldPerTick(GOLD_PER_TICK)
GameRules:SetGoldTickTime(GOLD_TICK_TIME)
GameRules:SetRuneSpawnTime(RUNE_SPAWN_TIME)
GameRules:SetUseBaseGoldBountyOnHeroes(USE_STANDARD_HERO_GOLD_BOUNTY)
GameRules:SetHeroMinimapIconScale( MINIMAP_ICON_SIZE )
GameRules:SetCreepMinimapIconScale( MINIMAP_CREEP_ICON_SIZE )
GameRules:SetRuneMinimapIconScale( MINIMAP_RUNE_ICON_SIZE )
print('[LEGION_TD] GameRules set')
-- Listeners - Event Hooks
-- All of these events can potentially be fired by the game, though only the uncommented ones have had
-- Functions supplied for them.
ListenToGameEvent('dota_player_gained_level', Dynamic_Wrap(GameMode, 'OnPlayerLevelUp'), self)
ListenToGameEvent('dota_ability_channel_finished', Dynamic_Wrap(GameMode, 'OnAbilityChannelFinished'), self)
ListenToGameEvent('dota_player_learned_ability', Dynamic_Wrap(GameMode, 'OnPlayerLearnedAbility'), self)
ListenToGameEvent('entity_killed', Dynamic_Wrap(GameMode, 'OnEntityKilled'), self)
ListenToGameEvent('player_connect_full', Dynamic_Wrap(GameMode, 'OnConnectFull'), self)
ListenToGameEvent('player_disconnect', Dynamic_Wrap(GameMode, 'OnDisconnect'), self)
ListenToGameEvent('dota_item_purchased', Dynamic_Wrap(GameMode, 'OnItemPurchased'), self)
ListenToGameEvent('dota_item_picked_up', Dynamic_Wrap(GameMode, 'OnItemPickedUp'), self)
ListenToGameEvent('last_hit', Dynamic_Wrap(GameMode, 'OnLastHit'), self)
ListenToGameEvent('dota_non_player_used_ability', Dynamic_Wrap(GameMode, 'OnNonPlayerUsedAbility'), self)
ListenToGameEvent('player_changename', Dynamic_Wrap(GameMode, 'OnPlayerChangedName'), self)
ListenToGameEvent('dota_rune_activated_server', Dynamic_Wrap(GameMode, 'OnRuneActivated'), self)
ListenToGameEvent('dota_player_take_tower_damage', Dynamic_Wrap(GameMode, 'OnPlayerTakeTowerDamage'), self)
ListenToGameEvent('tree_cut', Dynamic_Wrap(GameMode, 'OnTreeCut'), self)
ListenToGameEvent('entity_hurt', Dynamic_Wrap(GameMode, 'OnEntityHurt'), self)
ListenToGameEvent('player_connect', Dynamic_Wrap(GameMode, 'PlayerConnect'), self)
ListenToGameEvent('dota_player_used_ability', Dynamic_Wrap(GameMode, 'OnAbilityUsed'), self)
ListenToGameEvent('game_rules_state_change', Dynamic_Wrap(GameMode, 'OnGameRulesStateChange'), self)
ListenToGameEvent('npc_spawned', Dynamic_Wrap(GameMode, 'OnNPCSpawned'), self)
ListenToGameEvent('dota_player_pick_hero', Dynamic_Wrap(GameMode, 'OnPlayerPickHero'), self)
ListenToGameEvent('dota_team_kill_credit', Dynamic_Wrap(GameMode, 'OnTeamKillCredit'), self)
ListenToGameEvent("player_reconnected", Dynamic_Wrap(GameMode, 'OnPlayerReconnect'), self)
-- Change random seed
local timeTxt = string.gsub(string.gsub(GetSystemTime(), ':', ''), '0','')
math.randomseed(tonumber(timeTxt))
-- Initialized tables for tracking state
self.vUserIds = {}
self.vSteamIds = {}
self.vBots = {}
self.vBroadcasters = {}
self.vPlayers = {}
self.vRadiant = {}
self.vDire = {}
self.nRadiantKills = 0
self.nDireKills = 0
self.bSeenWaitForPlayers = false
-- BH Snippet
-- This can be called with an optional argument: nHalfMapLength (see readme)
BuildingHelper:Init()
--BuildingHelper:BlockRectangularArea(Vector(-192,-192,0), Vector(192,192,0))
print('[LEGION_TD] Done loading legionTD gamemode!\n\n')
end
mode = nil
-- This function is called 1 to 2 times as the player connects initially but before they
-- have completely connected
function GameMode:PlayerConnect(keys)
print('[LEGION_TD] PlayerConnect')
--DeepPrintTable(keys)
if keys.bot == 1 then
-- This user is a Bot, so add it to the bots table
self.vBots[keys.userid] = 1
end
end
-- This function is called once when the player fully connects and becomes "Ready" during Loading
function GameMode:OnConnectFull(keys)
print ('[LEGION_TD] OnConnectFull')
--DeepPrintTable(keys)
GameMode:CaptureGameMode()
local entIndex = keys.index+1
-- The Player entity of the joining user
local ply = EntIndexToHScript(entIndex)
-- The Player ID of the joining player
local playerID = ply:GetPlayerID()
-- Update the user ID table with this user
self.vUserIds[keys.userid] = ply
-- Update the Steam ID table
self.vSteamIds[PlayerResource:GetSteamAccountID(playerID)] = ply
-- If the player is a broadcaster flag it in the Broadcasters table
if PlayerResource:IsBroadcaster(playerID) then
self.vBroadcasters[keys.userid] = 1
return
end
end
-- This function is called as the first player loads and sets up the GameMode parameters
function GameMode:CaptureGameMode()
if mode == nil then
-- Set GameMode parameters
mode = GameRules:GetGameModeEntity()
mode:SetRecommendedItemsDisabled( RECOMMENDED_BUILDS_DISABLED )
mode:SetCameraDistanceOverride( CAMERA_DISTANCE_OVERRIDE )
mode:SetCustomBuybackCostEnabled( CUSTOM_BUYBACK_COST_ENABLED )
mode:SetCustomBuybackCooldownEnabled( CUSTOM_BUYBACK_COOLDOWN_ENABLED )
mode:SetBuybackEnabled( BUYBACK_ENABLED )
mode:SetTopBarTeamValuesOverride ( USE_CUSTOM_TOP_BAR_VALUES )
mode:SetTopBarTeamValuesVisible( TOP_BAR_VISIBLE )
mode:SetUseCustomHeroLevels ( USE_CUSTOM_HERO_LEVELS )
mode:SetCustomHeroMaxLevel ( MAX_LEVEL )
mode:SetCustomXPRequiredToReachNextLevel( XP_PER_LEVEL_TABLE )
--mode:SetBotThinkingEnabled( USE_STANDARD_DOTA_BOT_THINKING )
mode:SetTowerBackdoorProtectionEnabled( ENABLE_TOWER_BACKDOOR_PROTECTION )
mode:SetFogOfWarDisabled(DISABLE_FOG_OF_WAR_ENTIRELY)
mode:SetGoldSoundDisabled( DISABLE_GOLD_SOUNDS )
mode:SetRemoveIllusionsOnDeath( REMOVE_ILLUSIONS_ON_DEATH )
self:OnFirstPlayerLoaded()
end
end
--[[
This function should be used to set up Async precache calls at the beginning of the game. The Precache() function
in addon_game_mode.lua used to and may still sometimes have issues with client's appropriately precaching stuff.
If this occurs it causes the client to never precache things configured in that block.
In this function, place all of your PrecacheItemByNameAsync and PrecacheUnitByNameAsync. These calls will be made
after all players have loaded in, but before they have selected their heroes. PrecacheItemByNameAsync can also
be used to precache dynamically-added datadriven abilities instead of items. PrecacheUnitByNameAsync will
precache the precache{} block statement of the unit and all precache{} block statements for every Ability#
defined on the unit.
This function should only be called once. If you want to/need to precache more items/abilities/units at a later
time, you can call the functions individually (for example if you want to precache units in a new wave of
holdout).
]]
function GameMode:PostLoadPrecache()
print("[LEGION_TD] Performing Post-Load precache")
end
--[[
This function is called once and only once as soon as the first player (almost certain to be the server in local lobbies) loads in.
It can be used to initialize state that isn't initializeable in InitGameMode() but needs to be done before everyone loads in.
]]
function GameMode:OnFirstPlayerLoaded()
print("[LEGION_TD] First Player has loaded")
end
--[[
This function is called once and only once after all players have loaded into the game, right as the hero selection time begins.
It can be used to initialize non-hero player state or adjust the hero selection (i.e. force random etc)
]]
function GameMode:OnAllPlayersLoaded()
print("[LEGION_TD] All Players have loaded into the game")
end
--[[
This function is called once and only once for every player when they spawn into the game for the first time. It is also called
if the player's hero is replaced with a new hero for any reason. This function is useful for initializing heroes, such as adding
levels, changing the starting gold, removing/adding abilities, adding physics, etc.
The hero parameter is the hero entity that just spawned in.
]]
function GameMode:OnHeroInGame(hero)
print("[LEGION_TD] Hero spawned in game for first time -- " .. hero:GetUnitName())
-- Store a reference to the player handle inside this hero handle.
hero.player = PlayerResource:GetPlayer(hero:GetPlayerID())
-- Store the player's name inside this hero handle.
hero.playerName = PlayerResource:GetPlayerName(hero:GetPlayerID())
-- Store this hero handle in this table.
table.insert(self.vPlayers, hero)
-- This line for example will set the starting gold of every hero to 500 unreliable gold
hero:SetGold(500, false)
InitAbilities(hero)
-- These lines will create an item and add it to the player, effectively ensuring they start with the item
--local item = CreateItem("item_example_item", hero, hero)
--hero:AddItem(item)
end
-- Cleanup a player when they leave
function GameMode:OnDisconnect(keys)
print('[LEGION_TD] Player Disconnected ' .. tostring(keys.userid))
--DeepPrintTable(keys)
local name = keys.name
local networkid = keys.networkid
local reason = keys.reason
local userid = keys.userid
end
-- The overall game state has changed
function GameMode:OnGameRulesStateChange(keys)
print("[LEGION_TD] GameRules State Changed")
--DeepPrintTable(keys)
local newState = GameRules:State_Get()
if newState == DOTA_GAMERULES_STATE_WAIT_FOR_PLAYERS_TO_LOAD then
self.bSeenWaitForPlayers = true
elseif newState == DOTA_GAMERULES_STATE_INIT then
Timers:RemoveTimer("alljointimer")
elseif newState == DOTA_GAMERULES_STATE_HERO_SELECTION then
local et = 6
if self.bSeenWaitForPlayers then
et = .01
end
Timers:CreateTimer("alljointimer", {
useGameTime = true,
endTime = et,
callback = function()
if PlayerResource:HaveAllPlayersJoined() then
GameMode:PostLoadPrecache()
GameMode:OnAllPlayersLoaded()
return
end
return 1
end})
elseif newState == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
GameMode:OnGameInProgress()
end
end
-- An NPC has spawned somewhere in game. This includes heroes
function GameMode:OnNPCSpawned(keys)
print("[LEGION_TD] NPC Spawned")
--DeepPrintTable(keys)
local npc = EntIndexToHScript(keys.entindex)
if npc:IsRealHero() and npc.bFirstSpawned == nil then
npc.bFirstSpawned = true
GameMode:OnHeroInGame(npc)
end
end
-- An entity somewhere has been hurt. This event fires very often with many units so don't do too many expensive
-- operations here
function GameMode:OnEntityHurt(keys)
--print("[LEGION_TD] Entity Hurt")
--DeepPrintTable(keys)
local entCause = EntIndexToHScript(keys.entindex_attacker)
local entVictim = EntIndexToHScript(keys.entindex_killed)
end
-- An item was picked up off the ground
function GameMode:OnItemPickedUp(keys)
print ( '[LEGION_TD] OnItemPurchased' )
--DeepPrintTable(keys)
local heroEntity = EntIndexToHScript(keys.HeroEntityIndex)
local itemEntity = EntIndexToHScript(keys.ItemEntityIndex)
local player = PlayerResource:GetPlayer(keys.PlayerID)
local itemname = keys.itemname
end
-- A player has reconnected to the game. This function can be used to repaint Player-based particles or change
-- state as necessary
function GameMode:OnPlayerReconnect(keys)
print ( '[LEGION_TD] OnPlayerReconnect' )
--DeepPrintTable(keys)
end
-- An item was purchased by a player
function GameMode:OnItemPurchased( keys )
print ( '[LEGION_TD] OnItemPurchased' )
--DeepPrintTable(keys)
-- The playerID of the hero who is buying something
local plyID = keys.PlayerID
if not plyID then return end
-- The name of the item purchased
local itemName = keys.itemname
-- The cost of the item purchased
local itemcost = keys.itemcost
end
-- An ability was used by a player
function GameMode:OnAbilityUsed(keys)
print('[LEGION_TD] AbilityUsed')
--DeepPrintTable(keys)
local player = EntIndexToHScript(keys.PlayerID)
local abilityname = keys.abilityname
-- BH Snippet
if player.cursorStream ~= nil then
if not (string.len(abilityname) > 14 and string.sub(abilityname,1,14) == "move_to_point_") then
if not DontCancelBuildingGhostAbils[abilityname] then
player:CancelGhost()
else
print(abilityname .. " did not cancel building ghost.")
end
end
end
-- End of BH snippet
end
-- A non-player entity (necro-book, chen creep, etc) used an ability
function GameMode:OnNonPlayerUsedAbility(keys)
print('[LEGION_TD] OnNonPlayerUsedAbility')
--DeepPrintTable(keys)
local abilityname= keys.abilityname
end
-- A player changed their name
function GameMode:OnPlayerChangedName(keys)
print('[LEGION_TD] OnPlayerChangedName')
--DeepPrintTable(keys)
local newName = keys.newname
local oldName = keys.oldName
end
-- A player leveled up an ability
function GameMode:OnPlayerLearnedAbility( keys)
print ('[LEGION_TD] OnPlayerLearnedAbility')
--DeepPrintTable(keys)
local player = EntIndexToHScript(keys.player)
local abilityname = keys.abilityname
end
-- A channelled ability finished by either completing or being interrupted
function GameMode:OnAbilityChannelFinished(keys)
print ('[LEGION_TD] OnAbilityChannelFinished')
--DeepPrintTable(keys)
local abilityname = keys.abilityname
local interrupted = keys.interrupted == 1
end
-- A player leveled up
function GameMode:OnPlayerLevelUp(keys)
print ('[LEGION_TD] OnPlayerLevelUp')
--DeepPrintTable(keys)
local player = EntIndexToHScript(keys.player)
local level = keys.level
end
-- A player last hit a creep, a tower, or a hero
function GameMode:OnLastHit(keys)
print ('[LEGION_TD] OnLastHit')
--DeepPrintTable(keys)
local isFirstBlood = keys.FirstBlood == 1
local isHeroKill = keys.HeroKill == 1
local isTowerKill = keys.TowerKill == 1
local player = PlayerResource:GetPlayer(keys.PlayerID)
end
-- A tree was cut down by tango, quelling blade, etc
function GameMode:OnTreeCut(keys)
print ('[LEGION_TD] OnTreeCut')
--DeepPrintTable(keys)
local treeX = keys.tree_x
local treeY = keys.tree_y
end
-- A rune was activated by a player
function GameMode:OnRuneActivated (keys)
print ('[LEGION_TD] OnRuneActivated')
--DeepPrintTable(keys)
local player = PlayerResource:GetPlayer(keys.PlayerID)
local rune = keys.rune
end
-- A player took damage from a tower
function GameMode:OnPlayerTakeTowerDamage(keys)
print ('[LEGION_TD] OnPlayerTakeTowerDamage')
--DeepPrintTable(keys)
local player = PlayerResource:GetPlayer(keys.PlayerID)
local damage = keys.damage
end
-- A player picked a hero
function GameMode:OnPlayerPickHero(keys)
print ('[LEGION_TD] OnPlayerPickHero')
--DeepPrintTable(keys)
local heroClass = keys.hero
local heroEntity = EntIndexToHScript(keys.heroindex)
local player = EntIndexToHScript(keys.player)
end
-- A player killed another player in a multi-team context
function GameMode:OnTeamKillCredit(keys)
print ('[LEGION_TD] OnTeamKillCredit')
--DeepPrintTable(keys)
local killerPlayer = PlayerResource:GetPlayer(keys.killer_userid)
local victimPlayer = PlayerResource:GetPlayer(keys.victim_userid)
local numKills = keys.herokills
local killerTeamNumber = keys.teamnumber
end
-- An entity died
function GameMode:OnEntityKilled( keys )
print( '[LEGION_TD] OnEntityKilled Called' )
--DeepPrintTable( keys )
-- The Unit that was Killed
local killedUnit = EntIndexToHScript( keys.entindex_killed )
-- The Killing entity
local killerEntity = nil
if keys.entindex_attacker ~= nil then
killerEntity = EntIndexToHScript( keys.entindex_attacker )
end
-- Put code here to handle when an entity gets killed
-- START OF BH SNIPPET
if BuildingHelper:IsBuilding(killedUnit) then
killedUnit:RemoveBuilding(false)
end
-- END OF BH SNIPPET
for i, unit in pairs( tEnemiesRemaining ) do
if killedUnit == unit then
print('[sc] Enemies Remaining : ' .. #tEnemiesRemaining)
table.remove( tEnemiesRemaining, i )
break
end
end
end
--[[
This function is called once and only once when the game completely begins (about 0:00 on the clock). At this tSpawnPosition,
gold will begin to go up in ticks if configured, creeps will spawn, towers will become damageable etc. This function
is useful for starting any game logic timers/thinkers, beginning the first round, etc.
]]
function GameMode:OnGameInProgress()
print("[LEGION_TD] The game has officially begun")
local iUpdateInterval = 1
UpdatePreGame()
Timers:CreateTimer(function()
Update()
return iUpdateInterval
end)
--[[
Timers:CreateTimer(start_after, function()
CheckRoundEnd()
return check_interval
end)
]]
end
--[[
=============================================================================
OUR CODES STARTS FROM HERE
=============================================================================
iVariable = int
tVariable = Tables
bVariable = boolean
vVariable = Vector
]]
-- Radiant hero count
iRadiantHeroCount = 0
-- Dire hero count
iDireHeroCount = 0
-- Spawn of wave is called
bCalledSpawn = false
-- Wave began
bWaveStarted = false
-- Wave ended
bWaveEnded = true
-- Game OFFICIALY Started
bGameStarted = false
-- Current Wave Number
iWaveNumber = 1
-- Number of enemies remaining
tEnemiesRemaining = {}
-- Spawn Positions
tSpawnPosition ={}
-- Pool position
vPoolPos = 0
-- table of summons
tSummonedTower = {}
-- Summoned Tower Position
tSummonedTowerPos = {}
-- Tower Summonings
tHeroesSummoned = {}
function UpdatePreGame()
-- Handle radiant spawn tSpawnPositions
iRadiantHeroCount = PlayerResource:GetPlayerCountForTeam(DOTA_TEAM_GOODGUYS)
iDireHeroCount = PlayerResource:GetPlayerCountForTeam(DOTA_TEAM_BADGUYS)
print('[sc] Radiant Players: ' .. iRadiantHeroCount .. ' Dire Players: ' .. iDireHeroCount)
for i = 1, iRadiantHeroCount do
tSpawnPosition[i] = Entities:FindByName(nil, "spawn" .. i):GetAbsOrigin()
end
-- Handle dire spawn tSpawnPositions
for i = 5, iDireHeroCount + 4 do
tSpawnPosition[i] = Entities:FindByName(nil, "spawn" .. i):GetAbsOrigin()
end
vPoolPos = Entities:FindByName(nil, "Pool_Pos"):GetAbsOrigin()
--print('vPoolPos: ' .. vPoolPos)
end
function Update()
if bCalledSpawn == false and bWaveStarted == false and bWaveEnded == true then
bCalledSpawn = true
FireGameEvent('cgm_timer_display', { timerMsg = "Wave will start in", timerSeconds = 30, timerWarning = -1, timerEnd = false, timerPosition = 0})
Timers:CreateTimer(30, function()
ConvertToHeros()
SpawnCreeps(iWaveNumber)
bWaveStarted = true
end)
elseif IsRoundOver() == true and bWaveStarted == true then
iWaveNumber = iWaveNumber + 1
bWaveStarted = false
bWaveEnded = true
bCalledSpawn = false
RespawnBuildings()
end
end
function SpawnCreeps(waveNumber)
print('[SC] Spawn Them Creeps')
local units_to_spawn = 10;
local waypoint = Entities:FindByName(nil,"spawn11"):GetAbsOrigin()
for i = 1, units_to_spawn do
for _,v in pairs (tSpawnPosition) do
Timers:CreateTimer(function()
local unit = CreateUnitByName("creep_wave_" .. waveNumber, v, true, nil, nil, DOTA_TEAM_NEUTRALS)
ExecuteOrderFromTable({UnitIndex = unit:GetEntityIndex(),
OrderType = DOTA_UNIT_ORDER_ATTACK_MOVE,
Position = waypoint,Queue= true})
table.insert(tEnemiesRemaining, unit)
end)
end
end
end
function IsRoundOver()
return (#tEnemiesRemaining <= 0)
end
function ConvertToHeros()
for _,v in pairs (tSummonedTower) do
-- TODO: Call first skill to change to unit
local unit = CreateUnitByName("npc_dota_hero_antimage", v:GetAbsOrigin(), true, nil, nil, DOTA_TEAM_GOODGUYS)
table.insert(tHeroesSummoned, unit)
v:SetAbsOrigin(vPoolPos)
end
end
function RespawnBuildings()
for k,v in pairs (tSummonedTowerPos) do
k:SetAbsOrigin(v)
end
for k,v in pairs (tHeroesSummoned) do
v:Destroy()
tHeroesSummoned[k] = nil
end
print('Heroes in table: ' .. #tHeroesSummoned)
end<file_sep>--[[
Basic Barebones
]]
--[[
-- Required files to be visible from anywhere
require( 'timers' )
require( 'LegionTD' )
require( 'physics' )
require( 'FlashUtil' )
require( 'buildinghelper' )
require( 'abilities' )
]]
BASE_MODULES = {
'util',
'timers',
'physics',
'FlashUtil',
'lib.statcollection',
'abilities',
'buildinghelper',
'LegionTD',
}
--MODULE LOADER STUFF
BASE_LOG_PREFIX = '[LEGION_TD]'
LOG_FILE = "log/SampleRTS.txt"
InitLogFile(LOG_FILE, "[[ LEGION_TD ]]")
function log(msg)
print(BASE_LOG_PREFIX .. msg)
AppendToLogFile(LOG_FILE, msg .. '\n')
end
function err(msg)
display('[X] '..msg, COLOR_RED)
end
function warning(msg)
display('[W] '..msg, COLOR_DYELLOW)
end
function display(text, color)
color = color or COLOR_LGREEN
log('> '..text)
Say(nil, color..text, false)
end
local function load_module(mod_name)
-- load the module in a monitored environment
local status, err_msg = pcall(function()
require(mod_name)
end)
if status then
log(' module ' .. mod_name .. ' OK')
else
err(' module ' .. mod_name .. ' FAILED: '..err_msg)
end
end
--END OF MODULE LOADER STUFF
-- Load all modules
for i, mod_name in pairs(BASE_MODULES) do
load_module(mod_name)
end
function Precache( context )
-- NOTE: IT IS RECOMMENDED TO USE A MINIMAL AMOUNT OF LUA PRECACHING, AND A MAXIMAL AMOUNT OF DATADRIVEN PRECACHING.
-- Precaching guide: https://moddota.com/forums/discussion/119/precache-fixing-and-avoiding-issues
--[[
This function is used to precache resources/units/items/abilities that will be needed
for sure in your game and that cannot or should not be precached asynchronously or
after the game loads.
See GameMode:PostLoadPrecache() in barebones.lua for more information
]]
print("[LEGION_TD] Performing pre-load precache")
PrecacheUnitByNameSync("creep_wave_1", context)
PrecacheUnitByNameSync("creep_wave_2", context)
PrecacheUnitByNameSync("creep_wave_3", context)
PrecacheUnitByNameSync("creep_wave_4", context)
PrecacheUnitByNameSync("creep_wave_5", context)
PrecacheUnitByNameSync("creep_wave_6", context)
PrecacheUnitByNameSync("creep_wave_7", context)
PrecacheUnitByNameSync("creep_wave_8", context)
PrecacheUnitByNameSync("creep_wave_9", context)
PrecacheUnitByNameSync("creep_wave_10", context)
--[[
-- Particles can be precached individually or by folder
-- It it likely that precaching a single particle system will precache all of its children, but this may not be guaranteed
PrecacheResource("particle", "particles/econ/generic/generic_aoe_explosion_sphere_1/generic_aoe_explosion_sphere_1.vpcf", context)
PrecacheResource("particle_folder", "particles/test_particle", context)
-- Models can also be precached by folder or individually
-- PrecacheModel should generally used over PrecacheResource for individual models
PrecacheResource("model_folder", "particles/heroes/antimage", context)
PrecacheResource("model", "particles/heroes/viper/viper.vmdl", context)
PrecacheModel("models/heroes/viper/viper.vmdl", context)
-- Sounds can precached here like anything else
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_gyrocopter.vsndevts", context)
-- Entire items can be precached by name
-- Abilities can also be precached in this way despite the name
PrecacheItemByNameSync("example_ability", context)
PrecacheItemByNameSync("item_example_item", context)
-- Entire heroes (sound effects/voice/models/particles) can be precached with PrecacheUnitByNameSync
-- Custom units from npc_units_custom.txt can also have all of their abilities and precache{} blocks precached in this way
PrecacheUnitByNameSync("npc_dota_hero_ancient_apparition", context)
PrecacheUnitByNameSync("npc_dota_hero_enigma", context)
]]
-- Particles can be precached individually or by folder
-- It it likely that precaching a single particle system will precache all of its children, but this may not be guaranteed
PrecacheResource("particle_folder", "particles/buildinghelper", context)
-- Sounds can precached here like anything else
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_gyrocopter.vsndevts", context)
-- Entire items can be precached by name
-- Abilities can also be precached in this way despite the name
PrecacheItemByNameSync("example_ability", context)
-- Entire heroes (sound effects/voice/models/particles) can be precached with PrecacheUnitByNameSync
-- Custom units from npc_units_custom.txt can also have all of their abilities and precache{} blocks precached in this way
PrecacheUnitByNameSync("npc_dota_hero_ancient_apparition", context)
PrecacheUnitByNameSync("npc_dota_hero_enigma", context)
PrecacheUnitByNameSync("npc_dota_hero_antimage", context)
PrecacheUnitByNameSync("npc_dota_hero_drow_ranger", context)
PrecacheUnitByNameSync("npc_dota_hero_tinker", context)
PrecacheUnitByNameSync("npc_dota_hero_jakiro", context)
PrecacheUnitByNameSync("npc_barracks", context) -- Building that spawns units
PrecacheUnitByNameSync("npc_peasant", context) -- Unit that builds and gathers resources
PrecacheItemByNameSync("item_rally", context)
end
-- Create the game mode when we activate
function Activate()
GameRules.GameMode = GameMode()
GameRules.GameMode:InitGameMode()
--GameRules.GameMode:OnGameInProgress()
--GameRules.SampleRTS = SampleRTS()
--GameRules.SampleRTS:InitSampleRTS()
end
| 5b9cdf5b4621c2f8b231f7b73b3b41bc3b4ebaab | [
"Markdown",
"Lua"
] | 3 | Markdown | soonyee91/LEGIONTDBETA | e0a9975628163c039158583f0d6fa80f86bc0be6 | 3be4d43ab86e07cb9d4b0012e54578ed1beaea51 | |
refs/heads/master | <file_sep><?php
/*
|| --------------------------------------------------------------------------------------------
|| Admin Panel Config
|| --------------------------------------------------------------------------------------------
||
|| @package Dilaz Panel Options
|| @subpackage Config
|| @since Dilaz Panel 2.4.1
|| @author Rodgath, https://github.com/Rodgath
|| @copyright Copyright (C) 2017, Rodgath LTD
|| @link https://github.com/Rodgath/Dilaz-Panel
|| @License GPL-2.0+
|| @License URI http://www.gnu.org/licenses/gpl-2.0.txt
||
|| NOTE: Rename this file from "config-sample.php" to "config.php". If you
|| don't rename it, all your config parameters will be overwritten
|| when updating Dilaz Panel Options.
||
*/
defined('ABSPATH') || exit;
# Option parameters
$parameters = array(
'option_name' => 'dilaz_options', # must be unique. Used to save settings.
'option_prefix' => 'dilaz_panel', # must be unique. Not used to save settings.
'use_type' => 'theme', # 'theme' if used within a theme OR 'plugin' if used within a plugin
'default_options' => true, # whether to load default options. Always set to "false" on a live site.
'custom_options' => true, # whether to load custom options. Always set to "false" on a live site.
'page_slug' => 'dilaz_panel', # should be unique.
'page_title' => __('Dilaz Panel', 'dilaz-panel'), # The text to be displayed in the title tags of the page when the menu is selected.
'menu_title' => __('Dilaz Panel', 'dilaz-panel'), # The text to be used for the menu.
'options_view_cap' => array('manage_options'), # The capabilities required for this menu to be displayed to the user.
'options_save_cap' => array('manage_options'), # The capabilities required for the user to save the options for this panel.
'menu_icon' => '', # dashicon menu icon.
'menu_position' => null, # position in menu order. Works with top-level menu only.
'parent_slug' => '', # The slug name for the parent menu (or the file name of a standard WordPress admin page).
'admin_bar_menu' => true, # 'true' to show panel in admin bar menu.
'import_export' => true, # 'true' to enable import/export field.
'log_title' => __('Changelog', 'dilaz-panel'),
'log_url' => '#', # leave empty to disable.
'doc_title' => __('Documentation', 'dilaz-panel'),
'doc_url' => '#', # leave empty to disable.
'support_title' => __('Support', 'dilaz-panel'),
'support_url' => '#', # leave empty to disable.
);<file_sep><?php
/*
|| --------------------------------------------------------------------------------------------
|| Custom Options' Fields Example
|| --------------------------------------------------------------------------------------------
||
|| @package Dilaz Panel
|| @subpackage Custom Options
|| @since Dilaz Panel 1.1
|| @author Rodgath, https://github.com/Rodgath
|| @copyright Copyright (C) 2017, Rodgath LTD
|| @link https://github.com/Rodgath/Dilaz-Panel
|| @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
||
|| NOTE 1: Rename this file from "custom-options-sample.php" to "custom-options.php". If you
|| don't rename it, all your options and settings will be overwritten
|| when updating Dilaz Panel Options.
||
|| NOTE 2: Add all your theme/plugin custom options in this file
||
*/
defined('ABSPATH') || exit;
/**
* Add custom panel into dilaz panel
*
* @param array $dilaz_panel all registered dilaz panel
* @param string $parameters['option_name'] panel option name
* @param array $options panel options
*
* @return array
*/
add_filter('panel_option_filter_'. $parameters['option_name'], function($options) {
# BOX - Test Beta
# =============================================================================================
$options[] = array(
'id' => 'custom_options_main',
'name' => __('Custom Options Main', 'dilaz-panel'),
'type' => 'heading',
'icon' => 'mdi-settings'
);
# TAB - Beta Tab 1
# *****************************************************************************************
$options[] = array(
'id' => 'custom_options_sub',
'name' => __('Custom Options Sub', 'dilaz-panel'),
'type' => 'subheading'
);
# FIELDS - Beta Tab 1
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$options[] = array(
'id' => 'custom_1',
'name' => __('Custom One:', 'dilaz-panel'),
'desc' => '',
'type' => 'select',
'options' => array(
'one' => __('One', 'dilaz-panel'),
'two' => __('Two', 'dilaz-panel'),
'three' => __('Three', 'dilaz-panel')
),
'std' => 'default'
);
$options[] = array(
'id' => 'custom_2',
'name' => __('Custom Two:', 'dilaz-panel'),
'desc' => '',
'type' => 'radio',
'options' => array(
'yes' => __('Yes', 'dilaz-panel'),
'no' => __('No', 'dilaz-panel')
),
'std' => 'no'
);
$options[] = array(
'id' => 'custom_3',
'name' => __('Custom Three:', 'dilaz-panel'),
'desc' => '',
'type' => 'radio',
'options' => array(
'yes' => __('Yes', 'dilaz-panel'),
'no' => __('No', 'dilaz-panel')
),
'std' => 'no'
);
return $options;
}, 10);
/**
* Insert panel field before a specific field
*
* @param array $dilaz_panel all registered dilaz panel
* @param string $parameters['option_name'] panel option name
* @param array $options panel options
*
* @return array
*/
add_filter('panel_option_filter_'. $parameters['option_name'], function($options) {
# array data to be inserted
$insert_custom_data = [];
$insert_custom_data[] = array(
'id' => 'custom_2_b',
'name' => __('INSERTED - Custom Two B:', 'dilaz-panel'),
'desc' => __('Custom Two B inserted before Custom Two C.', 'dilaz-panel'),
'type' => 'radio',
'options' => array(
'yes' => __('Yes', 'dilaz-panel'),
'no' => __('No', 'dilaz-panel')
),
'std' => 'yes'
);
$insert_custom_data[] = array(
'id' => 'custom_2_c',
'name' => __('INSERTED - Custom Two C:', 'dilaz-panel'),
'desc' => __('Custom Two C inserted before Custom Three.', 'dilaz-panel'),
'type' => 'radio',
'options' => array(
'yes' => __('Yes', 'dilaz-panel'),
'no' => __('No', 'dilaz-panel')
),
'std' => 'yes'
);
$insert = DilazPanelFunctions::insertField($options, 'custom_options_main', 'custom_3', $insert_custom_data, 'before');
return $insert;
}, 10);
/**
* Insert panel sub-tab inside a specific tab before a specific sub-tab
*
* @param array $dilaz_panel all registered dilaz panel
* @param string $parameters['option_name'] panel option name
* @param array $options panel options
*
* @return array
*/
add_filter('panel_option_filter_'. $parameters['option_name'], function($options) {
# array data to be inserted
$insert_custom_data = [];
# TAB - INSERTED Sub-Tab
# *****************************************************************************************
$insert_custom_data[] = array(
'id' => 'inserted_custom_tab_before',
'name' => __('INSERTED Sub-Tab [Before]', 'dilaz-panel'),
'type' => 'subheading'
);
# FIELDS - INSERTED Sub-Tab fields
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$insert_custom_data[] = array(
'id' => 'custom_switch',
'name' => __('Custom Switch:', 'dilaz-panel'),
'desc' => __('On/Off switch option.', 'dilaz-panel'),
'type' => 'switch',
'options' => array(
1 => __('On', 'dilaz-panel'),
0 => __('Off', 'dilaz-panel'),
),
'std' => 1,
'class' => ''
);
$insert = DilazPanelFunctions::insertField($options, 'custom_options_main', 'custom_options_sub', $insert_custom_data, 'before');
return $insert;
}, 10);
/**
* Insert panel sub-tab inside a specific tab as the last sub-tab
*
* @param array $dilaz_panel all registered dilaz panel
* @param string $parameters['option_name'] panel option name
* @param array $options panel options
*
* @return array
*/
add_filter('panel_option_filter_'. $parameters['option_name'], function($options) {
# array data to be inserted
$insert_custom_data = [];
# TAB - INSERTED Sub-Tab
# *****************************************************************************************
$insert_custom_data[] = array(
'id' => 'inserted_custom_tab_last',
'name' => __('INSERTED Sub-Tab [Last]', 'dilaz-panel'),
'type' => 'subheading'
);
# FIELDS - INSERTED Sub-Tab fields
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$insert_custom_data[] = array(
'id' => 'custom_buttonset',
'name' => __('Custom Button Set:', 'dilaz-panel'),
'desc' => __('Set multiple options using buttonset.', 'dilaz-panel'),
'type' => 'buttonset',
'options' => array(
'yes' => __('Yes', 'dilaz-panel'),
'no' => __('No', 'dilaz-panel'),
'maybe' => __('Maybe', 'dilaz-panel')
),
'std' => 'no',
'class' => ''
);
$insert = DilazPanelFunctions::insertField($options, 'custom_options_main', '', $insert_custom_data, 'last');
return $insert;
}, 10);
<file_sep># CHANGELOG
## Version 2
###### v2.4.10
```
= ADDED - 'item_url' to use-type parameters
= UPDATED - default-options.php
```
###### v2.4.9
```
= IPROVED - 'radioimage' field sample
= ADDED - 'radioimage_tiled' field sample
```
###### v2.4.8
```
= ADDED - WordPress version check
= ADDED - dilaz_panel_get_use_type() to check current panel "use type"
= ADDED - dilaz_panel_theme_params() to fetch theme object parameters
= ADDED - dilaz_panel_plugin_params() to fetch plugin object parameters
= ADDED - new "use_type" check incase the user adds neither 'plugin' nor 'theme'
= ADDED - code field sample options in default-options.php
````
###### v2.4.7
```
= ADDED - PHP version check
= FIXED - 'DilazPanelFunctions' class check in custom-options-sample.php
```
###### v2.4.6
```
= REMOVED 'options_cap' from config parameters
= ADDED 'options_view_cap' to config parameters
= ADDED 'options_save_cap' to config parameters
```
###### v2.4.5
```
= IMPROVED - Import/Export field is now loaded via 'panel_option_filter_$option_name' hook
= ADDED - 'id' fields to 'heading' and 'subheading' field types
= ADDED - custom options example
```
###### v2.4.4
```
= REMOVED - Font Awesome webfont icons for tab icons
= ADDED - Material Design webfont icons for tab icons
```
###### v2.4.3
```
= FIXED - Empty plugin data returned when there's multiple PHP files in the plugin root directory
```
###### v2.4.2
```
= FIXED - Check if 'DilazPanel' class has been loaded in includes/load.php
```
###### v2.4.1
```
= ADDED - /config-sample.php - Helps in preserving config parameters during updates
```
###### v2.4
```
= FIXED - includes/use-type.php bugs
```
###### v2.3
```
= ADDED - 'menu_position' admin parameter
= ADDED - 'parent_slug' admin parameter
```
###### v2.2
```
= ADDED - 'DilazPanel' plugin requirement error notifications
```
###### v2.1
```
= ADDED - includes/load.php file
= IMPROVED - made admin.php file minimal by moving most of the code into includes/load.php
= FIXED - 'user-type' error notifications
```
###### v2.0.1
```
= MOVED - 'option_name' into parameters
= ADDED - panel attributes field (panel-atts)
= ADDED - $option_args field
```
## Version 1
###### v1.0
```
Initial release.
<file_sep><?php
/*
|| --------------------------------------------------------------------------------------------
|| Theme/Plugin Panel Options
|| --------------------------------------------------------------------------------------------
||
|| @package Dilaz Panel
|| @subpackage Main Options
|| @since Dilaz Panel 1.1
|| @author Rodgath, https://github.com/Rodgath
|| @copyright Copyright (C) 2017, Rodgath LTD
|| @link https://github.com/Rodgath/Dilaz-Panel
|| @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
||
|| NOTE 1: Rename this file from "options-sample.php" to "options.php". If you
|| don't rename it, all your options and settings will be overwritten
|| when updating Dilaz Panel Options.
||
|| NOTE 2: Add all your theme/plugin options in this file
||
*/
defined('ABSPATH') || exit;
<file_sep><?php
/*
|| --------------------------------------------------------------------------------------------
|| Default Panel Import/Export Option Fields
|| --------------------------------------------------------------------------------------------
||
|| @package Dilaz Panel
|| @subpackage Import/Export Fields
|| @since Dilaz Panel 1.1
|| @author Rodgath, https://github.com/Rodgath
|| @copyright Copyright (C) 2017, Rodgath LTD
|| @link https://github.com/Rodgath/Dilaz-Panel
|| @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
||
*/
defined('ABSPATH') || exit;
/**
* Add Import/Export option fields to the bottom of the panel
*
* @param array $dilaz_panel all registered dilaz panel
* @param string $parameters['option_name'] panel option name
* @param array $options panel options
*
* @return array
*/
add_filter('panel_option_filter_'. $parameters['option_name'], function($options) {
# MAIN TAB - Export / Import
# =============================================================================================
$options[] = array(
'name' => __('Export / Import', 'dilaz-panel'),
'type' => 'heading',
'icon' => 'mdi-download'
);
# SUB TAB - Export
# *****************************************************************************************
$options[] = array(
'name' => __('Export', 'dilaz-panel'),
'type' => 'subheading',
);
# FIELDS - Export
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$options[] = array(
'id' => 'export',
'name' => __('Export', 'dilaz-panel'),
'desc' => __('Export', 'dilaz-panel'),
'type' => 'export',
'std' => '',
'class' => ''
);
# SUB TAB - Import
# *****************************************************************************************
$options[] = array(
'name' => __('Import', 'dilaz-panel'),
'type' => 'subheading',
);
# FIELDS - Import
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$options[] = array(
'id' => 'import',
'name' => __('Import', 'dilaz-panel'),
'desc' => __('Import', 'dilaz-panel'),
'type' => 'import',
'std' => '',
'class' => 'last'
);
return $options;
}, 100);<file_sep><?php
/*
|| --------------------------------------------------------------------------------------------
|| Admin Options Panel
|| --------------------------------------------------------------------------------------------
||
|| @package Dilaz Panel
|| @subpackage Panel
|| @version 2.4.10
|| @since Dilaz Panel 1.0
|| @author Rodgath, https://github.com/Rodgath
|| @copyright Copyright (C) 2017, Rodgath LTD
|| @link https://github.com/Rodgath/Dilaz-Panel
|| @License GPL-2.0+
|| @License URI http://www.gnu.org/licenses/gpl-2.0.txt
||
|| NOTE: This options panel requires Dilaz Panel plugin installed.
||
*/
defined('ABSPATH') || exit;
# Load config
file_exists(dirname(__FILE__) .'/config.php') ? require_once dirname(__FILE__) .'/config.php' : require_once dirname(__FILE__) .'/config-sample.php';
# Load metabox options
require_once dirname(__FILE__) .'/includes/load.php';<file_sep><?php
/*
|| --------------------------------------------------------------------------------------------
|| Default Panel Option Fields
|| --------------------------------------------------------------------------------------------
||
|| @package Dilaz Panel
|| @subpackage Default Options
|| @since Dilaz Panel 1.1
|| @author Rodgath, https://github.com/Rodgath
|| @copyright Copyright (C) 2017, Rodgath LTD
|| @link https://github.com/Rodgath/Dilaz-Panel
|| @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
||
|| NOTE 1: This file is for experimetation and demo purposes. Do not use this file to add your options,
|| othersise all your options and settings will be overwritten when updating this panel.
||
|| NOTE 2: Use "options.php" file to add your plugin/theme options.
||
*/
defined('ABSPATH') || exit;
# MAIN TAB - General Settings
# =============================================================================================
$options[] = array(
'id' => 'general-options',
'name' => __('General Options', 'dilaz-panel'),
'type' => 'heading',
'icon' => 'mdi-settings'
);
# SUB TAB - Simple Options Set
# *****************************************************************************************
// $options[] = array(
// 'id' => 'general',
// 'name' => __('General', 'dilaz-panel'),
// 'type' => 'subheading',
// );
# FIELDS - Alpha Tab 1
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$options[] = array(
'id' => 'info',
'name' => __('Info Box Title', 'dilaz-panel'),
'desc' => __('Sample info description goes here.', 'dilaz-panel'),
'type' => 'info',
);
$options[] = array(
'id' => 'range',
'name' => __('Range:', 'dilaz-panel'),
'desc' => __('Set range between two minimum and maximum values.', 'dilaz-panel'),
'type' => 'range',
'args' => array(
'min' => array( 8, __('Min', 'dilaz-panel') ),
'max' => array( 100, __('Max', 'dilaz-panel') ),
'step' => '2',
'prefix' => '',
'suffix' => '%'
),
'std' => array('min_std' => 20, 'max_std' => 45),
);
$options[] = array(
'id' => 'slider',
'name' => __('Slider:', 'dilaz-panel'),
'desc' => __('Select value from range slider.', 'dilaz-panel'),
'type' => 'slider',
'args' => array('min' => 8, 'max' => 100, 'step' => 2, 'suffix' => '%'),
'std' => '40',
'class' => ''
);
// $options[] = array(
// 'id' => 'info',
// 'name' => __('Info Box Title', 'dilaz-panel'),
// 'desc' => __('Sample info description goes here.', 'dilaz-panel'),
// 'type' => 'info',
// );
$options[] = array(
'id' => 'switchenable',
'name' => __('Switch Enable/Disable:', 'dilaz-panel'),
'desc' => __('Enable/disable switch option.', 'dilaz-panel'),
'type' => 'switch',
'options' => array(
'enable' => __('Enable', 'dilaz-panel'),
'disable' => __('Disable', 'dilaz-panel'),
),
'std' => 'disable',
'class' => ''
);
$options[] = array(
'id' => 'switch',
'name' => __('Switch:', 'dilaz-panel'),
'desc' => __('On/Off switch option.', 'dilaz-panel'),
'type' => 'switch',
'options' => array(
1 => __('On', 'dilaz-panel'),
0 => __('Off', 'dilaz-panel'),
),
'std' => 0,
'class' => ''
);
$options[] = array(
'id' => 'buttonset',
'name' => __('Button Set:', 'dilaz-panel'),
'desc' => __('Set multiple options using buttonset.', 'dilaz-panel'),
'type' => 'buttonset',
'options' => array(
'yes' => __('Yes', 'dilaz-panel'),
'no' => __('No', 'dilaz-panel'),
'maybe' => __('Maybe', 'dilaz-panel')
),
'std' => 'no',
'class' => ''
);
$options[] = array(
'id' => 'background',
'name' => __('Background:', 'dilaz-panel'),
'desc' => __('Background style.', 'dilaz-panel'),
'type' => 'background',
'options' => array(
'image' => true,
'repeat' => true,
'size' => true,
'position' => true,
'attachment' => true,
'origin' => true,
'color' => true,
),
'std' => array(
'image' => '',
'repeat' => '',
'size' => '',
'position' => '',
'attachment' => '',
'origin' => '',
'color' => '',
),
'class' => ''
);
$options[] = array(
'id' => 'textarea',
'name' => __('Textarea:', 'dilaz-panel'),
'desc' => __('Enter text content. HTML tags are NOT enabled (use code field for HTML tags).', 'dilaz-panel'),
'type' => 'textarea',
'args' => array('rows' => 5),
'std' => 'Sample textarea content goes here.',
'class' => ''
);
$options[] = array(
'id' => 'code',
'name' => __('Code:', 'dilaz-panel'),
'desc' => __('Enter code content. HTML tags are enabled.', 'dilaz-panel'),
'type' => 'code',
'args' => array('rows' => 5),
'std' => '<b>Sample code content goes here.</b>',
'class' => ''
);
$options[] = array(
'id' => 'editor',
'name' => __('WP Editor:', 'dilaz-panel'),
'desc' => __('Enter text content.', 'dilaz-panel'),
'type' => 'editor',
'args' => array(
'editor' => array(
'wpautop' => false,
'media_buttons' => false,
// 'textarea_rows' => 11,
'editor_height' => 320,
// 'tabindex' => 1,
'editor_css' => '',
'teeny' => true,
// 'tinymce' => array(),
'quicktags' => false
)
),
'std' => 'Sample textarea content goes here.',
'class' => ''
);
$options[] = array(
'id' => 'text',
'name' => __('Text:', 'dilaz-panel'),
'desc' => __('Text field example.', 'dilaz-panel'),
'type' => 'text',
'std' => '',
'class' => ''
);
$options[] = array(
'id' => 'multi_text_inline',
'name' => __('Multiple Text (Inline 3 Columns):', 'dilaz-panel'),
'desc' => __('Set any number of multiple text field options.', 'dilaz-panel'),
'type' => 'multitext',
'options' => array(
'text1' => array('name' => __('Text 1', 'dilaz-panel'), 'default' => __('Sample One', 'dilaz-panel')),
'text2' => array('name' => __('Text 2', 'dilaz-panel'), 'default' => __('Sample Two', 'dilaz-panel')),
'text3' => array('name' => __('Text 3', 'dilaz-panel'), 'default' => __('Sample Three', 'dilaz-panel')),
'text4' => array('name' => __('Text 4', 'dilaz-panel'), 'default' => __('Sample Four', 'dilaz-panel')),
'text5' => array('name' => __('Text 5', 'dilaz-panel'), 'default' => __('Sample Five', 'dilaz-panel')),
'text6' => array('name' => __('Text 6', 'dilaz-panel'), 'default' => __('Sample Six', 'dilaz-panel')),
),
'args' => array('inline' => true, 'cols' => 3),
);
$options[] = array(
'id' => 'multi_text',
'name' => __('Multiple Text (Single Columns):', 'dilaz-panel'),
'desc' => __('Set any number of multiple text field options.', 'dilaz-panel'),
'type' => 'multitext',
'options' => array(
'text1' => array('name' => __('Text 1', 'dilaz-panel'), 'default' => 'Sample One'),
'text2' => array('name' => __('Text 2', 'dilaz-panel'), 'default' => 'Sample Two'),
'text3' => array('name' => __('Text 3', 'dilaz-panel'), 'default' => 'Sample Three')
),
'args' => array(),
);
# MAIN TAB - Media Options
# =============================================================================================
$options[] = array(
'id' => 'media-options',
'name' => __('Media Options', 'dilaz-panel'),
'type' => 'heading',
'icon' => 'mdi-monitor'
);
# SUB TAB - Image
# *****************************************************************************************
$options[] = array(
'id' => 'image_files_example',
'name' => __('Image', 'dilaz-panel'),
'type' => 'subheading',
);
# FIELDS - Image options
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$options[] = array(
'id' => 'image_multiple',
'name' => __('Image File (Multiple):', 'dilaz-panel'),
'desc' => __('Select/Upload multiple image files from media library.', 'dilaz-panel'),
'type' => 'upload',
'std' => '',
'args' => array(
'file_type' => 'image',
'multiple' => true
),
);
$options[] = array(
'id' => 'image_single',
'name' => __('Image File:', 'dilaz-panel'),
'desc' => __('Select/Upload single image file from media library.', 'dilaz-panel'),
'type' => 'upload',
'std' => '',
'args' => array(
'file_type' => 'image',
'show_thumb' => false,
),
);
# SUB TAB - Audio
# *****************************************************************************************
$options[] = array(
'id' => 'audio_files_example',
'name' => __('Audio', 'dilaz-panel'),
'type' => 'subheading',
);
# FIELDS - Audio options
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$options[] = array(
'id' => 'audio_multiple',
'name' => __('Audio File (Multiple):', 'dilaz-panel'),
'desc' => __('Select/Upload multiple audio files from media library.', 'dilaz-panel'),
'type' => 'upload',
'std' => '',
'args' => array(
'file_type' => 'audio',
'multiple' => true
),
);
$options[] = array(
'id' => 'audio_single',
'name' => __('Audio File:', 'dilaz-panel'),
'desc' => __('Select/Upload single audio file from media library.', 'dilaz-panel'),
'type' => 'upload',
'std' => '',
'args' => array(
'file_type' => 'audio',
),
);
# SUB TAB - Video
# *****************************************************************************************
$options[] = array(
'id' => 'video_files_example',
'name' => __('Video', 'dilaz-panel'),
'type' => 'subheading',
);
# FIELDS - Video options
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$options[] = array(
'id' => 'video_multiple',
'name' => __('Video File (Multiple):', 'dilaz-panel'),
'desc' => __('Select/Upload multiple video files from media library.', 'dilaz-panel'),
'type' => 'upload',
'std' => '',
'args' => array(
'file_type' => 'video',
'multiple' => true
),
);
$options[] = array(
'id' => 'video_single',
'name' => __('Video File:', 'dilaz-panel'),
'desc' => __('Select/Upload single video file from media library.', 'dilaz-panel'),
'type' => 'upload',
'std' => '',
'args' => array(
'file_type' => 'video',
),
);
# MAIN TAB - Color Options
# =============================================================================================
$options[] = array(
'id' => 'color-options',
'name' => __('Color Options', 'dilaz-panel'),
'type' => 'heading',
'icon' => 'mdi-format-color-fill'
);
# SUB TAB - Color
# *****************************************************************************************
// $options[] = array(
// 'id' => 'color',
// 'name' => __('Color', 'dilaz-panel'),
// 'type' => 'subheading',
// );
# FIELDS - Color options
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$options[] = array(
'id' => 'link',
'name' => __('Link Example:', 'dilaz-panel'),
'desc' => __('Link multiple color properties.', 'dilaz-panel'),
'type' => 'multicolor',
'options' => array(
'regular' => array('color' => '#111111', 'name' => __('Regular', 'dilaz-panel')),
'hover' => array('color' => '#333333', 'name' => __('Hover', 'dilaz-panel')),
'visited' => array('color' => '#555555', 'name' => __('Visited', 'dilaz-panel')),
'active' => array('color' => '#999999', 'name' => __('Active', 'dilaz-panel')),
),
);
$options[] = array(
'id' => 'multicolor',
'name' => __('Multicolor:', 'dilaz-panel'),
'desc' => __('General multiple color properties.', 'dilaz-panel'),
'type' => 'multicolor',
'options' => array(
'color1' => array('color' => '#111111', 'name' => __('Color 1', 'dilaz-panel')),
'color2' => array('color' => '#333333', 'name' => __('Color 2', 'dilaz-panel')),
'color3' => array('color' => '#555555', 'name' => __('Color 3', 'dilaz-panel')),
'color4' => array('color' => '#777777', 'name' => __('Color 4', 'dilaz-panel')),
'color5' => array('color' => '#999999', 'name' => __('Color 5', 'dilaz-panel')),
),
);
$options[] = array(
'id' => 'color',
'name' => __('Color:', 'dilaz-panel'),
'desc' => __('Single color option.', 'dilaz-panel'),
'type' => 'color',
'std' => '#ff2211',
'class' => ''
);
# MAIN TAB - General Settings
# =============================================================================================
$options[] = array(
'id' => 'repeatable-options',
'name' => __('Repeatable Options', 'dilaz-panel'),
'type' => 'heading',
'icon' => 'mdi-view-list'
);
# TAB - Repeatable Options Set
# *****************************************************************************************
// $options[] = array(
// 'id' => '',
// 'name' => __('', 'dilaz-panel'),
// 'type' => 'subheading'
// );
# FIELDS - Alpha Tab 1
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$options[] = array(
'id' => 'repeatable_one',
'name' => __('Repeatable (Single Field per Row):', 'dilaz-panel'),
'desc' => __('Single row items repeatable field. ', 'dilaz-panel'),
'type' => 'repeatable',
'args' => array(
'sortable' => true,
'removable' => true,
'add_more' => true,
'add_text' => __('Add More', 'dilaz-panel'),
),
'options' => array(
array(
array('label' => '', 'value' => 'Row 1 - Value 1'),
),
array(
array('label' => '', 'value' => 'Row 2 - Value 2'),
)
),
);
$options[] = array(
'id' => 'repeatable_two',
'name' => __('Repeatable (Multiple Fields per Row):', 'dilaz-panel'),
'desc' => __('Multiple row items repeatable field. You can add any number item fields per row.', 'dilaz-panel'),
'type' => 'repeatable',
'args' => array(
'sortable' => true,
'removable' => true,
'add_more' => true,
'add_text' => __('Add More Custom', 'dilaz-panel'),
),
'options' => array(
array(
array('label' => 'Label One', 'value' => 'Row 1 - Value 1', 'size' => 15),
array('label' => 'Label Two', 'value' => 'Row 1 - Value 2', 'size' => 15),
array('label' => 'Label Three', 'value' => 'Row 1 - Value 3', 'size' => 15),
array('label' => 'Label Four', 'value' => 'Row 1 - Value 4', 'size' => 15),
),
array(
array('label' => 'Label One', 'value' => 'Row 2 - Value 1', 'size' => 15),
array('label' => 'Label Two', 'value' => 'Row 2 - Value 2', 'size' => 15),
array('label' => 'Label Three', 'value' => 'Row 2 - Value 3', 'size' => 15),
array('label' => 'Label Four', 'value' => 'Row 2 - Value 4', 'size' => 15),
)
),
);
$options[] = array(
'id' => 'repeatable_three',
'name' => __('Repeatable (Add More Field Disabled):', 'dilaz-panel'),
'desc' => __('Add more button is disabled.', 'dilaz-panel'),
'type' => 'repeatable',
'args' => array(
'sortable' => true,
'removable' => true,
'add_more' => false,
),
'options' => array(
array(
array('label' => '', 'value' => 'Row 1 - Value 1'),
),
array(
array('label' => '', 'value' => 'Row 2 - Value 1'),
),
array(
array('label' => '', 'value' => 'Row 3 - Value 1'),
)
),
);
$options[] = array(
'id' => 'repeatable_four',
'name' => __('Repeatable (Sorting Disabled):', 'dilaz-panel'),
'desc' => __('Field sorting is disabled.', 'dilaz-panel'),
'type' => 'repeatable',
'args' => array(
'sortable' => false,
'removable' => true,
'add_more' => true,
),
'options' => array(
array(
array('label' => '', 'value' => 'Row 1 - Value 1'),
),
array(
array('label' => '', 'value' => 'Row 2 - Value 1'),
),
array(
array('label' => '', 'value' => 'Row 3 - Value 1'),
)
),
);
$options[] = array(
'id' => 'repeatable_five',
'name' => __('Repeatable (Sorting Disabled for First 2 Fields):', 'dilaz-panel'),
'desc' => __('Field sorting is disabled for the first 2 items.', 'dilaz-panel'),
'type' => 'repeatable',
'args' => array(
'sortable' => true,
'not_sortable' => 2,
'add_more' => true,
),
'options' => array(
array(
array('label' => '', 'value' => 'Row 1 - Value 1'),
),
array(
array('label' => '', 'value' => 'Row 2 - Value 1'),
),
array(
array('label' => '', 'value' => 'Row 3 - Value 1'),
)
),
);
$options[] = array(
'id' => 'repeatable_six',
'name' => __('Repeatable (Removal Disabled):', 'dilaz-panel'),
'desc' => __('Field removal is disabled.', 'dilaz-panel'),
'type' => 'repeatable',
'args' => array(
'removable' => false,
'add_more' => true,
),
'options' => array(
array(
array('label' => '', 'value' => 'Row 1 - Value 1'),
),
array(
array('label' => '', 'value' => 'Row 2 - Value 1'),
),
array(
array('label' => '', 'value' => 'Row 3 - Value 1'),
)
),
);
$options[] = array(
'id' => 'repeatable_seven',
'name' => __('Repeatable (Removal Disabled for the 1st and 2nd Fields):', 'dilaz-panel'),
'desc' => __('Field removal is disabled for the 1st and 2nd items.', 'dilaz-panel'),
'type' => 'repeatable',
'args' => array(
'not_removable' => 2,
'add_more' => true,
),
'options' => array(
array(
array('label' => '', 'value' => 'Row 1 - Value 1'),
),
array(
array('label' => '', 'value' => 'Row 2 - Value 1'),
),
array(
array('label' => '', 'value' => 'Row 3 - Value 1'),
)
),
);
# MAIN TAB - Typography Options
# =============================================================================================
$options[] = array(
'id' => 'typography-options',
'name' => __('Typography Options', 'dilaz-panel'),
'type' => 'heading',
'icon' => 'mdi-format-font'
);
# SUB TAB - Typography
# *****************************************************************************************
// $options[] = array(
// 'id' => 'typography',
// 'name' => __('Typography', 'dilaz-panel'),
// 'type' => 'subheading',
// );
# FIELDS - Typography options
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$options[] = array(
'id' => 'font',
'name' => __('Font:', 'dilaz-panel'),
'desc' => __('Typography style with many option properties.', 'dilaz-panel'),
'type' => 'font',
'options' => array(
'family' => true,
'backup' => true,
'subset' => true,
'weight' => true,
'size' => true,
'height' => true,
'style' => true,
'case' => true,
'color' => true
),
'std' => array(
'family' => 'Trebuchet',
'backup' => false,
'subset' => false,
'weight' => false,
'size' => '18',
'height' => false,
'style' => false,
'case' => false,
'color' => false,
),
'class' => ''
);
$options[] = array(
'id' => 'font_2',
'name' => __('Font 2:', 'dilaz-panel'),
'desc' => __('Typography style with few option properties.', 'dilaz-panel'),
'type' => 'font',
'options' => array(
'family' => true,
'backup' => true,
'subset' => false,
'weight' => true,
'size' => true,
'height' => true,
'style' => true,
'case' => true,
'color' => true,
),
'std' => array(
'family' => 'Trebuchet',
'backup' => false,
'subset' => false,
'weight' => false,
'size' => false,
'height' => false,
'style' => 'italic',
'case' => false,
'color' => false,
),
'class' => ''
);
# MAIN TAB - Choice Options
# =============================================================================================
$options[] = array(
'id' => 'choice-options',
'name' => __('Choice Options', 'dilaz-panel'),
'type' => 'heading',
'icon' => 'mdi-tune'
);
# SUB TAB - Choice
# *****************************************************************************************
// $options[] = array(
// 'id' => 'choice',
// 'name' => __('Choice', 'dilaz-panel'),
// 'type' => 'subheading',
// );
# FIELDS - Choice options
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$options[] = array(
'id' => 'radioimage',
'name' => __('Radio Image:', 'dilaz-panel'),
'desc' => __('Images used as radio option fields.', 'dilaz-panel'),
'type' => 'radioimage',
'options' => array(
'teal.css' => array('src' => $parameters['dir_url'] .'assets/images/colors/teal.png', 'alt' => 'teal'),
'cyan.css' => array('src' => $parameters['dir_url'] .'assets/images/colors/cyan.png', 'alt' => 'cyan'),
'amber.css' => array('src' => $parameters['dir_url'] .'assets/images/colors/amber.png', 'alt' => 'amber'),
),
'std' => 'amber.css',
'class' => ''
);
$options[] = array(
'id' => 'radioimage_tiled',
'name' => __('Radio Image Tiled Background:', 'dilaz-panel'),
'desc' => __('Images used as radio option fields.', 'dilaz-panel'),
'type' => 'radioimage',
'options' => array(
$parameters['dir_url'] .'assets/images/bg/crissXcross.png' => array('src' => $parameters['dir_url'] .'assets/images/bg/crissXcross.png', 'alt' => 'crissXcross'),
$parameters['dir_url'] .'assets/images/bg/nistri.png' => array('src' => $parameters['dir_url'] .'assets/images/bg/nistri.png', 'alt' => 'nistri'),
),
'std' => $parameters['dir_url'] .'assets/images/bg/nistri.png',
'args' => array('tiled_bg' => true),
'class' => ''
);
$options[] = array(
'id' => 'radio',
'name' => __('Radio:', 'dilaz-panel'),
'desc' => __('Tiled radio options selection.', 'dilaz-panel'),
'type' => 'radio',
'options' => array(
'one' => __('One', 'dilaz-panel'),
'two' => __('Two', 'dilaz-panel'),
'three' => __('Three', 'dilaz-panel')
),
'std' => 'two',
'class' => '',
);
$options[] = array(
'id' => 'radio_inline',
'name' => __('Radio Inline:', 'dilaz-panel'),
'desc' => __('Inline radio options selection.', 'dilaz-panel'),
'type' => 'radio',
'options' => array(
'one' => __('One', 'dilaz-panel'),
'two' => __('Two', 'dilaz-panel'),
'three' => __('Three', 'dilaz-panel'),
),
'std' => 'two',
'class' => '',
'args' => array('inline' => true),
);
$options[] = array(
'id' => 'multicheck',
'name' => __('Multicheck:', 'dilaz-panel'),
'desc' => __('Tiled multiple checkbox options selection.', 'dilaz-panel'),
'type' => 'multicheck',
'options' => array(
'mon' => __('Monday', 'dilaz-panel'),
'tue' => __('Tuesday', 'dilaz-panel'),
'wed' => __('Wednesday', 'dilaz-panel'),
'thu' => __('Thursday', 'dilaz-panel'),
'fri' => __('Friday', 'dilaz-panel'),
'sat' => __('Saturday', 'dilaz-panel'),
'sun' => __('Sunday', 'dilaz-panel')
),
'std' => array('thu', 'sat', 'sun'),
'class' => '',
);
$options[] = array(
'id' => 'multicheck_inline',
'name' => __('Multicheck Inline:', 'dilaz-panel'),
'desc' => __('Inline multiple checkbox options selection.', 'dilaz-panel'),
'type' => 'multicheck',
'options' => array(
'mon' => __('Monday', 'dilaz-panel'),
'tue' => __('Tuesday', 'dilaz-panel'),
'wed' => __('Wednesday', 'dilaz-panel'),
'thu' => __('Thursday', 'dilaz-panel'),
'fri' => __('Friday', 'dilaz-panel'),
'sat' => __('Saturday', 'dilaz-panel'),
'sun' => __('Sunday', 'dilaz-panel')
),
'std' => array('tue', 'fri'),
'class' => '',
'args' => array('inline' => true, 'cols' => 4),
);
$options[] = array(
'id' => 'checkbox',
'name' => __('Checkbox:', 'dilaz-panel'),
'desc' => __('Select the preferred layout type.', 'dilaz-panel'),
'type' => 'checkbox',
'std' => true,
'class' => ''
);
$options[] = array(
'id' => 'term_select',
'name' => __('Term Select:', 'dilaz-panel'),
'desc' => '',
'type' => 'queryselect',
'std' => '',
'args' => array(
'select2' => 'select2multiple',
'query_type' => 'term',
'placeholder' => __('Select category', 'dilaz-panel'),
'select2width' => '50%',
'min_input' => 1,
'max_input' => 100,
'max_options' => 10,
'query_args' => array(
'taxonomy' => 'category',
'hide_empty' => false,
'orderby' => 'term_id',
'order' => 'ASC',
),
),
);
$options[] = array(
'id' => 'user_select',
'name' => __('User Select:', 'dilaz-panel'),
'desc' => '',
'type' => 'queryselect',
'std' => '',
'args' => array(
'select2' => 'select2multiple',
'query_type' => 'user',
'placeholder' => __('Select user', 'dilaz-panel'),
'select2width' => '50%',
'min_input' => 1,
'max_input' => 100,
'max_options' => 10,
'query_args' => array(
'orderby' => 'ID',
'order' => 'ASC',
),
),
);
$options[] = array(
'id' => 'post_select',
'name' => __('Post Select:', 'dilaz-panel'),
'desc' => '',
'type' => 'queryselect',
'std' => '',
'args' => array(
'select2' => 'select2multiple',
'query_type' => 'post',
'placeholder' => __('Type to select a post', 'dilaz-panel'),
'select2width' => '50%',
'min_input' => 1,
'max_input' => 100,
'max_options' => 10,
'query_args' => array(
'posts_per_page' => -1,
'post_status' => array('publish'),
'post_type' => array('post'),
'order' => 'ASC',
'orderby' => 'ID',
),
),
);
$options[] = array(
'id' => 'page_select',
'name' => __('Page Select:', 'dilaz-panel'),
'desc' => '',
'type' => 'queryselect',
'std' => '',
'args' => array(
'select2' => 'select2multiple',
'query_type' => 'page',
'placeholder' => __('Type to select a page', 'dilaz-panel'),
'select2width' => '50%',
'min_input' => 1,
'max_input' => 100,
'max_options' => 10,
'query_args' => array(
'posts_per_page' => -1,
'post_status' => array('publish'),
'post_type' => array('page'),
'order' => 'ASC',
'orderby' => 'ID',
),
),
);
$options[] = array(
'id' => 'select_multiple_two',
'name' => __('"Select2" Multi-Select Field:', 'dilaz-panel'),
'desc' => __('Select the preferred header type', 'dilaz-panel'),
'type' => 'multiselect',
'options' => array(
'one' => __('One', 'dilaz-panel'),
'two' => __('Two', 'dilaz-panel'),
'three' => __('Three', 'dilaz-panel'),
'four' => __('Four', 'dilaz-panel')
),
'args' => array( 'select2' => 'select2multiple' ),
'std' => 'normal',
'class' => ''
);
$options[] = array(
'id' => 'select_multiple_one',
'name' => __('Default Milti-Select Field:', 'dilaz-panel'),
'desc' => __('Select the preferred header type', 'dilaz-panel'),
'type' => 'multiselect',
'options' => array(
'one' => __('One', 'dilaz-panel'),
'two' => __('Two', 'dilaz-panel'),
'three' => __('Three', 'dilaz-panel'),
'four' => __('Four', 'dilaz-panel')
),
'std' => 'normal',
'class' => ''
);
$options[] = array(
'id' => 'select_two',
'name' => __('"Select2" Select Field:', 'dilaz-panel'),
'desc' => __('Select the preferred header type', 'dilaz-panel'),
'type' => 'select',
'options' => array(
'one' => __('One', 'dilaz-panel'),
'two' => __('Two', 'dilaz-panel'),
'three' => __('Three', 'dilaz-panel'),
'four' => __('Four', 'dilaz-panel')
),
'args' => array( 'select2' => 'select2single' ),
'std' => 'normal',
'class' => ''
);
$options[] = array(
'id' => 'select_one',
'name' => __('Default Select Field:', 'dilaz-panel'),
'desc' => __('Select the preferred header type', 'dilaz-panel'),
'type' => 'select',
'options' => array(
'one' => __('One', 'dilaz-panel'),
'two' => __('Two', 'dilaz-panel'),
'three' => __('Three', 'dilaz-panel'),
'four' => __('Four', 'dilaz-panel')
),
'std' => 'normal',
'class' => ''
);
# TAB - Conditionals
# =============================================================================================
$options[] = array(
'id' => 'conditionals',
'name' => __('Conditionals', 'dilaz-panel'),
'type' => 'heading',
'icon' => 'mdi-toggle-switch'
);
# SUB TAB - Conditionals
# *****************************************************************************************
// $options[] = array(
// 'id' => 'conditionals',
// 'name' => __('Conditionals', 'dilaz-panel'),
// 'type' => 'subheading',
// );
# FIELDS - Conditional options
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$options[] = array(
'id' => 'continent',
'name' => __('Continent:', 'dilaz-panel'),
'desc' => '',
'type' => 'select',
'options' => array(
'' => __('Select Continent', 'dilaz-panel'),
'eu' => __('Europe', 'dilaz-panel'),
'na' => __('North America', 'dilaz-panel'),
),
'std' => 'default',
'args' => array('inline' => true),
);
$options[] = array(
'id' => 'eu_country',
'name' => __('Europe Country:', 'dilaz-panel'),
'desc' => '',
'type' => 'radio',
'options' => array(
'de' => __('Germany', 'dilaz-panel'),
'gb' => __('United Kingdom', 'dilaz-panel'),
),
'std' => 'default',
'args' => array('inline' => true),
'req_args' => array(
'continent' => 'eu'
),
'req_action' => 'show',
);
$options[] = array(
'id' => 'na_country',
'name' => __('North America Country:', 'dilaz-panel'),
'desc' => '',
'type' => 'radio',
'options' => array(
'us' => __('United States', 'dilaz-panel'),
'ca' => __('Canada', 'dilaz-panel'),
),
'std' => 'default',
'args' => array('inline' => true),
'req_args' => array(
'continent' => 'na'
),
'req_cond' => 'AND',
'req_action' => 'show',
);
$options[] = array(
'id' => 'de_division',
'name' => __('Germany Division:', 'dilaz-panel'),
'desc' => '',
'type' => 'multicheck',
'options' => array(
'hh' => __('Hamburg', 'dilaz-panel'),
'be' => __('Berlin', 'dilaz-panel'),
'sh' => __('Schleswig-Holstein', 'dilaz-panel'),
),
'std' => 'default',
'args' => array('inline' => true),
'req_args' => array(
'continent' => 'eu',
'eu_country' => 'de'
),
'req_cond' => 'AND',
'req_action' => 'show',
);
$options[] = array(
'id' => 'gb_division',
'name' => __('United Kingdom Division:', 'dilaz-panel'),
'desc' => '',
'type' => 'multicheck',
'options' => array(
'abd' => __('Aberdeen City', 'dilaz-panel'),
'bir' => __('Birmingham', 'dilaz-panel'),
'lce' => __('Leicester', 'dilaz-panel'),
'man' => __('Manchester', 'dilaz-panel'),
),
'std' => 'default',
'args' => array('inline' => true),
'req_args' => array(
'continent' => 'eu',
'eu_country' => 'gb'
),
'req_cond' => 'AND',
'req_action' => 'show',
);
$options[] = array(
'id' => 'us_division',
'name' => __('US State:', 'dilaz-panel'),
'desc' => '',
'type' => 'multicheck',
'options' => array(
'wa' => __('Washington', 'dilaz-panel'),
'oh' => __('Ohio', 'dilaz-panel'),
'mt' => __('Montana', 'dilaz-panel'),
'ga' => __('Georgia', 'dilaz-panel'),
),
'std' => 'default',
'args' => array('inline' => true),
'req_args' => array(
'continent' => 'na',
'na_country' => 'us'
),
'req_cond' => 'AND',
'req_action' => 'show',
);
$options[] = array(
'id' => 'us_division',
'name' => __('Canada Division:', 'dilaz-panel'),
'desc' => '',
'type' => 'multicheck',
'options' => array(
'on' => __('Ontario', 'dilaz-panel'),
'sk' => __('Saskatchewan', 'dilaz-panel'),
'qc' => __('Quebec', 'dilaz-panel'),
),
'std' => 'default',
'args' => array('inline' => true),
'req_args' => array(
'continent' => 'na',
'na_country' => 'ca'
),
'req_cond' => 'AND',
'req_action' => 'show',
);
return wp_parse_args($options, $options);<file_sep># Dilaz Panel Options Sample
This helps you to integrate [Dilaz Panel Plugin](https://github.com/Rodgath/Dilaz-Panel) into your WordPress theme/plugin development.
## How to use
1. Download and install [Dilaz Panel](https://github.com/Rodgath/Dilaz-Panel/archive/master.zip) plugin.
2. Download [Dilaz Panel Options](https://github.com/Rodgath/Dilaz-Panel-Options/archive/master.zip).
3. Add *Dilaz-Panel-Options* to the root directory of your theme or plugin. <br />
i) For example: <br />
> *wp-content/themes/__theme-name__/Dilaz-Panel-Options*
__OR__
> *wp-content/plugins/__plugin-name__/Dilaz-Panel-Options* <br />
ii) You can optionally rename *Dilaz-Panel-Options* folder.
4. Add the code provided below in your themes __functions.php__ file or in your plugin's __main/index__ file.
```php
/**
* Admin Panel Options
*/
require_once 'Dilaz-Panel-Options/admin.php';
```
5. Open ```Dilaz-Panel-Options``` folder and rename ```config-sample.php``` to ```config.php```.
6. Open ```Dilaz-Panel-Options/config.php``` and edit the parameters as you want. Simple guidelines are provided beside each parameter setting.
7. Open ```Dilaz-Panel-Options/options``` folder and rename ```options-sample.php``` to ```options.php```.
8. Open ```Dilaz-Panel-Options/options/options.php``` and add your admin options.
***
__NOTE:__
1. ```Dilaz-Panel-Options/custom-options-sample.php``` contains examples showing how to use actions hooks to add custom admin options to any Dilaz Panel implementation.
2. ```Dilaz-Panel-Options/default-options.php``` contains default options as examples for all possible admin fields.
3. ```Dilaz-Panel-Options/import-export.php``` contains import/export option settings.
***
## *config.php* parameters
| Parameter | Type | Default | Since (Dilaz Panel) | Details |
| :------------- |:----------|:----------| :-------------| :----- |
| `option_name` | *string* | dilaz_options | v2.3 | Used to save settings. Must be unique. |
| `option_prefix` | *string* | dilaz_panel | v2.0 | Not used to save settings. Must be unique. |
| `use_type` | *string* | theme | v2.0 | Where the panel is used. Enter `theme` if used within a theme OR `plugin` if used within a plugin |
| `default_options` | *boolean* | true | v2.0 | Whether to load default options. |
| `custom_options` | *boolean* | true | v2.0 | Whether to load custom options. |
| `page_slug` | *string* | dilaz_panel | v2.0 | Must be unique. |
| `page_title` | *string* | Dilaz Panel | v2.0 | The text to be displayed in the title tags of the page when the menu is selected. |
| `menu_title` | *string* | Dilaz Panel | v2.0 | The text to be used for the menu. |
| `options_view_cap` | *array* | array('manage_options') | v2.7.8 | The capabilities required for this menu to be displayed to the user. |
| `options_save_cap` | *array* | array('manage_options') | v2.7.8 | The capabilities required for the user to save the options for the panel. |
| `menu_icon` | *string* | null | v2.0 | Dashicon menu icon. |
| `menu_position` | *int* | null | v2.3 | Position in menu order. Works with top-level menu only. |
| `parent_slug` | *string* | null | v2.3 | The slug name for the parent menu (or the file name of a standard WordPress admin page). |
| `admin_bar_menu` | *boolean* | true | v2.0 | 'true' to show panel in admin bar menu. |
| `import_export` | *boolean* | true | v2.0 | 'true' to enable import/export field. |
| `log_title` | *string* | Changelog | v2.0 | Changlelog title. |
| `log_url` | *string* | # | v2.0 | Changlelog url. Leave empty to disable. |
| `doc_title` | *string* | Documentation | v2.0 | Documentation title. |
| `doc_url` | *string* | # | v2.0 | Documentation url. Leave empty to disable. |
| `support_title` | *string* | Support | v2.0 | Support title. |
| `support_url` | *string* | # | v2.0 | Support url. Leave empty to disable. |
| ~~`options_cap`~~ | *string* | manage_options | v2.0 | __Deprecated__ since v2.7.8. |
***
## Download
To get a local working copy of the development repository, do:
git clone https://github.com/Rodgath/Dilaz-Panel-Options.git
Alternatively, you can download the latest development version as a tarball
as follows:
wget --content-disposition https://github.com/Rodgath/Dilaz-Panel-Options/tarball/master
OR
curl -LJO https://github.com/Rodgath/Dilaz-Panel-Options/tarball/master
| 69aa58e45155a75b6e22e26503f54d5cd8bbe32f | [
"Markdown",
"PHP"
] | 8 | PHP | Rodgath/Dilaz-Panel-Options | 6ad67e176975625bb0e026c339eb1ab37f940e63 | b1b13107d192f12e7c9f0395d13af5238a0948ce | |
refs/heads/main | <file_sep>from GrandStand import GrandStand
from BoxStand import BoxStand
from TelescopicStand import TelescopicStand
from Pods import Pod
class Coliseum():
def __init__(self, name):
self.name = name
self.stands = list() # A list of all stands inside the coliseum
def get_name(self):
"""This method will return the name."""
return self.name
def set_name(self, name):
"""This method will change the name."""
self.name = name
def get_stands(self):
"""This method will return the list of stands inside the coliseum."""
return self.stands
def show_stands(self):
"""This will show all stands in the stands list."""
for i in self.stands:
print(i.name)
i.show_pods()
def add_stand_to_coliseum(self, stand):
"""This method will add a new stand inside the colisum list of stands."""
self.stands.append(stand)
def remove_stand_of_coliseum(self, stand_id):
"""This method will remove stand from stands list that contain all the stands objects. The parameter should be the pods id."""
found_stand = False
# Loop through each stand in our stands list.
for i in self.stands:
# If we find them, remove them from the list.
if i.id == stand_id:
self.stands.remove(i)
# set our indicator to True
found_stand = True
# If we looped through our list and did not find our stand, the indicator would never get change, so return 'Pod not found!'
if not found_stand:
print(f'Stand not found!')
if __name__ == "__main__":
# Create a Coliseum that will have three Stands and each
# of them will have some pods
# Coliseum
coliseum_humacao = Coliseum('Coliseum of Multiple Uses from Humacao')
# Stands
lateral_grand_stand_west = GrandStand('Lateral Grand Stand - West', 42, 17, 3)
lateral_grand_stand_east = GrandStand('Lateral Grand Stand - East', 42, 17, 3)
telescopic_stand_bottom = TelescopicStand('Telescopic Stand - South', 28, 11, 2)
# Pods
lateral_grand_stand_west.create_pod()
lateral_grand_stand_west.create_pod()
lateral_grand_stand_west.create_pod()
lateral_grand_stand_east.create_pod()
lateral_grand_stand_east.create_pod()
lateral_grand_stand_east.create_pod()
telescopic_stand_bottom.create_pod()
telescopic_stand_bottom.create_pod()
telescopic_stand_bottom.create_pod()
# Cheking for pods...
# print(f'{lateral_grand_stand_west.get_name()}')
# lateral_grand_stand_west.show_pods()
# print(f'{lateral_grand_stand_east.get_name()}')
# lateral_grand_stand_east.show_pods()
# print(f'{telescopic_stand_bottom.get_name()}')
# telescopic_stand_bottom.show_pods()
# Adding stands to stadium
coliseum_humacao.add_stand_to_coliseum(lateral_grand_stand_west)
coliseum_humacao.add_stand_to_coliseum(lateral_grand_stand_east)
coliseum_humacao.add_stand_to_coliseum(telescopic_stand_bottom)
# Cheking of what the stadium is made of
coliseum_humacao.show_stands()<file_sep>import numpy
import math
import helper_module
class Pod():
"""This class will create seats for people to sit down. Those seats are going to be called 'Pods'."""
def __init__(self, row, column):
"""This constructur will create and store the attribute for a pod."""
self.pod = self.create_pod(row, column)
self.id = helper_module.generate_id()
def show_pod(self):
"""This will display this pod."""
print(self.pod)
def create_pod(self, pod_row, pod_column):
"""It takes in two integer values; the number of rows and columns for the desire pod. Returns a matrix which have '0' where avaiable seats are and '2' where buffer seats are.'"""
# Creating a matrix that represent the seats on a pod
pod = numpy.zeros(shape=(pod_row, pod_column), dtype=int)
# Total available rows in the pod where people can sit. It round the value to the greatest integer.
total_avaliable_rows = math.ceil(pod_row/3)
# Here it will be save the a row that will represent a buffer marker. A buffer marker is important because it will denote where a two buffer rows will start.
buffer_row_marker = list()
# Here it will be store in a list the actual number of the rows people can sit in the pot.
actual_rows_people_sit = list()
# This for loop will run the amount of total avaliable rows and each time it will store a row that represent a buffer marker to one list and the actual rows people can sit in the other list.
# The 3*row represent sequence jump.
# The specific reason why the jump is 3*row is because the distance from where the person sit and the next person sits is a little bit over the 6ft. recommended for social distance.
# Each seat is 20in the leg room is also 20in so with two rows in between that adds up to eight feet and four inches. A row less and it will be just 5 feets.
# ***THE VALUES HERE FOR THE ROW ARE THE INDEXES. STARTING FROM 0.***
for row in range(total_avaliable_rows):
# The plus 1 is because the first row is always going to be avaliable.
buffer_row_marker.append(1+(3*row))
actual_rows_people_sit.append(3*row)
# Changing the values from zero to 2's for the Buffer Rows
for row in buffer_row_marker:
for column in range(pod_column):
# This run in the special case where the program can't add two buffer rows because there is just one row left.
# The minus one is because the pod_row represent the actual number of rows. Meaning it doesn't represent the index.
if row == pod_row-1:
pod[row][column] = 2
# This run in the special case where the program can't add two buffer rows because there is no row left.
# The break is to ignore adding the buffer rows and jump outside the elif and for loop.
elif row == pod_row:
break
# This run for everytime there is two rows that can be set as buffers.
else:
pod[row][column] = 2
pod[row+1][column] = 2
return pod
def sitting_people(self, amount_people_sitting):
"""This function will deside where to sit people on the pod. The amount of people is an integer and the pod needs to be an object type matrix. After seatting everyone it will set some buffer seats for social distance."""
# Finding the rows people can actually sit.
total_avaliable_rows = math.ceil(len(self.pod)/3)
actual_rows_people_sit = list()
for row in range(total_avaliable_rows):
actual_rows_people_sit.append(3*row)
# Finding the amount of rows and columns the pod have.
pod_num_column = len(self.pod[0])
# Creating a variable that is goint to be use to know how many sits the row have left to allow some desition making.
seats_left = pod_num_column
# There is a social distance recommended by the CDC of 6 feets, considering that each seat is 20x20 inches and each
# seat are side by side to satisfy this recommendation we need at least four seats in between the groups.
social_distance_buffer_seats = 4
# The reason why I went with this function is to have the ability of stopping all loops after sitting everyone. Break didn't work as intended and had to refactor the code.
pod = self.sitting_logistic(amount_people_sitting, self.pod, actual_rows_people_sit, seats_left, social_distance_buffer_seats)
self.pod = pod
return pod
def sitting_logistic(self, amount_people_sitting, pod, actual_rows_people_sit, seats_left, social_distance_buffer_seats):
"""This function is the one that is going to decide where to sit everyone."""
for row in actual_rows_people_sit: # This goes through all rows people can sit.
avaliable_seats_row = self.get_avaliable_seats_row(pod[row])
occupied_seats = self.get_occupied_seats_row(pod[row])
buffer_seats = self.get_buffer_seats_row(pod[row])
avaliable_seats_pod = self.get_seats_avaliable_pod()
# If avaliable seats are enough for the amount of people sitting and the buffer seats this will run.
if avaliable_seats_row >= (amount_people_sitting + social_distance_buffer_seats):
# This will run over each avaliable seat and change the value to represent is ocuppied '1' and to next amount of social_distance_buffer_seats as buffer seats '2'
if pod[row][0] == 0: # This will mean the row is empty
# Loop over as many times needed to sit everyone using the avaliable_seat value as an index.
self.sit_people_empty_row(pod, row, amount_people_sitting)
# Loop over as many times needed to satisfy the social distance buffer seats amount.
self.set_buffer_seat_empty_row(social_distance_buffer_seats, amount_people_sitting, pod, row)
# This run when the row is not empty
else:
# Loop over as many times needed to sit everyone using the avaliable_seat value as an index.
self.sit_people_row(pod, row, occupied_seats,buffer_seats, amount_people_sitting)
# Updating the new ocuppied seats that have been set in the function from above.
occupied_seats += amount_people_sitting
# Loop over as many times needed to satisfy the social distance buffer seats amount.
self.set_buffer_seat(social_distance_buffer_seats, occupied_seats, buffer_seats, pod,row)
return pod
# This will run when the avaliable sit are less than the people seatting plus the buffer seats.
else:
# This code cover the case when the people trying to sit get to the edge of the pod. The buffer seats will be ommited because the stair will work as the buffer.
if avaliable_seats_row == amount_people_sitting:
# This run when the row is empty.
if pod[row][0] == 0:
self.sit_people_empty_row(pod, row, amount_people_sitting)
return pod
# This run where the row is not empty.
else:
self.sit_people_row(pod, row, occupied_seats, buffer_seats, amount_people_sitting)
return pod
# This will run when there are not enough seats in the row but the amount people that want to be seated is less or equal that the actual seats in the whole row.
elif avaliable_seats_row < amount_people_sitting and amount_people_sitting <= len(pod[0]):
# This will run when the pod is full. Meaning the group is to big for the avaliable seats.
if amount_people_sitting > avaliable_seats_pod:
print(f'The pod is full. This last group of {amount_people_sitting} can\'t be seated to big for the avaliable seats.')
return self.pod
# This code will run when there are no more row left to seat people. Is going to update that there is not enough space.
if (pod[row] == self.pod[-2]).all():
print('This group is to large for the amount of seats in any of the rows.')
print(f'There is still {avaliable_seats_pod} seats scatter through the pod but there is no {amount_people_sitting}\nseats side by side empty.')
return self.pod
# This pass will allow the program to jump for the next row and check for avaliable seats.
pass
# This will run if the people that want to be seatted is larger that actual row length.
elif amount_people_sitting > len(pod[0]):
print(f'The amount of people to be seatted is larger than the actual row.')
return pod
# This will run when less than the actual amount for the social distance buffer seats are needed.
else:
seats_left = self.get_avaliable_seats_row(pod[row])
# This statement will verify if the difference of the seat left and the people who want to sit is a positive number. The value that this difference will give back is the amount of buffer seats that are needed.
if (seats_left - amount_people_sitting) > 0:
# Seating people
self.sit_people_row(pod, row, occupied_seats, buffer_seats, amount_people_sitting)
# Updating the new ocuppied seats that have been set in the function from above.
occupied_seats += amount_people_sitting
# Calculating how many buffers are needed and then setting the seats as buffers.
buffer_seats_needed = seats_left - amount_people_sitting
self.set_buffer_seat(buffer_seats_needed, occupied_seats, buffer_seats, pod, row)
return pod
def sitting_people_from_terminal(self, amount_people_sitting, terminal):
"""This function will deside where to sit people on the pod. The amount of people is an integer and the pod needs to be an object type matrix. After seatting everyone it will set some buffer seats for social distance."""
# Finding the rows people can actually sit.
total_avaliable_rows = math.ceil(len(self.pod)/3)
actual_rows_people_sit = list()
for row in range(total_avaliable_rows):
actual_rows_people_sit.append(3*row)
# Finding the amount of rows and columns the pod have.
pod_num_column = len(self.pod[0])
# Creating a variable that is goint to be use to know how many sits the row have left to allow some desition making.
seats_left = pod_num_column
# There is a social distance recommended by the CDC of 6 feets, considering that each seat is 20x20 inches and each
# seat are side by side to satisfy this recommendation we need at least four seats in between the groups.
social_distance_buffer_seats = 4
# The reason why I went with this function is to have the ability of stopping all loops after sitting everyone. Break didn't work as intended and had to refactor the code.
response = self.sitting_logistic_from_terminal(amount_people_sitting, self.pod, actual_rows_people_sit, seats_left, social_distance_buffer_seats, terminal)
if response is None:
pass
else:
self.pod = response
def sitting_logistic_from_terminal(self, amount_people_sitting, pod, actual_rows_people_sit, seats_left, social_distance_buffer_seats, terminal):
"""This function is the one that is going to decide where to sit everyone."""
for row in actual_rows_people_sit: # This goes through all rows people can sit.
avaliable_seats_row = self.get_avaliable_seats_row(pod[row])
occupied_seats = self.get_occupied_seats_row(pod[row])
buffer_seats = self.get_buffer_seats_row(pod[row])
avaliable_seats_pod = self.get_seats_avaliable_pod()
# If avaliable seats are enough for the amount of people sitting and the buffer seats this will run.
if avaliable_seats_row >= (amount_people_sitting + social_distance_buffer_seats):
# This will run over each avaliable seat and change the value to represent is ocuppied '1' and to next amount of social_distance_buffer_seats as buffer seats '2'
if pod[row][0] == 0: # This will mean the row is empty
# Loop over as many times needed to sit everyone using the avaliable_seat value as an index.
self.sit_people_empty_row(pod, row, amount_people_sitting)
# Loop over as many times needed to satisfy the social distance buffer seats amount.
self.set_buffer_seat_empty_row(social_distance_buffer_seats, amount_people_sitting, pod, row)
# This run when the row is not empty
else:
# Loop over as many times needed to sit everyone using the avaliable_seat value as an index.
self.sit_people_row(pod, row, occupied_seats,buffer_seats, amount_people_sitting)
# Updating the new ocuppied seats that have been set in the function from above.
occupied_seats += amount_people_sitting
# Loop over as many times needed to satisfy the social distance buffer seats amount.
self.set_buffer_seat(social_distance_buffer_seats, occupied_seats, buffer_seats, pod,row)
return pod
# This will run when the avaliable sit are less than the people seatting plus the buffer seats.
else:
# This code cover the case when the people trying to sit get to the edge of the pod. The buffer seats will be ommited because the stair will work as the buffer.
if avaliable_seats_row == amount_people_sitting:
# This run when the row is empty.
if pod[row][0] == 0:
self.sit_people_empty_row(pod, row, amount_people_sitting)
return pod
# This run where the row is not empty.
else:
self.sit_people_row(pod, row, occupied_seats, buffer_seats, amount_people_sitting)
return pod
# This will run when there are not enough seats in the row but the amount people that want to be seated is less or equal that the actual seats in the whole row.
elif avaliable_seats_row < amount_people_sitting and amount_people_sitting <= len(pod[0]):
# This will run when the pod is full. Meaning the group is to big for the avaliable seats.
if amount_people_sitting > avaliable_seats_pod:
#print(f'The pod is full. This last group of {amount_people_sitting} can\'t be seated to big for the avaliable seats.')
terminal.jump_to_next_pod = True
return
# This code will run when there are no more row left to seat people. Is going to update that there is not enough space.
if (pod[row] == self.pod[-2]).all():
#print('This group is to large for the amount of seats in any of the rows.')
#print(f'There is still {avaliable_seats_pod} seats scatter through the pod but there is no {amount_people_sitting}\nseats side by side empty.')
terminal.jump_to_next_pod = True
return
# This pass will allow the program to jump for the next row and check for avaliable seats.
pass
# This will run if the people that want to be seatted is larger that actual row length.
elif amount_people_sitting > len(pod[0]):
#print(f'The amount of people to be seatted is larger than the actual row.')
return pod # PUEDES DEVOLVER QUE BRINQUE A LA PROXIMA SECCION terminal.jump_to_next_pod = True
# This will run when less than the actual amount for the social distance buffer seats are needed.
else:
seats_left = self.get_avaliable_seats_row(pod[row])
# This statement will verify if the difference of the seat left and the people who want to sit is a positive number. The value that this difference will give back is the amount of buffer seats that are needed.
if (seats_left - amount_people_sitting) > 0:
# Seating people
self.sit_people_row(pod, row, occupied_seats, buffer_seats, amount_people_sitting)
# Updating the new ocuppied seats that have been set in the function from above.
occupied_seats += amount_people_sitting
# Calculating how many buffers are needed and then setting the seats as buffers.
buffer_seats_needed = seats_left - amount_people_sitting
self.set_buffer_seat(buffer_seats_needed, occupied_seats, buffer_seats, pod, row)
return pod
def get_id(self):
"""This method will return the id number."""
return self.id
def set_buffer_seat_empty_row(self, num_buffer_seats, amount_people_sitting, pod, row):
"""This function will set buffer seats as meany times passed for an empty row."""
for i in range(num_buffer_seats):
# buffer_seat_index will start at the next seat after everyone is seated instead of starting at zero
buffer_seat_index = amount_people_sitting + i
pod[row][buffer_seat_index] = 2
def set_buffer_seat(self, num_buffer_seats, occupied_seats, buffer_seats, pod, row):
"""This function will set buffer seats as meany times passed for rows that are not empty."""
for i in range(num_buffer_seats):
# This seat_skip function like the one before. Is a jump to start on the next seat after the occupied and buffer seats.
seat_skip = occupied_seats + buffer_seats
buffer_seat_index = seat_skip + i
pod[row][buffer_seat_index] = 2
def sit_people_empty_row(self, pod, row, amount_people_sitting):
"""This function will sit people on an empty row."""
# Loop over as many times needed to sit everyone using the avaliable_seat value as an index.
for avaliable_seat in range(amount_people_sitting):
pod[row][avaliable_seat] = 1
return pod
def sit_people_row(self, pod, row, occupied_seats, buffer_seats, amount_people_sitting):
"""This function will sit people on the rows which are not already empty."""
for avaliable_seat in range(amount_people_sitting):
# This seat_skip is because we are not on an empty row so we have to account for the seats already taken and the ones that functions as buffers.
seat_skip = occupied_seats + buffer_seats
pod[row][seat_skip+avaliable_seat] = 1
def get_seats_avaliable_pod(self):
"""This function return the amount of seats left in the entire pod."""
# Finding the rows people can actually sit.
total_avaliable_rows = math.ceil(len(self.pod)/3)
actual_rows_people_sit = list()
for row in range(total_avaliable_rows):
actual_rows_people_sit.append(3*row)
# Looking inside each row where people can actually sit and see the amount of places people can sit..
avaliable_seats = 0
for row in actual_rows_people_sit:
for seat in self.pod[row]:
if seat == 0:
avaliable_seats += 1
return avaliable_seats
def get_seats_occupied_pod(self):
"""This function return the amount of seats occupied in the entire pod."""
# Finding the rows people can actually sit.
total_avaliable_rows = math.ceil(len(self.pod)/3)
actual_rows_people_sit = list()
for row in range(total_avaliable_rows):
actual_rows_people_sit.append(3*row)
# Looking inside each row where people can actually sit and see the amount of places people can sit..
occupied_seats = 0
for row in actual_rows_people_sit:
for seat in self.pod[row]:
if seat == 1: # People are seated there.
occupied_seats += 1
if seat == 2: # This are seats that are buffer seats.
occupied_seats += 1
return occupied_seats
def get_people_on_seats(self):
"""This method will return the amount of people seated in the pod."""
# Finding the rows people can actually sit.
total_avaliable_rows = math.ceil(len(self.pod)/3)
actual_rows_people_sit = list()
for row in range(total_avaliable_rows):
actual_rows_people_sit.append(3*row)
# Looking inside each row where people can actually sit and see the amount of places people can sit..
people_seated = 0
for row in actual_rows_people_sit:
for seat in self.pod[row]:
if seat == 1: # People are seated there.
people_seated += 1
return people_seated
def get_buffer_seats_pod(self):
"""This method will return the buffer seats in the entire pod but just the ones inside the rows people can sit."""
# Finding the rows people can actually sit.
total_avaliable_rows = math.ceil(len(self.pod)/3)
actual_rows_people_sit = list()
for row in range(total_avaliable_rows):
actual_rows_people_sit.append(3*row)
# Looking inside each row where people can actually sit and see the amount of places people can sit..
buffer_seats = 0
for row in actual_rows_people_sit:
for seat in self.pod[row]:
if seat == 2: # This are seats that are buffer seats.
buffer_seats += 1
return buffer_seats
def get_total_buffer_seats_pod(self):
"""This method will return the value of buffer seats includding the rows that are mark as buffers."""
# Looking inside each row where people can actually sit and see the amount of places people can sit..
buffer_seats = 0
for row in range(len(self.pod)):
for seat in self.pod[row]:
if seat == 2: # This are seats that are buffer seats.
buffer_seats += 1
return buffer_seats
def get_total_seat_capacity_pod(self):
"""This method will return the amount of seats in the pod. Independently if they are occupied."""
# Looking inside each row where people can actually sit and see the amount of places people can sit..
seat_capacity = 0
for row in range(len(self.pod)):
for seat in self.pod[row]:
if seat == 0: # This are seats that are empty seats.
seat_capacity += 1
if seat == 1: # This are seats that are taken seats.
seat_capacity += 1
if seat == 2: # This are seats that are buffer seats.
seat_capacity += 1
return seat_capacity
def get_avaliable_seats_row(self, row):
"""This function will return the amount of avaliable seats in the row. The paramater is a row from the pod."""
avaliable_seats = 0
for seat in row:
# This will add up; every avaliable seat, occupied seat and buffer seat.
if seat == 0:
avaliable_seats += 1
return avaliable_seats
def get_occupied_seats_row(self, row):
"""This function will return the amount of occupied seats in the row. The paramater is a row from the pod."""
occupied_seats = 0
for seat in row:
# This will add up; every avaliable seat, occupied seat and buffer seat.
if seat == 1:
occupied_seats += 1
return occupied_seats
def get_buffer_seats_row(self, row):
"""This function will return the amount of buffer seats in the row. The paramater is a row from the pod."""
buffer_seats = 0
for seat in row:
# This will add up; every avaliable seat, occupied seat and buffer seat.
if seat == 2:
buffer_seats += 1
return buffer_seats
if __name__ == '__main__':
pass
# test = numpy.zeros(shape=(10, 10), dtype=int)
# print(test)
# print("\t\t\t\t\t" + str(test).replace('\n','\n\t\t\t\t\t'))
# grand_stand_pod_left = Pod(17,15)
# grand_stand_pod_left.sitting_people(5)
# grand_stand_pod_left.show_pod()
# # print()
# people = list()
# for i in range(20):
# people.append(i)
# people.append(5)
# for i in people:
# print()
# print(i)
# print()
# # print('before')
# # print(grand_stand_pod_left.pod)
# print(grand_stand_pod_left.sitting_people(i))
# # print('after')
# # print(grand_stand_pod_left.pod)
# print(len(grand_stand_pod_left.pod))
# print(grand_stand_pod_left.pod[16])
# print(grand_stand_pod_left.pod[-1])
# x = numpy.array([[10, 5], [10, 6]])
# print((x[-1] == x[0]).all())
# grand_stand_pod_left.show_pod()<file_sep>from abc import ABC
from Pods import Pod
from helper_module import print_newline
class Stand(ABC):
def __init__(self, name, row, column, num_pods):
self.name = name
self.row = row # All the rows that it has with counting different pods
self.column = column # All the columns
self.num_pods = num_pods # Quantity of pods wanted for the stand.
self.pod_rows = row
self.pod_columns = int(self.column / self.num_pods)
self.pods = list() # A list of all pods inside the stand
def create_pod(self):
"""This method will create and store pods inside the stand list."""
pod = Pod(self.pod_rows, self.pod_columns)
self.add_pod_to_stand(pod)
return pod
def get_pods(self):
"""This method will return a list of the pods for this stand."""
return self.pods
def show_pods(self):
"""This method will show all pods in the pods list."""
for i in self.pods:
i.show_pod()
print_newline()
def get_name(self):
"""This method will return the name."""
return self.name
def set_name(self, name):
"""This method will let you change the name."""
self.name = name
def get_row(self):
"""This method will return the row number."""
return self.row
def set_row(self, row):
"""This method will let you change the row number"""
self.row = row
def get_column(self):
"""This method will return the column number."""
return self.column
def set_column(self, column):
"""This method will let you change the column number"""
self.row = column
def get_num_pods(self):
"""This method will return the number of pods in this specific stand."""
return self.num_pods
def set_num_pods(self, num_pods):
"""This method will let you change the number of pods in this specific stand."""
self.num_pods = num_pods
def add_pod_to_stand(self, pod):
"""This method will add a pod to the stand list that contain all the pods objects."""
self.pods.append(pod)
def remove_pod_from_stand(self, pod_id):
"""This method will remove pod from stand list that contain all the pods objects. The parameter should be the pods id."""
found_pod = False
# Loop through each pod in our pods list.
for i in self.pods:
# If we find them, remove them from the list.
if i.id == pod_id:
self.pods.remove(i)
# set our indicator to True
found_pod = True
# If we looped through our list and did not find our pod, the indicator would never get change, so return 'Pod not found!'
if not found_pod:
print(f'Pod not found!')
if __name__ == "__main__":
pass<file_sep>from Stand import Stand
class BoxStand(Stand):
def __init__(self, name, row, column, num_pods):
super().__init__(name, row, column, num_pods)
self.stand_category = 'Box Stand'
if __name__ == "__main__":
pass<file_sep>from Stand import Stand
class TelescopicStand(Stand):
def __init__(self, name, row, column, num_pods):
super().__init__(name, row, column, num_pods)
self.stand_category = 'Telescopic Stand'
if __name__ == "__main__":
pass<file_sep># Assigning Seats COVID
## Table of Content
* [Introduction](#Introduction)
* [Motivation](#Motivation)
* [Implementation](#Implementation)
* [Assumed measurements](#Assume-measurements)
* [Classes](#Classes)
* [Illustrations](#Illustrations)
* [Coliseum](#Coliseum)
* [Stands](#Stands)
* [Technologies](#Technologies)
* [Project Status](#Project-Status)
## Introduction
The objective of this project is to automate the decision making of sitting people on a coliseum. The catch is that people need to be seated 6 feet apart, as recommended by the World Health Organization (WHO) and the Center of Disease Control and Prevention (CDC). In the case there is a group of people that want to be seated they all are going to be seated together and the next group or person is going to be 6 feet apart.
## Motivation
The motivation came from two places:
* This project was my last assignment of the CS 1.1 - Object Oriented Programming (OOP) class. I had the liberty of choosing anything to work on but I needed to implement an OOP design.
* Little before starting CS 1.1 I was talking with a friend and this idea came of sitting people on a coliseum with 6 feet apart of each other. He don't have the knowledge to program the solution and I just didn't had enough time. Then this opportunity where I can test my skills and also do something meaningful came. So, I took the challenge!
## Implementation
I'm sure there are countless ways to approach this problem, but I went with an Object Oriented Program (OOP) design. There are several classes, that are going to be explain briefly further down, which manipulate different pieces of the program.
To approach the problem I decided that there are going to be what I called buffer rows. This buffer rows just represent individual rows that are not going to be occupied because a distance of 6 feet will be needed. In this project I assume some measurements, shown further down, to complete the project.
From this measurements we can conclude that the buffers rows that are going to be needed are 3. Also, we can conclude that 4 seats are going to be needed to separate one person or group from another in the same row.
### Assumed measurements:
* Seats:
* 20x20 inches
* Legroom:
* 20 inches
### Classes:
* Terminal
* Manage everything from sitting the people to creating a coliseum, stands or pods. It has also features like getting reports of the entire coliseum.
* Coliseum
* A Coliseum will have instances of other classes, classes that will represent stands. This is better know as composition.
* Stand
* The Stand is an abstract class. An abstract class can't be instantiated. A programmer can only create other classes that inherit from an abstract class and those classes can be instantiate. This class is to honor the DRY principle (Don't Repeat Yourself).
* Classes that inherit from Stand:
* BoxStand
* GrandStand
* TelescopicStand
* Pods
* Pods are the name that I choose to give to the group of seats. The way I choose to represent each seat was as matrixes but there is a drawback when the stands in a coliseum are not rectangular or squares. A drawback that I need a solution but for now the code is good enough, just for now.
## Illustrations
### Coliseum
Using this coliseum I model the program and found problems and solutions. As I said before, there are some problems I have to find solutions but as of right now the program can create a coliseum, stands and sit people but the stands have to have a rectangular shape.
<img width="757" alt="Coliseum - Seats Configuration" src="https://user-images.githubusercontent.com/69913812/102847466-50269680-440a-11eb-8712-f9e1aac165b9.png">
### Stands
After creating stands and pods like "Pod #1", in the image below. The program will set some rows as Buffer Rows as seen in "Pod #2". After all this depending on the amount of people that want to be seated together, as a group. The program will seat them and seat the next group with 6 feet apart as seen in "Pod #1".

## Technologies
* Python 3.8
## Project Status
The project right now is on standby, but I do planned to keep innovating it.
Add more features like storing the coliseum, report to the person using the terminal the actual seats used to seat the person or group and work with the "irregular" stands, the ones that are not rectangular or square's shape.<file_sep>from random import randint
def generate_id():
"""Helper function that return a eight digit random number which is going to be of type string."""
id_number = ""
for _ in range(3):
id_number += str(randint(0,9))
return id_number
def print_newline():
"""Helper function that just add a new empty line."""
print("")<file_sep>from Coliseum import Coliseum
from Stand import Stand
from GrandStand import GrandStand
from BoxStand import BoxStand
from TelescopicStand import TelescopicStand
from Pods import Pod
from helper_module import print_newline
class Terminal():
def __init__(self, name):
self.name = name
self.jump_to_next_pod = False
def create_coliseum(self):
"""This method will create a new coliseum and return it. Name must be a string."""
name = input('Whats the name for the Coliseum?\n- ')
return Coliseum(name)
def show_coliseum_report(self, coliseum):
"""This method will print and extensive report of the coliseum."""
quantity_stands = 0
quantity_pods = 0
quantitiy_avaliable_seats_people_can_sit_coliseum = 0
quantity_seats_occupied_coliseum = 0
quantity_people_seated_coliseum = 0
quantity_buffer_seats_for_rows_people_sit = 0
full_seat_coliseum_capacity = 0 # This is the seat capacity for the rows people can actually seat of the whole coliseum. Independently if they are occupied or not.
buffer_seats_coliseum = 0
for stand in coliseum.stands:
quantity_stands += 1
for pod in stand.pods:
quantity_pods += 1
quantitiy_avaliable_seats_people_can_sit_coliseum += pod.get_seats_avaliable_pod()
quantity_seats_occupied_coliseum += pod.get_seats_occupied_pod()
quantity_people_seated_coliseum += pod.get_people_on_seats()
quantity_buffer_seats_for_rows_people_sit += pod.get_buffer_seats_pod()
full_seat_coliseum_capacity += pod.get_total_seat_capacity_pod()
buffer_seats_coliseum += pod.get_total_buffer_seats_pod()
print(f'The {coliseum.name} have:\n')
print(f'\tSTANDS:')
print(f'\t\tQuantity of Stands:\t\t\t\t\t{quantity_stands}\n')
print(f'\tPODS:')
print(f'\t\tQuantity of Pods:\t\t\t\t\t{quantity_pods}')
print(f'\tSEATS:')
print(f'\t\tColiseum Capacity (Including Buffer Rows):\t\t{full_seat_coliseum_capacity}')
print(f'\t\tBuffer Seats (Including Buffer Rows):\t\t\t{buffer_seats_coliseum}')
print(f'\t\tAvaliable Seats:\t\t\t\t\t{quantitiy_avaliable_seats_people_can_sit_coliseum}')
print(f'\t\tPeople Seated:\t\t\t\t\t\t{quantity_people_seated_coliseum}')
print(f'\t\tBuffer Seats (Excluding Buffer Rows):\t\t\t{quantity_buffer_seats_for_rows_people_sit}')
print(f'\t\tOccupied Seats:\t\t\t\t\t\t{quantity_seats_occupied_coliseum}')
def show_coliseum_layout(self, coliseum):
"""This method will display a more readable layout of the coliseum"""
quantity_stands = 0
quantitiy_avaliable_seats_people_can_sit_coliseum = 0
quantity_seats_occupied_coliseum = 0
quantity_people_seated_coliseum = 0
quantity_buffer_seats_for_rows_people_sit = 0 # Buffer Seats (Excluding Buffer Rows)
buffer_seats_coliseum = 0
# Collecting Information
for stand in coliseum.stands:
quantity_stands += 1
for pod in stand.pods:
quantitiy_avaliable_seats_people_can_sit_coliseum += pod.get_seats_avaliable_pod()
quantity_seats_occupied_coliseum += pod.get_seats_occupied_pod()
quantity_people_seated_coliseum += pod.get_people_on_seats()
quantity_buffer_seats_for_rows_people_sit += pod.get_buffer_seats_pod()
buffer_seats_coliseum += pod.get_total_buffer_seats_pod()
# Displaying Information
print(f'Coliseum: {coliseum.name}')
print(f'\tStands: {quantity_stands}')
for stand in coliseum.stands:
print(f'\t\tCategory: {stand.stand_category}')
print(f'\t\t\tName: {stand.name}')
for pod in stand.pods:
print(f'\t\t\t\tPod Id: {pod.get_id()}')
print("\t\t\t\t\t" + str(pod.pod).replace('\n','\n\t\t\t\t\t'))
def seatting_people(self, coliseum, amount_people_sitting):
"""This method will sit people inside the coliseum."""
for stand in coliseum.stands:
for pod in stand.pods:
self.jump_to_next_pod = False
# Here we are passing the terminal object to manipulate the attribute jump_to_next_pod from inside the method of the Pod type object.
pod.sitting_people_from_terminal(amount_people_sitting, self)
# In the case the pod was full this value was going to be changed inside sitting_people_from_terminal() and allow the program to move to the next pod.
if self.jump_to_next_pod == True:
pass
else:
if amount_people_sitting > 1:
print(f'The group of {amount_people_sitting} is seated.')
elif amount_people_sitting == 1:
print(f'The person was seated.')
print_newline()
return
print(f'Is not possible to sit {amount_people_sitting} in the entire coliseum!')
def create_grand_stand(self):
"""This method will prompt user to create a GrandStand object and return it."""
name = input('Whats the name for the GrandStand?\n- ')
row = int(input('How many rows the entire stand will have?\n- '))
column = int(input('How many columns the entire stand will have?\n- '))
num_pods = int(input('How many pods you want?\n- '))
return GrandStand(name, row, column, num_pods)
def create_box_stand(self):
"""This method will promt user to create a BoxStand object and return it."""
name = input('Whats the name for the BoxStand?\n- ')
row = int(input('How many rows the entire stand will have?\n- '))
column = int(input('How many columns the entire stand will have?\n- '))
num_pods = int(input('How many pods you want?\n- '))
return BoxStand(name, row, column, num_pods)
def create_telescopic_stand(self):
"""This method will promt user to create a TelescopicStand object and return it."""
name = input('Whats the name for the TelescopicStand?\n- ')
row = int(input('How many rows the entire stand will have?\n- '))
column = int(input('How many columns the entire stand will have?\n- '))
num_pods = int(input('How many pods you want?\n- '))
return TelescopicStand(name, row, column, num_pods)
def create_pod(self, row, column):
"""This method will create a new pod and return it."""
# row = int(input('How many rows the Pod will have?\n- '))
row = row
# column = int(input('How many column the Pod will have?\n- '))
column = column
return Pod(row, column)
def built_coliseum(self):
"""This method will prompt to built an entire coliseum and return it."""
print(f'Lets built the Coliseum...')
coliseum = self.create_coliseum()
print(f'So, now...')
amount = int(input((f'How many GrandStand you want?\n- ')))
for _ in range(amount):
# Creating and appending the grand stand to the coliseum.
grand_stand = self.create_grand_stand()
coliseum.add_stand_to_coliseum(grand_stand)
# Creating and appending the pods to the grand stand.
amount = grand_stand.num_pods
for _ in range(amount):
pod = self.create_pod(grand_stand.pod_rows, grand_stand.pod_columns)
grand_stand.add_pod_to_stand(pod)
amount = int(input((f'How many BoxStand you want?\n- ')))
for _ in range(amount):
# Creating and appending the box stand to the coliseum.
box_stand = self.create_box_stand()
coliseum.add_stand_to_coliseum(box_stand)
# Creating and appending the pods to the box stand.
amount = box_stand.num_pods
for _ in range(amount):
pod = self.create_pod(box_stand.pod_rows, box_stand.pod_columns)
box_stand.add_pod_to_stand(pod)
amount = int(input((f'How many TelescopicStand you want?\n- ')))
for _ in range(amount):
# Creating and appending the telescopic stand to the ccoliseum.
telescopic_stand = self.create_telescopic_stand()
coliseum.add_stand_to_coliseum(telescopic_stand)
# Creating and appending the pods to the telescopic stand.
amount = telescopic_stand.num_pods
for _ in range(amount):
pod = self.create_pod(telescopic_stand.pod_rows, telescopic_stand.pod_columns)
telescopic_stand.add_pod_to_stand(pod)
return coliseum
if __name__ == "__main__":
# Creating a terminal.
terminal_001 = Terminal('Terminnal 001')
# Creating a coliseum.
humacao_arena = terminal_001.built_coliseum()
print(f'The coliseum has been created. Now you can start sitting people.\n\n\n')
# Loop that only stop when user wants to quit.
quit_terminal = False
while quit_terminal == False:
user_response = int(input(f'[1]\tFull Report\t\t[2]\tColiseum Layout\t\t[3]\tSeating People\t\t[9]\tQuit Terminal\n- '))
# Show Full Report
if user_response == 1:
terminal_001.show_coliseum_report(humacao_arena)
# Show Coliseum Layout
elif user_response == 2:
terminal_001.show_coliseum_layout(humacao_arena)
# Seating People
elif user_response == 3:
amount_people_sitting = int(input(f'Whats the amount of people you want to sit?\n- '))
terminal_001.seatting_people(humacao_arena, amount_people_sitting)
# This will run when user wants to quit program.
elif user_response == 9:
quit_terminal = True
# More space, more readable.
print('\n\n\n')<file_sep>from Stand import Stand
from Pods import Pod
class GrandStand(Stand):
def __init__(self, name, row, column, num_pods):
super().__init__(name, row, column, num_pods)
self.stand_category = 'Grand Stand'
if __name__ == "__main__":
lateral_grand_stand_west = GrandStand('Lateral Grand Stand - West', 42, 17, 3)
print(lateral_grand_stand_west.get_name())
lateral_grand_stand_west_pod_1 = Pod(lateral_grand_stand_west.pod_rows,lateral_grand_stand_west.pod_columns)
lateral_grand_stand_west_pod_2 = Pod(lateral_grand_stand_west.pod_rows,lateral_grand_stand_west.pod_columns)
lateral_grand_stand_west_pod_3 = Pod(lateral_grand_stand_west.pod_rows,lateral_grand_stand_west.pod_columns)
lateral_grand_stand_west.add_pod_to_stand(lateral_grand_stand_west_pod_1)
lateral_grand_stand_west.add_pod_to_stand(lateral_grand_stand_west_pod_2)
lateral_grand_stand_west.add_pod_to_stand(lateral_grand_stand_west_pod_3)
lateral_grand_stand_west.remove_pod_from_stand(lateral_grand_stand_west_pod_3.get_id())
for i in lateral_grand_stand_west.get_pods():
print(i.pod) | 58f6f31d4395f81fec35b0f95a681dc845943df8 | [
"Markdown",
"Python"
] | 9 | Python | sicaramacuya/Assigning-Seats-COVID | d7bd6c64e88f6506a05368c5b9ea6ca168847146 | 56a97a1cd1ead4ad328260f3ea8aa63dcbf18e67 | |
refs/heads/master | <file_sep>import Foundation
struct Repository {
public let name: String
public let stargazerCount: Int
public let forkCount: Int
public let url: URL
public let updatedAt: Date
}
<file_sep>import Foundation
struct User {
let id: String
let password: String
}
<file_sep>import Foundation
import UIKit
let total: Int = 7
var answer: Int = 0
//////////////問題///////////////////
// 型指定あり
let question1: CGFloat = 10
let question2: String = "test"
let question3: [UIViewController] = []
// 型指定なし
let question4 = 0.0
let question5 = true
// Optional
let question6: Int? = nil
let question7: Bool? = true
/////////////////////////////////////
AnswerCheck: do {
/*
TODO: Any.selfをquestionNの型に書き換えてください
e.g question1がIntの場合
Any.self → Int.self
*/
// Question1
if type(of: question1) == Any.self {
answer += 1
print("Question 1 is the correct answer")
}
// Question2
if type(of: question2) == Any.self {
answer += 1
print("Question 2 is the correct answer")
}
// Question3
if type(of: question3) == Any.self {
answer += 1
print("Question 3 is the correct answer")
}
// Question4
if type(of: question4) == Any.self {
answer += 1
print("Question 4 is the correct answer")
}
// Question5
if type(of: question5) == Any.self {
answer += 1
print("Question 5 is the correct answer")
}
// Question6
if type(of: question6) == Any.self {
answer += 1
print("Question 6 is the correct answer")
}
// Question7
if type(of: question7) == Any.self {
answer += 1
print("Question 7 is the correct answer")
}
}
print("\(total)問中\(answer)問正解")
if total == answer {
print("全問正解👏")
}
<file_sep>import UIKit
class Lesson5ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
sampleMethod()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
sampleMethod()
}
func set() {
sampleMethod()
}
// 右クリック→`Find call hierarchy`
func sampleMethod() {
}
}
<file_sep>import UIKit
class SearchView: UIView {}
<file_sep>import UIKit
class Lesson4ViewController: UIViewController {
var str = ""
override func viewDidLoad() {
super.viewDidLoad()
}
func sampleLesson4Method() {
}
/*
大量のコードがある想定
*/
func checkDefinition() {
str = "checkDefinition"
// call sampleMethod
// cmd + ctrl + click
sampleLesson4Method()
}
}
<file_sep>2018 Haloween Swimee hands-on project.
## Requirements
- Xcode10
- Swift4.2
## Question & Answer
If you are interested in answering lesson1 and lesson3, please check answer branch
- [Quesiton](https://github.com/funzin/2018_haloween_handson/tree/master)
- [Answer](https://github.com/funzin/2018_haloween_handson/tree/answer)
<file_sep>import UIKit
import PlaygroundSupport
let baseView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
ButtonConigure: do {
// コメントを外して挙動を確認して下さい
//button.backgroundColor = .blue
//button.layer.borderColor = UIColor.red.cgColor
//button.layer.borderWidth = 10
//button.layer.cornerRadius = 5
//button.setTitle("button", for: .normal)
}
BaseViewConfigure: do {
baseView.backgroundColor = .white
button.center = baseView.center
baseView.addSubview(button)
}
PlaygroundPage.current.liveView = baseView
| 396910f5207643d91bfcfe72048823c90b773fd2 | [
"Swift",
"Markdown"
] | 8 | Swift | funzin/2018_haloween_handson | 1a4420631d2bf8553e2d44135fa18f9989798515 | e5555b84876a2a93a93996c131294b5e75560664 | |
refs/heads/master | <repo_name>AgustinRamiroDiaz/LCC-CM1-TP-Final<file_sep>/layout_graph.py
#! /usr/bin/python
# 6ta Practica Laboratorio
# Complementos Matematicos I
# Ejemplo parseo argumentos
import matplotlib.pyplot as plt
import numpy as np
import time
import pprint
class LayoutGraph:
def __init__(self, grafo, refresh, temperaturaInicial, constanteTemperatura, gravedad, repultionConstant, attractionConstant, iters = 100, verbose = False):
"""Parametros de layout:
iters: cantidad de iteraciones a realizar
refresh: Numero de iteraciones entre actualizaciones de pantalla.
0 -> se grafica solo al final.
repultionConstant: constante usada para calcular la repulsion entre vértices
attractionConstant: constante usada para calcular la atraccion de aristas"""
# Guardo el grafo
self.grafo = grafo
self.vertices = self.grafo[0]
self.aristas = self.grafo[1]
# Inicializo estado
# Completar
self.posiciones = {}
self.fuerzas = {}
self.accumx = {}
self.accumy = {}
# Guardo opciones
self.iters = int(iters)
self.verbose = verbose
if (refresh != 0):
self.refresh = refresh
else:
self.refresh = self.iters
self.repultionConstant = repultionConstant
self.attractionConstant = attractionConstant
self.c = 3
self.frameSize = 100
self.area = self.frameSize ** 2
self.k = self.c * np.sqrt(self.area / len(self.vertices))
self.gravity = gravedad
self.temperaturaInicial = temperaturaInicial
self.temperatura = self.temperaturaInicial
self.constanteTemperatura = constanteTemperatura
self.deltaTime = 0.01
self.centro = [self.frameSize / 2, self.frameSize / 2]
pass
def layout(self):
"""
Aplica el algoritmo de Fruchtermann-Reingold para obtener (y mostrar)
un layout
"""
self.algoritmoFruchtermanReingold()
pass
def posicionesAleatorias(self):
for vertice in self.vertices:
self.posiciones[vertice] = np.array([np.random.random_sample() * self.frameSize, np.random.random_sample() * self.frameSize])
pass
def plotear(self):
plt.clf()
for ni, nj in self.aristas:
posicionOrigen = self.posiciones[ni]
posicionDestino = self.posiciones[nj]
absisaOrigen = posicionOrigen[0]
ordenadaOrigen = posicionOrigen[1]
absisaDestino = posicionDestino[0]
ordenadaDestino = posicionDestino[1]
plt.plot([absisaOrigen, absisaDestino], [ordenadaOrigen, ordenadaDestino])
plt.pause(self.deltaTime)
pass
def algoritmoFruchtermanReingold(self):
# Seteamos posiciones iniciales aleatorias
self.posicionesAleatorias()
self.initializeTemperature()
start_time = time.time()
for count in range(self.iters):
self.step(count)
self.plotear()
if self.verbose:
print("--- Tiempo de ejecucion: %s segundos ---" % (time.time() - start_time))
plt.show()
pass
def step(self, count):
self.initializeAccumulators()
self.computeAttractionForces()
self.computeRepulsionForces()
self.computeGravityForces()
self.updatePositions()
self.updateTemperature()
if count % self.refresh == 0:
self.plotear()
self.mostrarVerbosidad(count)
pass
def mostrarVerbosidad(self, count):
if self.verbose:
print("\n Iteracion: ", count)
print("Temperatura: ", self.temperatura)
print("Fuerza acumulada en x: ")
pprint.pp(self.accumx)
print("Fuerza acumulada en y: ")
pprint.pp(self.accumy)
def initializeTemperature(self):
self.temperatura = self.temperaturaInicial
pass
def initializeAccumulators(self):
for vertice in self.vertices:
self.accumx[vertice] = 0
self.accumy[vertice] = 0
pass
def computeAttractionForces(self):
for ni, nj in self.aristas:
distance = distanciaEuclidiana(self.posiciones[ni], self.posiciones[nj])
modfa = self.attraction(distance)
fx = modfa * (self.abcisa(nj) - self.abcisa(ni)) / distance
fy = modfa * (self.ordenada(nj) - self.ordenada(ni)) / distance
self.accumx[ni] += fx
self.accumx[nj] -= fx
self.accumy[ni] += fy
self.accumy[nj] -= fy
pass
def computeRepulsionForces(self):
for ni in self.vertices:
for nj in self.vertices:
if ni != nj:
distance = distanciaEuclidiana(self.posiciones[ni], self.posiciones[nj])
modfa = self.repultion(distance)
fx = modfa * (self.abcisa(nj) - self.abcisa(ni)) / distance
fy = modfa * (self.ordenada(nj) - self.ordenada(ni)) / distance
self.accumx[ni] -= fx
self.accumx[nj] += fx
self.accumy[ni] -= fy
self.accumy[nj] += fy
pass
def computeGravityForces(self):
for ni in self.vertices:
distance = distanciaEuclidiana(self.posiciones[ni], self.centro)
modfa = self.gravity
fx = modfa * (self.centro[0] - self.abcisa(ni)) / distance
fy = modfa * (self.centro[1] - self.ordenada(ni)) / distance
self.accumx[ni] -= fx
self.accumy[ni] -= fy
def updatePositions(self):
for node in self.vertices:
f = np.array([self.accumx[node], self.accumy[node]])
if modulo(f) > self.temperatura:
f = productoPorEscalar(self.temperatura / modulo(f), f)
self.accumx[node] = f[0]
self.accumy[node] = f[1]
self.posiciones[node][0] += self.accumx[node]
self.posiciones[node][1] += self.accumy[node]
pass
def updateTemperature(self):
self.temperatura = self.temperatura * self.constanteTemperatura
pass
def ordenada(self, v):
return self.posiciones[v][1]
def repultion(self, distance):
return self.k ** 2 / distance * self.repultionConstant
def attraction(self, distance):
return distance ** 2 / self.k * self.attractionConstant
def abcisa(self, v):
return self.posiciones[v][0]
def distanciaEuclidiana(ni, nj):
return np.linalg.norm(ni - nj)
def modulo(vector):
return distanciaEuclidiana(vector, (0, 0))
def productoPorEscalar(escalar, vector):
return escalar * vector
if __name__ == "__main__":
for a, b, c in np.random.random((100, 3, 2)):
BA = distanciaEuclidiana(b, a)
AB = distanciaEuclidiana(a, b)
BC = distanciaEuclidiana(b, c)
AC = distanciaEuclidiana(a, c)
assert(AB == BA)
assert(AB >= 0)
assert(AB + BC >= AC)<file_sep>/main.py
import argparse
from layout_graph import LayoutGraph
def leeGrafoArchivo(file_path):
archivo = open(file_path)
lista = archivo.readlines()
cantidadDeVertices = int(lista.pop(0))
listaVertices = []
for x in range(cantidadDeVertices):
listaVertices.append(lista[x].rstrip("\n"))
ARITAS = lista[cantidadDeVertices:]
aristas = []
for par in ARITAS:
aristas.append((par.split()[0], par.split()[1]))
return listaVertices, aristas
def main():
# Definimos los argumentos de linea de comando que aceptamos
parser = argparse.ArgumentParser()
# Verbosidad, opcional, False por defecto
parser.add_argument(
'-v', '--verbose',
action = 'store_true',
help = 'Muestra mas informacion al correr el programa'
)
# Archivo del cual leer el grafo
parser.add_argument(
'file_name',
help = "Archivo del cual leer el grafo a dibujar"
)
# Cantidad de iteraciones
parser.add_argument(
'iters',
type = int,
help = "Cantidad de iteraciones del algoritmo"
)
# Temperatura inicial
parser.add_argument(
'--temp',
type = float,
help = 'Temperatura inicial',
default = 1000.0
)
# Cantidad de iteraciones entre actualizaciones de pantalla
parser.add_argument(
'--refresh',
type = int,
help = 'Cantidad de iteraciones entre actualizaciones de pantalla',
default = 1
)
# Constante temperatura
parser.add_argument(
'--ctemp',
type = float,
help = 'Constante con la cual baja la temperatura cada step',
default = 0.95
)
parser.add_argument(
'--crepul',
type = float,
help = 'constante usada para calcular la repulsion entre vértices',
default = 20
)
parser.add_argument(
'--catrac',
type = float,
help = 'constante usada para calcular la atraccion de aristas',
default = 3
)
parser.add_argument(
'--cgrav',
type = float,
help = 'constante usada para calcular la fuerza de gravedad',
default = 0.1
)
args = parser.parse_args()
# Creamos nuestro objeto LayoutGraph
layout_gr = LayoutGraph(
leeGrafoArchivo(args.file_name),
iters = args.iters,
refresh = args.refresh,
temperaturaInicial = args.temp,
constanteTemperatura = args.ctemp,
gravedad = args.cgrav,
repultionConstant = args.crepul,
attractionConstant = args.catrac,
verbose = args.verbose
)
# Ejecutamos el layout
layout_gr.layout()
return
if __name__ == '__main__':
main()
| 0ff1ea50b7eeb5c603655242aecaf8b867b5d89d | [
"Python"
] | 2 | Python | AgustinRamiroDiaz/LCC-CM1-TP-Final | c8442019baf7c662f574033375b7489d9bcaff2b | bb5bb295ff6d3f877e548b1485e350874417913e | |
refs/heads/master | <repo_name>Packetfahrer/libcephei<file_sep>/prefs/Makefile
include $(THEOS)/makefiles/common.mk
FRAMEWORK_NAME = CepheiPrefs
CepheiPrefs_FILES = $(wildcard *.x) $(wildcard *.m) ../Global.x
CepheiPrefs_PUBLIC_HEADERS = HBAboutListController.h HBAppearanceSettings.h HBDiscreteSliderTableCell.h HBImageTableCell.h HBInitialsLinkTableCell.h HBLinkTableCell.h HBListController.h HBListController+Actions.h HBListItemsController.h HBPackageTableCell.h HBPackageNameHeaderCell.h HBRootListController.h HBSpinnerTableCell.h HBStepperTableCell.h HBSupportController.h HBTintedTableCell.h HBTwitterCell.h PSListController+HBTintAdditions.h
CepheiPrefs_FRAMEWORKS = CoreGraphics MessageUI UIKit
CepheiPrefs_PRIVATE_FRAMEWORKS = Preferences
CepheiPrefs_EXTRA_FRAMEWORKS = Cephei
CepheiPrefs_WEAK_FRAMEWORKS = SafariServices
CepheiPrefs_LIBRARIES = prefs
CepheiPrefs_CFLAGS = -include ../Global.h -fobjc-arc
CepheiPrefs_LDFLAGS = -weak_framework TechSupport
ifeq ($(CEPHEI_EMBEDDED),1)
CepheiPrefs_INSTALL_PATH = @rpath
CepheiPrefs_LOGOSFLAGS = -c generator=internal
else
CepheiPrefs_EXTRA_FRAMEWORKS += CydiaSubstrate
endif
include $(THEOS_MAKE_PATH)/bundle.mk
include $(THEOS_MAKE_PATH)/framework.mk
after-CepheiPrefs-stage::
ifneq ($(CEPHEI_EMBEDDED),1)
@# create directories
$(ECHO_NOTHING)mkdir -p $(THEOS_STAGING_DIR)/usr/{include,lib} $(THEOS_STAGING_DIR)/Library/PreferenceBundles$(ECHO_END)
@# libhbangprefs.dylib -> CepheiPrefs.framework
$(ECHO_NOTHING)ln -s /Library/Frameworks/CepheiPrefs.framework/CepheiPrefs $(THEOS_STAGING_DIR)/usr/lib/libhbangprefs.dylib$(ECHO_END)
@# libcepheiprefs.dylib -> CepheiPrefs.framework
$(ECHO_NOTHING)ln -s /Library/Frameworks/CepheiPrefs.framework/CepheiPrefs $(THEOS_STAGING_DIR)/usr/lib/libcepheiprefs.dylib$(ECHO_END)
@# libhbangprefs.bundle -> Cephei.bundle
$(ECHO_NOTHING)ln -s Cephei.bundle $(THEOS_STAGING_DIR)/Library/PreferenceBundles/libhbangprefs.bundle$(ECHO_END)
@# Cephei.bundle -> CepheiPrefs.framework
$(ECHO_NOTHING)ln -s /Library/Frameworks/CepheiPrefs.framework $(THEOS_STAGING_DIR)/Library/PreferenceBundles/Cephei.bundle$(ECHO_END)
ifeq ($(PACKAGE_BUILDNAME),debug)
@# install demo entry plist
$(ECHO_NOTHING)mkdir -p $(THEOS_STAGING_DIR)/Library/PreferenceLoader/Preferences$(ECHO_END)
$(ECHO_NOTHING)ln -s /Library/PreferenceBundles/Cephei.bundle/entry.plist $(THEOS_STAGING_DIR)/Library/PreferenceLoader/Preferences/Cephei.plist$(ECHO_END)
endif
endif
<file_sep>/docs.mk
# ugly hack so we get Cephei{,Prefs}_PUBLIC_HEADERS :/
include Makefile
include prefs/Makefile
APPLEDOCFILES = $(Cephei_PUBLIC_HEADERS) $(foreach header,$(CepheiPrefs_PUBLIC_HEADERS),prefs/$(header))
DOCS_STAGING_DIR = _docs
DOCS_OUTPUT_PATH = docs
all:: docs
docs:
# eventually, this should probably be in theos.
# for now, this is good enough :p
[[ -d "$(DOCS_STAGING_DIR)" ]] && rm -r "$(DOCS_STAGING_DIR)" || true
-appledoc --project-name Cephei --project-company "HASHBANG Productions" --company-id ws.hbang --project-version 1.2 --no-install-docset \
--keep-intermediate-files --create-html --publish-docset --docset-feed-url "https://hbang.github.io/libcephei/xcode-docset.atom" \
--docset-atom-filename xcode-docset.atom --docset-package-url "https://hbang.github.io/libcephei/docset.xar" \
--docset-package-filename docset --docset-fallback-url "https://hbang.github.io/libcephei/" --docset-feed-name Cephei \
--index-desc README.md --no-repeat-first-par --include info \
--output "$(DOCS_STAGING_DIR)" $(APPLEDOCFILES)
[[ -d "$(DOCS_OUTPUT_PATH)" ]] || git clone -b gh-pages [email protected]:hbang/libcephei.git "$(DOCS_OUTPUT_PATH)"
rsync -ra "$(DOCS_STAGING_DIR)"/{html,publish}/ "$(DOCS_OUTPUT_PATH)"
rm -r "$(DOCS_STAGING_DIR)"
.PHONY: docs
<file_sep>/Makefile
export TARGET = iphone:clang:latest:5.0
export ADDITIONAL_CFLAGS = -Wextra -Wno-unused-parameter
export CEPHEI_EMBEDDED
INSTALL_TARGET_PROCESSES = Preferences
ifeq ($(RESPRING),1)
INSTALL_TARGET_PROCESSES += SpringBoard
endif
include $(THEOS)/makefiles/common.mk
FRAMEWORK_NAME = Cephei
Cephei_FILES = $(wildcard *.m) $(wildcard *.x) $(wildcard CompactConstraint/*.m)
Cephei_PUBLIC_HEADERS = HBOutputForShellCommand.h HBPreferences.h HBRespringController.h NSDictionary+HBAdditions.h NSString+HBAdditions.h UIColor+HBAdditions.h $(wildcard CompactConstraint/*.h)
Cephei_FRAMEWORKS = CoreGraphics UIKit
Cephei_WEAK_PRIVATE_FRAMEWORKS = FrontBoardServices SpringBoardServices
Cephei_CFLAGS = -include Global.h -fobjc-arc
# link arclite to polyfill some features iOS 5 lacks
armv7_LDFLAGS = -fobjc-arc
SUBPROJECTS = prefs
ifeq ($(CEPHEI_EMBEDDED),1)
PACKAGE_BUILDNAME += embedded
ADDITIONAL_CFLAGS += -DCEPHEI_EMBEDDED=1
Cephei_INSTALL_PATH = @rpath
Cephei_LOGOSFLAGS = -c generator=internal
else
ADDITIONAL_CFLAGS += -DCEPHEI_EMBEDDED=0
Cephei_LIBRARIES += rocketbootstrap
Cephei_EXTRA_FRAMEWORKS += CydiaSubstrate
SUBPROJECTS += defaults containersupport
endif
include $(THEOS_MAKE_PATH)/framework.mk
include $(THEOS_MAKE_PATH)/aggregate.mk
after-Cephei-stage::
ifneq ($(CEPHEI_EMBEDDED),1)
@# create directories
$(ECHO_NOTHING)mkdir -p $(THEOS_STAGING_DIR)/usr/{include,lib} $(THEOS_STAGING_DIR)/DEBIAN $(THEOS_STAGING_DIR)/Library/MobileSubstrate/DynamicLibraries$(ECHO_END)
@# libhbangcommon.dylib -> Cephei.framework
$(ECHO_NOTHING)ln -s /Library/Frameworks/Cephei.framework/Cephei $(THEOS_STAGING_DIR)/usr/lib/libhbangcommon.dylib$(ECHO_END)
@# libcephei.dylib -> Cephei.framework
$(ECHO_NOTHING)ln -s /Library/Frameworks/Cephei.framework/Cephei $(THEOS_STAGING_DIR)/usr/lib/libcephei.dylib$(ECHO_END)
@# postinst -> DEBIAN/post{inst,rm}
$(ECHO_NOTHING)cp postinst postrm $(THEOS_STAGING_DIR)/DEBIAN$(ECHO_END)
@# TODO: this is kind of a bad idea. maybe it should be in its own daemon?
@# CepheiSpringBoard.dylib -> Cephei.framework
$(ECHO_NOTHING)ln -s /Library/Frameworks/Cephei.framework/Cephei $(THEOS_STAGING_DIR)/Library/MobileSubstrate/DynamicLibraries/CepheiSpringBoard.dylib$(ECHO_END)
@# copy CepheiSpringBoard.plist
$(ECHO_NOTHING)cp CepheiSpringBoard.plist $(THEOS_STAGING_DIR)/Library/MobileSubstrate/DynamicLibraries$(ECHO_END)
endif
after-install::
ifneq ($(RESPRING)$(PACKAGE_BUILDNAME),1)
install.exec "uiopen 'prefs:root=Cephei%20Demo'"
endif
<file_sep>/postinst
#!/bin/bash
# restart installd so container support is (re)loaded
launchctl stop com.apple.mobile.installd
# due to some sort of unfortunate permission error created by an older build of cephei, and dpkg not
# really fixing them, we need to fix this ourselves
chown -R root:wheel /Library/Frameworks/Cephei.framework \
/Library/Frameworks/CepheiPrefs.framework \
/Library/PreferenceBundles/Cephei.bundle
# and this somehow became a directory instead of a symlink
if [[ -d /Library/PreferenceBundles/Cephei.bundle ]]; then
rm -r /Library/PreferenceBundles/Cephei.bundle
ln -s /Library/Frameworks/CepheiPrefs.framework /Library/PreferenceBundles/Cephei.bundle
fi
| 9e404fd34f42c8a861abbe90c1dea69bdcde6a13 | [
"Makefile",
"Shell"
] | 4 | Makefile | Packetfahrer/libcephei | 32aa5bb0500db562e081685886be15f25a4a4d66 | 35380979564e0bfcbd4af08c914e6731b28f2db1 | |
refs/heads/master | <file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2017-03-12 12:51
# @Author : <NAME>
# @File : anti_withdraw.py
import os
import re
import shutil
import time
import itchat
from itchat.content import *
import traceback
# {msg_id:(msg_from,msg_to,msg_time,msg_time_touser,msg_type,msg_content,msg_url)}
msg_dict = {}
#ClearTimeOutMsg用于清理消息字典,把超时消息清理掉
#为减少资源占用,此函数只在有新消息动态时调用
def ClearTimeOutMsg():
if msg_dict.__len__() > 0:
for msgid in list(msg_dict): #由于字典在遍历过程中不能删除元素,故使用此方法
if time.time() - msg_dict.get(msgid, None)["msg_time"] > 130.0: #超时两分钟
item = msg_dict.pop(msgid)
#print("超时的消息:", item['msg_content'])
#可下载类消息,并删除相关文件
if item['msg_type'] == "Picture" \
or item['msg_type'] == "Recording" \
or item['msg_type'] == "Video" \
or item['msg_type'] == "Attachment":
print("要删除的文件:", item['msg_content'])
os.remove(item['msg_content'])
#将接收到的消息存放在字典中,当接收到新消息时对字典中超时的消息进行清理
#没有注册note(通知类)消息,通知类消息一般为:红包 转账 消息撤回提醒等,不具有撤回功能
@itchat.msg_register([TEXT, PICTURE, MAP, CARD, SHARING, RECORDING, ATTACHMENT, VIDEO, FRIENDS], isFriendChat=True)
def Revocation(msg):
mytime = time.localtime() # 这儿获取的是本地时间
#获取用于展示给用户看的时间 2017/03/03 13:23:53
msg_time_touser = mytime.tm_year.__str__() \
+ "/" + mytime.tm_mon.__str__() \
+ "/" + mytime.tm_mday.__str__() \
+ " " + mytime.tm_hour.__str__() \
+ ":" + mytime.tm_min.__str__() \
+ ":" + mytime.tm_sec.__str__()
msg_id = msg['MsgId'] #消息ID
msg_time = msg['CreateTime'] #消息时间
# if msg['isAt']:
# msg_from = msg['FromUserName']
# #itchat.send(u'@%s\u2005I received: %s' % (msg['ActualNickName'], msg['Content']), msg['FromUserName'])
# else:
msg_from = itchat.search_friends(userName = msg['FromUserName'])['NickName'] #消息发送人昵称
msg_type = msg['Type'] #消息类型
msg_content = None #根据消息类型不同,消息内容不同
msg_url = None #分享类消息有url
#图片 语音 附件 视频,可下载消息将内容下载暂存到当前目录
if msg['Type'] == 'Text':
msg_content = msg['Text']
elif msg['Type'] == 'Picture':
msg_content = msg['FileName']
msg['Text'](msg['FileName'])
elif msg['Type'] == 'Card':
msg_content = msg['RecommendInfo']['NickName'] + r" 的名片"
elif msg['Type'] == 'Map':
x, y, location = re.search("<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msg['OriContent']).group(1,
2,
3)
if location is None:
msg_content = r"纬度->" + x.__str__() + " 经度->" + y.__str__()
else:
msg_content = r"" + location
elif msg['Type'] == 'Sharing':
msg_content = msg['Text']
msg_url = msg['Url']
elif msg['Type'] == 'Recording':
msg_content = msg['FileName']
msg['Text'](msg['FileName'])
elif msg['Type'] == 'Attachment':
msg_content = r"" + msg['FileName']
msg['Text'](msg['FileName'])
elif msg['Type'] == 'Video':
msg_content = msg['FileName']
msg['Text'](msg['FileName'])
elif msg['Type'] == 'Friends':
msg_content = msg['Text']
#更新字典
# {msg_id:(msg_from,msg_time,msg_time_touser,msg_type,msg_content,msg_url)}
msg_dict.update(
{msg_id: {"msg_from": msg_from, "msg_time": msg_time, "msg_time_touser": msg_time_touser, "msg_type": msg_type,
"msg_content": msg_content, "msg_url": msg_url, "msg_group_name": ""}})
print("FriendChat! ", "msg_from:", msg_from, "msg_content:", msg_content, "msg_id:", msg_id)
#清理字典
ClearTimeOutMsg()
#收到note类消息,判断是不是撤回并进行相应操作
@itchat.msg_register([NOTE], isFriendChat=True)
def SaveMsg(msg):
# print(msg)
#创建可下载消息内容的存放文件夹,并将暂存在当前目录的文件移动到该文件中
if not os.path.exists(".\\Revocation\\"):
os.mkdir(".\\Revocation\\")
# print(msg['Content'])
if re.search(r"\<replacemsg\>\<\!\[CDATA\[.+ recalled a message\.\]\]\>\<\/replacemsg\>", msg['Content']) != None:
old_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1)
old_msg = msg_dict.get(old_msg_id, {})
# print(old_msg_id, old_msg)
msg_send = r"您的好友:" \
+ old_msg.get('msg_from', "") \
+ r" 在 [" + old_msg.get('msg_time_touser', "") \
+ r"], 撤回了一条 ["+old_msg['msg_type']+"] 消息, 内容如下:" \
+ old_msg.get('msg_content', "")
if old_msg['msg_type'] == "Sharing":
msg_send += r", 链接: " \
+ old_msg.get('msg_url', "")
elif old_msg['msg_type'] == 'Picture' \
or old_msg['msg_type'] == 'Recording' \
or old_msg['msg_type'] == 'Video' \
or old_msg['msg_type'] == 'Attachment':
msg_send += r", 存储在当前目录下Revocation文件夹中"
shutil.move(old_msg['msg_content'], r".\\Revocation\\")
print("Message send to my phone: ", msg_send)
itchat.send(msg_send, toUserName='filehelper') #将撤回消息的通知以及细节发送到文件助手
msg_dict.pop(old_msg_id)
ClearTimeOutMsg()
# # 在注册时增加isGroupChat=True将判定为群聊回复
@itchat.msg_register([TEXT, PICTURE, MAP, CARD, SHARING, RECORDING, ATTACHMENT, VIDEO, FRIENDS], isGroupChat = True)
def groupchat_reply(msg):
try:
mytime = time.localtime() # 这儿获取的是本地时间
# 获取用于展示给用户看的时间 2017/03/03 13:23:53
msg_time_touser = mytime.tm_year.__str__() \
+ "/" + mytime.tm_mon.__str__() \
+ "/" + mytime.tm_mday.__str__() \
+ " " + mytime.tm_hour.__str__() \
+ ":" + mytime.tm_min.__str__() \
+ ":" + mytime.tm_sec.__str__()
msg_id = msg['MsgId'] # 消息ID
msg_time = msg['CreateTime'] # 消息时间
# if msg['isAt']:
# msg_from = msg['FromUserName']
# #itchat.send(u'@%s\u2005I received: %s' % (msg['ActualNickName'], msg['Content']), msg['FromUserName'])
# else:
try:
msg_from = msg['ActualNickName'] # 消息发送人昵称
except KeyError:
msg_from = "你自己"
except:
traceback.print_exc()
msg_type = msg['Type'] # 消息类型
msg_content = None # 根据消息类型不同,消息内容不同
msg_url = None # 分享类消息有url
# 图片 语音 附件 视频,可下载消息将内容下载暂存到当前目录
if msg['Type'] == 'Text':
msg_content = msg['Text']
elif msg['Type'] == 'Picture':
msg_content = msg['FileName']
msg['Text'](msg['FileName'])
elif msg['Type'] == 'Card':
msg_content = msg['RecommendInfo']['NickName'] + r" 的名片"
elif msg['Type'] == 'Map':
x, y, location = re.search("<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msg['OriContent']).group(
1,
2,
3)
if location is None:
msg_content = r"纬度->" + x.__str__() + " 经度->" + y.__str__()
else:
msg_content = r"" + location
elif msg['Type'] == 'Sharing':
msg_content = msg['Text']
msg_url = msg['Url']
elif msg['Type'] == 'Recording':
msg_content = msg['FileName']
msg['Text'](msg['FileName'])
elif msg['Type'] == 'Attachment':
msg_content = r"" + msg['FileName']
msg['Text'](msg['FileName'])
elif msg['Type'] == 'Video':
msg_content = msg['FileName']
msg['Text'](msg['FileName'])
elif msg['Type'] == 'Friends':
msg_content = msg['Text']
# 更新字典
# {msg_id:(msg_from,msg_time,msg_time_touser,msg_type,msg_content,msg_url)}
msg_dict.update(
{msg_id: {"msg_from": msg_from, "msg_time": msg_time, "msg_time_touser": msg_time_touser,
"msg_type": msg_type,
"msg_content": msg_content, "msg_url": msg_url, "msg_group_name": msg['GroupChatName']}})
print("GroupChat! ","msg_from:", msg_from, "msg_content:", msg_content, "msg_id:", msg_id,
"msg['GroupChatName'] = ", msg['GroupChatName'])
# 清理字典
ClearTimeOutMsg()
except:
traceback.print_exc()
#收到note类消息,判断是不是撤回并进行相应操作
@itchat.msg_register([NOTE], isGroupChat = True)
def SaveMsg(msg):
# print(msg)
#创建可下载消息内容的存放文件夹,并将暂存在当前目录的文件移动到该文件中
if not os.path.exists(".\\Revocation\\"):
os.mkdir(".\\Revocation\\")
# print('Groupchat Note message! ', "msg['Content'] = ", msg['Content'])
if re.search(r"\<replacemsg\>\<\!\[CDATA\[.+ recalled a message\.\]\]\>\<\/replacemsg\>", msg['Content']) != None:
# old_msg_id = re.search(";msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1)
old_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1)
old_msg = msg_dict.get(old_msg_id, {})
msg_send = r"您的好友:" \
+ old_msg.get('msg_from', "") \
+ r" 在 [" + old_msg.get('msg_time_touser', "") \
+ r"]于\"" + old_msg.get('msg_group_name', "") + "\"" \
+ r", 撤回了一条 [" + old_msg['msg_type'] + "] 消息, 内容如下:" \
+ old_msg.get('msg_content', "")
if old_msg['msg_type'] == "Sharing":
msg_send += r", 链接: " \
+ old_msg.get('msg_url', "")
elif old_msg['msg_type'] == 'Picture' \
or old_msg['msg_type'] == 'Recording' \
or old_msg['msg_type'] == 'Video' \
or old_msg['msg_type'] == 'Attachment':
msg_send += r", 存储在当前目录下Revocation文件夹中"
shutil.move(old_msg['msg_content'], r".\\Revocation\\")
print("Message send to my phone: ", msg_send)
itchat.send(msg_send, toUserName='filehelper') # 将撤回消息的通知以及细节发送到文件助手
msg_dict.pop(old_msg_id)
ClearTimeOutMsg()
elif re.search(r";!\[CDATA\[You've recalled a message\.\]\]", msg['Content']) != None:
old_msg_id = re.search(";msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1)
old_msg = msg_dict.get(old_msg_id, {})
msg_send = r"您的好友:" \
+ old_msg.get('msg_from', "") \
+ r" 在 [" + old_msg.get('msg_time_touser', "") \
+ "]于\"" + old_msg.get('msg_group_name', "") + "\"" \
+ r", 撤回了一条 [" + old_msg['msg_type'] + "] 消息, 内容如下:" \
+ old_msg.get('msg_content', "")
if old_msg['msg_type'] == "Sharing":
msg_send += r", 链接: " \
+ old_msg.get('msg_url', "")
elif old_msg['msg_type'] == 'Picture' \
or old_msg['msg_type'] == 'Recording' \
or old_msg['msg_type'] == 'Video' \
or old_msg['msg_type'] == 'Attachment':
msg_send += r", 存储在当前目录下Revocation文件夹中"
shutil.move(old_msg['msg_content'], r".\\Revocation\\")
print("Message send to my phone: ", msg_send)
itchat.send(msg_send, toUserName='filehelper') # 将撤回消息的通知以及细节发送到文件助手
msg_dict.pop(old_msg_id)
ClearTimeOutMsg()
else:
pass
itchat.auto_login(hotReload=True)
itchat.run() | 4c2e372332c90896ac300950db15b4a8ed33bd94 | [
"Python"
] | 1 | Python | Jason101616/ItChat | 600b71ed89733f030b7e1685858a5b6bda7ac055 | 40739534a499800c26ceda6cbec85c3280c36c3f | |
refs/heads/master | <file_sep>var APP_ID = "6cc6df33-1f71-48d0-9868-e1de48b64467";
var app = new PusherPlatform.App({
appId: '6cc6df33-1f71-48d0-9868-e1de48b64467',
});
console.log(app);
var myFeed = app.feed('newIdea-2');
load();
function addNewIdeaToList(newIdea, SEND_AGAIN) {
var newIdea = document.getElementById("newIdea").value;
if (SEND_AGAIN) {
myFeed.append(newIdea)
.then(function(response) {
console.log("Success" + newIdea);
console.log(response)
})
.catch(err => console.error('Error:', err));
console.log("Idea: " + newIdea);
myFeed.append({ yourKey: APP_ID, message: newIdea})
.then(response => console.log('Success:', response))
.catch(err => console.error('Error:', err));
}
}
function newItem(newItem) {
console.log(typeof newItem)
if (typeof newItem === "string") {
var newTextNode = document.createTextNode(newItem);
var newIdeaLi = document.createElement("li");
newIdeaLi.appendChild(newTextNode);
document.getElementById("ideasList").appendChild(newIdeaLi);
}
}
function load() {
myFeed.subscribe({
lastEventId: "25",
onOpen: () => console.log('Connection established'),
onItem: item => newItem(item.body),
onError: error => console.error('Error:', error),
});
}<file_sep># PusherFeedToDo
ToDOApp
| 96a0daaed32825be57f6896d5374595f7403aed3 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | arghasarkar/PusherFeedToDo | 858b3a442374a96b94f841ad78ffea7064389bdb | b9b2cac79efb7a3016843649e20a7b5d5a3de77d | |
refs/heads/master | <repo_name>yzy19900402/OFDR_GUI<file_sep>/Gui.py
from tkinter import *
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
import matplotlib.pyplot as plt
import Data as DT
import Draw
import tkinter as tk
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
import shlex
import subprocess
import os
class gui_window:
# The parameters
color_bg = 'white' # Set background color
color_text = '#E1F5FE' # Set text color
color_btn = '#212121' # Set button color
color_line = '#01579B' # Set line color
color_can = '#212121' # Set canvas colorcd ..
color_oval = '#2196F3' # Set oval color
target_color = '#FF6D00'
Debug_STOP = FALSE
Work_STOP = FALSE
Data_Save_STOP = TRUE
i = 1
def __init__(self, folder, Data_length, folder_number, UDP_MAX, COLUMN_NUM, TARGET_IP, TARGET_PORT):
self.root = Tk() # create root window
self.root.title("OFDR Client")
self.root.maxsize(800, 600)
self.root.config(bg="skyblue")
self.Data = DT.Data(folder, Data_length, folder_number, UDP_MAX, COLUMN_NUM, TARGET_IP, TARGET_PORT)
# Create left and right frames
self.Control_Frame = Frame(self.root, width=2560, height=200, bg='grey')
self.Control_Frame.pack(side='bottom', fill='x', padx=10, pady=5, expand=False)
self.Fig_Frame = Frame(self.root, width=2560, height=1200, bg='grey')
self.Fig_Frame.pack(side='bottom', fill='both', padx=10, pady=5, expand=True)
# self.tool_bar = Frame(self.Control_Frame, width=90, height=185, bg='lightgrey')
# self.tool_bar.grid(side='left', fill='both', padx=5, pady=5, expand=True)
self.Control_bar = Frame(self.Control_Frame, width=1024, height=200, bg='lightgrey')
self.Control_bar.pack(side='left', fill='y', padx=10, pady=5, expand=False)
self.Terminal_bar = Frame(self.Control_Frame, width=1536, height=200, bg='black')
self.Terminal_bar.pack(side='left', fill='both', padx=10, pady=5, expand=True)
wid = self.Terminal_bar.winfo_id()
args = shlex.split('xterm -into %d -geometry 80x80 -sb -e command &' % (wid))
# os.system('xterm -into %d -geometry 40x20 -sb -e command &' % wid)
self.terminal = subprocess.Popen(args)
self.root.protocol('WM_DELETE_WINDOW', self.before_close)
# Example labels that serve as placeholders for other widgets
Label(self.Control_bar, text="Control", font=64).grid(column=5, row=0, sticky='news')
# For now, when the buttons are clicked, they only call the clicked() method. We will add functionality later.
Button(self.Control_bar, text="Debug", command=self.ReDebug).grid(column=0, row=1, sticky='news')
Button(self.Control_bar, text="Stop", command=self.Stop).grid(column=0, row=2, sticky='news')
Button(self.Control_bar, text="Work", command=self.Restart).grid(column=0, row=3, sticky='news')
self.E1 = tk.Entry(self.Control_bar, show=None, width=30, bg="#37474F", fg='#eceff1')
self.E1.grid(column=2, row=1, columnspan=6, sticky='news') #Define a Entry and put it in position
self.E1.insert(0, './Debug')
Button(self.Control_bar, text="Debug Save", command=self.Debug_Save_data).grid(column=10, row=1, sticky='news')
self.E2 = tk.Entry(self.Control_bar, show=None, width=30, bg="#37474F", fg='#eceff1')
self.E2.grid(column=2, row=2, columnspan=6, sticky='news') #Define a Entry and put it in position
self.E2.insert(0, '128')
self.E3 = tk.Entry(self.Control_bar, show=None, width=30, bg="#37474F", fg='#eceff1')
self.E3.grid(column=2, row=3, columnspan=6, sticky='news') #Define a Entry and put it in position
self.E3.insert(0, './Data')
Button(self.Control_bar, text="Stream Save", command=self.Save_data_Stream).grid(column=10, row=3, sticky='news')
self.Fig = Draw.DRAW(self.Data)
self.canvas = FigureCanvasTkAgg(self.Fig.fig, master=self.Fig_Frame) # A tk.DrawingArea.
self.canvas.get_tk_widget().pack(side='right', fill='both', padx=5, pady=5, expand=True)
self.Fig.Test()
self.canvas.draw()
toolbar = NavigationToolbar2Tk(self.canvas, self.Fig_Frame)
toolbar.config(background=self.color_bg)
toolbar._message_label.config(background=self.color_bg)
for button in toolbar.winfo_children():
button.config(background=self.color_bg)
toolbar.update()
self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1, padx=0, pady=0)
self.i = 1
def ReDebug(self):
self.Work_STOP = TRUE
self.Data_Save_STOP = TRUE
self.Debug_STOP = FALSE
self.Debug()
def Restart(self):
self.Work_STOP = FALSE
self.Debug_STOP = TRUE
self.Data_Save_STOP = FALSE
self.Work()
def Stop(self):
# print("tick")
self.Work_STOP = TRUE
self.Debug_STOP = TRUE
self.Data_Save_STOP = FALSE
def Start_gui(self):
self.root.after(100, self.clicked)
self.root.mainloop()
def clicked(self):
'''if button is clicked, display message'''
print("Clicked.")
def Debug_Save_data(self):
name = self.E1.get()
Status = self.Data.save_data(name)
tk.messagebox.showinfo('Info', 'Debug data saved')
def Save_data_Stream(self):
self.Debug_STOP = TRUE
self.Work_STOP = TRUE
if self.Data_Save_STOP:
self.i = 1
print("Data saving stops")
else:
self.root.after(20, self.Save_data_Stream)
if self.i < int(self.E2.get()):
if self.Data.Try_data_run():
self.Fig.Work_moniter()
self.canvas.draw()
name = self.E3.get() + '/' + str(self.i) + '/'
print(name)
Status = self.Data.save_data(name)
self.i += 1
else:
self.Data_Save_STOP = TRUE
tk.messagebox.showinfo('Info', 'Stream data saved')
def Debug(self):
if self.Debug_STOP:
print("Debug stops")
else:
self.Fig.Test()
self.canvas.draw()
self.root.after(20, self.Debug)
def Work(self):
if self.Work_STOP:
print("Working stops")
else:
self.root.after(20, self.Work)
if self.Data.Try_data_run():
self.Fig.Work_moniter()
self.canvas.draw()
def before_close(self):
# self.terminal.terminate()
self.root.destroy()
<file_sep>/Main.py
import Gui
import math
#global paramters
TARGET_IP = ''
TARGET_PORT = 8001
Data_length = 65536# the data length for u64, 8bytes
UDP_MAX = 32768 # the max byte length for UDP
COLUMN_NUM = math.floor(UDP_MAX / 8)
folder = '/home/clark/Documents/Measurements/01_15_20_Fiber_cable_ID/226ns/01_23_20_Cables/CableAA1/'
folder_number = 1
gui = Gui.gui_window(folder, Data_length, folder_number, UDP_MAX, COLUMN_NUM, TARGET_IP, TARGET_PORT)
gui.Start_gui()<file_sep>/Draw.py
import Data as DT
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
name = 'temp'
flag = False
lflag = False
ymax = 0
fs = 125e6
stop_thread = False
fp = 5
tau_d = 226e-9 # 1025e-9 # 226e-9
vp = 2e8 # The light speed in fiber
f0 = 43e3 # corresponding with L0
class DRAW:
def __init__(self, DT):
self.data_src = DT
self.fig = plt.figure(figsize=(3, 2), dpi=100)
self.fig.set_tight_layout(True)
self.i = 0
def Test(self):
self.fig.clf()
self.i += 5
fig1 = plt.subplot(111)
t = np.arange(1024)
t = t*np.pi/512
y = np.sin(t+self.i)
plt.plot(t, y)
plt.xlim(0, 6)
plt.ylim(-1, 1)
plt.grid()
# SMALL_SIZE = 4
# MEDIUM_SIZE = 10
# BIGGER_SIZE = 12
# plt.rc('font', size=SMALL_SIZE) # controls default text sizes
# plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title
# plt.rc('axes', labelsize=SMALL_SIZE) # fontsize of the x and y labels
# plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
# plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
# plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
# plt.rc('figure', titlesize=SMALL_SIZE) # fontsize of the figure title
# fig1.plot.grid()
def Test_stop(self):
self.fig.clf()
def Work_moniter(self):
print('started\n')
self.fig.clf()
index = np.arange(0, self.data_src.Data_length)
t_us = index / fs * 1e6
ADC_data_A, ADC_data_B, DAC_data, CMP_Delay, Trigger, COMP_in, Phase_error, Up, Dn = self.data_src.get_data()
fig1 = plt.subplot(231)
plt.plot(t_us, DAC_data / 39.7727, linewidth=0.8)
plt.xlim(0, max(t_us))
plt.grid()
plt.xlabel('Time(\u03BCs)')
plt.ylabel('Current(mA)')
plt.title('Driving Current')
fig2 = plt.subplot(232)
plt.plot(t_us, ADC_data_A * 1000 / pow(2, 13), linewidth=0.8)
plt.grid()
plt.xlim(0, max(t_us))
plt.xlabel('Time(\u03BCs)')
plt.ylabel('Voltage (mV)')
plt.title('MZI time domain signal')
fig3 = plt.subplot(233)
plt.plot(t_us, (Phase_error) / fp, linewidth=0.8)
plt.grid()
plt.xlim(0, max(t_us))
plt.xlabel('Time(\u03BCs)')
plt.ylabel('Phase error(\u03C0)')
plt.title('Phase error over Time')
f, t, Zxx = signal.stft(ADC_data_A, fs, nperseg=1000, noverlap=990)
fig4 = plt.subplot(234)
plt.pcolormesh(t * 1e6, f / 1e6, np.abs(Zxx))
plt.ylabel('Frequency(MHz)')
plt.xlabel('Time(\u03BCs)')
plt.title('MZI STFFT')
plt.xlim(0, max(t_us))
plt.grid()
plt.ylim(0, 30)
fig5 = plt.subplot(2, 3, 5)
freq = np.arange(int(self.data_src.Data_length))
freq = freq * fs / self.data_src.Data_length
sp = np.abs(np.fft.fft(ADC_data_A)) / self.data_src.Data_length
# print(np.max(sp))
sp_dB = 20 * np.log10(sp)
plt.plot(freq / 1e6, sp_dB)
plt.title('MZI FFT')
plt.xlabel('Frequency(MHz)')
plt.ylabel('magnitude(real dB)')
plt.xlim(0, 30)
# plt.ylim(max(sp_dB) - 40, max(sp_dB))
plt.grid()
fig6 = plt.subplot(2, 3, 6)
sp = np.abs(np.fft.fft(ADC_data_B)) / self.data_src.Data_length
# print(np.max(sp))
sp_dB = 20 * np.log10(sp)
distance = (freq - f0) / fs * tau_d * fp * vp
plt.plot(distance, sp_dB)
plt.title('Fiber length')
plt.xlabel('Fiber length(m)')
plt.ylabel('magnitude(real dB)')
plt.xlim(-0.1, 6)
# plt.ylim(max(sp_dB) - 70, max(sp_dB))
plt.grid()
<file_sep>/Data.py
import numpy as np
import socket
import math
import Gui
# folder = './data/'
# Socket part capture the data
class Data:
Data_length = 0
UDP_MAX = 1
TARGET_IP = ''
TARGET_PORT = 8001
TARGET = (TARGET_IP, TARGET_PORT)
COLUMN_NUM = 0
ADC_data_A = 0
ADC_data_B = 0
DAC_data = 0
CMP_Delay = 0
Dn = 0
CMP_in = 0
Trigger = 0
Up = 0
Phase_error = 0
folder_number = 0
folder = 0
ss = 0
Depth = 1
data_ready = False
i = 0
data = 0
def __init__(self, folder, Data_length, folder_number, UDP_MAX, COLUMN_NUM, TARGET_IP, TARGET_PORT):
self.ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.TARGET = (TARGET_IP, TARGET_PORT)
self.ss.bind(self.TARGET)
self.folder = folder
self.folder_number = folder_number
self.ADC_data_A = np.zeros(Data_length, dtype=np.int16)
self.ADC_data_B = np.zeros(Data_length, dtype=np.int16)
self.DAC_data = np.zeros(Data_length, dtype=np.uint16)
self.Other = np.zeros(COLUMN_NUM, dtype=np.uint16)
self.Trigger = np.zeros(Data_length, dtype=np.uint8)
self.Up = np.zeros(Data_length, dtype=np.uint8)
self.Dn = np.zeros(Data_length, dtype=np.uint8)
self.CMP_in = np.zeros(Data_length, dtype=np.uint8)
self.CMP_Delay = np.zeros(Data_length, dtype=np.uint8)
self.Phase_error = np.zeros(Data_length, dtype=np.int16)
self.data_ready = False
self.temp_buffer = np.zeros([math.floor(Data_length * 8 / UDP_MAX), UDP_MAX], dtype=np.uint8)
self.Data_length = Data_length
self.UDP_MAX = UDP_MAX
self.Depth = math.floor(self.Data_length*8/self.UDP_MAX)
def close(self):
self.stop_thread = True
def reset(self):
self.i = self.Depth - 1
def Try_data_run(self):
self.ss.settimeout(0.05)
try:
data, addrRsv = self.ss.recvfrom(self.UDP_MAX)
except:
return False
else:
# print(self.i)
if not self.data_ready:
if data[7] == 0x5a:
self.i = 0
if data[7] == 0xa5:
if self.i == self.Depth - 1:
self.data_ready = True
# print('Ready')
self.temp_buffer[self.i, :] = np.frombuffer(data, dtype=np.uint8)
self.i = (self.i + 1) % self.Depth
if self.data_ready:
self.data_ready = False
data = self.temp_buffer.tobytes()
self.data = np.frombuffer(data, np.int16)
data_temp = np.reshape(self.data, [self.Data_length, 4])
self.ADC_data_A = data_temp[:, 0]
self.ADC_data_B = data_temp[:, 1]
DAC_data_temp = data_temp[:, 2]
self.DAC_data = DAC_data_temp.astype(np.uint16)
Other = data_temp[:, 3]
Other = Other.astype(np.uint16)
self.CMP_Delay = Other % 2
self.Dn = ((Other // 2) % 16)
self.CMP_in = (Other // pow(2, 5)) % 2
self.Trigger = (Other // pow(2, 6)) % 2
self.Up = (Other // pow(2, 7)) % 2
Upcumsum = self.Up.cumsum()
Dncumsum = self.Dn.cumsum()
self.data_ready = False
self.Phase_error = np.int16(Upcumsum - Dncumsum)
return True
else:
return False
# print(self.i)
# Debug_test = self.DAC_data
# print(Debug_test)
# break
def save_data(self, name):
print('Saving')
np.savetxt(name + '/MZI.txt', self.ADC_data_A)
np.savetxt(name + '/Reflect.txt', self.ADC_data_B)
np.savetxt(name + '/Up.txt', self.Up)
np.savetxt(name + '/Dn.txt', self.Dn)
np.savetxt(name + '/CMP_Delay.txt', self.CMP_Delay)
np.savetxt(name + '/CMP_in.txt', self.CMP_in)
np.savetxt(name + '/DAC.txt', self.DAC_data)
np.savetxt(name + '/Trigger.txt', self.Trigger)
return 'Saved'
def get_shot(self):
return self.DAC_data
def if_ready(self):
return self.data_ready
def get_data(self):
return (self.ADC_data_A - np.mean(self.ADC_data_A)), (
self.ADC_data_B - np.mean(
self.ADC_data_B)), self.DAC_data, self.CMP_Delay, self.Trigger, self.CMP_in, self.Phase_error, self.Up, self.Dn
| 35546bf0c0ceae25a68e63c5ff901fd239845fd1 | [
"Python"
] | 4 | Python | yzy19900402/OFDR_GUI | 2130168f1bd9884015e1934b2c63929f6957e602 | ad0ebf1ceb7eb3c4253a0ca3239a84d87af4b7d6 | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GameOfLife
{
public partial class LifeGrid : UserControl
{
private bool[][] alive;
public Color colorAlive;
public Color colorDead;
public List<int> rulesCreate;
public List<int> rulesSurvive;
private Point mouseLocation;
private int cellSize;
public bool brush;
public int liveCells;
public int getCellSize()
{
return cellSize;
}
public LifeGrid()
{
liveCells = 0;
cellSize = 4;
brush = true;
InitializeComponent();
Random rnd = new Random();
alive = new bool[Height/cellSize][];
for (int i = 0; i < Height/cellSize; i++)
{
alive[i] = new bool[Width/cellSize];
for (int j = 0; j < Width/cellSize; j++)
{
alive[i][j] = false; //rnd.Next() % 2 == 0;
}
}
rulesCreate = new List<int>();
rulesCreate.Add(3);
rulesSurvive = new List<int>();
rulesSurvive.Add(2);
rulesSurvive.Add(3);
colorAlive = Color.Green;
colorDead = Color.Black;
pictureBox1.Image = new Bitmap(Width, Height);
mouseLocation = Point.Empty;
drawCurrentIteration();
}
public void drawCurrentIteration()
{
SolidBrush brushA = new SolidBrush(colorAlive);
SolidBrush brushD = new SolidBrush(colorDead);
liveCells = 0;
for (int i=0; i<Height/cellSize; i++)
{
for(int j=0; j<Width/cellSize; j++)
{
using(var canvas = Graphics.FromImage(pictureBox1.Image))
{
if (alive[i][j])
{
canvas.FillRectangle(brushA, i * cellSize, j * cellSize, cellSize, cellSize);
liveCells++;
}
else
{
canvas.FillRectangle(brushD, i * cellSize, j * cellSize, cellSize, cellSize);
}
}
}
}
pictureBox1.Refresh();
brushA.Dispose();
brushD.Dispose();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Left)
{
if (e.Location.X <= Height && e.Location.X >= 0 && e.Location.Y <= Width && e.Location.Y >= 0)
{
mouseLocation = e.Location;
alive[mouseLocation.X / cellSize][mouseLocation.Y / cellSize] = brush;
drawCurrentIteration();
}
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Left && mouseLocation != Point.Empty)
{
if (e.Location.X <= Height && e.Location.X >= 0 && e.Location.Y <= Width && e.Location.Y >= 0)
{
int x0 = mouseLocation.X/cellSize, y0 = mouseLocation.Y/cellSize, x1 = e.X/cellSize, y1 = e.Y/cellSize;
bool steep = Math.Abs(y1 - y0) > Math.Abs(x1 - x0);
if (steep) {
int t = x0;
x0 = y0;
y0 = t;
t = x1;
x1 = y1;
y1 = t;
}
if (x0 > x1) {
int t = x0;
x0 = x1;
x1 = t;
t = y0;
y0 = y1;
y1 = t;
}
int dX = (x1 - x0), dY = Math.Abs(y1 - y0), err = (dX / 2), ystep = (y0 < y1 ? 1 : -1), y = y0;
for (int x = x0; x <= x1; ++x)
{
if (x < 0 || x >= Width / cellSize || y < 0 || y >= Height / cellSize)
break;
if (steep)
alive[y][x] = brush;
else
alive[x][y] = brush;
err = err - dY;
if (err < 0) { y += ystep; err += dX; }
}
mouseLocation = e.Location;
//alive[mouseLocation.X / cellSize][mouseLocation.Y / cellSize] = brush;
drawCurrentIteration();
}
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
mouseLocation = Point.Empty;
}
public void computeNextState()
{
bool[][] tmp = new bool[Height/cellSize][];
for(int i=0; i<Height/cellSize; i++)
{
tmp[i] = new bool[Width/cellSize];
for(int j=0; j<Width/cellSize; j++)
{
int count = 0;
if(i != 0)
{
if (j != 0 && alive[i - 1][j - 1])
count++;
if (alive[i-1][j])
count++;
if (j < Width/cellSize - 1 && alive[i - 1][j + 1])
count++;
}
if (i < Height/cellSize - 1)
{
if (j != 0 && alive[i + 1][j - 1])
count++;
if (alive[i+1][j])
count++;
if (j < Width/cellSize - 1 && alive[i + 1][j + 1])
count++;
}
if (j != 0 && alive[i][j - 1])
count++;
if (j < Width/cellSize - 1 && alive[i][j + 1])
count++;
if (alive[i][j])
{
bool flag = true;
foreach(int rule in rulesSurvive)
{
if (rule == count)
{
flag = false;
tmp[i][j] = true;
break;
}
}
if (flag)
tmp[i][j] = false;
}
else
{
bool flag = true;
foreach (int rule in rulesCreate)
{
if (rule == count)
{
flag = false;
tmp[i][j] = true;
break;
}
}
if (flag)
tmp[i][j] = false;
}
}
}
alive = tmp;
drawCurrentIteration();
}
private void LifeGrid_Resize(object sender, EventArgs e)
{
alive = new bool[Height / cellSize][];
for (int i = 0; i < Height / cellSize; i++)
{
alive[i] = new bool[Width / cellSize];
for (int j = 0; j < Width / cellSize; j++)
{
alive[i][j] = false; //rnd.Next() % 2 == 0;
}
}
pictureBox1.Image.Dispose();
pictureBox1.Image = new Bitmap(Width, Height);
pictureBox1.Refresh();
drawCurrentIteration();
}
public void changeSize(int size)
{
cellSize = size;
LifeGrid_Resize(null, null);
}
public void fillRandom()
{
Random rnd = new Random();
for (int i = 0; i < Height / cellSize; i++)
{
for (int j = 0; j < Width / cellSize; j++)
{
alive[i][j] = rnd.Next() % 2 == 0;
}
}
drawCurrentIteration();
}
public void clear()
{
for (int i = 0; i < Height / cellSize; i++)
for (int j = 0; j < Width / cellSize; j++)
alive[i][j] = false;
drawCurrentIteration();
}
public Image getImg()
{
return pictureBox1.Image;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GameOfLife
{
public partial class Form1 : Form
{
int childN;
public Form1()
{
childN = 1;
InitializeComponent();
Text = "Game of Life";
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
LifeForm child = new LifeForm();
child.Text = "Game " + childN.ToString();
child.MdiParent = this;
child.Show();
childN++;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
if(ActiveMdiChild != null)
((LifeForm)ActiveMdiChild).saveToolStripMenuItem_Click(null, null);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GameOfLife
{
public partial class LifeForm : Form
{
public LifeForm()
{
InitializeComponent();
colorDialog.Color = lifeGrid1.colorAlive;
aliveToolStripMenuItem.ForeColor = lifeGrid1.colorAlive;
deadToolStripMenuItem.ForeColor = lifeGrid1.colorDead;
clickTypeToolStripMenuItem.ForeColor = lifeGrid1.colorAlive;
}
private void timer1_Tick(object sender, EventArgs e)
{
lifeGrid1.computeNextState();
}
private void LifeForm_ResizeEnd(object sender, EventArgs e)
{
if (Height < Width)
Height = Width + 48;
else
Width = Height - 48;
}
private void timer2_Tick(object sender, EventArgs e)
{
statusCellNumber.Text = lifeGrid1.liveCells.ToString();
}
private void playToolStripMenuItem_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
if (timer1.Enabled)
playToolStripMenuItem.Text = "Pause";
else
playToolStripMenuItem.Text = "Play";
}
private void aliveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (colorDialog.ShowDialog() == DialogResult.OK)
{
lifeGrid1.colorAlive = colorDialog.Color;
aliveToolStripMenuItem.ForeColor = colorDialog.Color;
lifeGrid1.drawCurrentIteration();
if (lifeGrid1.brush)
clickTypeToolStripMenuItem.ForeColor = colorDialog.Color;
}
}
private void deadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (colorDialog.ShowDialog() == DialogResult.OK)
{
lifeGrid1.colorDead = colorDialog.Color;
deadToolStripMenuItem.ForeColor = colorDialog.Color;
lifeGrid1.drawCurrentIteration();
if (!lifeGrid1.brush)
clickTypeToolStripMenuItem.ForeColor = colorDialog.Color;
}
}
private void rulesToolStripMenuItem_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
FormRules frm = new FormRules(lifeGrid1, timer1);
frm.Show();
playToolStripMenuItem.Text = "Play";
}
private void clickTypeToolStripMenuItem_Click(object sender, EventArgs e)
{
lifeGrid1.brush = !lifeGrid1.brush;
if (lifeGrid1.brush)
{
clickTypeToolStripMenuItem.Text = "Mode: Create";
clickTypeToolStripMenuItem.ForeColor = aliveToolStripMenuItem.ForeColor;
}
else
{
clickTypeToolStripMenuItem.Text = "Mode: Destroy";
clickTypeToolStripMenuItem.ForeColor = deadToolStripMenuItem.ForeColor;
}
}
private void randomToolStripMenuItem_Click(object sender, EventArgs e)
{
lifeGrid1.fillRandom();
}
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
lifeGrid1.clear();
}
public void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter =
"JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
saveFileDialog1.Title = "Save an Image File";
if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
{
try
{
Image tmp = lifeGrid1.getImg();
tmp.Save(saveFileDialog1.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not save file \"" +
saveFileDialog1.FileName + "\" to disk. Original error: " +
ex.Message);
}
}
}
}
}
<file_sep># Game of Life
# <NAME> 151524
# Опис на апликација:
Апликацијата што ја развив е имлементација на Conway's Game of Life проширена со опции да се менуваат правилата на креирање и останување во живот како и соодветен кориснички интерфејс.
# Упатство на користење:
# Нова игра:
Корисникот може да отвори нова игра преку File -> New. Можат да работат повеќе игри во исто време.
Интеракција со играта:
Корисникот може во секое време да “црта” живи клетки во панелот или да ги брише со кликање и влечење на маусот. Менување помеѓу овие два начина на работа се прави преку кликање на “Mode: Create”/”Mode: Destroy” во менито.
# Play/Pause:
Преку “Play/Pause” копчето во менито се запира или продолжува со евулузијата на играта.
# Промена на бои:
Боите на живите и мртвите клетки можат да се сменат преку Colors во менито за опции.
# Дополнителни опции:
Во менито “Tools” корисникот може да добие нова случајно генерирана мапа или празна.
Промена на правла за живот:
При кликање на “Rules” во менито се отвара ново прозорче со правилата на играта. Во тоа прозорче корисникот може да додаде или отстрани правила, како и да ја смени големината на клетките и времето помеѓу еволуции. Секоја игра почнува со основните правила на играта. Ако има три или две живи клетки околу жива клетка, таа останува жива во следната итерација. Ако има три живи клетки околу мртва клетка, таа оживува. Во сите други случаеви клетката умира или останува умрена.
# Зачувување:
Воведена е и опцијата корисникот да може да зачува слика од играта преку “File -> Save”.
# Претставување на проблемот:
За чување на состојбата на клетките се користи матрица со bool елементи каде true означува дека е жива и false дека е мртва. Матрицата во себе држи број на елементи пресметано со височината на контејнерот помножена со должината поделено со должината на страните на една клетка. Бројот на елементи е динамичен и се мења со променување на големината на прозорецот.
Правилата за живот се држат во две листи, и при секое итерирање се проверуваат дали важат за одредена клетка.
Текот на животот се води со помош на тајмер кој ја повикува функцијата за еволуција и прикажување на следната состојба.
За читање и цртање со зимање на инпут од маусот на корисникот се користи “Bresenham's Line Algorithm” за цртање на линија врз пиксели.
# Кориснички интерфејс:
Состојбата на играта е прикажана со цртање на квадрати со бои кој што можат да се променат од корисникот врз PictureBox. Сите алатки и опции се достапни преку менито. Бројот на живи клетки се прикажани на статус лентата на дното од прозорецот. Корисникот може да отвори повеќе игри истовремено. Оваа функционалност е овозможена преку MDI контејнер, со цел да може да спореди еволуција според различни правила.
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GameOfLife
{
public partial class FormRules : Form
{
LifeGrid Grid;
Timer Tmr;
public FormRules(LifeGrid grid, Timer tmr)
{
InitializeComponent();
Grid = grid;
Tmr = tmr;
foreach (int rule in grid.rulesCreate)
listBoxCreation.Items.Add(rule);
foreach (int rule in grid.rulesSurvive)
listBoxSurvival.Items.Add(rule);
numericUpDownSize.Value = grid.getCellSize();
numericUpDownTimer.Value = tmr.Interval;
}
private void numericUpDownSize_ValueChanged(object sender, EventArgs e)
{
Grid.changeSize((int) numericUpDownSize.Value);
}
private void removeSurvivalRule_Click(object sender, EventArgs e)
{
if(listBoxSurvival.Items.Count != 0 && listBoxSurvival.SelectedIndex != -1)
{
Grid.rulesSurvive.Remove((int)listBoxSurvival.Items[listBoxSurvival.SelectedIndex]);
listBoxSurvival.Items.RemoveAt(listBoxSurvival.SelectedIndex);
}
}
private void addSurvivalRule_Click(object sender, EventArgs e)
{
if (!listBoxSurvival.Items.Contains(numericUpDownSurvival.Value))
{
Grid.rulesSurvive.Add((int)numericUpDownSurvival.Value);
listBoxSurvival.Items.Add((int)numericUpDownSurvival.Value);
}
}
private void removeCreationRule_Click(object sender, EventArgs e)
{
if (listBoxCreation.Items.Count != 0 && listBoxCreation.SelectedIndex != -1)
{
Grid.rulesCreate.Remove((int)listBoxCreation.Items[listBoxCreation.SelectedIndex]);
listBoxCreation.Items.RemoveAt(listBoxCreation.SelectedIndex);
}
}
private void addCreationRule_Click(object sender, EventArgs e)
{
if (!listBoxCreation.Items.Contains(numericUpDownCreation.Value))
{
Grid.rulesCreate.Add((int)numericUpDownCreation.Value);
listBoxCreation.Items.Add((int)numericUpDownCreation.Value);
}
}
private void buttonSize_Click(object sender, EventArgs e)
{
Grid.changeSize((int)numericUpDownSize.Value);
}
private void numericUpDownTimer_ValueChanged(object sender, EventArgs e)
{
Tmr.Interval = (int)numericUpDownTimer.Value;
}
}
}
| 7ae9c2326b68c7157553f7a090b6967bad6872f2 | [
"Markdown",
"C#"
] | 5 | C# | hdraganovski/game-of-life | e194eaa151025638a237ad33d860500b1507c68b | c08e80f5d5704579664aa36f6d1b2f7262811480 | |
refs/heads/master | <repo_name>11813147ak/Data-science-required-python<file_sep>/README.md
# Data-science-required-python<file_sep>/Seaborn practise.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# In[4]:
tips=sns.load_dataset('tips')
# In[5]:
tips
# In[6]:
tips.head()
# In[9]:
# for categorical data
sns.barplot(x='sex',y='total_bill',data=tips)
# In[16]:
sns.countplot(x='time',data=tips)
# In[17]:
sns.countplot(x='sex',data=tips)
# In[34]:
sns.violinplot(x='day',y='total_bill',data=tips,hue='smoker',split=True)
# In[28]:
sns.boxplot(x='day',y='total_bill',data=tips,hue='smoker')
# In[22]:
tips.columns
# In[24]:
sns.boxplot(x='day',y='total_bill',data=tips)
# In[26]:
sns.pointplot(x='day',y='total_bill',data=tips)
# In[30]:
sns.stripplot(x='day',y='total_bill',data=tips)
# In[31]:
sns.boxenplot(x='day',y='total_bill',data=tips)
# In[39]:
# distribution plot
#it is a univariate
# In[43]:
sns.distplot(tips['total_bill'],kde=False,bins=40)
# In[45]:
sns.kdeplot(tips['total_bill'])
# In[56]:
sns.jointplot(x='total_bill',y='tip',data=tips,kind='kde')
# In[52]:
sns.distplot(tips['tip'],kde=False)
# In[57]:
sns.jointplot(x='total_bill',y='tip',data=tips,kind='reg')
# In[65]:
sns.pairplot(tips,hue='sex')
# In[66]:
sns.pairplot(tips,hue='smoker')
# In[67]:
sns.pairplot(tips)
# In[69]:
tips_corr=tips.corr()
# In[70]:
tips_corr
# In[73]:
sns.heatmap(tips_corr,annot=True)
# only with non categorical variables
# In[ ]:
# In[76]:
flights=sns.load_dataset('flights')
# In[77]:
flights.head()
# In[82]:
x=flights.pivot_table(index='month',columns='year',values="passengers")
# In[83]:
sns.heatmap(x)
# In[ ]:
# In[ ]:
# In[ ]:
<file_sep>/numpy session cb.py
#!/usr/bin/env python
# coding: utf-8
# In[67]:
import numpy as np
np.random.seed(1)
# In[68]:
np.random.randint(1,100,(5,5))
# In[69]:
x=np.array([1,2,4])
# In[70]:
x
# In[71]:
x.shape
# In[72]:
a=np.zeros((3,3))
# In[73]:
a
# In[74]:
b=np.ones((1,2))
# In[75]:
b
# In[76]:
np.full((3,2),5)
# In[77]:
x1=np.eye(4)
# In[78]:
x1
# In[79]:
x1[1,:]=5
# In[80]:
x1
# In[81]:
x=np.array([[1,2],[1,2]])
y=np.array([[1,2],[1,2]])
# In[82]:
np.add(x,y)
# In[83]:
np.subtract(x,y)
# In[84]:
np.divide(x,y)
# In[85]:
np.multiply(x,y)
# In[86]:
np.dot(x,y)
# In[87]:
xe=np.arange(10)+5
# In[88]:
np.random.shuffle(xe)
xe
# In[89]:
a=np.random.randn(2,3)
# In[90]:
a
# In[91]:
b=np.random.randint(5,10,2)
# In[92]:
b
# In[93]:
c=np.arange(66)+1
element=np.random.choice(c)
element
# In[ ]:
# In[97]:
a=np.array([[1,2,5,23,54,658],[65,67,657,7,87]])
# In[101]:
print(np.min(a,axis=0))
# In[104]:
print(np.max(a,axis=0))
# In[109]:
b=np.array([1,2,3,4,5,5,6,7,8,6,5,5,5,5])
m=sum(b)/5
# In[110]:
int(m)
# In[112]:
np.median(b)
# In[115]:
np.std(b)
# In[116]:
np.mean(b)
# In[117]:
np.average(b)
# In[118]:
np.var(b)
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
<file_sep>/Normal distribution 1D and 2D.py
#!/usr/bin/env python
# coding: utf-8
# In[2]:
# Generate a ND(1-D)
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# In[16]:
u=2
sigma=3
vals=u+sigma*np.random.randn(1000)
plt.hist(vals)
plt.show()
# In[17]:
vals=np.round(vals)
z=np.unique(vals,return_counts=True)
print(z)
# In[ ]:
# In[ ]:
# In[24]:
u=5
sigma=5
vals=u+sigma*np.random.randn(100)
plt.hist(vals)
plt.show()
# In[25]:
x=vals
y=np.zeros(x.shape)
plt.scatter(x,y)
plt.show()
# In[ ]:
# In[ ]:
# Generate a ND (MULTI VARIATE)
# In[36]:
mean=np.array([0.0,0.0])
cov=np.array([[1,0.8],[0.8,1]])
mean2=np.array([5.0,6.0])
cov2=np.array([[1.3,0.2],[0.2,1.1]])
dist=np.random.multivariate_normal(mean,cov,500)
dist2=np.random.multivariate_normal(mean2,cov2,500)
print(dist.shape)
plt.scatter(dist[:,0],dist[:,1])
plt.scatter(dist2[:,0],dist2[:,1])
plt.show()
# In[ ]:
b
<file_sep>/Visualization.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
# In[10]:
x=np.array([[1,2,3,4,5,1,2,3,4]])
# In[11]:
x
# In[12]:
x.T
# In[14]:
x.reshape(3,3)
# In[18]:
import pandas as pd
import matplotlib.pyplot as plt
# In[23]:
x=np.arange(10)
y=x**2
# In[24]:
plt.plot(x,y)
# In[44]:
plt.plot(x,y,label='graph')
plt.plot(y,x,label='kiwi')
plt.xlabel('graph')
plt.ylabel('kiwi')
plt.legend()
# In[27]:
plt.style.available
# In[32]:
plt.style.use('seaborn')
# In[40]:
get_ipython().run_line_magic('pinfo', 'plt.plot')
# In[42]:
#scatter
# In[49]:
plt.figure(figsize=(5,5))
plt.scatter(x,y,label='graph',marker='o')
plt.scatter(y,x,label='kiwi',marker='^')
plt.xlabel('graph')
plt.ylabel('kiwi')
plt.legend()
# In[50]:
#bar graph
# In[57]:
plt.bar(x,y,width=0.4)
# In[66]:
plt.figure(figsize=(7,5))
x_coordinates=np.array([0,1,2])*2
plt.bar(x_coordinates,[10,20,15],width=0.5,label='Current year',tick_label=['Gold','Platinum','Diamond'])
plt.bar(x_coordinates+0.5,[20,10,12],width=0.5,label='Next year')
plt.legend()
plt.show()
# In[68]:
plt.style.available
# In[71]:
plt.style.use('fivethirtyeight')
plt.figure(figsize=(7,5))
x_coordinates=np.array([0,1,2])*2
plt.bar(x_coordinates,[10,20,15],width=0.5,label='Current year',tick_label=['Gold','Platinum','Diamond'])
plt.bar(x_coordinates+0.5,[20,10,12],width=0.5,label='Next year')
plt.legend()
plt.show()
# In[73]:
#pie
# In[81]:
plt.pie(x,explode=None)
plt.show()
# In[98]:
subjects='Maths','english','hindi','sanskrit'
marks=[20,25,45,64]
plt.pie(marks,labels=subjects,explode=(0,0,0.1,0),shadow=True,counterclock=True,autopct='%1.1f%%')
plt.show()
# In[96]:
get_ipython().run_line_magic('pinfo', 'plt.pie')
# In[99]:
#histogram
# In[118]:
xsn=np.random.randn(100)
sigma=8
u=70
X=np.round(xsn*sigma+u)
X2=np.round(xsn*15+40)
print(X)
# In[112]:
print(xsn)
# In[120]:
plt.style.use('seaborn')
plt.hist(X,alpha=0.8,label='Physics')
plt.hist(X2,alpha=0.9,label="Maths")
# In[ ]:
<file_sep>/Mnist dataset.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# In[5]:
read=pd.read_csv('C:/Users/HP/Desktop/train.csv')
# In[6]:
read.shape
# In[7]:
read.head()
# In[13]:
print(type(read))
# In[37]:
data=read.values
np.random.shuffle(data)
# In[17]:
print(type(data))
# In[18]:
data.shape
# In[19]:
X=data[:,1:]
Y=data[:,0]
# In[20]:
print(X.shape,Y.shape)
# In[21]:
print(X)
# In[23]:
print(Y)
# In[24]:
#to visualise one image
# In[25]:
X[0].shape
# In[40]:
def drawimg(X,Y,i):
plt.imshow(X[i].reshape(28,28),cmap='gray')
plt.title("Label "+str(Y[i]))
plt.show()
for i in range(5):
drawimg(X,Y,i)
# In[34]:
split=int(0.80*X.shape[0])
print(split)
# In[48]:
from sklearn.model_selection import train_test_split
XT,Xt,YT,Yt=train_test_split(X,Y,test_size=0.2,random_state=5)
print(XT.shape,YT.shape)
print(Xt.shape,Yt.shape)
# In[47]:
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.imshow(XT[i].reshape(28,28))
plt.title(YT[i])
plt.axis("off")
# In[ ]:
| 468ef5a7106bbbb6600d015a5795591af09e35c9 | [
"Markdown",
"Python"
] | 6 | Markdown | 11813147ak/Data-science-required-python | 3204de299998ccb43203b585ddf85d3b89d91f42 | c3d89189cd5505d8b27dbf6df87dba96bd2e1da0 | |
refs/heads/master | <file_sep># Uni
My work for uni
<file_sep># Graph coloring
Goal : coloring the vertices of a graph such that no two adjacent vertices are of the same color
Condition : Use lp_solve API with cpp program, take in entry a graph (dimacs format) and resolve it.
<file_sep>package infection;
/**
* Classe qui représente l'intelligence artificielle associée à un joueur Le
* raisonnement se fait avec l'algorithme minMax. Le but est de trouver le
* meilleur coup à jouer en fonction des suivants.
*/
public class IA {
/**
* Définition du joueur qui raisonne, celui pour qui on doit avoir le score
* maximal.
*/
protected int joueurRaisonne;
/**
* Booléan pour utilisation de l'élégage alphabeta
*/
protected boolean cut;
/**
* Nombre d'appels de MinMax ou de Alphabeta
*/
public static long cptAppels = 0;
/**
* Définition de constantes pour les algorithmes qui nécessitent des bornes
* inatteignables.
*/
private static final int MINUS_INFINITE = -10;
private static final int PLUS_INFINITE = 10;
/**
* Constructeur avec paramètre, on associe un joueur à l'IA
*
* @param joueurRaisonne Le joueur auquel on s'intérresse
*/
public IA(int joueurRaisonne, boolean cut) {
this.joueurRaisonne = joueurRaisonne;
this.cut = cut;
}
/**
* Méthode qui permet de trouver le noeud qui donne le plus de chance de gagner.
* On parcours tout le graphe des possibilités en appelant au niveau de
* profondeur 2 l'algorithme minMax. Le meilleur coup est renvoyé.
*
* @param s L'état du plateau courant
* @param profondeur La profondeur de recherche de l'IA
* @return Le Move qui donne le plus de chance de gagner la partie
*/
public Move decide(State s, int profondeur) {
double b = MINUS_INFINITE;
double m = 0;
State snew = null;
Move c = new Move(0, 0, 0, 0, false);
for (Move mv : s.getMoves(s.getCurrentPlayer())) {
snew = s.play(mv);
if (this.cut) {
m = alphabeta(snew, MINUS_INFINITE, PLUS_INFINITE, profondeur - 1);
} else {
m = miniMax(snew, profondeur - 1);
}
if (b < m) {
b = m;
c = mv;
}
}
return c;
}
/**
* Algorithme minMax qui parcours l'ensemble des possibilités de l'arbre de
* recherche et récupère la valeur qui donne le plus de chance de gagner la
* partie pour le joueur qui raisonne.
*
* @param s L'état actuel du plateau
* @param profondeur La profondeur de recherche de l'algorithme
* @return La meilleur valeur de la fonction d'évaluation
*/
private double miniMax(State s, int profondeur) {
IA.cptAppels++;
State snew = null;
double b, m;
// Si le jeu est terminé, on ne peut pas descendre plus bas dans la profondeur
if (profondeur == 0 || s.isFinished()) {
// Score du joueur qui raisonne
return s.getScore(this.joueurRaisonne);
} else {
if (s.getCurrentPlayer() == this.joueurRaisonne) {
b = MINUS_INFINITE;
for (Move mv : s.getMoves(s.getCurrentPlayer())) {
snew = s.play(mv);
m = miniMax(snew, profondeur - 1);
b = b < m ? m : b;
}
} else {
b = PLUS_INFINITE;
for (Move mv : s.getMoves(s.getCurrentPlayer())) {
snew = s.play(mv);
m = miniMax(snew, profondeur - 1);
b = b > m ? m : b;
}
}
return b;
}
}
/**
* Algorithme Alphabeta, version optimisée de MinMax avec élégage des branches
* qui ne rapportent pas de points au joueur. L'arbre des possibilités est
* réduit.
*
* @param s Le plataeu de jeu courant
* @param alpha Valeur minimun pour le joueur qui raisonne
* @param beta Valeur maximum pour le joueur qui raisonne
* @param profondeur Profondeur de recherche de l'algorithme
* @return La valeur du noeud qui apporte le plus au joueur
*/
private double alphabeta(State s, double alpha, double beta, int profondeur) {
IA.cptAppels++;
double m = 0;
if (profondeur == 0 || s.isFinished()) {
return s.getScore(this.joueurRaisonne);
} else {
if (s.currentPlayer == this.joueurRaisonne) {
for (Move mv : s.getMoves(s.currentPlayer)) {
m = this.alphabeta(s.play(mv), alpha, beta, profondeur - 1);
alpha = alpha > m ? alpha : m;
if (alpha >= beta) {
return alpha;
}
}
return alpha;
} else {
for (Move mv : s.getMoves(s.getCurrentPlayer())) {
m = this.alphabeta(s.play(mv), alpha, beta, profondeur - 1);
beta = beta < m ? beta : m;
if (alpha >= beta) {
return beta;
}
}
return beta;
}
}
}
}
<file_sep>package infection;
/**
* Classe représentant un mouvement de pion. La position de départ, la position
* d'arrivée sous forme de coordonnées d'entiers. Le type de mouvement est un
* booléen.
*/
public class Move {
/** Couple position départ */
protected int startX;
protected int startY;
/** Couple position d'arrivée */
protected int endX;
protected int endY;
/**
* Type de mouvement possible du pion :
* <ul>
* <li>True : dupliquer</li>
* <li>false ; déplacement</li>
*/
protected boolean type;
/**
* Constructeur avec paramètres, coordonnées du point de départ et du point
* d'arrivée. Le type est spécifié également.
*
* @param x1 Position x de départ
* @param y1 Position y de départ
* @param x2 Position x d'arrivée
* @param y2 Position y d'arrivée
* @param type Type de mouvement
*/
public Move(int x1, int y1, int x2, int y2, boolean type) {
this.startX = x1;
this.startY = y1;
this.endX = x2;
this.endY = y2;
this.type = type;
}
@Override
public String toString() {
return "(" + this.startX + "," + this.startY + ");(" + this.endX + "," + this.endY + ") : " + this.type + "\n";
}
}
<file_sep># Game and rules
Infection set
It's a board game with two players. A field of m * n squares is empty. Each player (black and white) has a checker in the opposite corners of the board.
Each player plays in turn, one checker can move two squares in the four cardinal directions and into an empty square (even over another checker). Or a checker can duplicate itself in one of the four cardinal positions if no checker is already there. After duplicating, it changes the colour of the pieces that touch it to its own colour. The game is over if one of the two players has no more possible moves, it has run out of checkers, or the board is full.
## Resolution
The algorithm used is that of minimax and alphabeta (pruning of minimax). The search depth is given in the command line.
The score function of a player is the proportion of pieces of his color on the board compared to the total number of pieces.<file_sep>#include <lpsolve/lp_lib.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <math.h>
#include <string>
#include <sstream>
#include <cstdlib>
// g++ Mycielski.cpp -llpsolve55 -lcolamd -ldl -o Mycielski
// ./Mycielski graph.dimacs
// Need lp_solve and liblpsolve55-dev to compile and execute
void vider_row(REAL row[], const int& taille);
int main(int argc, char* argv[])
{
lprec* lp;
int nbNoeuds = 0, nbArcs = 0;
if(argv[1] == nullptr)
{
std::cout << "Fichier graphe en paramètre nécessaire." << std::endl;
exit(EXIT_FAILURE);
}
std::ifstream fichier (argv[1]);
if (!fichier.is_open())
{
std::cout << "Impossible d'ouvrir le fichier du graphe." << std::endl;
exit(EXIT_FAILURE);
}
std::string ligne;
while (getline(fichier, ligne))
{
std::string mot;
std::istringstream iss(ligne);
iss >> mot;
if (mot == "p")
{
iss >> mot;
iss >> mot;
nbNoeuds = stoi(mot);
iss >> mot;
nbArcs = stoi(mot);
break;
}
}
lp = make_lp(0, nbNoeuds*nbNoeuds+nbNoeuds);
REAL row[nbNoeuds*nbNoeuds+nbNoeuds + 1];
vider_row(row, nbNoeuds*nbNoeuds+nbNoeuds+1);
for (int i = 1; i <= (nbNoeuds*nbNoeuds+nbNoeuds); i++)
{
row[i] = 1.0;
set_int(lp, i, true);
add_constraint(lp, row, GE, 0);
add_constraint(lp, row, LE, 1);
row[i] = 0.0;
}
for (int i = 0; i < nbNoeuds; i++)
{
for (int j = 0; j < nbNoeuds; j++)
{
row[i*nbNoeuds+j+1] = 1.0;
}
add_constraint(lp, row, EQ, 1);
vider_row(row, nbNoeuds*nbNoeuds+nbNoeuds+1);
}
while (getline(fichier, ligne))
{
std::string mot;
std::istringstream iss(ligne);
iss >> mot;
if (mot == "e")
{
iss >> mot;
int premierNode = stoi(mot);
iss >> mot;
int secondNode = stoi(mot);
for (int i = 1; i <= nbNoeuds; i++)
{
row[premierNode*nbNoeuds-nbNoeuds+i] = 1.0;
row[secondNode*nbNoeuds-nbNoeuds+i] = 1.0;
row[(nbNoeuds*nbNoeuds+1)+i] = -1.0;
add_constraint(lp, row, LE, 0);
vider_row(row, nbNoeuds*nbNoeuds+nbNoeuds+1);
}
}
}
for (int i = 0; i < nbNoeuds; i++)
{
row[nbNoeuds*nbNoeuds+i+1] = 1.0;
}
set_obj_fn(lp, row);
vider_row(row, nbNoeuds*nbNoeuds+nbNoeuds+1);
if (solve(lp) != 0)
{
fprintf(stderr, "INFEASIBLE\n");
return(1);
}
else
{
get_variables(lp, row);
int cptCol = 0;
for (int i = 0; i < nbNoeuds ; i++)
{
for (int j = 1; j < nbNoeuds; j++)
{
cptCol++;
if(row[i*nbNoeuds+j] == 1) {break;};
}
std::cout << "Noeud" << (i+1) << ", couleur :" << cptCol << std::endl;
cptCol = 0;
}
print_objective(lp);
}
return(0);
}
void vider_row(REAL row[], const int& taille)
{
for (int i = 0; i < taille; i++)
{
row[i] = 0.0;
}
}
| 107f5fa94f258360413d1348d230e8d9ecde9573 | [
"Markdown",
"Java",
"C++"
] | 6 | Markdown | Fimeo/Uni | cbb1fcade149f24fc39de8ead0ee3f8dd5a3bba5 | ce3401ecc1c868d3ec70eceb28155b0c963687df | |
refs/heads/development | <repo_name>BootcampersCollective/slackbot-project<file_sep>/charlieBot/scripts/list-slack-channels.js
// Description:
// Example scripts for you to examine and try out.
// commands:
var authKey = require('../../authKey.js')
module.exports = function (robot) {
// robot.hear(/bootcampers/i, function (res) {
// res.send("It's going");
// });
robot.respond(/list channels/i, function (res) {
var slackURL = "https://slack.com/api/channels.list?token=" + authKey.authKey
robot.http(slackURL)
.header('Content-Type', 'application/x-www-form-urlencoded')
.get()(function (err, response, body) {
if (err) {
robot.logger.info(err)
res.send("Something went wrong")
} else if (response.statusCode === 200) {
var data = JSON.parse(body);
for (var i = 0; i < data.channels.length; i++) {
res.send("*" + data.channels[i].name+ "*" + ": " + data.channels[i].purpose.value);
}
robot.logger.info(data.channels);
// res.send(JSON.stringify(data));
} else {
robot.logger.info(body + response.statusCode)
res.send("Something went wrong")
}
});
});
};
<file_sep>/README.md
[](https://waffle.io/BootcampersCollective/slackbot-project?utm_source=badge)
# slackbot-project
Repository for the BCC Slackbot Project.
## Contributing
* To initially begin working on the project, you'll need to first reach out to <NAME> on [Slack](https://bootcamperscollective.com) to be added to the team.
* Once you have been added to the team, clone the repository to your machine.
- git clone <insert URL>
* Finally, to begin working on a particular issue, you'll need to branch off of the development branch, write the code to solve the issue, then submit a PR into the development branch. You should use the naming convention [issue-number]-[page]-[quick description].
- git checkout -b [new branch name]
* Once you have finished building a feature, you will need to submit a PR to the development branch and add <NAME> to review.
- git push origin [branch name]
- On code page of repo, you can submit PR.
- Please check the issues page at [waffle.io](https://waffle.io/BootcampersCollective/slackbot-project/join)
## Technologies Used:
<file_sep>/charlieBot/scripts/joeysTest.js
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
module.exports = function(robot) {
robot.hear(/meetups/i, function(res) {
robot.http("https://api.meetup.com/Bootcampers-Collective/events?&sign=true&photo-host=public&page=20")
.header('Accept', 'application/json')
.get()(function(err, response, body) {
// error checking code here
if (err){
res.send('done fucked up')
robot.logger.info(err)
}
else if(response.statusCode === 200){
const data = JSON.parse(body);
for(var i=0; i < 5; i++){
res.send(data[i].name + ' : ' + data[i].link);
}
robot.logger.info(body);
} else {
res.send('done fucked up')
robot.logger.info(response.statusCode + body)
}
})
});
};
| 1d787b6f65088352992a13d5afdfe2def5f3c4d0 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | BootcampersCollective/slackbot-project | 416e059ab395ea9ae1d544eae49818125815a75d | bee28efd2300751e230faf63779666ead78ca205 | |
refs/heads/master | <file_sep>package com.superexercisebook.bugreport.okhttp.framework;
import okhttp3.*;
import java.io.IOException;
import java.util.Objects;
public class JavaHttpClient {
public String test(String s) {
OkHttpClient client = new OkHttpClient();
String url = "https://one.one.one.one/cdn-cgi/trace";
RequestBody body = RequestBody.create(MediaType.parse("plain/text; charset=utf-8"), s);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
return Objects.requireNonNull(response.body()).string();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
<file_sep>plugins {
id 'org.springframework.boot'
id 'io.spring.dependency-management'
id 'java'
id 'org.jetbrains.kotlin.jvm'
}
group = 'com.superexercisebook'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
// Kotlin Support
compile "org.jetbrains.kotlin:kotlin-reflect"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
api project(path: ':framework')
}
test {
useJUnitPlatform()
}
compileKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
<file_sep>package com.superexercisebook.bugreport.okhttp.framework
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
class KotlinHttpClient {
fun test(s: String): String {
val client = OkHttpClient()
val url = "https://one.one.one.one/cdn-cgi/trace"
val body: RequestBody = s.toRequestBody("plain/text; charset=utf-8".toMediaTypeOrNull())
val request: Request = Request.Builder()
.url(url)
.post(body)
.build()
client.newCall(request).execute().use { response ->
return response.body!!.string()
}
}
}
<file_sep>plugins {
id 'org.springframework.boot' version '2.4.5'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.5.0'
id 'maven-publish'
id "org.springframework.boot.experimental.thin-launcher" version "1.0.25.RELEASE"
}
subprojects {
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
}
group 'com.marigold'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
publishing {
publications {
maven(MavenPublication) {
from components.java
}
}
}
<file_sep># An issue in OkHttp Kotlin
## build
Use IDEA to run the `Application.kt` file.
## Description
### Dependency Graph
```
OkHttp -> Framework -> Project
```
In this case, we can assume that framework prepares some commonly used OkHttp operations for every module in the whole project.
### What Happened
#### `framework` module
In module `framework`, we can run all the OkHttp operations successfully.
But we can't compile `MediaType.parse("plain/text; charset=utf-8")` in the main function, because the code of OkHttp blocked it.
```
@JvmName("-deprecated_parse")
@Deprecated(
message = "moved to extension function",
replaceWith = ReplaceWith(
expression = "mediaType.toMediaTypeOrNull()",
imports = ["okhttp3.MediaType.Companion.toMediaTypeOrNull"]),
level = DeprecationLevel.ERROR) // <------- this line
fun parse(mediaType: String): MediaType? = mediaType.toMediaTypeOrNull()
```
#### `project` module
In module `project`, we can only run the OkHttp operation which is written by java in `framework` successfully.
But we can compile `MediaType.parse("plain/text; charset=utf-8")` in the main function.
## Something I guess
In `framework` module, `@Deprecated` blocks this kind of usage, but `@JvmStatic @JvmName` let the function below visible to `project`.
```
@JvmStatic
@JvmName("parse")
fun String.toMediaTypeOrNull(): MediaType? {
return try {
toMediaType()
} catch (_: IllegalArgumentException) {
null
}
}
```
We can use `MediaType.parse("plain/text; charset=utf-8")` in `project` module.
Because of the same reason. `@JvmStatic @JvmName` let `okhttp3.MediaType.Companion.toMediaTypeOrNull` become `okhttp3.MediaType.parse`.
We can see an `Exception in thread "main" java.lang.NoSuchFieldError: Companion` error when running main function of `project` module.
## Conclusion
I am not sure what this issue blame to, but I prefer to change the `DepreciationLevel` to a lower level to resolve this issue temporary.<file_sep>package com.superexercisebook.bugreport.okhttp.framework
import okhttp3.MediaType
object Application {
@JvmStatic
fun main(args : Array<String>) {
// Succeed
println(JavaHttpClient().test("test"))
// Success
println(KotlinHttpClient().test("test"))
// Blocked by @Deprecated annotation
// MediaType.parse("plain/text; charset=utf-8")
}
}
<file_sep>pluginManagement {
repositories {
maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
mavenCentral()
maven { url 'https://plugins.gradle.org/m2/' }
}
}
rootProject.name = 'Server'
include ':framework'
include ':project'
project(':framework').projectDir = "$rootDir/framework" as File
project(':project').projectDir = "$rootDir/project" as File
| a245b87b5b98e31da1f5a1acdc785983d6a0eee5 | [
"Markdown",
"Java",
"Kotlin",
"Gradle"
] | 7 | Java | ExerciseBook/okhttp-issue-in-kotlin | 1707c92ff1dcc56a3cc241616dbb0e89e30503cb | 251868d9a1c2488c3e0eb290e15b14d6d33057ce | |
refs/heads/master | <file_sep>from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras.applications.vgg16 import VGG16
from keras.applications.inception_v3 import InceptionV3
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np
import h5py
from keras.models import load_model
def create_model(model):
print("Loading Keras model from a h5 file.")
model_folder = "keras_frozen/"
if model == "alexnet":
return load_model(model_folder + "keras_alexnet.h5", compile=False)
elif model == "vgg":
return load_model(model_folder + "keras_vgg.h5", compile=False)
elif model == "inception":
return load_model(model_folder + "keras_inception.h5", compile=False)
elif model == "resnet":
return load_model(model_folder + "keras_resnet.h5", compile=False)
else:
raise RuntimeError("No such model exists: " + str(model))
def create_model_old(model):
if model == "alexnet":
return create_model_alex()
elif model == "vgg":
return create_model_vgg16()
elif model == "inception":
return create_model_inception_v3()
elif model == "resnet":
return create_model_resnet50()
else:
raise RuntimeError("No such model exists: " + str(model))
# AlexNet with batch normalization in Keras
# input image is 224x224
def create_model_alex():
model = Sequential()
# FEATURES
model.add(Convolution2D(filters=64, kernel_size=11, strides=(4, 4),
padding="same", input_shape=(224, 224, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=2))
model.add(Convolution2D(filters=192, kernel_size=5, padding="same"))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=2))
model.add(Convolution2D(filters=384, kernel_size=3, padding="same"))
model.add(Activation('relu'))
model.add(Convolution2D(filters=256, kernel_size=3, padding="same"))
model.add(Activation('relu'))
model.add(Convolution2D(filters=256, kernel_size=3, padding="same"))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=2))
# CLASSIFIER
model.add(Flatten())
# model.add(Dropout(0.5))
model.add(Dense(4096, kernel_initializer="normal", use_bias=True))
model.add(Activation('relu'))
# model.add(Dropout(0.5))
model.add(Dense(4096, kernel_initializer="normal", use_bias=True))
model.add(Activation('relu'))
model.add(Dense(1000, kernel_initializer="normal", use_bias=True))
# model.add(Activation('softmax'))
print(model.summary())
return model
def create_model_vgg16():
model = VGG16(weights='imagenet', include_top=True)
print(model.summary())
return model
def create_model_resnet50():
model = ResNet50(weights='imagenet', include_top=True)
print(model.summary())
return model
def create_model_inception_v3():
model = InceptionV3(weights='imagenet', include_top=True)
print(model.summary())
return model
<file_sep>#!/bin/bash
# Basic range in for loop
for value in $(seq 1 10)
do
echo $value
python throughput.py --framework keras --num_batches 10000 --batch_size $value --model alexnet
done
echo All done
<file_sep>#!/bin/bash
# Basic range in for loop
for value in $(seq 1 10); do
for frameworkName in keras torch; do
for convNet in resnet vgg inception; do
python throughput.py --framework $frameworkName --num_batches 10000 --batch_size $value --model $convNet
done
done
done
for value in $(seq 7 10); do
for frameworkName in tf; do
for convNet in resnet vgg inception; do
python throughput.py --framework $frameworkName --num_batches 10000 --batch_size $value --model $convNet
done
done
done
echo All done
<file_sep>import tensorflow as tf
import _thread as thread
import rpyc
from concurrent.futures import ThreadPoolExecutor
from rpyc.utils.server import ThreadedServer
import queue
import time
from torch.autograd import Variable
from skimage import io
import argparse
import random
import os
from utils import round_ms,get_image_size
import cProfile, pstats, io as io2
from numpy import prod
import numpy as np
BATCH_SIZE = 4
BATCH_TIMEOUT = 0.1
FRAMEWORK = ""
MODEL = "alexnet"
tpe_in = ThreadPoolExecutor(max_workers=8)
#tpe_out = tpe
tpe_out = ThreadPoolExecutor(max_workers=None)
image_queue = queue.Queue()
time_q = queue.Queue()
total_latency = 0.0
count_lat = 0
total_done = 0
total_classification_time = 0
classification_batches = 0
global classify, t1
graph = None
def generate_dummy_images(fw, batch_size, image_size):
if fw in {"torch", "pytorch"}:
images = np.random.randint(256, size=(batch_size, 3, image_size, image_size)) / 255.
elif fw in {"tensorflow", "tf", "keras"}:
images = np.random.randint(256, size=(batch_size, image_size, image_size, 3)) / 255.
else:
raise RuntimeError("Mock images not defined for framework: " + str(fw))
print("Images shape", images.shape)
return images.astype(np.float32)
def prepare_keras(model):
print("Preparing Keras")
import models_keras
global net, graph
net = models_keras.create_model(model)
# net.save('keras_alex2.h5')
# print("Saved")
graph = tf.get_default_graph()
# Easiest way to make the model build and compute the prediction function
net.predict(np.random.randint(0, 256, size=(1, 224, 224, 3), dtype=np.uint8))
# net.build()
# net.model._make_predict_function()
def keras_classify(imgs):
global graph
with graph.as_default():
imgs = np.stack(imgs, axis=0)
# try:
res = net.predict(imgs)
# except Exception as e:
# print(e)
# print(res)
output = res.argmax(axis=1)
# print(output)
return output
def prepare_torch(model):
global torch
global torchvision
import torch
import torchvision
print("Preparing Torch")
global net
model_file = "torch_frozen/torch_" + str(model) + ".out"
net = torch.load(model_file)
# if model == "alexnet":
# from torch_models.torch_alexnet import alexnet
# net = alexnet(pretrained=True) # works
# elif model == "vgg":
# from torch_models.torch_vgg import vgg16
# net = vgg16(pretrained=True) # works
# elif model == "inception":
# from torch_models.torch_inception import inception_v3
# net = inception_v3(pretrained=True) # 299 x 299 x 3
# elif model == "resnet":
# from torch_models.torch_resnet import resnet50
# net = resnet50(pretrained=True) # works
net.cuda()
print(net)
image_size = get_image_size(model)
# Generate one dummy img.
images = generate_dummy_images("torch", 1, image_size)
net.forward(Variable(torch.from_numpy(images)).cuda())
def torch_classify(imgs):
transform = torchvision.transforms.ToTensor()
img_data = list(map(lambda x: Variable(transform(x)).cuda(), imgs))
# print(img_data)
# print("Batch", batch)
batch = torch.stack(img_data)
try:
output = net.forward(batch)
except Exception as e:
print("Torch_classify failed, err: " + str(e))
# print("Output", output)
max_val, max_index = torch.max(output, 1)
output = max_index.cpu().data.numpy()
return output
def load_frozen_tensorflow_graph(model):
model_file = "tf_frozen/"
if model == "alexnet":
# model_file += "tf_alexnetOP.pb"
model_file += "tf_alex.pb"
elif model == "vgg":
model_file += "tf_vgg.pb"
elif model == "inception":
model_file += "tf_inception.pb"
elif model == "resnet":
model_file += "tf_resnet.pb"
print("TF model file", model_file)
with tf.gfile.GFile(model_file, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def, name="main")
return graph
def prepare_tf(model):
print("Preparing TensorFlow")
from alexnet_tf import alexnet_inference
global fnames, enq_op, prob, main_sess, images_placeholder, g, g_input, g_output
g = load_frozen_tensorflow_graph(model)
#for op in g.get_operations():
# print(op.name, op.type)
input_tensor_name = g.get_operations()[0].name + ":0"
output_tensor_name = g.get_operations()[-1].name + ":0"
print(input_tensor_name, "<->", output_tensor_name)
with g.as_default():
g_input = g.get_tensor_by_name(input_tensor_name)
g_output = g.get_tensor_by_name(output_tensor_name)
# g_input = tf.placeholder(tf.uint8, shape=(None, 224, 224, 3))
#
# img_batch_float = tf.cast(g_input, tf.float32)
# img_batch_float = tf.map_fn(tf.image.per_image_standardization, img_batch_float)
# img_batch_float = tf.map_fn(lambda frame: tf.clip_by_value(frame, -1.0, 1.0), img_batch_float)
# g_output, __ = alexnet_inference(img_batch_float)
# image_batch = tf.stack(images)
# print(image_batch) #/image_batch.dtype)
# prob, __ = vgg_16(img_batch_float)
# print(main_sess.run(prob))
init_global = tf.global_variables_initializer()
main_sess = tf.Session(graph=g)
main_sess.run(init_global)
image_size = get_image_size(model)
dummy_images = generate_dummy_images("tf", BATCH_SIZE, image_size)
main_sess.run(g_output, feed_dict={g_input: dummy_images})
def tf_classify(imgs):
global g, g_input, g_output
# img_data = np.empty(shape=(len(imgs), 224, 224, 3))
# for i, img in enumerate(imgs):
# print(img)
# img_data[i] = img
imgs = np.stack(imgs, axis=0)
result = main_sess.run(g_output, feed_dict={g_input: imgs})
# print(result)
return result.argmax(axis=1)
def mock_classify(raw_images):
def get_random_num(raw_img):
return random.randint(0, 1000)
return list(map(get_random_num, raw_images))
class MyService(rpyc.Service):
def __init__(self, conn):
super().__init__(conn)
print("MASTER INIT")
def on_connect(self):
print("Executive connected", thread.get_ident())
def on_disconnect(self):
global total_latency, count_lat
print("Executive has disconnected...")
print("count_lat=", count_lat)
print("Avg latency server side (ms)", round_ms(total_latency / count_lat))
def exposed_RemoteCallbackTest(self, raw_img, callback):
img = np.fromstring(raw_img, dtype=np.uint8)
elems = int(img.shape[0])
dim = int((elems / 3) ** 0.5)
img = img.reshape(dim, dim, 3)
image_queue.put((img, callback))
t = time.time()
# print("GOT", round_ms(t) % 10000)
time_q.put(t)
def parse_arguments():
global BATCH_SIZE, FRAMEWORK, BATCH_TIMEOUT, MODEL
parser = argparse.ArgumentParser()
parser.add_argument("-b", "--batch_size", help="batch_size", type=int)
parser.add_argument("-t", "--timeout", help="timeout for batch", type=float)
parser.add_argument("-f", "--framework", help="framework")
parser.add_argument("-m", "--model", help="convnet model")
args = parser.parse_args()
if args.batch_size is not None:
BATCH_SIZE = args.batch_size
if args.framework is not None:
FRAMEWORK = args.framework
if args.timeout is not None:
BATCH_TIMEOUT = args.timeout
if args.model is not None:
if args.model.startswith("vgg"):
MODEL = "vgg"
elif args.model.startswith("incep"):
MODEL = "inception"
elif args.model.startswith("res"):
MODEL = "resnet"
else:
MODEL = "alexnet"
print("Model:", MODEL)
print("Batch sizes:", BATCH_SIZE)
print("Batch timeout:", BATCH_TIMEOUT)
def run_job_batcher():
batch_size = BATCH_SIZE
last_batch_time = None
# TODO - now first batch always full
while True:
if image_queue.qsize() >= batch_size:
last_batch_time = time.time()
process_and_return(batch_size)
elif image_queue.qsize() and last_batch_time and (time.time() - last_batch_time) >= BATCH_TIMEOUT:
last_batch_time = time.time()
print("Timed out")
process_and_return(image_queue.qsize())
else:
time.sleep(0)
def process_and_return(batch_size):
global total_classification_time, classification_batches
inputs = [None] * batch_size
callbacks = [None] * batch_size
for i in range(batch_size):
inputs[i], callbacks[i] = image_queue.get()
classify_start = time.time()
# pr.enable()
# THE CLASSIFICATION
try:
outputs = classify(inputs)
except Exception as e:
print("Classification error:", e)
# pr.disable()
classify_time = time.time() - classify_start
total_classification_time += classify_time
classification_batches += 1
if not classification_batches % 20:
print("batch=" + str(batch_size) +
", took (ms) " + str(round_ms(classify_time)) +
", avg (ms) " + str(round_ms(total_classification_time / classification_batches)))
# s = io2.StringIO()
# ps = pstats.Stats(pr, stream=s).sort_stats("cumulative")
# ps.print_stats()
# print(s.getvalue())
for i in range(batch_size):
#send_response(callbacks[i], outputs[i])
tpe_out.submit(send_response, callbacks[i],outputs[i])
def send_response(callback, result):
global total_latency, count_lat, total_done
curr_latency = time.time() - time_q.get()
total_done += 1
if total_done > 50:
count_lat += 1
total_latency += curr_latency
#print("S",end="")
callback(result)
def prepare_framework():
global classify
if FRAMEWORK == "tf" or FRAMEWORK == "tensorflow":
prepare_tf(MODEL)
classify = tf_classify
print("Using TensorFlow")
elif FRAMEWORK == "torch" or FRAMEWORK == "pytorch":
prepare_torch(MODEL)
classify = torch_classify
print("Using PyTorch")
elif FRAMEWORK == "keras":
prepare_keras(MODEL)
classify = keras_classify
print("Using Keras")
else:
classify = mock_classify
print("using MOCK framework")
if __name__ == '__main__':
pr = cProfile.Profile()
parse_arguments()
prepare_framework()
my_service = ThreadedServer(MyService, port=1200,
protocol_config={"allow_public_attrs": True})
print("Waiting for a connection...")
tpe_in.submit(run_job_batcher)
my_service.start()
<file_sep>
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
#from memory_profiler import profile
import argparse
import cProfile
import io as io2
import math
import pstats
import sys
import time
from datetime import datetime
import numpy as np
import tensorflow as tf
import torch
from keras import backend as K
from six.moves import xrange
from tensorflow.python.client import timeline
from torch.autograd import Variable
from utils import get_image_size, round_ms
FLAGS = None
g = None
run_metadata = tf.RunMetadata()
options = None
prep_start = 0
def prepare_torch(model):
print("Preparing Torch")
global net
model_file = "torch_frozen/torch_" + str(model) + ".out"
net = torch.load(model_file)
if torch.cuda.is_available():
net.cuda()
# torch.set_num_threads(4)
# print(net)
def torch_classify(imgs, opts=None, run_md=None):
batch = Variable(torch.from_numpy(imgs), requires_grad=False)
if torch.cuda.is_available():
r = net.forward(batch.cuda())
r.cpu()
else:
net.forward(batch)
def prepare_keras(model):
print("Preparing Keras")
import models_keras
global net, graph
net = models_keras.create_model(model)
net.summary()
graph = tf.get_default_graph()
keras_session = K.get_session()
# old_run = keras_session.run
# print("old_run", old_run)
# print("K.sess 1", keras_session)
#
# def new_run(*args, **kwargs):
# # print("X", self)
# print("NewRunning", *args)
# old_run(*args, **kwargs)
# keras_session.run = new_run
def keras_classify(imgs, opts=None, run_md=None):
global graph
with graph.as_default():
net.predict(imgs)
def prepare_tf(model):
print("Preparing TensorFlow")
global main_sess, images_placeholder, g, g_input, g_output
g = load_frozen_tensorflow_graph(model)
input_tensor_name = g.get_operations()[0].name + ":0"
if model in {"alexnet"}:
output_tensor_name = "dense_3/BiasAdd:0"
else:
output_tensor_name = g.get_operations()[-1].name + ":0"
print("I:", input_tensor_name)
print("O:", output_tensor_name)
with g.as_default():
g_input = g.get_tensor_by_name(input_tensor_name)
g_output = g.get_tensor_by_name(output_tensor_name)
init_global = tf.global_variables_initializer()
config = tf.ConfigProto()
# Not relevant for non-GPU
# config.gpu_options.allocator_type = 'BFC'
main_sess = tf.Session(graph=g, config=config)
main_sess.run(init_global)
def load_frozen_tensorflow_graph(model):
global main_sess, g
# saver = tf.train.import_meta_graph('./tmp/model.ckpt-55695.meta')
# saver.restore(session, './tmp/model.ckpt-55695')
model_file = "./tf_frozen/" if model in {"alexnet"} else "tf_frozen/"
if model == "alexnet":
model_file += "tf_alexnet.ckpt"
with tf.Graph().as_default() as g, tf.Session() as sess:
saver = tf.train.import_meta_graph(model_file + ".meta")
saver.restore(sess, model_file)
print("TF model file", model_file)
else:
if model == "vgg":
model_file += "tf_vgg.pb"
elif model == "inception":
model_file += "tf_inception.pb"
elif model == "resnet":
model_file += "tf_resnet.pb"
print("TF model file", model_file)
with tf.gfile.GFile(model_file, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as g:
tf.import_graph_def(graph_def, name="main")
return g
def tf_classify(imgs, opts=None, run_md=None):
main_sess.run(g_output, options=opts, run_metadata=run_md, feed_dict={g_input: imgs})
def time_run(info_string, imgs, fw, model):
global run_inference, run_metadata, prep_start
"""Run the computation and print timing stats.
Args:
session: the TensorFlow session to run the computation under.
target: the target Tensor that is passed to the session's run() function.
info_string: a string summarizing this run, to be printed with the stats.
Returns:
None
"""
num_steps_burn_in = 25
total_duration = 0.0
total_duration_squared = 0.0
durs = []
for i in xrange(FLAGS.num_batches + num_steps_burn_in):
start_time = time.time()
run_inference(imgs)
duration = time.time() - start_time
if i >= num_steps_burn_in:
if not i % 50:
print('%s: step %d, duration = %.3f' %
(datetime.now(), i - num_steps_burn_in, duration))
total_duration += duration
total_duration_squared += duration * duration
durs.append(duration)
if i == 0:
print(datetime.now(), "Classified first batch, time since start (ms): ",
int(round_ms(time.time() - prep_start)))
mn = total_duration / FLAGS.num_batches
vr = total_duration_squared / FLAGS.num_batches - mn * mn
sd = math.sqrt(vr)
batches_per_second = 1.0 / mn
images_per_second = batches_per_second * FLAGS.batch_size
#durs
durs50 = np.percentile(durs,50)
durs75 = np.percentile(durs,75)
durs90 = np.percentile(durs,90)
durs99 = np.percentile(durs,99)
print('%s: %s across %d steps (WALL TIME), %.4f +/- %.4f sec / batch' %
(datetime.now(), info_string, FLAGS.num_batches, mn, sd))
print('%s: PERCENTILES - 50: %.4f, 75: %.4f, 90: %.4f sec/batch' %
(datetime.now(), durs50, durs75, durs90))
print('%s: 99LAT - %.4f s/batch, THROUGHPUT (IPS) - %.3f' % (datetime.now(), durs99, images_per_second))
result_file = ("tp_logs/" + str(fw) + "_" + str(model) + "_b" + str(FLAGS.batch_size) + "_num" +
str(FLAGS.num_batches) + "_" + datetime.now().strftime("%m%d_%H%M%S") + ".out")
with open(result_file, "w") as f:
f.write("Framework\t" + str(fw) + "\n")
f.write("Model____\t" + str(model) + "\n")
f.write("Bsize____\t" + str(FLAGS.batch_size) + "\n")
f.write("TP (Img/s)\t%.2f\n" % (images_per_second))
f.write("99pct LAT\t%.4f\n" % (durs99))
f.write("90pct LAT\t%.4f\n" % (durs90))
f.write("\n75pct LAT\t%.4f\n" % (durs75))
f.write("50pct LAT\t%.4f\n "% (durs50))
def generate_dummy_images(fw, batch_size, image_size):
if fw in {"torch", "pytorch"}:
images = np.random.randint(256, size=(batch_size, 3, image_size, image_size)) / 255.
elif fw in {"tensorflow", "tf", "keras"}:
images = np.random.randint(256, size=(batch_size, image_size, image_size, 3)) / 255.
else:
raise RuntimeError("Mock images not defined for framework: " + str(fw))
print("Images shape", images.shape)
return images.astype(np.float32)
def run_benchmark(fw, model):
global g
if fw in {"keras"}:
g = g or tf.get_default_graph()
image_size = get_image_size(model)
# Generate some dummy images.
images = generate_dummy_images(fw, FLAGS.batch_size, image_size)
info_string = str(fw) + ", " + str(model) + ", batch_size " + str(FLAGS.batch_size) + " |"
time_run(info_string, images, fw, model)
def prepare_benchmark(fw, model):
global run_inference
print("Params: ", fw, "running", model)
if fw in {"tensorflow", "tf"}:
prepare_tf(model)
run_inference = tf_classify
elif fw in {"pytorch", "torch"}:
prepare_torch(model)
run_inference = torch_classify
elif fw in {"keras"}:
prepare_keras(model)
run_inference = keras_classify
else:
raise RuntimeError("No framework with this name")
def main(_):
pr = cProfile.Profile()
global prep_start
model = FLAGS.model.lower()
framework = FLAGS.framework.lower()
prep_start = time.time()
# pr.enable()
prepare_benchmark(framework, model)
# pr.disable()
run_benchmark(framework, model)
def get_argument_parser():
global parser
parser = argparse.ArgumentParser()
parser.add_argument(
'--batch_size',
type=int,
default=1,
help='Batch size.'
)
parser.add_argument(
'--num_batches',
type=int,
default=1000,
help='Number of batches to run.'
)
parser.add_argument(
'--framework',
type=str,
default="tensorflow",
help='Framework to use'
)
parser.add_argument(
'--model',
type=str,
default="alexnet",
help='ConvNet model to use'
)
return parser
if __name__ == '__main__':
parser = get_argument_parser()
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
__weights_dict = dict()
def load_weights(weight_file):
if weight_file == None:
return
try:
weights_dict = np.load(weight_file).item()
except:
weights_dict = np.load(weight_file, encoding='bytes').item()
return weights_dict
class KitModel(nn.Module):
def __init__(self, weight_file):
super(KitModel, self).__init__()
global __weights_dict
__weights_dict = load_weights(weight_file)
self.block1_conv1 = self.__conv(2, name='block1_conv1', in_channels=3, out_channels=64, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.block1_conv2 = self.__conv(2, name='block1_conv2', in_channels=64, out_channels=64, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.block2_conv1 = self.__conv(2, name='block2_conv1', in_channels=64, out_channels=128, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.block2_conv2 = self.__conv(2, name='block2_conv2', in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.block3_conv1 = self.__conv(2, name='block3_conv1', in_channels=128, out_channels=256, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.block3_conv2 = self.__conv(2, name='block3_conv2', in_channels=256, out_channels=256, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.block3_conv3 = self.__conv(2, name='block3_conv3', in_channels=256, out_channels=256, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.block4_conv1 = self.__conv(2, name='block4_conv1', in_channels=256, out_channels=512, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.block4_conv2 = self.__conv(2, name='block4_conv2', in_channels=512, out_channels=512, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.block4_conv3 = self.__conv(2, name='block4_conv3', in_channels=512, out_channels=512, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.block5_conv1 = self.__conv(2, name='block5_conv1', in_channels=512, out_channels=512, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.block5_conv2 = self.__conv(2, name='block5_conv2', in_channels=512, out_channels=512, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.block5_conv3 = self.__conv(2, name='block5_conv3', in_channels=512, out_channels=512, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.fc1 = self.__dense(name = 'fc1', in_features = 25088, out_features = 4096, bias = True)
self.fc2 = self.__dense(name = 'fc2', in_features = 4096, out_features = 4096, bias = True)
self.predictions = self.__dense(name = 'predictions', in_features = 4096, out_features = 1000, bias = True)
def forward(self, x):
block1_conv1_pad = F.pad(x, (1, 1, 1, 1))
block1_conv1 = self.block1_conv1(block1_conv1_pad)
block1_conv1_activation = F.relu(block1_conv1, inplace=True)
block1_conv2_pad = F.pad(block1_conv1_activation, (1, 1, 1, 1))
block1_conv2 = self.block1_conv2(block1_conv2_pad)
block1_conv2_activation = F.relu(block1_conv2, inplace=True)
block1_pool = F.max_pool2d(block1_conv2_activation, kernel_size=(2, 2), stride=(2, 2))
block2_conv1_pad = F.pad(block1_pool, (1, 1, 1, 1))
block2_conv1 = self.block2_conv1(block2_conv1_pad)
block2_conv1_activation = F.relu(block2_conv1, inplace=True)
block2_conv2_pad = F.pad(block2_conv1_activation, (1, 1, 1, 1))
block2_conv2 = self.block2_conv2(block2_conv2_pad)
block2_conv2_activation = F.relu(block2_conv2, inplace=True)
block2_pool = F.max_pool2d(block2_conv2_activation, kernel_size=(2, 2), stride=(2, 2))
block3_conv1_pad = F.pad(block2_pool, (1, 1, 1, 1))
block3_conv1 = self.block3_conv1(block3_conv1_pad)
block3_conv1_activation = F.relu(block3_conv1, inplace=True)
block3_conv2_pad = F.pad(block3_conv1_activation, (1, 1, 1, 1))
block3_conv2 = self.block3_conv2(block3_conv2_pad)
block3_conv2_activation = F.relu(block3_conv2, inplace=True)
block3_conv3_pad = F.pad(block3_conv2_activation, (1, 1, 1, 1))
block3_conv3 = self.block3_conv3(block3_conv3_pad)
block3_conv3_activation = F.relu(block3_conv3, inplace=True)
block3_pool = F.max_pool2d(block3_conv3_activation, kernel_size=(2, 2), stride=(2, 2))
block4_conv1_pad = F.pad(block3_pool, (1, 1, 1, 1))
block4_conv1 = self.block4_conv1(block4_conv1_pad)
block4_conv1_activation = F.relu(block4_conv1, inplace=True)
block4_conv2_pad = F.pad(block4_conv1_activation, (1, 1, 1, 1))
block4_conv2 = self.block4_conv2(block4_conv2_pad)
block4_conv2_activation = F.relu(block4_conv2, inplace=True)
block4_conv3_pad = F.pad(block4_conv2_activation, (1, 1, 1, 1))
block4_conv3 = self.block4_conv3(block4_conv3_pad)
block4_conv3_activation = F.relu(block4_conv3, inplace=True)
block4_pool = F.max_pool2d(block4_conv3_activation, kernel_size=(2, 2), stride=(2, 2))
block5_conv1_pad = F.pad(block4_pool, (1, 1, 1, 1))
block5_conv1 = self.block5_conv1(block5_conv1_pad)
block5_conv1_activation = F.relu(block5_conv1, inplace=True)
block5_conv2_pad = F.pad(block5_conv1_activation, (1, 1, 1, 1))
block5_conv2 = self.block5_conv2(block5_conv2_pad)
block5_conv2_activation = F.relu(block5_conv2, inplace=True)
block5_conv3_pad = F.pad(block5_conv2_activation, (1, 1, 1, 1))
block5_conv3 = self.block5_conv3(block5_conv3_pad)
block5_conv3_activation = F.relu(block5_conv3, inplace=True)
block5_pool = F.max_pool2d(block5_conv3_activation, kernel_size=(2, 2), stride=(2, 2))
flatten = block5_pool.view(block5_pool.size(0), -1)
fc1 = self.fc1(flatten)
fc1_activation = F.relu(fc1, inplace=True)
fc2 = self.fc2(fc1_activation)
fc2_activation = F.relu(fc2, inplace=True)
predictions = self.predictions(fc2_activation)
predictions_activation = F.softmax(predictions,dim=1)
return predictions_activation
@staticmethod
def __conv(dim, name, **kwargs):
if dim == 1: layer = nn.Conv1d(**kwargs)
elif dim == 2: layer = nn.Conv2d(**kwargs)
elif dim == 3: layer = nn.Conv3d(**kwargs)
else: raise NotImplementedError()
layer.state_dict()['weight'].copy_(torch.from_numpy(__weights_dict[name]['weights']))
if 'bias' in __weights_dict[name]:
layer.state_dict()['bias'].copy_(torch.from_numpy(__weights_dict[name]['bias']))
return layer
@staticmethod
def __dense(name, **kwargs):
layer = nn.Linear(**kwargs)
layer.state_dict()['weight'].copy_(torch.from_numpy(__weights_dict[name]['weights']))
if 'bias' in __weights_dict[name]:
layer.state_dict()['bias'].copy_(torch.from_numpy(__weights_dict[name]['bias']))
return layer
<file_sep>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import tensorrt as trt
from tensorrt.parsers import uffparser
import pycuda.driver as cuda
import pycuda.autoinit
import numpy as np
from random import randint # generate a random test case
from PIL import Image
import time #import system tools
import os
import uff
OUTPUT_NAMES = ["predictions/Softmax"]
PB_DIR = "../tf_frozen/"
uff_model = uff.from_tensorflow_frozen_model(PB_DIR + "tf_inception.pb", OUTPUT_NAMES)
G_LOGGER = trt.infer.ConsoleLogger(trt.infer.LogSeverity.ERROR)
parser = uffparser.create_uff_parser()
parser.register_input("input_1", (3,299,299), 0)
parser.register_output(OUTPUT_NAMES[0])
engine = trt.utils.uff_to_trt_engine(G_LOGGER, uff_model, parser, 1, 1 << 20)
parser.destroy()
img = np.random.randint(256, size=(3, 299, 299)) / 255.
img = img.astype(np.float32)
label = 123
runtime = trt.infer.create_infer_runtime(G_LOGGER)
context = engine.create_execution_context()
output = np.empty(1000, dtype = np.float32)
d_input = cuda.mem_alloc(1 * img.size * img.dtype.itemsize)
d_output = cuda.mem_alloc(1 * output.size * output.dtype.itemsize)
bindings = [int(d_input), int(d_output)]
stream = cuda.Stream()
#transfer input data to device
cuda.memcpy_htod_async(d_input, img, stream)
#execute model
context.enqueue(1, bindings, stream.handle, None)
#transfer predictions back
cuda.memcpy_dtoh_async(output, d_output, stream)
#syncronize threads
stream.synchronize()
print("Test Case: " + str(label))
print ("Prediction: " + str(np.argmax(output)))
def infer():
#transfer input data to device
cuda.memcpy_htod_async(d_input, img, stream)
#execute model
context.enqueue(1, bindings, stream.handle, None)
#transfer predictions back
cuda.memcpy_dtoh_async(output, d_output, stream)
#syncronize threads
stream.synchronize()
RUNS = 1000
total_run_time = 0
for i in range(1000):
img = np.random.randint(256, size=(3, 299, 299)) / 255.
img = img.astype(np.float32)
start = time.time()
infer()
end = time.time()
run_time = end-start
total_run_time += run_time
print("Test vs Pred: " + str(label) + " " + str(np.argmax(output)))
print("Ran for: " + str(1000 * (end-start)) + " ms")
print("Done.")
print("Avg: " + str(1000 * (total_run_time / RUNS)) + " ms")
<file_sep>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import tensorrt as trt
from tensorrt.parsers import uffparser
import pycuda.driver as cuda
import pycuda.autoinit
import numpy as np
# from PIL import Image
import time #import system tools
import os
import uff
PB_DIR = "../tf_frozen/"
OUTPUT_NAMES = ["activation_8/Softmax"]
BATCH_SIZE = 6
uff_model = uff.from_tensorflow_frozen_model(PB_DIR + "tf_alex.pb", OUTPUT_NAMES)
G_LOGGER = trt.infer.ConsoleLogger(trt.infer.LogSeverity.ERROR)
parser = uffparser.create_uff_parser()
parser.register_input("conv2d_1_input", (3,224,224),0)
parser.register_output(OUTPUT_NAMES[0])
engine = trt.utils.uff_to_trt_engine(G_LOGGER, uff_model, parser, BATCH_SIZE, 0) # 1 << 20
#engine = trt.utils.load_engine(G_LOGGER, "./alex.engine")
#parser.destroy()
img = np.random.randint(256, size=(BATCH_SIZE, 3, 224, 224)) / 255.
img = img.astype(np.float32)
label = 123
runtime = trt.infer.create_infer_runtime(G_LOGGER)
context = engine.create_execution_context()
output = np.empty((BATCH_SIZE, 1000), dtype = np.float32)
d_input = cuda.mem_alloc(BATCH_SIZE * img.size * img.dtype.itemsize)
d_output = cuda.mem_alloc(BATCH_SIZE * output.size * output.dtype.itemsize)
bindings = [int(d_input), int(d_output)]
stream = cuda.Stream()
def infer():
#transfer input data to device
cuda.memcpy_htod_async(d_input, img, stream)
#execute model
context.enqueue(BATCH_SIZE, bindings, stream.handle, None)
#transfer predictions back
cuda.memcpy_dtoh_async(output, d_output, stream)
#syncronize threads
stream.synchronize()
for i in range(1000):
img = np.random.randint(256, size=(BATCH_SIZE, 3, 224, 224)) / 255.
img = img.astype(np.float32)
start = time.time()
infer()
end = time.time()
print("Test vs Pred: " + str(label) + " " +str(np.argmax(output, axis=1)) + " " + str(np.max(output, axis=1)))
print("Ran for: " + str(1000 * (end-start)) + " ms")
<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
__weights_dict = dict()
def load_weights(weight_file):
if weight_file == None:
return
try:
weights_dict = np.load(weight_file).item()
except:
weights_dict = np.load(weight_file, encoding='bytes').item()
return weights_dict
class KitModel(nn.Module):
def __init__(self, weight_file):
super(KitModel, self).__init__()
global __weights_dict
__weights_dict = load_weights(weight_file)
self.conv2d_1 = self.__conv(2, name='conv2d_1', in_channels=3, out_channels=64, kernel_size=(11, 11), stride=(4, 4), groups=1, bias=True)
self.conv2d_2 = self.__conv(2, name='conv2d_2', in_channels=64, out_channels=192, kernel_size=(5, 5), stride=(1, 1), groups=1, bias=True)
self.conv2d_3 = self.__conv(2, name='conv2d_3', in_channels=192, out_channels=384, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.conv2d_4 = self.__conv(2, name='conv2d_4', in_channels=384, out_channels=256, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.conv2d_5 = self.__conv(2, name='conv2d_5', in_channels=256, out_channels=256, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.dense_1 = self.__dense(name = 'dense_1', in_features = 9216, out_features = 4096, bias = True)
self.dense_2 = self.__dense(name = 'dense_2', in_features = 4096, out_features = 4096, bias = True)
self.dense_3 = self.__dense(name = 'dense_3', in_features = 4096, out_features = 1000, bias = True)
def forward(self, x):
conv2d_1_pad = F.pad(x, (3, 4, 3, 4))
conv2d_1 = self.conv2d_1(conv2d_1_pad)
activation_1 = F.relu(conv2d_1)
max_pooling2d_1 = F.max_pool2d(activation_1, kernel_size=(3, 3), stride=(2, 2))
conv2d_2_pad = F.pad(max_pooling2d_1, (2, 2, 2, 2))
conv2d_2 = self.conv2d_2(conv2d_2_pad)
activation_2 = F.relu(conv2d_2)
max_pooling2d_2 = F.max_pool2d(activation_2, kernel_size=(3, 3), stride=(2, 2))
conv2d_3_pad = F.pad(max_pooling2d_2, (1, 1, 1, 1))
conv2d_3 = self.conv2d_3(conv2d_3_pad)
activation_3 = F.relu(conv2d_3)
conv2d_4_pad = F.pad(activation_3, (1, 1, 1, 1))
conv2d_4 = self.conv2d_4(conv2d_4_pad)
activation_4 = F.relu(conv2d_4)
conv2d_5_pad = F.pad(activation_4, (1, 1, 1, 1))
conv2d_5 = self.conv2d_5(conv2d_5_pad)
activation_5 = F.relu(conv2d_5)
max_pooling2d_3 = F.max_pool2d(activation_5, kernel_size=(3, 3), stride=(2, 2))
flatten_1 = max_pooling2d_3.view(max_pooling2d_3.size(0), -1)
dense_1 = self.dense_1(flatten_1)
activation_6 = F.relu(dense_1)
dense_2 = self.dense_2(activation_6)
activation_7 = F.relu(dense_2)
dense_3 = self.dense_3(activation_7)
return dense_3
@staticmethod
def __dense(name, **kwargs):
layer = nn.Linear(**kwargs)
layer.state_dict()['weight'].copy_(torch.from_numpy(__weights_dict[name]['weights']))
if 'bias' in __weights_dict[name]:
layer.state_dict()['bias'].copy_(torch.from_numpy(__weights_dict[name]['bias']))
return layer
@staticmethod
def __conv(dim, name, **kwargs):
if dim == 1: layer = nn.Conv1d(**kwargs)
elif dim == 2: layer = nn.Conv2d(**kwargs)
elif dim == 3: layer = nn.Conv3d(**kwargs)
else: raise NotImplementedError()
layer.state_dict()['weight'].copy_(torch.from_numpy(__weights_dict[name]['weights']))
if 'bias' in __weights_dict[name]:
layer.state_dict()['bias'].copy_(torch.from_numpy(__weights_dict[name]['bias']))
return layer
<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
__weights_dict = dict()
def load_weights(weight_file):
if weight_file == None:
return
try:
weights_dict = np.load(weight_file).item()
except:
weights_dict = np.load(weight_file, encoding='bytes').item()
return weights_dict
class KitModel(nn.Module):
def __init__(self, weight_file):
super(KitModel, self).__init__()
global __weights_dict
__weights_dict = load_weights(weight_file)
self.conv2d_1 = self.__conv(2, name='conv2d_1', in_channels=3, out_channels=32, kernel_size=(3, 3), stride=(2, 2), groups=1, bias=False)
self.batch_normalization_1 = self.__batch_normalization(2, 'batch_normalization_1', num_features = 32, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_2 = self.__conv(2, name='conv2d_2', in_channels=32, out_channels=32, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_2 = self.__batch_normalization(2, 'batch_normalization_2', num_features = 32, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_3 = self.__conv(2, name='conv2d_3', in_channels=32, out_channels=64, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_3 = self.__batch_normalization(2, 'batch_normalization_3', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_4 = self.__conv(2, name='conv2d_4', in_channels=64, out_channels=80, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_4 = self.__batch_normalization(2, 'batch_normalization_4', num_features = 80, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_5 = self.__conv(2, name='conv2d_5', in_channels=80, out_channels=192, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_5 = self.__batch_normalization(2, 'batch_normalization_5', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_9 = self.__conv(2, name='conv2d_9', in_channels=192, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_7 = self.__conv(2, name='conv2d_7', in_channels=192, out_channels=48, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_6 = self.__conv(2, name='conv2d_6', in_channels=192, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_9 = self.__batch_normalization(2, 'batch_normalization_9', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_7 = self.__batch_normalization(2, 'batch_normalization_7', num_features = 48, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_12 = self.__conv(2, name='conv2d_12', in_channels=192, out_channels=32, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_6 = self.__batch_normalization(2, 'batch_normalization_6', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_12 = self.__batch_normalization(2, 'batch_normalization_12', num_features = 32, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_10 = self.__conv(2, name='conv2d_10', in_channels=64, out_channels=96, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
self.conv2d_8 = self.__conv(2, name='conv2d_8', in_channels=48, out_channels=64, kernel_size=(5, 5), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_10 = self.__batch_normalization(2, 'batch_normalization_10', num_features = 96, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_8 = self.__batch_normalization(2, 'batch_normalization_8', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_11 = self.__conv(2, name='conv2d_11', in_channels=96, out_channels=96, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_11 = self.__batch_normalization(2, 'batch_normalization_11', num_features = 96, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_16 = self.__conv(2, name='conv2d_16', in_channels=256, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_14 = self.__conv(2, name='conv2d_14', in_channels=256, out_channels=48, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_13 = self.__conv(2, name='conv2d_13', in_channels=256, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_16 = self.__batch_normalization(2, 'batch_normalization_16', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_14 = self.__batch_normalization(2, 'batch_normalization_14', num_features = 48, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_19 = self.__conv(2, name='conv2d_19', in_channels=256, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_13 = self.__batch_normalization(2, 'batch_normalization_13', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_19 = self.__batch_normalization(2, 'batch_normalization_19', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_17 = self.__conv(2, name='conv2d_17', in_channels=64, out_channels=96, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
self.conv2d_15 = self.__conv(2, name='conv2d_15', in_channels=48, out_channels=64, kernel_size=(5, 5), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_17 = self.__batch_normalization(2, 'batch_normalization_17', num_features = 96, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_15 = self.__batch_normalization(2, 'batch_normalization_15', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_18 = self.__conv(2, name='conv2d_18', in_channels=96, out_channels=96, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_18 = self.__batch_normalization(2, 'batch_normalization_18', num_features = 96, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_23 = self.__conv(2, name='conv2d_23', in_channels=288, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_21 = self.__conv(2, name='conv2d_21', in_channels=288, out_channels=48, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_20 = self.__conv(2, name='conv2d_20', in_channels=288, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_23 = self.__batch_normalization(2, 'batch_normalization_23', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_21 = self.__batch_normalization(2, 'batch_normalization_21', num_features = 48, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_26 = self.__conv(2, name='conv2d_26', in_channels=288, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_20 = self.__batch_normalization(2, 'batch_normalization_20', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_26 = self.__batch_normalization(2, 'batch_normalization_26', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_24 = self.__conv(2, name='conv2d_24', in_channels=64, out_channels=96, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
self.conv2d_22 = self.__conv(2, name='conv2d_22', in_channels=48, out_channels=64, kernel_size=(5, 5), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_24 = self.__batch_normalization(2, 'batch_normalization_24', num_features = 96, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_22 = self.__batch_normalization(2, 'batch_normalization_22', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_25 = self.__conv(2, name='conv2d_25', in_channels=96, out_channels=96, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_25 = self.__batch_normalization(2, 'batch_normalization_25', num_features = 96, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_28 = self.__conv(2, name='conv2d_28', in_channels=288, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_27 = self.__conv(2, name='conv2d_27', in_channels=288, out_channels=384, kernel_size=(3, 3), stride=(2, 2), groups=1, bias=False)
self.batch_normalization_28 = self.__batch_normalization(2, 'batch_normalization_28', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_27 = self.__batch_normalization(2, 'batch_normalization_27', num_features = 384, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_29 = self.__conv(2, name='conv2d_29', in_channels=64, out_channels=96, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_29 = self.__batch_normalization(2, 'batch_normalization_29', num_features = 96, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_30 = self.__conv(2, name='conv2d_30', in_channels=96, out_channels=96, kernel_size=(3, 3), stride=(2, 2), groups=1, bias=False)
self.batch_normalization_30 = self.__batch_normalization(2, 'batch_normalization_30', num_features = 96, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_35 = self.__conv(2, name='conv2d_35', in_channels=768, out_channels=128, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_32 = self.__conv(2, name='conv2d_32', in_channels=768, out_channels=128, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_31 = self.__conv(2, name='conv2d_31', in_channels=768, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_35 = self.__batch_normalization(2, 'batch_normalization_35', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_32 = self.__batch_normalization(2, 'batch_normalization_32', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_40 = self.__conv(2, name='conv2d_40', in_channels=768, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_31 = self.__batch_normalization(2, 'batch_normalization_31', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_40 = self.__batch_normalization(2, 'batch_normalization_40', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_36 = self.__conv(2, name='conv2d_36', in_channels=128, out_channels=128, kernel_size=(7, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_33 = self.__conv(2, name='conv2d_33', in_channels=128, out_channels=128, kernel_size=(1, 7), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_36 = self.__batch_normalization(2, 'batch_normalization_36', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_33 = self.__batch_normalization(2, 'batch_normalization_33', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_37 = self.__conv(2, name='conv2d_37', in_channels=128, out_channels=128, kernel_size=(1, 7), stride=(1, 1), groups=1, bias=False)
self.conv2d_34 = self.__conv(2, name='conv2d_34', in_channels=128, out_channels=192, kernel_size=(7, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_37 = self.__batch_normalization(2, 'batch_normalization_37', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_34 = self.__batch_normalization(2, 'batch_normalization_34', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_38 = self.__conv(2, name='conv2d_38', in_channels=128, out_channels=128, kernel_size=(7, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_38 = self.__batch_normalization(2, 'batch_normalization_38', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_39 = self.__conv(2, name='conv2d_39', in_channels=128, out_channels=192, kernel_size=(1, 7), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_39 = self.__batch_normalization(2, 'batch_normalization_39', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_45 = self.__conv(2, name='conv2d_45', in_channels=768, out_channels=160, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_42 = self.__conv(2, name='conv2d_42', in_channels=768, out_channels=160, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_41 = self.__conv(2, name='conv2d_41', in_channels=768, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_45 = self.__batch_normalization(2, 'batch_normalization_45', num_features = 160, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_42 = self.__batch_normalization(2, 'batch_normalization_42', num_features = 160, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_50 = self.__conv(2, name='conv2d_50', in_channels=768, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_41 = self.__batch_normalization(2, 'batch_normalization_41', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_50 = self.__batch_normalization(2, 'batch_normalization_50', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_46 = self.__conv(2, name='conv2d_46', in_channels=160, out_channels=160, kernel_size=(7, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_43 = self.__conv(2, name='conv2d_43', in_channels=160, out_channels=160, kernel_size=(1, 7), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_46 = self.__batch_normalization(2, 'batch_normalization_46', num_features = 160, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_43 = self.__batch_normalization(2, 'batch_normalization_43', num_features = 160, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_47 = self.__conv(2, name='conv2d_47', in_channels=160, out_channels=160, kernel_size=(1, 7), stride=(1, 1), groups=1, bias=False)
self.conv2d_44 = self.__conv(2, name='conv2d_44', in_channels=160, out_channels=192, kernel_size=(7, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_47 = self.__batch_normalization(2, 'batch_normalization_47', num_features = 160, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_44 = self.__batch_normalization(2, 'batch_normalization_44', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_48 = self.__conv(2, name='conv2d_48', in_channels=160, out_channels=160, kernel_size=(7, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_48 = self.__batch_normalization(2, 'batch_normalization_48', num_features = 160, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_49 = self.__conv(2, name='conv2d_49', in_channels=160, out_channels=192, kernel_size=(1, 7), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_49 = self.__batch_normalization(2, 'batch_normalization_49', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_55 = self.__conv(2, name='conv2d_55', in_channels=768, out_channels=160, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_52 = self.__conv(2, name='conv2d_52', in_channels=768, out_channels=160, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_51 = self.__conv(2, name='conv2d_51', in_channels=768, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_55 = self.__batch_normalization(2, 'batch_normalization_55', num_features = 160, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_52 = self.__batch_normalization(2, 'batch_normalization_52', num_features = 160, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_60 = self.__conv(2, name='conv2d_60', in_channels=768, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_51 = self.__batch_normalization(2, 'batch_normalization_51', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_60 = self.__batch_normalization(2, 'batch_normalization_60', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_56 = self.__conv(2, name='conv2d_56', in_channels=160, out_channels=160, kernel_size=(7, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_53 = self.__conv(2, name='conv2d_53', in_channels=160, out_channels=160, kernel_size=(1, 7), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_56 = self.__batch_normalization(2, 'batch_normalization_56', num_features = 160, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_53 = self.__batch_normalization(2, 'batch_normalization_53', num_features = 160, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_57 = self.__conv(2, name='conv2d_57', in_channels=160, out_channels=160, kernel_size=(1, 7), stride=(1, 1), groups=1, bias=False)
self.conv2d_54 = self.__conv(2, name='conv2d_54', in_channels=160, out_channels=192, kernel_size=(7, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_57 = self.__batch_normalization(2, 'batch_normalization_57', num_features = 160, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_54 = self.__batch_normalization(2, 'batch_normalization_54', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_58 = self.__conv(2, name='conv2d_58', in_channels=160, out_channels=160, kernel_size=(7, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_58 = self.__batch_normalization(2, 'batch_normalization_58', num_features = 160, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_59 = self.__conv(2, name='conv2d_59', in_channels=160, out_channels=192, kernel_size=(1, 7), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_59 = self.__batch_normalization(2, 'batch_normalization_59', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_65 = self.__conv(2, name='conv2d_65', in_channels=768, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_62 = self.__conv(2, name='conv2d_62', in_channels=768, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_61 = self.__conv(2, name='conv2d_61', in_channels=768, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_65 = self.__batch_normalization(2, 'batch_normalization_65', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_62 = self.__batch_normalization(2, 'batch_normalization_62', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_70 = self.__conv(2, name='conv2d_70', in_channels=768, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_61 = self.__batch_normalization(2, 'batch_normalization_61', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_70 = self.__batch_normalization(2, 'batch_normalization_70', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_66 = self.__conv(2, name='conv2d_66', in_channels=192, out_channels=192, kernel_size=(7, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_63 = self.__conv(2, name='conv2d_63', in_channels=192, out_channels=192, kernel_size=(1, 7), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_66 = self.__batch_normalization(2, 'batch_normalization_66', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_63 = self.__batch_normalization(2, 'batch_normalization_63', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_67 = self.__conv(2, name='conv2d_67', in_channels=192, out_channels=192, kernel_size=(1, 7), stride=(1, 1), groups=1, bias=False)
self.conv2d_64 = self.__conv(2, name='conv2d_64', in_channels=192, out_channels=192, kernel_size=(7, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_67 = self.__batch_normalization(2, 'batch_normalization_67', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_64 = self.__batch_normalization(2, 'batch_normalization_64', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_68 = self.__conv(2, name='conv2d_68', in_channels=192, out_channels=192, kernel_size=(7, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_68 = self.__batch_normalization(2, 'batch_normalization_68', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_69 = self.__conv(2, name='conv2d_69', in_channels=192, out_channels=192, kernel_size=(1, 7), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_69 = self.__batch_normalization(2, 'batch_normalization_69', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_73 = self.__conv(2, name='conv2d_73', in_channels=768, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_71 = self.__conv(2, name='conv2d_71', in_channels=768, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_73 = self.__batch_normalization(2, 'batch_normalization_73', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_71 = self.__batch_normalization(2, 'batch_normalization_71', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_74 = self.__conv(2, name='conv2d_74', in_channels=192, out_channels=192, kernel_size=(1, 7), stride=(1, 1), groups=1, bias=False)
self.conv2d_72 = self.__conv(2, name='conv2d_72', in_channels=192, out_channels=320, kernel_size=(3, 3), stride=(2, 2), groups=1, bias=False)
self.batch_normalization_74 = self.__batch_normalization(2, 'batch_normalization_74', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_72 = self.__batch_normalization(2, 'batch_normalization_72', num_features = 320, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_75 = self.__conv(2, name='conv2d_75', in_channels=192, out_channels=192, kernel_size=(7, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_75 = self.__batch_normalization(2, 'batch_normalization_75', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_76 = self.__conv(2, name='conv2d_76', in_channels=192, out_channels=192, kernel_size=(3, 3), stride=(2, 2), groups=1, bias=False)
self.batch_normalization_76 = self.__batch_normalization(2, 'batch_normalization_76', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_81 = self.__conv(2, name='conv2d_81', in_channels=1280, out_channels=448, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_78 = self.__conv(2, name='conv2d_78', in_channels=1280, out_channels=384, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_77 = self.__conv(2, name='conv2d_77', in_channels=1280, out_channels=320, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_81 = self.__batch_normalization(2, 'batch_normalization_81', num_features = 448, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_78 = self.__batch_normalization(2, 'batch_normalization_78', num_features = 384, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_85 = self.__conv(2, name='conv2d_85', in_channels=1280, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_77 = self.__batch_normalization(2, 'batch_normalization_77', num_features = 320, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_85 = self.__batch_normalization(2, 'batch_normalization_85', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_82 = self.__conv(2, name='conv2d_82', in_channels=448, out_channels=384, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
self.conv2d_79 = self.__conv(2, name='conv2d_79', in_channels=384, out_channels=384, kernel_size=(1, 3), stride=(1, 1), groups=1, bias=False)
self.conv2d_80 = self.__conv(2, name='conv2d_80', in_channels=384, out_channels=384, kernel_size=(3, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_82 = self.__batch_normalization(2, 'batch_normalization_82', num_features = 384, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_79 = self.__batch_normalization(2, 'batch_normalization_79', num_features = 384, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_80 = self.__batch_normalization(2, 'batch_normalization_80', num_features = 384, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_83 = self.__conv(2, name='conv2d_83', in_channels=384, out_channels=384, kernel_size=(1, 3), stride=(1, 1), groups=1, bias=False)
self.conv2d_84 = self.__conv(2, name='conv2d_84', in_channels=384, out_channels=384, kernel_size=(3, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_83 = self.__batch_normalization(2, 'batch_normalization_83', num_features = 384, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_84 = self.__batch_normalization(2, 'batch_normalization_84', num_features = 384, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_90 = self.__conv(2, name='conv2d_90', in_channels=2048, out_channels=448, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_87 = self.__conv(2, name='conv2d_87', in_channels=2048, out_channels=384, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.conv2d_86 = self.__conv(2, name='conv2d_86', in_channels=2048, out_channels=320, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_90 = self.__batch_normalization(2, 'batch_normalization_90', num_features = 448, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_87 = self.__batch_normalization(2, 'batch_normalization_87', num_features = 384, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_94 = self.__conv(2, name='conv2d_94', in_channels=2048, out_channels=192, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_86 = self.__batch_normalization(2, 'batch_normalization_86', num_features = 320, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_94 = self.__batch_normalization(2, 'batch_normalization_94', num_features = 192, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_91 = self.__conv(2, name='conv2d_91', in_channels=448, out_channels=384, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=False)
self.conv2d_88 = self.__conv(2, name='conv2d_88', in_channels=384, out_channels=384, kernel_size=(1, 3), stride=(1, 1), groups=1, bias=False)
self.conv2d_89 = self.__conv(2, name='conv2d_89', in_channels=384, out_channels=384, kernel_size=(3, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_91 = self.__batch_normalization(2, 'batch_normalization_91', num_features = 384, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_88 = self.__batch_normalization(2, 'batch_normalization_88', num_features = 384, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_89 = self.__batch_normalization(2, 'batch_normalization_89', num_features = 384, eps = 0.0010000000474974513, momentum = 0.0)
self.conv2d_92 = self.__conv(2, name='conv2d_92', in_channels=384, out_channels=384, kernel_size=(1, 3), stride=(1, 1), groups=1, bias=False)
self.conv2d_93 = self.__conv(2, name='conv2d_93', in_channels=384, out_channels=384, kernel_size=(3, 1), stride=(1, 1), groups=1, bias=False)
self.batch_normalization_92 = self.__batch_normalization(2, 'batch_normalization_92', num_features = 384, eps = 0.0010000000474974513, momentum = 0.0)
self.batch_normalization_93 = self.__batch_normalization(2, 'batch_normalization_93', num_features = 384, eps = 0.0010000000474974513, momentum = 0.0)
self.predictions = self.__dense(name = 'predictions', in_features = 2048, out_features = 1000, bias = True)
def forward(self, x):
conv2d_1 = self.conv2d_1(x)
batch_normalization_1 = self.batch_normalization_1(conv2d_1)
activation_1 = F.relu(batch_normalization_1)
conv2d_2 = self.conv2d_2(activation_1)
batch_normalization_2 = self.batch_normalization_2(conv2d_2)
activation_2 = F.relu(batch_normalization_2)
conv2d_3_pad = F.pad(activation_2, (1, 1, 1, 1))
conv2d_3 = self.conv2d_3(conv2d_3_pad)
batch_normalization_3 = self.batch_normalization_3(conv2d_3)
activation_3 = F.relu(batch_normalization_3)
max_pooling2d_1 = F.max_pool2d(activation_3, kernel_size=(3, 3), stride=(2, 2))
conv2d_4 = self.conv2d_4(max_pooling2d_1)
batch_normalization_4 = self.batch_normalization_4(conv2d_4)
activation_4 = F.relu(batch_normalization_4)
conv2d_5 = self.conv2d_5(activation_4)
batch_normalization_5 = self.batch_normalization_5(conv2d_5)
activation_5 = F.relu(batch_normalization_5)
max_pooling2d_2 = F.max_pool2d(activation_5, kernel_size=(3, 3), stride=(2, 2))
conv2d_9 = self.conv2d_9(max_pooling2d_2)
conv2d_7 = self.conv2d_7(max_pooling2d_2)
average_pooling2d_1_pad = F.pad(max_pooling2d_2, (1, 1, 1, 1))
average_pooling2d_1 = F.avg_pool2d(average_pooling2d_1_pad, kernel_size=(3, 3), stride=(1, 1))
conv2d_6 = self.conv2d_6(max_pooling2d_2)
batch_normalization_9 = self.batch_normalization_9(conv2d_9)
batch_normalization_7 = self.batch_normalization_7(conv2d_7)
conv2d_12 = self.conv2d_12(average_pooling2d_1)
batch_normalization_6 = self.batch_normalization_6(conv2d_6)
activation_9 = F.relu(batch_normalization_9)
activation_7 = F.relu(batch_normalization_7)
batch_normalization_12 = self.batch_normalization_12(conv2d_12)
activation_6 = F.relu(batch_normalization_6)
conv2d_10_pad = F.pad(activation_9, (1, 1, 1, 1))
conv2d_10 = self.conv2d_10(conv2d_10_pad)
conv2d_8_pad = F.pad(activation_7, (2, 2, 2, 2))
conv2d_8 = self.conv2d_8(conv2d_8_pad)
activation_12 = F.relu(batch_normalization_12)
batch_normalization_10 = self.batch_normalization_10(conv2d_10)
batch_normalization_8 = self.batch_normalization_8(conv2d_8)
activation_10 = F.relu(batch_normalization_10)
activation_8 = F.relu(batch_normalization_8)
conv2d_11_pad = F.pad(activation_10, (1, 1, 1, 1))
conv2d_11 = self.conv2d_11(conv2d_11_pad)
batch_normalization_11 = self.batch_normalization_11(conv2d_11)
activation_11 = F.relu(batch_normalization_11)
mixed0 = torch.cat((activation_6, activation_8, activation_11, activation_12), 1)
conv2d_16 = self.conv2d_16(mixed0)
conv2d_14 = self.conv2d_14(mixed0)
average_pooling2d_2_pad = F.pad(mixed0, (1, 1, 1, 1))
average_pooling2d_2 = F.avg_pool2d(average_pooling2d_2_pad, kernel_size=(3, 3), stride=(1, 1))
conv2d_13 = self.conv2d_13(mixed0)
batch_normalization_16 = self.batch_normalization_16(conv2d_16)
batch_normalization_14 = self.batch_normalization_14(conv2d_14)
conv2d_19 = self.conv2d_19(average_pooling2d_2)
batch_normalization_13 = self.batch_normalization_13(conv2d_13)
activation_16 = F.relu(batch_normalization_16)
activation_14 = F.relu(batch_normalization_14)
batch_normalization_19 = self.batch_normalization_19(conv2d_19)
activation_13 = F.relu(batch_normalization_13)
conv2d_17_pad = F.pad(activation_16, (1, 1, 1, 1))
conv2d_17 = self.conv2d_17(conv2d_17_pad)
conv2d_15_pad = F.pad(activation_14, (2, 2, 2, 2))
conv2d_15 = self.conv2d_15(conv2d_15_pad)
activation_19 = F.relu(batch_normalization_19)
batch_normalization_17 = self.batch_normalization_17(conv2d_17)
batch_normalization_15 = self.batch_normalization_15(conv2d_15)
activation_17 = F.relu(batch_normalization_17)
activation_15 = F.relu(batch_normalization_15)
conv2d_18_pad = F.pad(activation_17, (1, 1, 1, 1))
conv2d_18 = self.conv2d_18(conv2d_18_pad)
batch_normalization_18 = self.batch_normalization_18(conv2d_18)
activation_18 = F.relu(batch_normalization_18)
mixed1 = torch.cat((activation_13, activation_15, activation_18, activation_19), 1)
conv2d_23 = self.conv2d_23(mixed1)
conv2d_21 = self.conv2d_21(mixed1)
average_pooling2d_3_pad = F.pad(mixed1, (1, 1, 1, 1))
average_pooling2d_3 = F.avg_pool2d(average_pooling2d_3_pad, kernel_size=(3, 3), stride=(1, 1))
conv2d_20 = self.conv2d_20(mixed1)
batch_normalization_23 = self.batch_normalization_23(conv2d_23)
batch_normalization_21 = self.batch_normalization_21(conv2d_21)
conv2d_26 = self.conv2d_26(average_pooling2d_3)
batch_normalization_20 = self.batch_normalization_20(conv2d_20)
activation_23 = F.relu(batch_normalization_23)
activation_21 = F.relu(batch_normalization_21)
batch_normalization_26 = self.batch_normalization_26(conv2d_26)
activation_20 = F.relu(batch_normalization_20)
conv2d_24_pad = F.pad(activation_23, (1, 1, 1, 1))
conv2d_24 = self.conv2d_24(conv2d_24_pad)
conv2d_22_pad = F.pad(activation_21, (2, 2, 2, 2))
conv2d_22 = self.conv2d_22(conv2d_22_pad)
activation_26 = F.relu(batch_normalization_26)
batch_normalization_24 = self.batch_normalization_24(conv2d_24)
batch_normalization_22 = self.batch_normalization_22(conv2d_22)
activation_24 = F.relu(batch_normalization_24)
activation_22 = F.relu(batch_normalization_22)
conv2d_25_pad = F.pad(activation_24, (1, 1, 1, 1))
conv2d_25 = self.conv2d_25(conv2d_25_pad)
batch_normalization_25 = self.batch_normalization_25(conv2d_25)
activation_25 = F.relu(batch_normalization_25)
mixed2 = torch.cat((activation_20, activation_22, activation_25, activation_26), 1)
conv2d_28 = self.conv2d_28(mixed2)
conv2d_27 = self.conv2d_27(mixed2)
max_pooling2d_3 = F.max_pool2d(mixed2, kernel_size=(3, 3), stride=(2, 2))
batch_normalization_28 = self.batch_normalization_28(conv2d_28)
batch_normalization_27 = self.batch_normalization_27(conv2d_27)
activation_28 = F.relu(batch_normalization_28)
activation_27 = F.relu(batch_normalization_27)
conv2d_29_pad = F.pad(activation_28, (1, 1, 1, 1))
conv2d_29 = self.conv2d_29(conv2d_29_pad)
batch_normalization_29 = self.batch_normalization_29(conv2d_29)
activation_29 = F.relu(batch_normalization_29)
conv2d_30 = self.conv2d_30(activation_29)
batch_normalization_30 = self.batch_normalization_30(conv2d_30)
activation_30 = F.relu(batch_normalization_30)
mixed3 = torch.cat((activation_27, activation_30, max_pooling2d_3), 1)
conv2d_35 = self.conv2d_35(mixed3)
conv2d_32 = self.conv2d_32(mixed3)
average_pooling2d_4_pad = F.pad(mixed3, (1, 1, 1, 1))
average_pooling2d_4 = F.avg_pool2d(average_pooling2d_4_pad, kernel_size=(3, 3), stride=(1, 1))
conv2d_31 = self.conv2d_31(mixed3)
batch_normalization_35 = self.batch_normalization_35(conv2d_35)
batch_normalization_32 = self.batch_normalization_32(conv2d_32)
conv2d_40 = self.conv2d_40(average_pooling2d_4)
batch_normalization_31 = self.batch_normalization_31(conv2d_31)
activation_35 = F.relu(batch_normalization_35)
activation_32 = F.relu(batch_normalization_32)
batch_normalization_40 = self.batch_normalization_40(conv2d_40)
activation_31 = F.relu(batch_normalization_31)
conv2d_36_pad = F.pad(activation_35, (0, 0, 3, 3))
conv2d_36 = self.conv2d_36(conv2d_36_pad)
conv2d_33_pad = F.pad(activation_32, (3, 3, 0, 0))
conv2d_33 = self.conv2d_33(conv2d_33_pad)
activation_40 = F.relu(batch_normalization_40)
batch_normalization_36 = self.batch_normalization_36(conv2d_36)
batch_normalization_33 = self.batch_normalization_33(conv2d_33)
activation_36 = F.relu(batch_normalization_36)
activation_33 = F.relu(batch_normalization_33)
conv2d_37_pad = F.pad(activation_36, (3, 3, 0, 0))
conv2d_37 = self.conv2d_37(conv2d_37_pad)
conv2d_34_pad = F.pad(activation_33, (0, 0, 3, 3))
conv2d_34 = self.conv2d_34(conv2d_34_pad)
batch_normalization_37 = self.batch_normalization_37(conv2d_37)
batch_normalization_34 = self.batch_normalization_34(conv2d_34)
activation_37 = F.relu(batch_normalization_37)
activation_34 = F.relu(batch_normalization_34)
conv2d_38_pad = F.pad(activation_37, (0, 0, 3, 3))
conv2d_38 = self.conv2d_38(conv2d_38_pad)
batch_normalization_38 = self.batch_normalization_38(conv2d_38)
activation_38 = F.relu(batch_normalization_38)
conv2d_39_pad = F.pad(activation_38, (3, 3, 0, 0))
conv2d_39 = self.conv2d_39(conv2d_39_pad)
batch_normalization_39 = self.batch_normalization_39(conv2d_39)
activation_39 = F.relu(batch_normalization_39)
mixed4 = torch.cat((activation_31, activation_34, activation_39, activation_40), 1)
conv2d_45 = self.conv2d_45(mixed4)
conv2d_42 = self.conv2d_42(mixed4)
average_pooling2d_5_pad = F.pad(mixed4, (1, 1, 1, 1))
average_pooling2d_5 = F.avg_pool2d(average_pooling2d_5_pad, kernel_size=(3, 3), stride=(1, 1))
conv2d_41 = self.conv2d_41(mixed4)
batch_normalization_45 = self.batch_normalization_45(conv2d_45)
batch_normalization_42 = self.batch_normalization_42(conv2d_42)
conv2d_50 = self.conv2d_50(average_pooling2d_5)
batch_normalization_41 = self.batch_normalization_41(conv2d_41)
activation_45 = F.relu(batch_normalization_45)
activation_42 = F.relu(batch_normalization_42)
batch_normalization_50 = self.batch_normalization_50(conv2d_50)
activation_41 = F.relu(batch_normalization_41)
conv2d_46_pad = F.pad(activation_45, (0, 0, 3, 3))
conv2d_46 = self.conv2d_46(conv2d_46_pad)
conv2d_43_pad = F.pad(activation_42, (3, 3, 0, 0))
conv2d_43 = self.conv2d_43(conv2d_43_pad)
activation_50 = F.relu(batch_normalization_50)
batch_normalization_46 = self.batch_normalization_46(conv2d_46)
batch_normalization_43 = self.batch_normalization_43(conv2d_43)
activation_46 = F.relu(batch_normalization_46)
activation_43 = F.relu(batch_normalization_43)
conv2d_47_pad = F.pad(activation_46, (3, 3, 0, 0))
conv2d_47 = self.conv2d_47(conv2d_47_pad)
conv2d_44_pad = F.pad(activation_43, (0, 0, 3, 3))
conv2d_44 = self.conv2d_44(conv2d_44_pad)
batch_normalization_47 = self.batch_normalization_47(conv2d_47)
batch_normalization_44 = self.batch_normalization_44(conv2d_44)
activation_47 = F.relu(batch_normalization_47)
activation_44 = F.relu(batch_normalization_44)
conv2d_48_pad = F.pad(activation_47, (0, 0, 3, 3))
conv2d_48 = self.conv2d_48(conv2d_48_pad)
batch_normalization_48 = self.batch_normalization_48(conv2d_48)
activation_48 = F.relu(batch_normalization_48)
conv2d_49_pad = F.pad(activation_48, (3, 3, 0, 0))
conv2d_49 = self.conv2d_49(conv2d_49_pad)
batch_normalization_49 = self.batch_normalization_49(conv2d_49)
activation_49 = F.relu(batch_normalization_49)
mixed5 = torch.cat((activation_41, activation_44, activation_49, activation_50), 1)
conv2d_55 = self.conv2d_55(mixed5)
conv2d_52 = self.conv2d_52(mixed5)
average_pooling2d_6_pad = F.pad(mixed5, (1, 1, 1, 1))
average_pooling2d_6 = F.avg_pool2d(average_pooling2d_6_pad, kernel_size=(3, 3), stride=(1, 1))
conv2d_51 = self.conv2d_51(mixed5)
batch_normalization_55 = self.batch_normalization_55(conv2d_55)
batch_normalization_52 = self.batch_normalization_52(conv2d_52)
conv2d_60 = self.conv2d_60(average_pooling2d_6)
batch_normalization_51 = self.batch_normalization_51(conv2d_51)
activation_55 = F.relu(batch_normalization_55)
activation_52 = F.relu(batch_normalization_52)
batch_normalization_60 = self.batch_normalization_60(conv2d_60)
activation_51 = F.relu(batch_normalization_51)
conv2d_56_pad = F.pad(activation_55, (0, 0, 3, 3))
conv2d_56 = self.conv2d_56(conv2d_56_pad)
conv2d_53_pad = F.pad(activation_52, (3, 3, 0, 0))
conv2d_53 = self.conv2d_53(conv2d_53_pad)
activation_60 = F.relu(batch_normalization_60)
batch_normalization_56 = self.batch_normalization_56(conv2d_56)
batch_normalization_53 = self.batch_normalization_53(conv2d_53)
activation_56 = F.relu(batch_normalization_56)
activation_53 = F.relu(batch_normalization_53)
conv2d_57_pad = F.pad(activation_56, (3, 3, 0, 0))
conv2d_57 = self.conv2d_57(conv2d_57_pad)
conv2d_54_pad = F.pad(activation_53, (0, 0, 3, 3))
conv2d_54 = self.conv2d_54(conv2d_54_pad)
batch_normalization_57 = self.batch_normalization_57(conv2d_57)
batch_normalization_54 = self.batch_normalization_54(conv2d_54)
activation_57 = F.relu(batch_normalization_57)
activation_54 = F.relu(batch_normalization_54)
conv2d_58_pad = F.pad(activation_57, (0, 0, 3, 3))
conv2d_58 = self.conv2d_58(conv2d_58_pad)
batch_normalization_58 = self.batch_normalization_58(conv2d_58)
activation_58 = F.relu(batch_normalization_58)
conv2d_59_pad = F.pad(activation_58, (3, 3, 0, 0))
conv2d_59 = self.conv2d_59(conv2d_59_pad)
batch_normalization_59 = self.batch_normalization_59(conv2d_59)
activation_59 = F.relu(batch_normalization_59)
mixed6 = torch.cat((activation_51, activation_54, activation_59, activation_60), 1)
conv2d_65 = self.conv2d_65(mixed6)
conv2d_62 = self.conv2d_62(mixed6)
average_pooling2d_7_pad = F.pad(mixed6, (1, 1, 1, 1))
average_pooling2d_7 = F.avg_pool2d(average_pooling2d_7_pad, kernel_size=(3, 3), stride=(1, 1))
conv2d_61 = self.conv2d_61(mixed6)
batch_normalization_65 = self.batch_normalization_65(conv2d_65)
batch_normalization_62 = self.batch_normalization_62(conv2d_62)
conv2d_70 = self.conv2d_70(average_pooling2d_7)
batch_normalization_61 = self.batch_normalization_61(conv2d_61)
activation_65 = F.relu(batch_normalization_65)
activation_62 = F.relu(batch_normalization_62)
batch_normalization_70 = self.batch_normalization_70(conv2d_70)
activation_61 = F.relu(batch_normalization_61)
conv2d_66_pad = F.pad(activation_65, (0, 0, 3, 3))
conv2d_66 = self.conv2d_66(conv2d_66_pad)
conv2d_63_pad = F.pad(activation_62, (3, 3, 0, 0))
conv2d_63 = self.conv2d_63(conv2d_63_pad)
activation_70 = F.relu(batch_normalization_70)
batch_normalization_66 = self.batch_normalization_66(conv2d_66)
batch_normalization_63 = self.batch_normalization_63(conv2d_63)
activation_66 = F.relu(batch_normalization_66)
activation_63 = F.relu(batch_normalization_63)
conv2d_67_pad = F.pad(activation_66, (3, 3, 0, 0))
conv2d_67 = self.conv2d_67(conv2d_67_pad)
conv2d_64_pad = F.pad(activation_63, (0, 0, 3, 3))
conv2d_64 = self.conv2d_64(conv2d_64_pad)
batch_normalization_67 = self.batch_normalization_67(conv2d_67)
batch_normalization_64 = self.batch_normalization_64(conv2d_64)
activation_67 = F.relu(batch_normalization_67)
activation_64 = F.relu(batch_normalization_64)
conv2d_68_pad = F.pad(activation_67, (0, 0, 3, 3))
conv2d_68 = self.conv2d_68(conv2d_68_pad)
batch_normalization_68 = self.batch_normalization_68(conv2d_68)
activation_68 = F.relu(batch_normalization_68)
conv2d_69_pad = F.pad(activation_68, (3, 3, 0, 0))
conv2d_69 = self.conv2d_69(conv2d_69_pad)
batch_normalization_69 = self.batch_normalization_69(conv2d_69)
activation_69 = F.relu(batch_normalization_69)
mixed7 = torch.cat((activation_61, activation_64, activation_69, activation_70), 1)
conv2d_73 = self.conv2d_73(mixed7)
conv2d_71 = self.conv2d_71(mixed7)
max_pooling2d_4 = F.max_pool2d(mixed7, kernel_size=(3, 3), stride=(2, 2))
batch_normalization_73 = self.batch_normalization_73(conv2d_73)
batch_normalization_71 = self.batch_normalization_71(conv2d_71)
activation_73 = F.relu(batch_normalization_73)
activation_71 = F.relu(batch_normalization_71)
conv2d_74_pad = F.pad(activation_73, (3, 3, 0, 0))
conv2d_74 = self.conv2d_74(conv2d_74_pad)
conv2d_72 = self.conv2d_72(activation_71)
batch_normalization_74 = self.batch_normalization_74(conv2d_74)
batch_normalization_72 = self.batch_normalization_72(conv2d_72)
activation_74 = F.relu(batch_normalization_74)
activation_72 = F.relu(batch_normalization_72)
conv2d_75_pad = F.pad(activation_74, (0, 0, 3, 3))
conv2d_75 = self.conv2d_75(conv2d_75_pad)
batch_normalization_75 = self.batch_normalization_75(conv2d_75)
activation_75 = F.relu(batch_normalization_75)
conv2d_76 = self.conv2d_76(activation_75)
batch_normalization_76 = self.batch_normalization_76(conv2d_76)
activation_76 = F.relu(batch_normalization_76)
mixed8 = torch.cat((activation_72, activation_76, max_pooling2d_4), 1)
conv2d_81 = self.conv2d_81(mixed8)
conv2d_78 = self.conv2d_78(mixed8)
average_pooling2d_8_pad = F.pad(mixed8, (1, 1, 1, 1))
average_pooling2d_8 = F.avg_pool2d(average_pooling2d_8_pad, kernel_size=(3, 3), stride=(1, 1))
conv2d_77 = self.conv2d_77(mixed8)
batch_normalization_81 = self.batch_normalization_81(conv2d_81)
batch_normalization_78 = self.batch_normalization_78(conv2d_78)
conv2d_85 = self.conv2d_85(average_pooling2d_8)
batch_normalization_77 = self.batch_normalization_77(conv2d_77)
activation_81 = F.relu(batch_normalization_81)
activation_78 = F.relu(batch_normalization_78)
batch_normalization_85 = self.batch_normalization_85(conv2d_85)
activation_77 = F.relu(batch_normalization_77)
conv2d_82_pad = F.pad(activation_81, (1, 1, 1, 1))
conv2d_82 = self.conv2d_82(conv2d_82_pad)
conv2d_79_pad = F.pad(activation_78, (1, 1, 0, 0))
conv2d_79 = self.conv2d_79(conv2d_79_pad)
conv2d_80_pad = F.pad(activation_78, (0, 0, 1, 1))
conv2d_80 = self.conv2d_80(conv2d_80_pad)
activation_85 = F.relu(batch_normalization_85)
batch_normalization_82 = self.batch_normalization_82(conv2d_82)
batch_normalization_79 = self.batch_normalization_79(conv2d_79)
batch_normalization_80 = self.batch_normalization_80(conv2d_80)
activation_82 = F.relu(batch_normalization_82)
activation_79 = F.relu(batch_normalization_79)
activation_80 = F.relu(batch_normalization_80)
conv2d_83_pad = F.pad(activation_82, (1, 1, 0, 0))
conv2d_83 = self.conv2d_83(conv2d_83_pad)
conv2d_84_pad = F.pad(activation_82, (0, 0, 1, 1))
conv2d_84 = self.conv2d_84(conv2d_84_pad)
mixed9_0 = torch.cat((activation_79, activation_80), 1)
batch_normalization_83 = self.batch_normalization_83(conv2d_83)
batch_normalization_84 = self.batch_normalization_84(conv2d_84)
activation_83 = F.relu(batch_normalization_83)
activation_84 = F.relu(batch_normalization_84)
concatenate_1 = torch.cat((activation_83, activation_84), 1)
mixed9 = torch.cat((activation_77, mixed9_0, concatenate_1, activation_85), 1)
conv2d_90 = self.conv2d_90(mixed9)
conv2d_87 = self.conv2d_87(mixed9)
average_pooling2d_9_pad = F.pad(mixed9, (1, 1, 1, 1))
average_pooling2d_9 = F.avg_pool2d(average_pooling2d_9_pad, kernel_size=(3, 3), stride=(1, 1))
conv2d_86 = self.conv2d_86(mixed9)
batch_normalization_90 = self.batch_normalization_90(conv2d_90)
batch_normalization_87 = self.batch_normalization_87(conv2d_87)
conv2d_94 = self.conv2d_94(average_pooling2d_9)
batch_normalization_86 = self.batch_normalization_86(conv2d_86)
activation_90 = F.relu(batch_normalization_90)
activation_87 = F.relu(batch_normalization_87)
batch_normalization_94 = self.batch_normalization_94(conv2d_94)
activation_86 = F.relu(batch_normalization_86)
conv2d_91_pad = F.pad(activation_90, (1, 1, 1, 1))
conv2d_91 = self.conv2d_91(conv2d_91_pad)
conv2d_88_pad = F.pad(activation_87, (1, 1, 0, 0))
conv2d_88 = self.conv2d_88(conv2d_88_pad)
conv2d_89_pad = F.pad(activation_87, (0, 0, 1, 1))
conv2d_89 = self.conv2d_89(conv2d_89_pad)
activation_94 = F.relu(batch_normalization_94)
batch_normalization_91 = self.batch_normalization_91(conv2d_91)
batch_normalization_88 = self.batch_normalization_88(conv2d_88)
batch_normalization_89 = self.batch_normalization_89(conv2d_89)
activation_91 = F.relu(batch_normalization_91)
activation_88 = F.relu(batch_normalization_88)
activation_89 = F.relu(batch_normalization_89)
conv2d_92_pad = F.pad(activation_91, (1, 1, 0, 0))
conv2d_92 = self.conv2d_92(conv2d_92_pad)
conv2d_93_pad = F.pad(activation_91, (0, 0, 1, 1))
conv2d_93 = self.conv2d_93(conv2d_93_pad)
mixed9_1 = torch.cat((activation_88, activation_89), 1)
batch_normalization_92 = self.batch_normalization_92(conv2d_92)
batch_normalization_93 = self.batch_normalization_93(conv2d_93)
activation_92 = F.relu(batch_normalization_92)
activation_93 = F.relu(batch_normalization_93)
concatenate_2 = torch.cat((activation_92, activation_93), 1)
mixed10 = torch.cat((activation_86, mixed9_1, concatenate_2, activation_94), 1)
avg_pool = F.avg_pool2d(input = mixed10, kernel_size = mixed10.size()[2:])
avg_pool_flatten = avg_pool.view(avg_pool.size(0), -1)
predictions = self.predictions(avg_pool_flatten)
predictions_activation = F.softmax(predictions)
return predictions_activation
@staticmethod
def __dense(name, **kwargs):
layer = nn.Linear(**kwargs)
layer.state_dict()['weight'].copy_(torch.from_numpy(__weights_dict[name]['weights']))
if 'bias' in __weights_dict[name]:
layer.state_dict()['bias'].copy_(torch.from_numpy(__weights_dict[name]['bias']))
return layer
@staticmethod
def __conv(dim, name, **kwargs):
if dim == 1: layer = nn.Conv1d(**kwargs)
elif dim == 2: layer = nn.Conv2d(**kwargs)
elif dim == 3: layer = nn.Conv3d(**kwargs)
else: raise NotImplementedError()
layer.state_dict()['weight'].copy_(torch.from_numpy(__weights_dict[name]['weights']))
if 'bias' in __weights_dict[name]:
layer.state_dict()['bias'].copy_(torch.from_numpy(__weights_dict[name]['bias']))
return layer
@staticmethod
def __batch_normalization(dim, name, **kwargs):
if dim == 1: layer = nn.BatchNorm1d(**kwargs)
elif dim == 2: layer = nn.BatchNorm2d(**kwargs)
elif dim == 3: layer = nn.BatchNorm3d(**kwargs)
else: raise NotImplementedError()
if 'scale' in __weights_dict[name]:
layer.state_dict()['weight'].copy_(torch.from_numpy(__weights_dict[name]['scale']))
else:
layer.weight.data.fill_(1)
if 'bias' in __weights_dict[name]:
layer.state_dict()['bias'].copy_(torch.from_numpy(__weights_dict[name]['bias']))
else:
layer.bias.data.fill_(0)
layer.state_dict()['running_mean'].copy_(torch.from_numpy(__weights_dict[name]['mean']))
layer.state_dict()['running_var'].copy_(torch.from_numpy(__weights_dict[name]['var']))
return layer
<file_sep>import tensorflow as tf
from numpy import prod
def print_activations(t):
print(t.op.name, ' ', t.get_shape().as_list())
def alexnet_inference(images):
"""Build the AlexNet model.
Args:
images: Images Tensor
Returns:
pool5: the last Tensor in the convolutional component of AlexNet.
parameters: a list of Tensors corresponding to the weights and biases of the
AlexNet model.
"""
parameters = []
# conv1
with tf.name_scope('conv1') as scope:
kernel = tf.Variable(tf.truncated_normal([11, 11, 3, 64], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(images, kernel, [1, 4, 4, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[64], dtype=tf.float32),
trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv1 = tf.nn.relu(bias, name=scope)
print_activations(conv1)
parameters += [kernel, biases]
# lrn1
lrn1 = conv1
# with tf.name_scope('lrn1') as scope:
# lrn1 = tf.nn.local_response_normalization(conv1,
# alpha=1e-4,
# beta=0.75,
# depth_radius=2,
# bias=2.0)
# pool1
pool1 = tf.nn.max_pool(lrn1,
ksize=[1, 3, 3, 1],
strides=[1, 2, 2, 1],
padding='VALID',
name='pool1')
print_activations(pool1)
# conv2
with tf.name_scope('conv2') as scope:
kernel = tf.Variable(tf.truncated_normal([5, 5, 64, 192], dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(pool1, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[192], dtype=tf.float32),
trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv2 = tf.nn.relu(bias, name=scope)
parameters += [kernel, biases]
print_activations(conv2)
# lrn2
lrn2 = conv2
# with tf.name_scope('lrn2') as scope:
# lrn2 = tf.nn.local_response_normalization(conv2,
# alpha=1e-4,
# beta=0.75,
# depth_radius=2,
# bias=2.0)
# pool2
pool2 = tf.nn.max_pool(lrn2,
ksize=[1, 3, 3, 1],
strides=[1, 2, 2, 1],
padding='VALID',
name='pool2')
print_activations(pool2)
# conv3
with tf.name_scope('conv3') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 192, 384],
dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(pool2, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[384], dtype=tf.float32),
trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv3 = tf.nn.relu(bias, name=scope)
parameters += [kernel, biases]
print_activations(conv3)
# conv4
with tf.name_scope('conv4') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 384, 256],
dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(conv3, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32),
trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv4 = tf.nn.relu(bias, name=scope)
parameters += [kernel, biases]
print_activations(conv4)
# conv5
with tf.name_scope('conv5') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 256, 256],
dtype=tf.float32,
stddev=1e-1), name='weights')
conv = tf.nn.conv2d(conv4, kernel, [1, 1, 1, 1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape=[256], dtype=tf.float32),
trainable=True, name='biases')
bias = tf.nn.bias_add(conv, biases)
conv5 = tf.nn.relu(bias, name=scope)
parameters += [kernel, biases]
print_activations(conv5)
# pool5
pool5 = tf.nn.max_pool(conv5,
ksize=[1, 3, 3, 1],
strides=[1, 2, 2, 1],
padding='VALID',
name='pool5')
print_activations(pool5)
maxpool5 = pool5
# fc6
# fc(4096, name='fc6')
# fc6W = tf.Variable(net_data["fc6"][0])
# fc6b = tf.Variable(net_data["fc6"][1])
# print(tf.reshape(maxpool5, [-1, int(prod(maxpool5.get_shape()[1:]))])) #1, 9216
with tf.name_scope('fcc6') as scope:
fc6W = tf.Variable(tf.random_normal([9216, 4096],
mean=0,
stddev=1.0,
dtype=tf.float32,
name='fc6_weights'))
fc6b = tf.Variable(tf.constant(0.0, shape=[4096], dtype=tf.float32,
name='fc6_biases'))
fc6 = tf.nn.relu_layer(tf.reshape(maxpool5, [-1, int(prod(maxpool5.get_shape()[1:]))]), fc6W, fc6b)
print_activations(fc6)
# fc7
# fc(4096, name='fc7')
with tf.name_scope('fcc7') as scope:
fc7W = tf.Variable(tf.random_normal([4096, 4096], mean=0, stddev=1.0, dtype=tf.float32, name='fc7_weights'))
fc7b = tf.Variable(tf.constant(0.0, shape=[4096], dtype=tf.float32, name='fc7_biases'))
fc7 = tf.nn.relu_layer(fc6, fc7W, fc7b)
print_activations(fc7)
# fc8
# fc(1000, relu=False, name='fc8')
with tf.name_scope('fcc7') as scope:
fc8W = tf.Variable(tf.random_normal([4096, 1000], mean=0, stddev=1.0, dtype=tf.float32, name='fc8_weights'))
fc8b = tf.Variable(tf.constant(0.0, shape=[1000], dtype=tf.float32, name='fc8_biases'))
fc8 = tf.nn.xw_plus_b(fc7, fc8W, fc8b)
print_activations(fc8)
# return fc8, parameters
prob = tf.nn.softmax(fc8)
return prob, parameters
<file_sep>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import tensorrt as trt
from tensorrt.parsers import uffparser
import pycuda.driver as cuda
import pycuda.autoinit
import numpy as np
from random import randint # generate a random test case
from PIL import Image
import time #import system tools
import os
import uff
OUTPUT_NAMES = ["predictions/Softmax"]
uff_model = uff.from_tensorflow_frozen_model("tf_vgg.pb", OUTPUT_NAMES)
G_LOGGER = trt.infer.ConsoleLogger(trt.infer.LogSeverity.ERROR)
parser = uffparser.create_uff_parser()
parser.register_input("input_1", (3,224,224), 0)
parser.register_output(OUTPUT_NAMES[0])
engine = trt.utils.uff_to_trt_engine(G_LOGGER, uff_model, parser, 1, 1 << 20)
parser.destroy()
img = np.random.randint(256, size=(3, 224, 224)) / 255.
img = img.astype(np.float32)
label = 123
runtime = trt.infer.create_infer_runtime(G_LOGGER)
context = engine.create_execution_context()
output = np.empty(1000, dtype = np.float32)
d_input = cuda.mem_alloc(1 * img.size * img.dtype.itemsize)
d_output = cuda.mem_alloc(1 * output.size * output.dtype.itemsize)
bindings = [int(d_input), int(d_output)]
stream = cuda.Stream()
#transfer input data to device
cuda.memcpy_htod_async(d_input, img, stream)
#execute model
context.enqueue(1, bindings, stream.handle, None)
#transfer predictions back
cuda.memcpy_dtoh_async(output, d_output, stream)
#syncronize threads
stream.synchronize()
print("Test Case: " + str(label))
print ("Prediction: " + str(np.argmax(output)))
trt.utils.write_engine_to_file("./tf_mnist.engine", engine.serialize())
<file_sep>def round_ms(seconds):
return round(1000 * seconds, 3)
def get_image_size(model):
if model in {"alexnet", "resnet", "vgg"}:
image_size = 224
elif model in {"inception"}:
image_size = 299
else:
raise RuntimeError("Image size not defined for model: " + str(model))
return image_size<file_sep>import rpyc
import glob
import time
import argparse
from skimage import io
import random
import numpy as np
from utils import round_ms
from concurrent.futures import ThreadPoolExecutor
import cProfile, pstats, io as io2
tpe = ThreadPoolExecutor(max_workers=None)
#print(tpe)
tpe_out = ThreadPoolExecutor(max_workers=15)
TOTAL_SENT = 500
TIME_BETWEEN_REQUESTS = 0.02
total_latency = 0.0
TOTAL_RECEIVED = 0
IMG_SIZE = None
moving_latency_average = 0.0
first_packet_time = None
last_packet_time = None
ALPHA = 0.925 # moving average
def callback_func_higher(i, start_time):
def cb_func(x):
# print("Got answer", time.time())
global total_latency, count_latency, TOTAL_RECEIVED, ALPHA, moving_latency_average
latency = time.time() - start_time
moving_latency_average = ALPHA * moving_latency_average + (1 - ALPHA) * latency
if not i % 100:
print("GOT " + str(i) + " c: " + str(x) +
" LAT: " + str(round_ms(latency)) +
" Moving LAT avg:" + str(round_ms(moving_latency_average)))
total_latency += latency
TOTAL_RECEIVED += 1
return cb_func
def report_stats():
global last_packet_time, first_packet_time
print("COUNT:", TOTAL_RECEIVED)
time_to_send_all = last_packet_time - first_packet_time
time_to_send_one = time_to_send_all / TOTAL_RECEIVED
packets_sent_per_second = 1 / time_to_send_one
print("TOTAL time taken to send (ms):", round_ms(time_to_send_all))
print("Packets sent per sec", packets_sent_per_second)
print("AVG latency (ms):", round_ms(total_latency / TOTAL_RECEIVED))
def parse_arguments():
global TOTAL_SENT, TIME_BETWEEN_REQUESTS, IMG_SIZE
parser = argparse.ArgumentParser()
parser.add_argument("--requests", help="num of total requests", type=int)
parser.add_argument("--time", help="time between each request", type=float)
parser.add_argument("--size", help="size of img (pix)", type=int)
args = parser.parse_args()
if args.requests is not None:
TOTAL_SENT = args.requests
if args.time is not None:
TIME_BETWEEN_REQUESTS = args.time
if args.size is not None:
IMG_SIZE = args.size
print("Sending", TOTAL_SENT, "requests")
print("Sleeping", TIME_BETWEEN_REQUESTS, "between each")
time.sleep(0.1)
def main():
global first_packet_time, last_packet_time
parse_arguments()
host = "localhost"
port = 1200
conn = rpyc.connect(host, port)
rpyc.BgServingThread.SLEEP_INTERVAL = 0
rpyc.BgServingThread(conn)
#tpe.submit(rpyc.BgServingThread, conn)
filenames = glob.glob("/Users/justas/PycharmProjects/ugproject/img/*.jpg") # assuming gif
random.shuffle(filenames)
t1 = time.time()
first_packet_time = time.time()
for i in range(TOTAL_SENT):
t2 = time.time()
#if not ((i + 1) % 50):
# print("SENT", i, t2 - t1)
t1 = t2
if IMG_SIZE is not None:
img_numpy = np.random.randint(256, size=(IMG_SIZE, IMG_SIZE, 3), dtype=np.uint8)
# print(img_numpy.shape)
else:
file_name = filenames[i]
img_numpy = io.imread(file_name)
# print(img_numpy)
raw_data = img_numpy.tobytes()
tpe_out.submit(send_img, conn, i, raw_data)
time.sleep(TIME_BETWEEN_REQUESTS)
while TOTAL_RECEIVED < TOTAL_SENT:
time.sleep(0.01)
report_stats()
def send_img(conn, i, raw_data):
conn.root.RemoteCallbackTest(raw_data, callback_func_higher(i, start_time=time.time()), )
if not i % 50:
print("SENT\t" + str(i) + " " + str(time.time()))
# print("Sent img", time.time())
# pr.enable()
if i == 0:
global first_packet_time
first_packet_time = time.time()
if i == (TOTAL_SENT - 1):
global last_packet_time
last_packet_time = time.time()
# pr.disable()
# s = io2.StringIO()
# sortby = 'cumulative'
# ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
# ps.print_stats()
# print(s.getvalue())
if __name__ == '__main__':
pr = cProfile.Profile()
main()
<file_sep>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import tensorrt as trt
from tensorrt.parsers import uffparser
import pycuda.driver as cuda
import pycuda.autoinit
import numpy as np
from random import randint # generate a random test case
from PIL import Image
import time #import system tools
import os
import uff
OUTPUT_NAMES = ["fc1000/Softmax"]
BATCH_SIZE = 2
PB_DIR = "../tf_frozen/"
uff_model = uff.from_tensorflow_frozen_model(PB_DIR + "tf_resnet.pb", OUTPUT_NAMES)
G_LOGGER = trt.infer.ConsoleLogger(trt.infer.LogSeverity.ERROR)
parser = uffparser.create_uff_parser()
parser.register_input("input_1", (3,224,224), 0)
parser.register_output(OUTPUT_NAMES[0])
engine = trt.utils.uff_to_trt_engine(G_LOGGER, uff_model, parser, BATCH_SIZE, 0) #1 << 20) #, datatype=trt.infer.DataType.HALF)
parser.destroy()
img = np.random.randint(256, size=(3, 224, 224)) / 255.
img = img.astype(np.float32)
label = 123
runtime = trt.infer.create_infer_runtime(G_LOGGER)
context = engine.create_execution_context()
output = np.empty((BATCH_SIZE,1000), dtype = np.float32)
d_input = cuda.mem_alloc(BATCH_SIZE * img.size * img.dtype.itemsize)
d_output = cuda.mem_alloc(BATCH_SIZE * output.size * output.dtype.itemsize)
bindings = [int(d_input), int(d_output)]
stream = cuda.Stream()
def infer(img_input):
global output
#transfer input data to device
cuda.memcpy_htod_async(d_input, img_input, stream)
#execute model
context.enqueue(BATCH_SIZE, bindings, stream.handle, None)
#transfer predictions back
cuda.memcpy_dtoh_async(output, d_output, stream)
#syncronize threads
stream.synchronize()
total_run_time = 0.0
RUNS = 1000
for i in range(RUNS):
img = np.random.randint(256, size=(BATCH_SIZE, 3, 224, 224)) / 255.
img = img.astype(np.float32)
start = time.time()
infer(img)
end = time.time()
print("Ran for: " + str(1000 * (end-start)) + " ms\t\t" + "test v prod " + str(label) + " " + str(np.argmax(output, axis=1)))
total_run_time += (end-start)
print("Done.")
print("AVG: " + str(1000 * (total_run_time / RUNS)))
<file_sep>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import argparse
import cProfile, pstats, io as io2
from datetime import datetime
import math
import sys
import time
import gc
import numpy as np
from torch.autograd import Variable
import torch
from tensorflow.python.client import timeline
from six.moves import xrange
import torchvision
from memory_profiler import profile
from keras import backend as K
from utils import get_image_size, round_ms
FLAGS = None
g = None
run_metadata = tf.RunMetadata()
options = None
prep_start = 0
def prepare_torch(model):
print("Preparing Torch")
global net
model_file = "torch_frozen/torch_" + str(model) + ".out"
net = torch.load(model_file)
net.cuda()
# torch.set_num_threads(4)
print(net)
def torch_classify(imgs, opts=None, run_md=None):
batch = Variable(torch.from_numpy(imgs))
r = net.forward(batch.cuda())
r.cpu()
# #@profile
def prepare_keras(model):
print("Preparing Keras")
import models_keras
global net, graph
net = models_keras.create_model(model)
graph = tf.get_default_graph()
keras_session = K.get_session()
# if FLAGS.trace:
# run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
# net.compile(loss='MSE', optimizer='Adam', options=run_options, run_metadata=run_metadata)
# old_run = keras_session.run
# print("old_run", old_run)
# print("K.sess 1", keras_session)
#
# def new_run(*args, **kwargs):
# # print("X", self)
# print("NewRunning", *args)
# old_run(*args, **kwargs)
# keras_session.run = new_run
# #@profile
def keras_classify(imgs, opts=None, run_md=None):
global graph
with graph.as_default():
net.predict(imgs)
def prepare_tf(model):
print("Preparing TensorFlow")
global main_sess, images_placeholder, g, g_input, g_output
g = load_frozen_tensorflow_graph(model)
input_tensor_name = g.get_operations()[0].name + ":0"
output_tensor_name = g.get_operations()[-1].name + ":0"
with g.as_default():
g_input = g.get_tensor_by_name(input_tensor_name)
g_output = g.get_tensor_by_name(output_tensor_name)
init_global = tf.global_variables_initializer()
config = tf.ConfigProto()
# Not relevant for non-GPU
# config.gpu_options.allocator_type = 'BFC'
main_sess = tf.Session(graph=g, config=config)
main_sess.run(init_global)
def load_frozen_tensorflow_graph(model):
model_file = "tf_frozen/"
if model == "alexnet":
model_file += "tf_alex.pb"
elif model == "vgg":
model_file += "tf_vgg.pb"
elif model == "inception":
model_file += "tf_inception.pb"
elif model == "resnet":
model_file += "tf_resnet.pb"
print("TF model file", model_file)
with tf.gfile.GFile(model_file, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def, name="main")
return graph
# #@profile
def tf_classify(imgs, opts=None, run_md=None):
main_sess.run(g_output, options=opts, run_metadata=run_md, feed_dict={g_input: imgs})
def time_run(info_string, imgs, fw, model):
global run_inference, run_metadata, prep_start
"""Run the computation and print timing stats.
Args:
session: the TensorFlow session to run the computation under.
target: the target Tensor that is passed to the session's run() function.
info_string: a string summarizing this run, to be printed with the stats.
Returns:
None
"""
num_steps_burn_in = 10
total_duration = 0.0
total_duration_squared = 0.0
total_process_duration = 0.0
total_process_duration_squared = 0.0
file_name = 'tf_traces/batch_' + str(fw) + "_" + str(model) + str(FLAGS.batch_size) + '.json'
torch_chrome_file_name = 'torch_traces/batch_' + str(fw) + "_" + str(model) + str(FLAGS.batch_size) + '.json'
dump_profiler_file_name = 'profiler_traces/' + str(fw) + "_" + str(model) + str(FLAGS.batch_size) + '.pstats'
pr = cProfile.Profile()
output_trace = FLAGS.trace
print("Output trace: " + str(output_trace))
for i in xrange(FLAGS.num_batches + num_steps_burn_in):
# options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) if output_trace else None
# run_metadata = tf.RunMetadata()
start_p_time = time.process_time()
start_time = time.time()
if output_trace:
if fw in {"torch", "pytorch"}:
with torch.autograd.profiler.profile() as torch_prof:
run_inference(imgs)
# print(torch_prof.key_averages())
torch_prof.export_chrome_trace(torch_chrome_file_name)
else:
if i >= num_steps_burn_in:
pr.enable()
# run_inference(imgs, opts=options, run_md=run_metadata)
run_inference(imgs) # , opts=options, run_md=run_metadata)
if i >= num_steps_burn_in:
pr.disable()
else:
run_inference(imgs)
duration = time.time() - start_time
p_duration = time.process_time() - start_p_time
if output_trace:
fetched_timeline = timeline.Timeline(run_metadata.step_stats)
chrome_trace = fetched_timeline.generate_chrome_trace_format(show_dataflow=True, show_memory=False)
with open(file_name, 'w') as f:
f.write(chrome_trace)
if i >= num_steps_burn_in:
if not i % 10:
print('%s: step %d, duration = %.3f' %
(datetime.now(), i - num_steps_burn_in, duration))
total_duration += duration
total_duration_squared += duration * duration
total_process_duration += p_duration
total_process_duration_squared += p_duration * p_duration
# if i == 0:
# print(datetime.now(), "Classified first batch, time since start (ms): ",
# int(round_ms(time.time() - prep_start)))
if output_trace:
s = io2.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats("cumulative")
ps.dump_stats(dump_profiler_file_name)
# ps.print_stats()
mn = total_duration / FLAGS.num_batches
vr = total_duration_squared / FLAGS.num_batches - mn * mn
sd = math.sqrt(vr)
mean_process = total_process_duration / FLAGS.num_batches
var_process = total_process_duration_squared / FLAGS.num_batches - mean_process * mean_process
sd_process = math.sqrt(var_process)
print('%s: %s across %d steps (WALL TIME), %.3f +/- %.3f sec / batch' %
(datetime.now(), info_string, FLAGS.num_batches, mn, sd))
print('%s: PROCESS_TIME: %.3f +/- %.3f sec / batch' %
(datetime.now(), mean_process, sd_process))
def generate_dummy_images(fw, batch_size, image_size):
if fw in {"torch", "pytorch"}:
images = np.random.randint(256, size=(batch_size, 3, image_size, image_size)) / 255.
elif fw in {"tensorflow", "tf", "keras"}:
images = np.random.randint(256, size=(batch_size, image_size, image_size, 3)) / 255.
else:
raise RuntimeError("Mock images not defined for framework: " + str(fw))
print("Images shape", images.shape)
return images.astype(np.float32)
def run_benchmark(fw, model):
global g
if fw in {"keras"}:
g = g or tf.get_default_graph()
image_size = get_image_size(model)
# Generate some dummy images.
images = generate_dummy_images(fw, FLAGS.batch_size, image_size)
info_string = str(fw) + ", " + str(model) + ", batch_size " + str(FLAGS.batch_size) + " |"
time_run(info_string, images, fw, model)
# #@profile
def prepare_benchmark(fw, model):
global run_inference
print("Params: ", fw, "running", model)
if fw in {"tensorflow", "tf"}:
prepare_tf(model)
run_inference = tf_classify
elif fw in {"pytorch", "torch"}:
prepare_torch(model)
run_inference = torch_classify
elif fw in {"keras"}:
prepare_keras(model)
run_inference = keras_classify
else:
raise RuntimeError("No framework with this name")
# @profile
def main(_):
# pr = cProfile.Profile()
global prep_start
model = FLAGS.model.lower()
framework = FLAGS.framework.lower()
# prep_start = time.time()
# pr.enable()
prepare_benchmark(framework, model)
# pr.disable()
# s = io2.StringIO()
# ps = pstats.Stats(pr, stream=s).sort_stats("cumulative")
# prep_pstats = str(framework) + "_" + str(model) + "_prep.pstats"
# ps.dump_stats(prep_pstats)
# prep_end = time.time()
# print("PREP_TIME (ms)", int(round_ms(prep_end - prep_start)))
run_benchmark(framework, model)
def get_argument_parser():
global parser
parser = argparse.ArgumentParser()
parser.add_argument(
'--batch_size',
type=int,
default=1,
help='Batch size.'
)
parser.add_argument(
'--num_batches',
type=int,
default=20,
help='Number of batches to run.'
)
parser.add_argument(
'--framework',
type=str,
default="tensorflow",
help='Framework to use'
)
parser.add_argument(
'--model',
type=str,
default="alexnet",
help='ConvNet model to use'
)
parser.add_argument(
'--trace',
type=bool,
default=False,
help='trace'
)
return parser
if __name__ == '__main__':
parser = get_argument_parser()
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
<file_sep>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import tensorrt as trt
from tensorrt.parsers import uffparser
import pycuda.driver as cuda
import pycuda.autoinit
import numpy as np
from random import randint # generate a random test case
from PIL import Image
import time #import system tools
import os
import uff
OUTPUT_NAMES = ["predictions/Softmax"]
BATCH_SIZE = 1
PB_DIR = "../tf_frozen/"
uff_model = uff.from_tensorflow_frozen_model(PB_DIR + "tf_vgg.pb", OUTPUT_NAMES)
G_LOGGER = trt.infer.ConsoleLogger(trt.infer.LogSeverity.ERROR)
parser = uffparser.create_uff_parser()
parser.register_input("input_1", (3,224,224), 0)
parser.register_output(OUTPUT_NAMES[0])
engine = trt.utils.uff_to_trt_engine(G_LOGGER, uff_model, parser, BATCH_SIZE, 1 << 20)
#engine = trt.utils.load_engine(G_LOGGER, "./vgg.engine")
#parser.destroy()
img = np.random.randint(256, size=(3, 224, 224)) / 255.
img = img.astype(np.float32)
label = 123
runtime = trt.infer.create_infer_runtime(G_LOGGER)
context = engine.create_execution_context()
output = np.empty(1000, dtype = np.float32)
d_input = cuda.mem_alloc(BATCH_SIZE * img.size * img.dtype.itemsize)
d_output = cuda.mem_alloc(BATCH_SIZE * output.size * output.dtype.itemsize)
bindings = [int(d_input), int(d_output)]
stream = cuda.Stream()
def infer():
global img
#transfer input data to device
cuda.memcpy_htod_async(d_input, img, stream)
#execute model
context.enqueue(BATCH_SIZE, bindings, stream.handle, None)
#transfer predictions back
cuda.memcpy_dtoh_async(output, d_output, stream)
#syncronize threads
stream.synchronize()
for i in range(1000):
img = np.random.randint(256, size=(3, 224, 224)) / 255.
img = img.astype(np.float32)
start = time.time()
infer()
end = time.time()
print("Test vs Pred: " + str(label) + " " + str(np.argmax(output)))
print("Ran for: " + str(1000 * (end-start)) + " ms")
<file_sep>python benchmark.py --batch_size 2 --num_batches 1 --framework keras --model inception<file_sep>'''
HelloWorld example using TensorFlow library.
Author: <NAME>
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
from __future__ import print_function
import tensorflow as tf
import numpy as np
def load_frozen_graph():
with tf.gfile.GFile("tf_vgg.pb", "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def, name="main")
return graph
# Simple hello world using TensorFlow
# Create a Constant op
# The op is added as a node to the default graph.
#
# The value returned by the constructor represents the output
# of the Constant op.
hello = tf.constant('Hello, TensorFlow!')
# Start tf session
g = load_frozen_graph()
sess = tf.Session(graph=g)
# Run the op
for op in g.as_graph_def().node:
print(op.name)
# for op in g.get_operations():
# print(op.name)
x = g.get_tensor_by_name('main/input_1:0')
y = g.get_tensor_by_name('main/output_node0:0')
for i in range(10):
print("BEFORE")
y_out = sess.run(y, feed_dict={x: np.random.randint(225, size=(5,224,224,3))})
print(y_out.argmax(axis=1))
# print(sess.run(y))
print("AFTER")
<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
__weights_dict = dict()
def load_weights(weight_file):
if weight_file == None:
return
try:
weights_dict = np.load(weight_file).item()
except:
weights_dict = np.load(weight_file, encoding='bytes').item()
return weights_dict
class KitModel(nn.Module):
def __init__(self, weight_file):
super(KitModel, self).__init__()
global __weights_dict
__weights_dict = load_weights(weight_file)
self.conv1 = self.__conv(2, name='conv1', in_channels=3, out_channels=64, kernel_size=(7, 7), stride=(2, 2), groups=1, bias=True)
self.bn_conv1 = self.__batch_normalization(2, 'bn_conv1', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.res2a_branch2a = self.__conv(2, name='res2a_branch2a', in_channels=64, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.res2a_branch1 = self.__conv(2, name='res2a_branch1', in_channels=64, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn2a_branch2a = self.__batch_normalization(2, 'bn2a_branch2a', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.bn2a_branch1 = self.__batch_normalization(2, 'bn2a_branch1', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res2a_branch2b = self.__conv(2, name='res2a_branch2b', in_channels=64, out_channels=64, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn2a_branch2b = self.__batch_normalization(2, 'bn2a_branch2b', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.res2a_branch2c = self.__conv(2, name='res2a_branch2c', in_channels=64, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn2a_branch2c = self.__batch_normalization(2, 'bn2a_branch2c', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res2b_branch2a = self.__conv(2, name='res2b_branch2a', in_channels=256, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn2b_branch2a = self.__batch_normalization(2, 'bn2b_branch2a', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.res2b_branch2b = self.__conv(2, name='res2b_branch2b', in_channels=64, out_channels=64, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn2b_branch2b = self.__batch_normalization(2, 'bn2b_branch2b', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.res2b_branch2c = self.__conv(2, name='res2b_branch2c', in_channels=64, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn2b_branch2c = self.__batch_normalization(2, 'bn2b_branch2c', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res2c_branch2a = self.__conv(2, name='res2c_branch2a', in_channels=256, out_channels=64, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn2c_branch2a = self.__batch_normalization(2, 'bn2c_branch2a', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.res2c_branch2b = self.__conv(2, name='res2c_branch2b', in_channels=64, out_channels=64, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn2c_branch2b = self.__batch_normalization(2, 'bn2c_branch2b', num_features = 64, eps = 0.0010000000474974513, momentum = 0.0)
self.res2c_branch2c = self.__conv(2, name='res2c_branch2c', in_channels=64, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn2c_branch2c = self.__batch_normalization(2, 'bn2c_branch2c', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res3a_branch2a = self.__conv(2, name='res3a_branch2a', in_channels=256, out_channels=128, kernel_size=(1, 1), stride=(2, 2), groups=1, bias=True)
self.res3a_branch1 = self.__conv(2, name='res3a_branch1', in_channels=256, out_channels=512, kernel_size=(1, 1), stride=(2, 2), groups=1, bias=True)
self.bn3a_branch2a = self.__batch_normalization(2, 'bn3a_branch2a', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.bn3a_branch1 = self.__batch_normalization(2, 'bn3a_branch1', num_features = 512, eps = 0.0010000000474974513, momentum = 0.0)
self.res3a_branch2b = self.__conv(2, name='res3a_branch2b', in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn3a_branch2b = self.__batch_normalization(2, 'bn3a_branch2b', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.res3a_branch2c = self.__conv(2, name='res3a_branch2c', in_channels=128, out_channels=512, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn3a_branch2c = self.__batch_normalization(2, 'bn3a_branch2c', num_features = 512, eps = 0.0010000000474974513, momentum = 0.0)
self.res3b_branch2a = self.__conv(2, name='res3b_branch2a', in_channels=512, out_channels=128, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn3b_branch2a = self.__batch_normalization(2, 'bn3b_branch2a', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.res3b_branch2b = self.__conv(2, name='res3b_branch2b', in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn3b_branch2b = self.__batch_normalization(2, 'bn3b_branch2b', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.res3b_branch2c = self.__conv(2, name='res3b_branch2c', in_channels=128, out_channels=512, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn3b_branch2c = self.__batch_normalization(2, 'bn3b_branch2c', num_features = 512, eps = 0.0010000000474974513, momentum = 0.0)
self.res3c_branch2a = self.__conv(2, name='res3c_branch2a', in_channels=512, out_channels=128, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn3c_branch2a = self.__batch_normalization(2, 'bn3c_branch2a', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.res3c_branch2b = self.__conv(2, name='res3c_branch2b', in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn3c_branch2b = self.__batch_normalization(2, 'bn3c_branch2b', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.res3c_branch2c = self.__conv(2, name='res3c_branch2c', in_channels=128, out_channels=512, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn3c_branch2c = self.__batch_normalization(2, 'bn3c_branch2c', num_features = 512, eps = 0.0010000000474974513, momentum = 0.0)
self.res3d_branch2a = self.__conv(2, name='res3d_branch2a', in_channels=512, out_channels=128, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn3d_branch2a = self.__batch_normalization(2, 'bn3d_branch2a', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.res3d_branch2b = self.__conv(2, name='res3d_branch2b', in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn3d_branch2b = self.__batch_normalization(2, 'bn3d_branch2b', num_features = 128, eps = 0.0010000000474974513, momentum = 0.0)
self.res3d_branch2c = self.__conv(2, name='res3d_branch2c', in_channels=128, out_channels=512, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn3d_branch2c = self.__batch_normalization(2, 'bn3d_branch2c', num_features = 512, eps = 0.0010000000474974513, momentum = 0.0)
self.res4a_branch2a = self.__conv(2, name='res4a_branch2a', in_channels=512, out_channels=256, kernel_size=(1, 1), stride=(2, 2), groups=1, bias=True)
self.res4a_branch1 = self.__conv(2, name='res4a_branch1', in_channels=512, out_channels=1024, kernel_size=(1, 1), stride=(2, 2), groups=1, bias=True)
self.bn4a_branch2a = self.__batch_normalization(2, 'bn4a_branch2a', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.bn4a_branch1 = self.__batch_normalization(2, 'bn4a_branch1', num_features = 1024, eps = 0.0010000000474974513, momentum = 0.0)
self.res4a_branch2b = self.__conv(2, name='res4a_branch2b', in_channels=256, out_channels=256, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn4a_branch2b = self.__batch_normalization(2, 'bn4a_branch2b', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res4a_branch2c = self.__conv(2, name='res4a_branch2c', in_channels=256, out_channels=1024, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn4a_branch2c = self.__batch_normalization(2, 'bn4a_branch2c', num_features = 1024, eps = 0.0010000000474974513, momentum = 0.0)
self.res4b_branch2a = self.__conv(2, name='res4b_branch2a', in_channels=1024, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn4b_branch2a = self.__batch_normalization(2, 'bn4b_branch2a', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res4b_branch2b = self.__conv(2, name='res4b_branch2b', in_channels=256, out_channels=256, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn4b_branch2b = self.__batch_normalization(2, 'bn4b_branch2b', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res4b_branch2c = self.__conv(2, name='res4b_branch2c', in_channels=256, out_channels=1024, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn4b_branch2c = self.__batch_normalization(2, 'bn4b_branch2c', num_features = 1024, eps = 0.0010000000474974513, momentum = 0.0)
self.res4c_branch2a = self.__conv(2, name='res4c_branch2a', in_channels=1024, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn4c_branch2a = self.__batch_normalization(2, 'bn4c_branch2a', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res4c_branch2b = self.__conv(2, name='res4c_branch2b', in_channels=256, out_channels=256, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn4c_branch2b = self.__batch_normalization(2, 'bn4c_branch2b', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res4c_branch2c = self.__conv(2, name='res4c_branch2c', in_channels=256, out_channels=1024, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn4c_branch2c = self.__batch_normalization(2, 'bn4c_branch2c', num_features = 1024, eps = 0.0010000000474974513, momentum = 0.0)
self.res4d_branch2a = self.__conv(2, name='res4d_branch2a', in_channels=1024, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn4d_branch2a = self.__batch_normalization(2, 'bn4d_branch2a', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res4d_branch2b = self.__conv(2, name='res4d_branch2b', in_channels=256, out_channels=256, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn4d_branch2b = self.__batch_normalization(2, 'bn4d_branch2b', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res4d_branch2c = self.__conv(2, name='res4d_branch2c', in_channels=256, out_channels=1024, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn4d_branch2c = self.__batch_normalization(2, 'bn4d_branch2c', num_features = 1024, eps = 0.0010000000474974513, momentum = 0.0)
self.res4e_branch2a = self.__conv(2, name='res4e_branch2a', in_channels=1024, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn4e_branch2a = self.__batch_normalization(2, 'bn4e_branch2a', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res4e_branch2b = self.__conv(2, name='res4e_branch2b', in_channels=256, out_channels=256, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn4e_branch2b = self.__batch_normalization(2, 'bn4e_branch2b', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res4e_branch2c = self.__conv(2, name='res4e_branch2c', in_channels=256, out_channels=1024, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn4e_branch2c = self.__batch_normalization(2, 'bn4e_branch2c', num_features = 1024, eps = 0.0010000000474974513, momentum = 0.0)
self.res4f_branch2a = self.__conv(2, name='res4f_branch2a', in_channels=1024, out_channels=256, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn4f_branch2a = self.__batch_normalization(2, 'bn4f_branch2a', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res4f_branch2b = self.__conv(2, name='res4f_branch2b', in_channels=256, out_channels=256, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn4f_branch2b = self.__batch_normalization(2, 'bn4f_branch2b', num_features = 256, eps = 0.0010000000474974513, momentum = 0.0)
self.res4f_branch2c = self.__conv(2, name='res4f_branch2c', in_channels=256, out_channels=1024, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn4f_branch2c = self.__batch_normalization(2, 'bn4f_branch2c', num_features = 1024, eps = 0.0010000000474974513, momentum = 0.0)
self.res5a_branch2a = self.__conv(2, name='res5a_branch2a', in_channels=1024, out_channels=512, kernel_size=(1, 1), stride=(2, 2), groups=1, bias=True)
self.res5a_branch1 = self.__conv(2, name='res5a_branch1', in_channels=1024, out_channels=2048, kernel_size=(1, 1), stride=(2, 2), groups=1, bias=True)
self.bn5a_branch2a = self.__batch_normalization(2, 'bn5a_branch2a', num_features = 512, eps = 0.0010000000474974513, momentum = 0.0)
self.bn5a_branch1 = self.__batch_normalization(2, 'bn5a_branch1', num_features = 2048, eps = 0.0010000000474974513, momentum = 0.0)
self.res5a_branch2b = self.__conv(2, name='res5a_branch2b', in_channels=512, out_channels=512, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn5a_branch2b = self.__batch_normalization(2, 'bn5a_branch2b', num_features = 512, eps = 0.0010000000474974513, momentum = 0.0)
self.res5a_branch2c = self.__conv(2, name='res5a_branch2c', in_channels=512, out_channels=2048, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn5a_branch2c = self.__batch_normalization(2, 'bn5a_branch2c', num_features = 2048, eps = 0.0010000000474974513, momentum = 0.0)
self.res5b_branch2a = self.__conv(2, name='res5b_branch2a', in_channels=2048, out_channels=512, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn5b_branch2a = self.__batch_normalization(2, 'bn5b_branch2a', num_features = 512, eps = 0.0010000000474974513, momentum = 0.0)
self.res5b_branch2b = self.__conv(2, name='res5b_branch2b', in_channels=512, out_channels=512, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn5b_branch2b = self.__batch_normalization(2, 'bn5b_branch2b', num_features = 512, eps = 0.0010000000474974513, momentum = 0.0)
self.res5b_branch2c = self.__conv(2, name='res5b_branch2c', in_channels=512, out_channels=2048, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn5b_branch2c = self.__batch_normalization(2, 'bn5b_branch2c', num_features = 2048, eps = 0.0010000000474974513, momentum = 0.0)
self.res5c_branch2a = self.__conv(2, name='res5c_branch2a', in_channels=2048, out_channels=512, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn5c_branch2a = self.__batch_normalization(2, 'bn5c_branch2a', num_features = 512, eps = 0.0010000000474974513, momentum = 0.0)
self.res5c_branch2b = self.__conv(2, name='res5c_branch2b', in_channels=512, out_channels=512, kernel_size=(3, 3), stride=(1, 1), groups=1, bias=True)
self.bn5c_branch2b = self.__batch_normalization(2, 'bn5c_branch2b', num_features = 512, eps = 0.0010000000474974513, momentum = 0.0)
self.res5c_branch2c = self.__conv(2, name='res5c_branch2c', in_channels=512, out_channels=2048, kernel_size=(1, 1), stride=(1, 1), groups=1, bias=True)
self.bn5c_branch2c = self.__batch_normalization(2, 'bn5c_branch2c', num_features = 2048, eps = 0.0010000000474974513, momentum = 0.0)
self.fc1000 = self.__dense(name = 'fc1000', in_features = 2048, out_features = 1000, bias = True)
def forward(self, x):
conv1_pad = F.pad(x, (2, 3, 2, 3))
conv1 = self.conv1(conv1_pad)
bn_conv1 = self.bn_conv1(conv1)
activation_1 = F.relu(bn_conv1)
max_pooling2d_1 = F.max_pool2d(activation_1, kernel_size=(3, 3), stride=(2, 2))
res2a_branch2a = self.res2a_branch2a(max_pooling2d_1)
res2a_branch1 = self.res2a_branch1(max_pooling2d_1)
bn2a_branch2a = self.bn2a_branch2a(res2a_branch2a)
bn2a_branch1 = self.bn2a_branch1(res2a_branch1)
activation_2 = F.relu(bn2a_branch2a)
res2a_branch2b_pad = F.pad(activation_2, (1, 1, 1, 1))
res2a_branch2b = self.res2a_branch2b(res2a_branch2b_pad)
bn2a_branch2b = self.bn2a_branch2b(res2a_branch2b)
activation_3 = F.relu(bn2a_branch2b)
res2a_branch2c = self.res2a_branch2c(activation_3)
bn2a_branch2c = self.bn2a_branch2c(res2a_branch2c)
add_1 = bn2a_branch2c+ bn2a_branch1
activation_4 = F.relu(add_1)
res2b_branch2a = self.res2b_branch2a(activation_4)
bn2b_branch2a = self.bn2b_branch2a(res2b_branch2a)
activation_5 = F.relu(bn2b_branch2a)
res2b_branch2b_pad = F.pad(activation_5, (1, 1, 1, 1))
res2b_branch2b = self.res2b_branch2b(res2b_branch2b_pad)
bn2b_branch2b = self.bn2b_branch2b(res2b_branch2b)
activation_6 = F.relu(bn2b_branch2b)
res2b_branch2c = self.res2b_branch2c(activation_6)
bn2b_branch2c = self.bn2b_branch2c(res2b_branch2c)
add_2 = bn2b_branch2c+ activation_4
activation_7 = F.relu(add_2)
res2c_branch2a = self.res2c_branch2a(activation_7)
bn2c_branch2a = self.bn2c_branch2a(res2c_branch2a)
activation_8 = F.relu(bn2c_branch2a)
res2c_branch2b_pad = F.pad(activation_8, (1, 1, 1, 1))
res2c_branch2b = self.res2c_branch2b(res2c_branch2b_pad)
bn2c_branch2b = self.bn2c_branch2b(res2c_branch2b)
activation_9 = F.relu(bn2c_branch2b)
res2c_branch2c = self.res2c_branch2c(activation_9)
bn2c_branch2c = self.bn2c_branch2c(res2c_branch2c)
add_3 = bn2c_branch2c+ activation_7
activation_10 = F.relu(add_3)
res3a_branch2a = self.res3a_branch2a(activation_10)
res3a_branch1 = self.res3a_branch1(activation_10)
bn3a_branch2a = self.bn3a_branch2a(res3a_branch2a)
bn3a_branch1 = self.bn3a_branch1(res3a_branch1)
activation_11 = F.relu(bn3a_branch2a)
res3a_branch2b_pad = F.pad(activation_11, (1, 1, 1, 1))
res3a_branch2b = self.res3a_branch2b(res3a_branch2b_pad)
bn3a_branch2b = self.bn3a_branch2b(res3a_branch2b)
activation_12 = F.relu(bn3a_branch2b)
res3a_branch2c = self.res3a_branch2c(activation_12)
bn3a_branch2c = self.bn3a_branch2c(res3a_branch2c)
add_4 = bn3a_branch2c+ bn3a_branch1
activation_13 = F.relu(add_4)
res3b_branch2a = self.res3b_branch2a(activation_13)
bn3b_branch2a = self.bn3b_branch2a(res3b_branch2a)
activation_14 = F.relu(bn3b_branch2a)
res3b_branch2b_pad = F.pad(activation_14, (1, 1, 1, 1))
res3b_branch2b = self.res3b_branch2b(res3b_branch2b_pad)
bn3b_branch2b = self.bn3b_branch2b(res3b_branch2b)
activation_15 = F.relu(bn3b_branch2b)
res3b_branch2c = self.res3b_branch2c(activation_15)
bn3b_branch2c = self.bn3b_branch2c(res3b_branch2c)
add_5 = bn3b_branch2c+ activation_13
activation_16 = F.relu(add_5)
res3c_branch2a = self.res3c_branch2a(activation_16)
bn3c_branch2a = self.bn3c_branch2a(res3c_branch2a)
activation_17 = F.relu(bn3c_branch2a)
res3c_branch2b_pad = F.pad(activation_17, (1, 1, 1, 1))
res3c_branch2b = self.res3c_branch2b(res3c_branch2b_pad)
bn3c_branch2b = self.bn3c_branch2b(res3c_branch2b)
activation_18 = F.relu(bn3c_branch2b)
res3c_branch2c = self.res3c_branch2c(activation_18)
bn3c_branch2c = self.bn3c_branch2c(res3c_branch2c)
add_6 = bn3c_branch2c+ activation_16
activation_19 = F.relu(add_6)
res3d_branch2a = self.res3d_branch2a(activation_19)
bn3d_branch2a = self.bn3d_branch2a(res3d_branch2a)
activation_20 = F.relu(bn3d_branch2a)
res3d_branch2b_pad = F.pad(activation_20, (1, 1, 1, 1))
res3d_branch2b = self.res3d_branch2b(res3d_branch2b_pad)
bn3d_branch2b = self.bn3d_branch2b(res3d_branch2b)
activation_21 = F.relu(bn3d_branch2b)
res3d_branch2c = self.res3d_branch2c(activation_21)
bn3d_branch2c = self.bn3d_branch2c(res3d_branch2c)
add_7 = bn3d_branch2c+ activation_19
activation_22 = F.relu(add_7)
res4a_branch2a = self.res4a_branch2a(activation_22)
res4a_branch1 = self.res4a_branch1(activation_22)
bn4a_branch2a = self.bn4a_branch2a(res4a_branch2a)
bn4a_branch1 = self.bn4a_branch1(res4a_branch1)
activation_23 = F.relu(bn4a_branch2a)
res4a_branch2b_pad = F.pad(activation_23, (1, 1, 1, 1))
res4a_branch2b = self.res4a_branch2b(res4a_branch2b_pad)
bn4a_branch2b = self.bn4a_branch2b(res4a_branch2b)
activation_24 = F.relu(bn4a_branch2b)
res4a_branch2c = self.res4a_branch2c(activation_24)
bn4a_branch2c = self.bn4a_branch2c(res4a_branch2c)
add_8 = bn4a_branch2c+ bn4a_branch1
activation_25 = F.relu(add_8)
res4b_branch2a = self.res4b_branch2a(activation_25)
bn4b_branch2a = self.bn4b_branch2a(res4b_branch2a)
activation_26 = F.relu(bn4b_branch2a)
res4b_branch2b_pad = F.pad(activation_26, (1, 1, 1, 1))
res4b_branch2b = self.res4b_branch2b(res4b_branch2b_pad)
bn4b_branch2b = self.bn4b_branch2b(res4b_branch2b)
activation_27 = F.relu(bn4b_branch2b)
res4b_branch2c = self.res4b_branch2c(activation_27)
bn4b_branch2c = self.bn4b_branch2c(res4b_branch2c)
add_9 = bn4b_branch2c+ activation_25
activation_28 = F.relu(add_9)
res4c_branch2a = self.res4c_branch2a(activation_28)
bn4c_branch2a = self.bn4c_branch2a(res4c_branch2a)
activation_29 = F.relu(bn4c_branch2a)
res4c_branch2b_pad = F.pad(activation_29, (1, 1, 1, 1))
res4c_branch2b = self.res4c_branch2b(res4c_branch2b_pad)
bn4c_branch2b = self.bn4c_branch2b(res4c_branch2b)
activation_30 = F.relu(bn4c_branch2b)
res4c_branch2c = self.res4c_branch2c(activation_30)
bn4c_branch2c = self.bn4c_branch2c(res4c_branch2c)
add_10 = bn4c_branch2c+ activation_28
activation_31 = F.relu(add_10)
res4d_branch2a = self.res4d_branch2a(activation_31)
bn4d_branch2a = self.bn4d_branch2a(res4d_branch2a)
activation_32 = F.relu(bn4d_branch2a)
res4d_branch2b_pad = F.pad(activation_32, (1, 1, 1, 1))
res4d_branch2b = self.res4d_branch2b(res4d_branch2b_pad)
bn4d_branch2b = self.bn4d_branch2b(res4d_branch2b)
activation_33 = F.relu(bn4d_branch2b)
res4d_branch2c = self.res4d_branch2c(activation_33)
bn4d_branch2c = self.bn4d_branch2c(res4d_branch2c)
add_11 = bn4d_branch2c+ activation_31
activation_34 = F.relu(add_11)
res4e_branch2a = self.res4e_branch2a(activation_34)
bn4e_branch2a = self.bn4e_branch2a(res4e_branch2a)
activation_35 = F.relu(bn4e_branch2a)
res4e_branch2b_pad = F.pad(activation_35, (1, 1, 1, 1))
res4e_branch2b = self.res4e_branch2b(res4e_branch2b_pad)
bn4e_branch2b = self.bn4e_branch2b(res4e_branch2b)
activation_36 = F.relu(bn4e_branch2b)
res4e_branch2c = self.res4e_branch2c(activation_36)
bn4e_branch2c = self.bn4e_branch2c(res4e_branch2c)
add_12 = bn4e_branch2c+ activation_34
activation_37 = F.relu(add_12)
res4f_branch2a = self.res4f_branch2a(activation_37)
bn4f_branch2a = self.bn4f_branch2a(res4f_branch2a)
activation_38 = F.relu(bn4f_branch2a)
res4f_branch2b_pad = F.pad(activation_38, (1, 1, 1, 1))
res4f_branch2b = self.res4f_branch2b(res4f_branch2b_pad)
bn4f_branch2b = self.bn4f_branch2b(res4f_branch2b)
activation_39 = F.relu(bn4f_branch2b)
res4f_branch2c = self.res4f_branch2c(activation_39)
bn4f_branch2c = self.bn4f_branch2c(res4f_branch2c)
add_13 = bn4f_branch2c+ activation_37
activation_40 = F.relu(add_13)
res5a_branch2a = self.res5a_branch2a(activation_40)
res5a_branch1 = self.res5a_branch1(activation_40)
bn5a_branch2a = self.bn5a_branch2a(res5a_branch2a)
bn5a_branch1 = self.bn5a_branch1(res5a_branch1)
activation_41 = F.relu(bn5a_branch2a)
res5a_branch2b_pad = F.pad(activation_41, (1, 1, 1, 1))
res5a_branch2b = self.res5a_branch2b(res5a_branch2b_pad)
bn5a_branch2b = self.bn5a_branch2b(res5a_branch2b)
activation_42 = F.relu(bn5a_branch2b)
res5a_branch2c = self.res5a_branch2c(activation_42)
bn5a_branch2c = self.bn5a_branch2c(res5a_branch2c)
add_14 = bn5a_branch2c+ bn5a_branch1
activation_43 = F.relu(add_14)
res5b_branch2a = self.res5b_branch2a(activation_43)
bn5b_branch2a = self.bn5b_branch2a(res5b_branch2a)
activation_44 = F.relu(bn5b_branch2a)
res5b_branch2b_pad = F.pad(activation_44, (1, 1, 1, 1))
res5b_branch2b = self.res5b_branch2b(res5b_branch2b_pad)
bn5b_branch2b = self.bn5b_branch2b(res5b_branch2b)
activation_45 = F.relu(bn5b_branch2b)
res5b_branch2c = self.res5b_branch2c(activation_45)
bn5b_branch2c = self.bn5b_branch2c(res5b_branch2c)
add_15 = bn5b_branch2c+ activation_43
activation_46 = F.relu(add_15)
res5c_branch2a = self.res5c_branch2a(activation_46)
bn5c_branch2a = self.bn5c_branch2a(res5c_branch2a)
activation_47 = F.relu(bn5c_branch2a)
res5c_branch2b_pad = F.pad(activation_47, (1, 1, 1, 1))
res5c_branch2b = self.res5c_branch2b(res5c_branch2b_pad)
bn5c_branch2b = self.bn5c_branch2b(res5c_branch2b)
activation_48 = F.relu(bn5c_branch2b)
res5c_branch2c = self.res5c_branch2c(activation_48)
bn5c_branch2c = self.bn5c_branch2c(res5c_branch2c)
add_16 = bn5c_branch2c+ activation_46
activation_49 = F.relu(add_16)
avg_pool = F.avg_pool2d(activation_49, kernel_size=(7, 7), stride=(7, 7))
flatten_1 = avg_pool.view(avg_pool.size(0), -1)
fc1000 = self.fc1000(flatten_1)
fc1000_activation = F.softmax(fc1000)
return fc1000_activation
@staticmethod
def __conv(dim, name, **kwargs):
if dim == 1: layer = nn.Conv1d(**kwargs)
elif dim == 2: layer = nn.Conv2d(**kwargs)
elif dim == 3: layer = nn.Conv3d(**kwargs)
else: raise NotImplementedError()
layer.state_dict()['weight'].copy_(torch.from_numpy(__weights_dict[name]['weights']))
if 'bias' in __weights_dict[name]:
layer.state_dict()['bias'].copy_(torch.from_numpy(__weights_dict[name]['bias']))
return layer
@staticmethod
def __batch_normalization(dim, name, **kwargs):
if dim == 1: layer = nn.BatchNorm1d(**kwargs)
elif dim == 2: layer = nn.BatchNorm2d(**kwargs)
elif dim == 3: layer = nn.BatchNorm3d(**kwargs)
else: raise NotImplementedError()
if 'scale' in __weights_dict[name]:
layer.state_dict()['weight'].copy_(torch.from_numpy(__weights_dict[name]['scale']))
else:
layer.weight.data.fill_(1)
if 'bias' in __weights_dict[name]:
layer.state_dict()['bias'].copy_(torch.from_numpy(__weights_dict[name]['bias']))
else:
layer.bias.data.fill_(0)
layer.state_dict()['running_mean'].copy_(torch.from_numpy(__weights_dict[name]['mean']))
layer.state_dict()['running_var'].copy_(torch.from_numpy(__weights_dict[name]['var']))
return layer
@staticmethod
def __dense(name, **kwargs):
layer = nn.Linear(**kwargs)
layer.state_dict()['weight'].copy_(torch.from_numpy(__weights_dict[name]['weights']))
if 'bias' in __weights_dict[name]:
layer.state_dict()['bias'].copy_(torch.from_numpy(__weights_dict[name]['bias']))
return layer
| 8a20b41c223dfbf273567f9949f8b637b720c1c2 | [
"Python",
"Shell"
] | 20 | Python | justasbr/batch-dispatch | 0a390b4e17ea7abf1243450b70ee15b034a48f52 | b1e2adb73399e00086763b4890f5b2548d629a7d | |
refs/heads/master | <repo_name>derick092/App03Jokenpo<file_sep>/index.ios.js
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button,
Image
} from 'react-native';
import Topo from './src/components/topo';
import Icone from './src/components/icone';
class app03 extends Component{
constructor(props){
super(props);
this.state = { escolhaUsuario:'', escolhaComputador:'', resultado:'' }
}
jokenpo(escolhaUsuario){
var numeroAleatorio = Math.floor(Math.random() * 3);
var escolhaComputador = '';
switch (numeroAleatorio) {
case 0: escolhaComputador = 'Pedra'; break;
case 1: escolhaComputador = 'Papel'; break;
case 2: escolhaComputador = 'Tesoura'; break;
}
var resultado = '';
if(escolhaComputador == 'Pedra'){
if(escolhaUsuario == 'Pedra'){
resultado = 'Empate!';
}
if(escolhaUsuario == 'Papel'){
resultado = 'Você venceu!';
}else
if(escolhaUsuario == 'Tesoura'){
resultado = 'Você perdeu!';
}
}
if(escolhaComputador == 'Papel'){
if(escolhaUsuario == 'Pedra'){
resultado = 'Você perdeu!';
}
if(escolhaUsuario == 'Papel'){
resultado = 'Empate!';
}else
if(escolhaUsuario == 'Tesoura'){
resultado = 'Você venceu!';
}
}
if(escolhaComputador == 'Tesoura'){
if(escolhaUsuario == 'Pedra'){
resultado = 'Você venceu!';
}
if(escolhaUsuario == 'Papel'){
resultado = 'Você perdeu!';
}else
if(escolhaUsuario == 'Tesoura'){
resultado = 'Empate!';
}
}
this.setState(
{
escolhaUsuario : escolhaUsuario,
escolhaComputador : escolhaComputador,
resultado : resultado});
}
render(){
return(
<View>
<Topo/>
<View style = {styles.vwAcoes}>
<View style = {styles.btnEscolha}>
<Button
title='Pedra'
onPress={() => {this.jokenpo('Pedra')}}/>
</View>
<View style = {styles.btnEscolha}>
<Button
title='Papel'
onPress={() => {this.jokenpo('Papel')}}/>
</View>
<View style = {styles.btnEscolha}>
<Button
title='Tesoura'
onPress={() => {this.jokenpo('Tesoura')}}/>
</View>
</View>
<View style = {styles.vwPalco}>
<Text style = {styles.txtResultado}>{this.state.resultado}</Text>
<Icone escolha={this.state.escolhaComputador} jogador='Computador'></Icone>
<Icone escolha={this.state.escolhaUsuario} jogador='Você'></Icone>
</View>
</View>
);
}
}
/*class Topo extends Component{
render(){
return(
<Image source={require('./imgs/jokenpo.png')}/>
);
}
}*/
const styles = StyleSheet.create({
vwAcoes:{
flexDirection:'row',
justifyContent:'space-between',
padding:10
},
btnEscolha:{
width:90
},
vwPalco:{
alignItems:'center',
marginTop:10
},
txtResultado:{
fontSize:25,
fontWeight:'bold',
color:'red',
height:60
}
});
/*class Icone extends Component {
render(){
if(this.props.escolha == 'Pedra'){
return (
<View style={styles.vwJogador}>
<Text style={styles.txtJogador}>{this.props.jogador}</Text>
<Image source={require('./imgs/pedra.png')}/>
</View>
);
}else if(this.props.escolha == 'Papel'){
return (
<View style={styles.vwJogador}>
<Text style={styles.txtJogador}>{this.props.jogador}</Text>
<Image source={require('./imgs/papel.png')}/>
</View>
);
}else if(this.props.escolha == 'Tesoura'){
return (
<View style={styles.vwJogador}>
<Text style={styles.txtJogador}>{this.props.jogador}</Text>
<Image source={require('./imgs/tesoura.png')}/>
</View>
);
}else{
return false;
}
}
}*/
AppRegistry.registerComponent('app03', () => app03);
// <MeuComponente p1='1' p2='2' p3='3'></MeuComponente>
// class MeuComponente extends Component{
// render(){
// return (
// <View >
// <Text>{this.props.p1}</Text>
// <Text>{this.props.p2}</Text>
// <Text>{this.props.p3}</Text>
// </View>
// )
// };
// }
| a32f23c31dfc4f6c97b7cf1e7ff7be93d065bc38 | [
"JavaScript"
] | 1 | JavaScript | derick092/App03Jokenpo | 2a071a08fb60a998f54cdafb5d9956716b981770 | ce739a61260af1949120c3aeb8cb87f28f85917e | |
refs/heads/master | <repo_name>forsythrosin/svg101<file_sep>/src/app/splitPane.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactSplitPane from 'react-split-pane';
import './splitPane.scss';
class SplitPane extends Component {
render() {
const { children, defaultSize } = this.props;
let def = localStorage.getItem('splitPos');
if (def) def = def * 100 + '%';
else def = defaultSize;
return (
<ReactSplitPane
{...this.props}
defaultSize={def}
onChange={size => localStorage.setItem('splitPos', size / window.innerWidth)}
>
{children}
</ReactSplitPane>
);
}
}
SplitPane.propTypes = {
children: PropTypes.node,
defaultSize: PropTypes.string,
};
export default SplitPane;
<file_sep>/src/theme/index.js
import React from 'react';
const themes = {
light: {
name: 'light',
primary: '#93bf6e',
header: {
backgroundColor: '#222',
color: '#f7f7f7'
},
panel: {
backgroundColor: '#f7f7f7',
color: '#222',
},
backgroundColor: '#fff',
color: '#222',
},
dark: {
name: 'dark',
primary: '#93bf6e',
header: {
backgroundColor: '#000',
color: '#e7e7e7'
},
panel: {
backgroundColor: '#222',
color: '#f7f7f7'
},
backgroundColor: '#111',
color: '#f7f7f7'
},
};
const ThemeContext = React.createContext(themes.light);
const ThemeProvider = ThemeContext.Provider;
export {
themes,
ThemeContext,
ThemeProvider,
};
| a2d8daaf6d15e73e8c5cece2aa9e4078521fc92f | [
"JavaScript"
] | 2 | JavaScript | forsythrosin/svg101 | 723f52ccd8c3176261b8a54aa6b0beb83a67c8b3 | 49b6fded40ab0e50d7d044ad2b3be122c755913e | |
refs/heads/master | <file_sep>This is a simple tool to harvest data from sites that support the `OAI PMH v2 protocol <http://www.openarchives.org/OAI/2.0/openarchivesprotocol.htm>`_.
It has thus far only been tested on `the arXiv <http://arxiv.org/>`_, but should work with other OAI PMH v2 Repositories.
An example of use (with the astro-ph part of arXiv) might be::
harvesterkwargs = dict(incremental=incremental, basewritename='arXiv_oai/reclist',
startdate=None, format='arXivRaw', recordset='physics:astro-ph',
baseurl='http://export.arxiv.org/oai2', recnumpadding=4)
pyoai2.run_session(**harvesterkwargs)
<file_sep># provided only to make it easier to include this is a git submodule
| b266cf5512f85ba0018b1bd98009a0377f0b864e | [
"Python",
"reStructuredText"
] | 2 | reStructuredText | eteq/pyoai2 | c5072b8d86c9f7ce4c15d677d42aa1a0d016e95c | 3ca8411efcdb5aaa50ed877cefedae73cf35fb2f | |
refs/heads/master | <repo_name>jepa/Transboundary_Chapter<file_sep>/Data_Wrangling.R
library(dplyr)
library(tidyr)
library(ggplot2)
min(chinook_data$X.1, na.rm=T)
unique(chinook_data$X.1)
names(chinook_data)[1:5]
View(head(chinook_data))
unique(chinook_data$`AABM Fishery..8`)
AABM_SEAK_N <- chinook_data %>%
gather("Erraseme","AABM_SEAK_N",`AABM Fishery..5`:`AABM Fishery..8`) %>%
filter(!is.na(AABM_SEA_N)) %>%
mutate(Region = "SEAK",
Gear = "N") %>%
select(1:2,Region,Gear,AABM_SEAK_N)
AABM_SEAK_S <- chinook_data %>%
gather("Erraseme","AABM_SEAK_S",`AABM Fishery..9`:`AABM Fishery..13`) %>%
filter(!is.na(AABM_SEAK_S)) %>%
select(1:2,AABM_SEAK_S)
ISBM_NBC_T <- chinook_data %>%
gather("Erraseme","ISBM_NBC_T",ISBM_Fishery..14:ISBM_Fishery..17) %>%
filter(!is.na(ISBM_NBC_T)) %>%
select(1:2,ISBM_NBC_T)
ISBM_NBC_S <- chinook_data %>%
gather("Erraseme","ISBM_NBC_S",ISBM_Fishery..18:ISBM_Fishery..21) %>%
filter(!is.na(ISBM_NBC_S)) %>%
select(1:2,ISBM_NBC_S)
ISBM_WCVI_T <- chinook_data %>%
gather("Erraseme","ISBM_WCVI_T",ISBM_Fishery..22:ISBM_Fishery..25) %>%
filter(!is.na(ISBM_WCVI_T)) %>%
select(1:2,ISBM_WCVI_T)
Col_Names <- c(
"Year",
"Est",
"Agesa",
"Agesb",
paste("SEAK-",letters,sep="")[1:8],
paste("NBC-",letters,sep="")[1:7],
paste("WCVI-",letters,sep="")[1:5],
paste("NBC_CBC-",letters,sep="")[1:10],
paste("SBC-",letters,sep="")[1:10],
paste("Falcon-",letters,sep="")[1:11],
paste("WAC-",letters,sep="")[1:3],
paste("Puget_Sd-",letters,sep="")[1:7],
paste("Terminal_Seak-",letters,sep="")[1:7],
paste("Terminal_Canada-",letters,sep="")[1:6],
paste("Terminal_SUS-",letters,sep="")[1:9],
paste("Stray-",letters,sep="")[1:4],
paste("Esc-",letters,sep="")[1:8]
)
Places <- c(
"Alaska Spring (Alaska South SE)",
"Atnarko River (North/Central BC) total fishing mortalities",
"Atnarko River (North/Central BC) 5-age ERA output total",
"Atnarko Yearling (North/Central BC) total fishing mortalities",
"Atnarko Yearling (North/Central BC) 5-age ERA output total",
"Big Qualicum River Fall (Lower Strait of Georgia Hatchery and Natural)",
"Chilliwack River Fall (Fraser Late)",
"Chilkat River",
"Cowichan River Fall (Lower Strait of Georgia Natural)",
"Cowlitz Fall Tule (Fall Cowlitz Hatchery)",
"Dome Creek Spring (Fraser Early)",
"Elk River (Oregon Coast)",
"Elwha River",
"George Adams Fall Fingerling",
"Hanford Wild Brights",
"Harrison River (Fraser Late)",
"Hoko Fall Fingerling",
"Kitsumkalum River Summer (North/Central BC)",
"Kitsumkalum Yearling (North/Central BC)",
"Lower River Hatchery Tule (Lower Bonneville Hatchery)",
"Lewis River Wild (Lewis River Wild)",
"<NAME> (Lyons Ferry Hatchery)",
"Lyons Ferry Yearling",
"Middle Shuswap River Summer (Fraser Early)",
"Nanaimo River Fall (Lower Strait of Georgia Natural)",
"Nicola River Spring (Fraser Early)",
"Nisqually Fall Fingerling",
"Nooksack Spring Yearling (Nooksack Spring Yearling)",
"Nooksack Spring Fingerling (Nooksack Spring Yearling)",
"Phillips River Fall (Upper Strait of Georgia)",
"Puntledge River Summer (Lower Strait of Georgia Hatchery)",
"Queets Fall Fingerling (Washington Coastal Wild)",
"Quinsam River Fall (Upper Strait of Georgia)",
"River Fall (Upper Strait of Georgia) 5-age ERA",
"Robertson Creek Fall (WCVI Hatchery and Natural)",
"Samish Fall Fingerling (Nooksack Fall Fingerling)",
"Lower Shuswap River Summer (Fraser Early)",
"Skagit Spring Fingerling",
"Skagit Spring Yearling",
"Skykomish Fall Fingerling (Snohomish Wild)",
"Sooes (now Tsoo-Yess) Fall Fingerling (Washington Coastal Wild)",
"Spring Creek Tule (Spring Creek Hatchery)",
"South Puget Sound Fall Fingerling (Puget Sound Hatchery Fingerling)",
"South Puget Sound Fall Yearling (Puget Sound Hatchery Yearling)",
"Squaxin Pens Fall Yearling (Puget Sound Hatchery Yearling)",
"Salmon River (Oregon Coast)",
"Skagit Summer Fingerling (Skagit Wild)",
"Stikine River",
"Stillaguamish Fall Fingerling (Stillaguamish Wild)",
"Columbia River Summers (Columbia River Summer)",
"Taku River",
"Unuk River",
"Columbia River Upriver Bright (Columbia River Upriver Brights)",
"University Of Washington Accelerated",
"White River Spring Yearling",
"Willamette Spring (Willamette River Hatchery)"
)
Rivers <- c(
"Alaska Spring",
"Atnarko",
"Atnarko",
"Atnarko",
"Atnarko",
"Big Qualicum",
"Chilliwack",
"Chilkat",
"Cowichan",
"Cowlitz",
"Dome Creek Spring",
"Elk",
"Elwha",
"<NAME>",
"Hanford",
"Harrison",
"Hoko",
"Kitsumkalum",
"Kitsumkalum",
"Lower",
"Lewis",
"<NAME>",
"<NAME>",
"Middle Shuswap",
"Nanaimo",
"Nicola",
"Nisqually",
"Nooksack",
"Nooksack",
"Strait of Georgia",
"Strait of Georgia",
"Queets",
"Strait of Georgia",
"Strait of Georgia",
"Robertson Creek",
"Samish",
"Shuswap",
"Skagit",
"Skagit",
"Skykomish",
"Sooes (now Tsoo-Yess)",
"Spring Creek",
"Puget Sound",
"Puget Sound",
"Puget Sound",
"Salmon",
"Skagit",
"Stikine",
"Stillaguamish",
"Columbia",
"Taku",
"Unuk",
"Columbia",
"University of Washington Accelerated",
"White",
"Willamette"
)
colnames(chinook_data) <- Col_Names
Chiiii <- chinook_data %>%
filter(Year == 2016) %>%
mutate(Source = Places,
River = Rivers) %>%
gather("Regions","Value",5:88) %>%
select(Year,River,Regions,Value) %>%
mutate(Regions = gsub("\\-.*","",Regions),
Value = as.numeric(Value)
) %>%
group_by(River,Regions,Year) %>%
summarise(Per_Region = sum(Value,na.rm=T)) %>%
filter(Per_Region > 0) %>%
mutate(State = ifelse(Regions %in% BC_Regions, "BC",
ifelse(Regions %in% Al_Regions,"Alaska","US_Mainlyand")))
ggplot(Chiiii) +
geom_bar(aes(
x = Regions,
y = Per_Region,
fill = Regions
),
stat = "identity"
) +
facet_wrap(~ River) +
coord_polar("y", start=0)
# Please make no-place over 100%
# Non is over 100%
Places_per <- Chiiii %>%
group_by(River) %>%
summarise(sum(Per_Region,na.rm=T))
<file_sep>/Functions/get_data_fx.R
# Sheets = "SUM total mort"
# Sheets <- NULL
# Data <- NULL
# Chinook_Data <- NULL
get_chinook_data <- function(Sheets){
Chinook_Raw_Data <- read_excel("/Volumes/Enterprise/Data/NRCAN_chapter/Species_Data/2018 Chinook Total Mortality Distribution.xlsx",
sheet = Sheets, col_names = FALSE)
colnames(Chinook_Raw_Data) <- as.character(seq(1:33))
Data <- Chinook_Raw_Data %>%
filter(`1` == "09–17") %>%
gather("Original_Fishery","Percentage",4:33) %>%
mutate(
Catch = (as.numeric(Percentage)/100)*as.numeric(`2`), # Converts percentage to weight
Fishery = Fishery_Set
) %>%
# Aggregates weights by fisheries
group_by(Fishery) %>%
summarize(Fishery_Catch = sum(Catch)) %>%
left_join(Fishery_to_Country) %>%
filter(!Fishery %in% c("Stray","Esc")) %>%
# Aggregates fisherie's catch by Country
group_by(Fishing_Country) %>%
summarize(Catch_Country = sum(Fishery_Catch)) %>%
mutate(StockName = Chinook_Raw_Data$`1`[1]) %>%
left_join(Acronyms, by ="StockName")
return(Data)
}
<file_sep>/Figures.Rmd
---
title: "R Notebook"
output:
html_notebook:
df_print: paged
toc: yes
toc_float: yes
---
# Set up
First make sure to install and load all packages needed. This chunk will also load functions related to the analysis.
```{r setup, eval=T, echo=T, warning=F,message=F, results='hide'}
# Load libraries and functions #
ipak <- function(pkg){
new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}
#### Library ####
packages <- c(
"readxl", # Read dataframe in excel format
"dplyr", # Data manipulation
"tidyr", # Data manipulation
"ggplot2", #Nice grpahs and spatial analysis
# "cowplot",
# "forcasts",
# "rgdal",
# "RColorBrewer",
"knitr",
"kableExtra",
"data.table", # Fast read data
# "ggrepel",
# "gridExtra",
# "ggmap",
# "rgeos",
"sf",
# "sp",
# "rgdal", #Spatial analysis
"tools", #Spatial analysis
# "png", # For reading plots in chunk codes
# "grid" # For reading plots in chunk codes
"stringr" # For filtering by string
)
ipak(packages)
##__________________FUNCTIONS _________________________##
# Standarization of plots
ggtheme_plot <- function() {
theme(
plot.title = element_text(size = rel(1), hjust = 0, face = "bold"),
panel.background = element_blank(),
strip.background = element_blank(),
# strip.text = element_text(size = base_size, face = "italic"),
panel.border = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
axis.ticks = element_blank(),
axis.text.x = element_text(size = 10,
angle = 0,
face = "plain"),
axis.text.y = element_text(size = 12),
axis.title = element_text(size = 14),
legend.key = element_rect(colour = NA, fill = NA),
legend.position = "top",
legend.title = element_text(size = 16),
legend.text = element_text(size = 14),
strip.text.x = element_text(size = 18, colour = "darkgrey"),
strip.text = element_text(size = 18)
)
}
# Standarization of maps
ggtheme_map <- function(base_size = 9, Region = "NA") {
theme(text = element_text(#family = "Helvetica",
color = "gray30", size = base_size),
plot.title = element_text(size = rel(1.25), hjust = 0, face = "bold"),
panel.background = element_blank(),
panel.border = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major = element_line(color = "transparent"),
strip.background =element_rect(fill = "transparent"),
strip.text.x = element_text(size = 18, colour = "black",face= "bold.italic", angle = 0),
axis.line = element_blank(), # element_line(colour = "grey30", size = .5))
axis.ticks = element_blank(),
axis.text = element_blank(),
axis.title = element_blank(),
# legend.key = element_rect(colour = NA, fill = NA, size = 4),
legend.position = "bottom"#,
# legend.key.width =unit(6,"line")
)
}
```
# Overall Map
## Loading DBEM data
```{r Load_DBEM_Data, echo = T, eval = T, results='hide', warning=F,message=F}
# List of DBEM INDEX within the EEZ
#Data provided by <NAME>
EEZIDs_List <- read_excel("~/Documents/UBC/Oceans_Project/Distribution/By Cell/Cell_Data/Updated_EEZList_17June2016.xlsx")
EEZ_CellID <- read_excel("~/Documents/UBC/Oceans_Project/Distribution/By Cell/Cell_Data/EEZ_CellID.xlsx")
colnames(EEZ_CellID) <- c("EEZID","INDEX")
# DBEM Coordinate system
Coor <- fread("~/Documents/UBC/Oceans_Project/Distribution/DBEM/Data/Lon_Lat_DBEM.txt",header = FALSE)
colnames(Coor) <- c("INDEX","Longitude","Latitude")
# Exploited Species for common names
# exploited_species_list <- fread("/Volumes/DATA/PROJECTION exploited species ENM/exploited_species_list.csv") %>%
# select(Species =TaxonName,
# CommonName)
# From (/Users/jpalacios/Documents/UBC/Oceans_Project/Distribution/By Cell/By_Cell_Analysis.Rmd)
DBEM_Results <- data.table::fread("~/Documents/UBC/Oceans_Project/Manuscript/Data/Raw_Data.csv")
#### All North America ####
EEZs <- c(
"Canada (Pacific)",
"USA (West Coast)",
"USA (Alaska, Arctic)",
"USA (Alaska, Subarctic)",
# "Canada (Arctic)",
"Canada (East Coast)",
"USA (East Coast)"
)
All_EEZs <- EEZIDs_List %>%
filter(Name %in% EEZs) %>%
left_join(EEZ_CellID,
by = "EEZID")
names(All_EEZs)[3] <- "INDEX"
```
## Data Wrangling
- We need to make some corrections to the shapefile to project everything with North America centered. Basically solve for the fact that Alaska is in the other side of the globe because the Earth is round, shocking!
- We also have to include a column referencing the country's EEZ for the analysis
```{r Correct_DBEM_Data, echo = T, eval = T, warning=F,message=F, results='asis'}
# LAT LONG Corrections for map projection
DBEM_Corrected <- DBEM_Results %>%
filter(INDEX %in% All_EEZs$INDEX) %>%
filter(Longitude > 0) %>%
mutate(Longitude = Longitude - 360)
DBEM_Corrected <- DBEM_Results %>%
filter(INDEX %in% All_EEZs$INDEX) %>%
filter(Longitude < 0) %>%
bind_rows(DBEM_Corrected)
# head(DBEM_Corrected)
# Just checking #####
# DBEM_Corrected %>%
# group_by(INDEX, Longitude, Latitude) %>%
# summarise(n =n()) %>%
# ggplot(.,
# aes(x = Longitude,
# y = Latitude,
# fill = n
# ),
# size = 0.05,
# alpha = 0.5) +
# geom_tile() #+
# coord_map(projection = "mercator")
### Get ridd of any Pacific Species in NAFO
NAFO_E <- DBEM_Corrected %>%
filter(Longitude >= -100)
Pacific <- DBEM_Corrected %>%
filter(Treaty != "NAFO")
DBEM_Corrected <- NAFO_E %>%
bind_rows(Pacific)
# unique(DBEM_Corrected$Species)
# Remove salmons...
Salmons <- c("Oncorhynchus keta","Oncorhynchus kisutch","Oncorhynchus nerka","Oncorhynchus tshawytscha","Oncorhynchus gorbuscha","Salmo salar")
Chapter_Data <- DBEM_Corrected %>%
# filter(!Species %in% Salmons) %>% # Reomve or only analysis with salmons
left_join(All_EEZs,
by ="INDEX") %>%
select(-EEZID)
# Show table with species
# names(Chapter_Data)
# head(Chapter_Data)
Chapter_Data %>%
group_by(Species, Treaty) %>%
summarise(n=n()) %>%
ungroup() %>%
left_join(exploited_species_list,
by = "Species") %>%
arrange(Treaty) %>%
select(Species,CommonName,Treaty) %>%
kable()
```
## Loading Spatial data
```{r, Load_Spatial_Data, eval = T, echo = T}
# Countries included
Countries <- c("Canada","United States","Alaska")
# World shapefile
path_world <- "~/Documents/R Code/Spatial_Analysis/Data/TM_WORLD_BORDERS-0.3"
file_name <- "TM_WORLD_BORDERS"
World_Land_sf <- st_read(dsn = path_world,
layer = file_path_sans_ext(file_name)
) %>%
st_transform(crs = 3832)
North_America_Land <- World_Land_sf %>%
filter(NAME %in% Countries)
# Checkpoint
# unique(North_America_Land$NAME) [1] Canada Greenland United States
# Map it? Yup!
# ggplot(North_America_Land) +
# geom_sf()
# EEZs shapefile ####
path_eez<- ("~/Documents/R Code/Spatial_Analysis/Data/World_EEZ_v10_2018")
#The File
fnam_eez <- "eez_boundaries_v10.shp" # Just lines
# fnam_eez <- "eez_v10.shp" # Actual shapefiles (takes 4-ever, for ever ever? fooor eever eeever!?)
eez_world_sf <- st_read(dsn = path_eez,
layer = file_path_sans_ext(fnam_eez)
) %>%
st_transform(crs = 4326) #3832 centered
# head(eez_world_sf)
#Checkpoint
# unique(eez_world_sf$Territory1)
# North_America_EEZ <- eez_world_sf %>%
# filter(Territory1 %in% Countries) %>%
# st_transform(crs = 4326)
#Checkpoint
# unique(North_America_EEZ$Territory1)
# Map it?
# ggplot(North_America_EEZ) +
# geom_sf()
# Nope, Alaska is not showing up. Neither East Greenland
# Greenland Shapefile Bug ####
# First lets get all of greenalnd in the map...
#
# eez_world_sf %>%
# filter(str_detect(Territory1,"Canada")) %>%
# # mutate(Basin = ifelse( x_1 >= -100, "Atlantic","Pacific")) %>%
# head()
# ggplot() +
# # geom_sf(aes(fill = Basin))
# geom_sf()
#
#
#
# # The chunk missing is from Iceland
# Iceland <- eez_world_sf %>%
# # group_by(Territory1) %>%
# # summarise(n()) %>%
# # filter(str_detect(Territory1,"Iceland")) # %>%
# filter(Line_ID ==135)
# # ggplot() +
# # geom_sf()
#
# eez_world_sf %>%
# filter(str_detect(Territory1,"Greenland") |
# Line_ID == 135) %>% # Include this in final map plot
# ggplot() +
# geom_sf() #+
# # geom_sf(data = Iceland)
#
# # Alaska Shapefile Bug ####
# eez_world_sf %>%
# filter(Territory1 %in% Countries) %>%
# st_transform(crs = 3832) %>%
# ggplot() +
# geom_sf()
#
# # The chunk missing is from Russia
# eez_world_sf %>%
# filter(str_detect(Territory1,"Alaska") |
# MRGID_Ter2 == 8684) %>% # This includes Russia side (Include in final plot)
# st_transform(crs = 3832) %>%
# # View()
# ggplot() +
# geom_sf(aes(col=Line_type))
#
#
# # South US (Atlantic) Shapefile Bug ####
#
# # The chunk missing is from ... Mexico and Cuba?... and Bahamas. Nope, just Mexico
# eez_world_sf %>%
# # filter(str_detect(Territory1"United States")) %>%
# filter(Territory1 %in% c ("United States", "Mexico", "Cuba","Bahamas"))
#
#
# ### Mexico First (Taht's it! )
#
# eez_world_sf %>%
# # filter(str_detect(Territory1"United States")) %>%
# filter(Territory1 %in% c ("United States") |
# MRGID_Ter2 == 2204) %>% # Inlcude this for Mexico's southern boundary
# # st_transform(crs = 3832) %>%
# # View()
# ggplot() +
# geom_sf(aes(col=Line_type))
#### The Actual Map ####
# We need to inlcude alaska in here
Countries <- c("Canada","United States", "Alaska")
# Here we go again
North_America_EEZ <- eez_world_sf %>%
filter(Territory1 %in% Countries |
Line_ID == 135 | # # Line missing from Greenland (Iceland)
MRGID_Ter2 == 8684 |
MRGID_Ter2 == 2204) %>% # Line missing from Alaska (Russia)
st_transform(crs = 3832)
# Finall check!
# ggplot(North_America_EEZ) +
# geom_sf()
# Yup!
# Map both shapefiles to see how it looks
# ggplot() +
# geom_sf(data = North_America_Land) +
# geom_sf(data = North_America_EEZ)
# Annnnd.... Is... Done!!!!!!!
# But not really because those are lines and we actually need polygons...
# Its way easier, they are all there... ¬ ¬ It does take for ever, thou so projection issues should be deal with in the line version. But maybe the line fizes cuz they are polygons? We will see...
North_America_EEZ <- eez_world_sf %>%
filter(Territory1 %in% Countries) %>%
st_transform(crs = 3832) #3832
# Let's try this... I think It will take 4-ever
# Shapefile_Map <- ggplot() +
# geom_sf(data = North_America_Land) +
# geom_sf(data = North_America_EEZ)
#
# # 6.26pm and 18:34 on carmelia
# ggsave("Shapefile_Map.png",
# plot = last_plot(),
# width = 12,
# height = 10,
# units = "in"
# )
### Explorting new dataset, hopefully is faster... ####
path_eez<- ("~/Documents/R CODE/Spatial_Analysis/Data/Intersect_EEZ_IHO_v3")
#The File
# fnam_eez <- "eez_boundaries_v10.shp" # Just lines
fnam_eez <- "EEZ_IHO_v3.shp" # Actual shapefiles (takes 4-ever, for ever ever? fooor eever eeever!?)
new_eez_sf <- st_read(dsn = path_eez,
layer = file_path_sans_ext(fnam_eez)
) #%>%
# st_transform(crs = 4326) #3832 centered
# See map
# ggplot(new_eez_sf) +
# geom_sf()
# head(new_eez_sf)
# new_eez_sf %>%
# filter(Territory1 == "Canada",
# Longitude > -100) %>%
# tail()
# filter(Territory1 == "Canada",
# IHO_Sea %in% c("North Atlantic Ocean")) %>%
# head()
# ggplot() +
# geom_sf()
# Canada Pacific (Half arctic sea) <- Longitude < -100
Canada_shp <- new_eez_sf %>%
filter(Territory1 == "Canada") %>%
mutate(Basin = ifelse(Longitude > -100, "Can E","Can W")) %>%
select(Territory1,
Basin,
geometry)
# head(Canada_shp) yes!
# US Pacific (Half arctic sea) <- Longitude < -100
US_shp <- new_eez_sf %>%
filter(Territory1 == "United States") %>%
mutate(Basin = ifelse(Longitude > -100, "USA E","USA W")) %>%
select(Territory1,
Basin,
geometry)
# Alaska
Alaska_shp <- new_eez_sf %>%
filter(Territory1 == "Alaska") %>%
mutate(Basin = "Alaska") %>%
select(Territory1,
Basin,
geometry)
# Greenland
# Greenland_shp <-
# new_eez_sf %>%
# filter(Territory1 == "Greenland") %>%
# mutate(Basin = "Alaska") %>%
# select(Territory1,
# Basin,
# geometry)
North_America_EEZ_sp <- Alaska_shp %>%
rbind(US_shp,Canada_shp)
```
## DBEM data analysis for NAFO
```{r Chapter_Function, eval =T, echo=T}
Areas <- c(
"Canada (Arctic)",
"Canada (East Coast)",
"Canada (Pacific)",
"USA (East Coast)",
"USA (West Coast)",
"USA (Alaska, Arctic)",
"USA (Alaska, Subarctic)"
)
RCP = c("GFDL26F1","IPSL26F1","MPI26F1") #Low RCP
Selected_Areas <- EEZIDs_List %>%
filter(Name %in% Areas)
# DBEM_Corrected %>%
# filter(Treaty == "NAFO") %>%
# View()
Overall <- DBEM_Corrected %>%
left_join(EEZ_CellID,
by = "INDEX") %>%
# head() %>%
filter(EEZID %in% Selected_Areas$EEZID) %>%
mutate( # uncomment to get overall by nation
Nation = ifelse(EEZID >= 958, "Alaska",
ifelse(EEZID == 925,"Can W",
ifelse(EEZID == 851, "USA E",
ifelse( EEZID== 848, "USA W","Can E"))
)),
RCP = ifelse(Model %in% RCP,"Low","High"),
Basin = ifelse(Nation %in% c("USA E","Can E"),"Atlantic","Pacific")
) %>%
# View()
group_by(Model,Nation,RCP,Basin,Species) %>%
summarise_if(is.numeric,sum,na.rm=T) %>%
group_by(Nation,RCP,Basin,Species) %>%
summarise_at(vars(`2005`:`2099`),mean,na.rm=T) %>% #Average of models
gather("Year","MCP",`2005`:`2099`)
# Average of each Species MCP today
Today_Mean <- Overall %>%
filter(Year >= 2005 & Year <= 2014) %>%
group_by(Nation,RCP,Species) %>%
summarise(Today_MCP = mean(MCP))
# View(Today_Mean)
#### Change in proportions ####
# Average of each Species MCP today in both nations
Today_Total_MCP <- Overall %>%
filter(Year >= 2005 & Year <= 2014) %>%
group_by(RCP,Nation,Basin, Species) %>%
summarise(Mean_MCP = mean(MCP)) %>%
group_by(RCP,Basin,Species) %>%
summarise(Total_MCP = sum(Mean_MCP))
Today_Proportion <- Overall %>%
# mutate(Basin = ifelse(Nation %in% c("USA E","Can E"),"Atlantic","Pacific")) %>%
filter(Year >= 2005 & Year <= 2014) %>%
group_by(Nation,RCP,Basin,Species) %>%
summarise(Today_MCP = mean(MCP)) %>%
left_join(Today_Total_MCP,
by = c("RCP","Basin","Species")
) %>%
mutate(
Prop_Today = (Today_MCP/Total_MCP)*100
) %>%
select(Nation,RCP,Basin,Prop_Today,Species)
### Check point
# Today_Proportion %>%
# group_by(RCP,Basin) %>%
# summarise(sum(Prop_Today))
### Proportion change ##
Future_Totals <- Overall %>%
filter(Year >= 2046) %>%
mutate(#Basin = ifelse(Nation %in% c("USA E","Can E"),"Atlantic","Pacific"),
Period = (ifelse(Year >= 2046 & Year <= 2055,"Mid Century","End Century"))
) %>%
# filter(Year >= 2046 & Year <= 2055) %>%
group_by(RCP,Nation,Basin,Period,Species) %>%
summarise(Mean_MCP = mean(MCP)) %>%
group_by(RCP,Basin,Period,Species) %>%
summarise(Total_MCP_Fut = sum(Mean_MCP))
Result_Table <- Overall %>%
mutate(#Basin = ifelse(Nation %in% c("USA E","Can E"),"Atlantic","Pacific"),
Period = ifelse(Year >= 2046 & Year <= 2055,"Mid Century",
ifelse(Year >= 2090 & Year <= 2099,"End Century","Other_Years"))
) %>%
filter(Period != "Other_Years") %>%
group_by(Nation,RCP,Basin,Period,Species) %>%
summarise(Fut_MCP = mean(MCP)) %>%
# View()
left_join(Future_Totals,
by = c("RCP","Basin","Period","Species")
) %>%
mutate(
Prop_Fut = (Fut_MCP/Total_MCP_Fut)*100
) %>%
left_join(Today_Proportion,
by = c("Nation","RCP","Basin","Species")) %>%
mutate(Change = Prop_Fut/Prop_Today,
Percentage_Mid = round(-(1-Change)*100)
) %>%
View()
# select(Species,Nation:Period,Percentage_Mid) %>%
group_by(Nation,RCP,Period) %>%
summarise(
Mean_All = mean(Percentage_Mid, na.rm = T),
sd_All = sd(Percentage_Mid, na.rm = T)
) %>%
View()
Result_Map <- Result_Table %>%
filter(RCP == "High",
Period == "Mid Century") %>%
ungroup() %>%
select(
Basin= Nation,
Mean_All
)
# COnvert DBEM data to a shapefile (points)
Mid_Century_Plot <- North_America_EEZ_sp %>%
left_join(Result_Map,
by ="Basin") %>%
st_transform(crs = 3832)
# head(Mid_Century_Plot)
# tail(Mid_Century_Plot)
# unique(Mid_Century_Plot$)
#### Map checking #### Works!!!!
Seq <- seq(-12,12,2)
Plot <- ggplot(Mid_Century_Plot) +
geom_sf(aes(fill = Mean_All,
colour=Mean_All)) +
scale_fill_gradient2(
limits=c(-12,12),
breaks = Seq ) +
scale_colour_gradient2(
limits=c(-12,12),
breaks = Seq) +
# geom_sf(data = North_America_Land) +
# geom_sf(data = North_America_EEZ, colour = "black") +
ggtheme_map() +
theme(legend.key = element_rect(size = 4),
legend.key.width =unit(6,"line"));Plot
# ggsave("Mid_Century.png", #03:24
# plot = Plot,
# width = 12,
# height = 10,
# units = "in"
# )
```
# Chinook Map
```{r chinook_map, eval = T}
# libraries needed
library(dplyr)
library(tidyr)
library(ggplot2)
library(readxl)
library(rnaturalearth)
library(sf)
library(wesanderson)
source("./Functions/get_data_fx.R")
#### Data Source ###
# Data shared by <NAME> thanks to <NAME> from PSC
# Reference info
# If the 2018 report is not yet published it might be better to referrer
# the Chinook Technical Committee of the Pacific Salmon Commission as the source.
#________________________________________________________________________________#
# Manually create fisheries labels for fixing data
Fishery_Set <- c(
rep("SEK",3),
rep("NBC",2),
rep("WCVI",2),
rep("NBC&CB",3),
rep("SBC",3),
rep("NF",2),
rep("SF",2),
rep("WAK",1),
rep("PUG",2),
rep("SEK",3),
rep("CAN",2),
rep("SUS",3),
"Stray",
"Esc"
)
# Create tabel relation
Fishery_to_Country <- tibble(
Fishery = c("SEK","NBC","WCVI","NBC&CB","SBC","NF","SF","WAK","PUG","CAN","SUS","Stray","Esc"),
Fishing_Country = c("US Alaska",rep("Canada",4),rep("US Contiguous States",2),rep("US Contiguous States",2),"Canada","US Contiguous States","Stray","Esc")
)
# Load Fishery Acronyms
Acronyms <- read_excel("/Volumes/Enterprise/Data/NRCAN_chapter/Species_Data/2018 Chinook Total Mortality Distribution.xlsx",
sheet = "Fisheries", col_names = TRUE) %>%
arrange(Region) %>%
mutate(Sheet = paste(StockAcronym,"total mort")) %>%
mutate(Country = c(rep("US Contiguous States",22),rep("Canada",4),rep("US Contiguous States",18),rep("US Alaska",3),rep("Transboundary",2),"Canada",rep("US Contiguous States",4))
)
# Run function to get all Data
suppressMessages(
Chinook_Data <- bind_rows(
lapply(Acronyms$Sheet,get_chinook_data)
)
)
Total_Region_Catch <- Chinook_Data %>%
group_by(Region) %>%
summarise(Total_Reg_Catch = sum(Catch_Country,na.rm=T)) %>%
filter(!is.na(Region))
Regional_Coord <- tibble(
Region = unique(Total_Region_Catch$Region),
Lon = c(122,123,132.9,137,122,145,140,128,128),
Lat = c(43.5,53,50.4,54,48,57,48,48,43.5)
)
Chinook_Per_Region <- Chinook_Data %>%
group_by(Fishing_Country,Region) %>%
summarise(Total_Country_Catch = sum(Catch_Country,na.rm=T)) %>%
left_join(Total_Region_Catch,
by = "Region") %>%
mutate(Region_per = (Total_Country_Catch/Total_Reg_Catch)*100) %>%
filter(!is.na(Region)) %>%
left_join(Regional_Coord)
# Plot Pie charts
# ggplot(Chinook_Per_Region) +
# geom_bar(
# aes(
# x = "",
# y = Region_per,
# fill = Fishing_Country
# ),
# stat ="identity"
# ) +
# coord_polar("y", start=0) +
# facet_wrap(~Region)
#### The Map
### Give coord for map
Test <- Chinook_Per_Region %>%
select(Region,Fishing_Country,Region_per) %>%
spread(Fishing_Country,Region_per) %>%
left_join(Regional_Coord) %>%
mutate(Lon = Lon*-1,
radius = 3)
#### Option C
# Map Dimenssions
xmin=-121
xmax=-150
ymin=33
ymax=63
world = map_data("world", resolution=0)
p <- ggplot(world, aes(long, lat)) +
geom_map(map=world, aes(map_id=region),
fill=wes_palette(name = "IsleofDogs2")[1],
# fill = "grey90",
color="black",
size = 0.1) +
coord_quickmap(xlim = c(xmin, xmax), ylim = c(ymin, ymax)) +
theme(
panel.grid = element_blank(),
# panel.grid.major = element_line(color = "gray90",
# linetype = "dashed",
# size = 0.5),
# panel.grid.minor = element_line(color = "gray90",
# linetype = "dashed",
# size = 0.5),
# panel.grid.minor = element_blank(),
# panel.background = element_blank()
panel.background = element_rect(fill = wes_palette(name = "Darjeeling2")[4])
)
# Make magic for Pie not to be distorted
# https://stackoverflow.com/questions/51398344/r-pie-charts-distorted-when-adding-to-projected-map-using-ggplot
pie.list <- Test %>%
tidyr::gather(type, value, -Lon, -Lat, -radius, -Region) %>%
tidyr::nest(type, value) %>%
# make a pie chart from each row, & convert to grob
mutate(pie.grob = purrr::map(data,
function(d) ggplotGrob(ggplot(d,
aes(x = 1, y = value, fill = type)) +
geom_col(color = "black",
show.legend = FALSE) +
coord_polar(theta = "y") +
scale_fill_manual("Fishing Entity",
values = c(wes_palette(name = "Darjeeling1")[2:5]
)
) +
theme_void()))) %>%
# convert each grob to an annotation_custom layer. I've also adjusted the radius
# value to a reasonable size (based on my screen resolutions).
rowwise() %>%
mutate(subgrob = list(annotation_custom(grob = pie.grob,
xmin = Lon - radius, xmax = Lon + radius,
ymin = Lat - radius, ymax = Lat + radius))
)
### Final Map
p +
geom_tile(data = Test %>% tidyr::gather(type, value, -Lon, -Lat, -radius,-Region),
aes(x = Lon, y = Lat, fill = type),
color = "black", width = 0.01, height = 0.01,
inherit.aes = FALSE) +
pie.list$subgrob +
ggrepel::geom_text_repel(data = Test,
aes(
x = Lon,
y = Lat,
label = Region),
force = 5,
size = 3,
nudge_x = 0,
nudge_y = 2.1,
segment.color = NA
) +
scale_fill_manual("Fishing Entity",
values = c(wes_palette(name = "Darjeeling1")[2:5]
)
) +
scale_x_continuous("Longitude",
breaks = seq(xmax,-120,5)
) +
scale_y_continuous("Latitude",
breaks = seq(30,65,5)
) +
annotate("text",
x =-140,
y = 36.3,
label = "Sharing Chinook Salmon",
color="black",
size=6,
angle=0,
fontface="italic",
hjust=0) +
annotate("text",
x =-132,
y = 34.8,
label = "Regional Chinook Salmon Captures per\nFishing Entity Between 2009 and 2017",
color="black",
size=3,
angle=0,
# fontface="italic",
hjust=0.5) +
theme(
legend.position = c(0.18,0.09),
legend.background = element_rect(fill = wes_palette(name = "Darjeeling2")[4])
)
ggsave("Col_Chinook_Map.png",
plot = last_plot(),
width = 6,
height = 8,
units = "in")
### Map for migration
xmin=-111
xmax=-160
ymin=45
ymax=63
states <- map_data("state")
ggplot(world, aes(long, lat)) +
geom_map(map=world, aes(map_id=region),
fill=wes_palette(name = "IsleofDogs2")[1],
# fill = "grey90",
color="black",
size = 0.1) +
geom_polygon(data = states,
aes(x = long, y = lat,
group = group),
fill=wes_palette(name = "IsleofDogs2")[1],
color = "black",
# fill = "grey90",
size = 0.1) +
coord_quickmap(xlim = c(xmin, xmax), ylim = c(ymin, ymax)) +
theme(
panel.grid = element_blank(),
# panel.grid.major = element_line(color = "gray90",
# linetype = "dashed",
# size = 0.5),
# panel.grid.minor = element_line(color = "gray90",
# linetype = "dashed",
# size = 0.5),
# panel.grid.minor = element_blank(),
# panel.background = element_blank()
panel.background = element_rect(fill = wes_palette(name = "Darjeeling2")[4])
)
ggsave("col_migration_map.png",
plot = last_plot(),
width = 8,
height = 6,
units = "in")
```
<file_sep>/README.md
# Transboundary_Chapter
This repository supports the transboundary resource management section of the International Dimensions Chapter for NRCan’s National Knowledge Assessment of Climate Change Impacts and Adaptation than can be found in [this link](https://changingclimate.ca/site/assets/uploads/sites/3/2020/05/Chapter-9_International-Dimensions_Final_EN-1.pdf).
# Chapter Authors
<NAME>. and <NAME>.
# Reference
<NAME>., <NAME>., <NAME>., <NAME>. and <NAME>. (2021): International Dimensions; Chapter 9 in Canada in a Changing Climate: National Issues Report, (ed.) <NAME> and <NAME>; Government of Canada, Ottawa, Ontario.
| 0bf5db41f5f060c29df67c7c7ec0653322829b2c | [
"Markdown",
"R",
"RMarkdown"
] | 4 | R | jepa/Transboundary_Chapter | 5de9dbb37ad41651a204e8df5967df0004e94711 | 966c24fc858589f063d35176487fee92c3e04f3a | |
refs/heads/master | <repo_name>jimi9527/AutoLocationRecyclerView<file_sep>/app/src/main/java/com/example/dengjx/verticalrecylerviewselector/RulerRecyclerView.java
package com.example.dengjx.verticalrecylerviewselector;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
/**
* Created by dengjx on 2017/12/27.
*/
public class RulerRecyclerView extends RecyclerView {
//偏移的距离
private int delta;
public RulerRecyclerView(Context context) {
this(context,null);
}
public RulerRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onScrolled(int dx, int dy) {
super.onScrolled(dx, dy);
delta = delta + dx;
}
@Override
public void onScrollStateChanged(int state) {
super.onScrollStateChanged(state);
// 手抬起的动作
if(state == SCROLL_STATE_IDLE){
}
}
}
<file_sep>/app/src/main/java/com/example/dengjx/verticalrecylerviewselector/RulerView.java
package com.example.dengjx.verticalrecylerviewselector;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
/**
* Created by dengjx on 2017/12/26.
*/
public class RulerView extends View{
private static final String TAG ="RulerView";
//中间标准刻度的颜色
private int mCenterColor = Color.RED;
// 中间刻度文字的颜色
private int mCenterTextColor = Color.BLUE;
// 中间刻度线的高大小
private int mCenterHigh = 80;
// 中间线条的宽度
private int mCenterWidth = 6;
private int leftMargin = 50;
private int mCenterTextHeight ;
// 刻度的起点X
private int ruleX;
// 显示刻度
private String mCenterText = "5";
// 偏移值
private int offset = 5;
// 平均刻度的值
private int avagerNum;
// 刻度的高度
private int ruleHeigt;
// 滚动器
private RulerViewScroller scroller;
// 是否执行滚动
private boolean isScrollingPerformed;
// 屏幕的宽度
private int mScreenWidth;
public RulerView(Context context) {
this(context,null);
}
public RulerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public RulerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setBackgroundColor(Color.BLUE);
// scroller = new RulerViewScroller(context,scrollinglistener);
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
mScreenWidth = displayMetrics.widthPixels;
Log.d(TAG,"mScreenWidth:"+ mScreenWidth);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureWidthSize(widthMeasureSpec),measureHeightSize(heightMeasureSpec));
}
private int measureHeightSize(int heightMeasureSpec) {
int result;
int mode=MeasureSpec.getMode(heightMeasureSpec);
int size=MeasureSpec.getSize(heightMeasureSpec);
if(mode==MeasureSpec.EXACTLY){
result=size;
}else{
result = getHeight() + getPaddingTop() + getPaddingBottom();
if(mode==MeasureSpec.AT_MOST){
result=Math.min(result,size);
}
}
Log.d(TAG,"result---HEIGHT:"+result);
return result;
}
private int measureWidthSize(int widthMeasureSpec) {
int result;
int mode=MeasureSpec.getMode(widthMeasureSpec);
int size=MeasureSpec.getSize(widthMeasureSpec);
if(mode==MeasureSpec.EXACTLY){
result=size;
}else{
result=size + getPaddingLeft() + getPaddingRight();
if(mode==MeasureSpec.AT_MOST){
result=Math.min(result,size);
}
}
Log.d(TAG,"result:"+result);
return result;
}
public int returnAvg(){
return avagerNum;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//drawCenterLine(canvas);
drwacenterBottonLine(canvas);
}
// 绘制底部直线
public void drwacenterBottonLine(Canvas canvas){
// 底部直线
Paint paint = new Paint();
paint.setColor(mCenterColor);
paint.setStrokeWidth(mCenterWidth / 2);
canvas.drawLine(leftMargin+mCenterWidth/2 ,getMeasuredHeight() / 2 +mCenterHigh + offset / 2,
mScreenWidth - leftMargin ,getMeasuredHeight() / 2 + mCenterHigh + offset / 2,paint);
// 绘制底部数字
for(int i = 1; i <= 10; i++){
Paint mTextPaint = new Paint();
mTextPaint.setTextSize(40);
mTextPaint.setColor(Color.BLACK);
Rect mCenterRect = new Rect();
mTextPaint.getTextBounds(String.valueOf(i),0,1,mCenterRect);
Log.d(TAG,"mCenterRect.width:"+mCenterRect.width());
mCenterTextHeight = mCenterRect.height();
avagerNum = (mScreenWidth-leftMargin *2 ) / 9 ;
ruleX = leftMargin - mCenterRect.width() / 2;
Log.d(TAG,"ruleX.width:"+ ruleX);
canvas.drawText(String.valueOf(i),ruleX + avagerNum * (i-1) ,
getMeasuredHeight() / 2 + mCenterHigh + 50 ,mTextPaint);
}
// 绘制刻度
for(int j = 1; j <= 10; j++){
Paint linepaint = new Paint();
linepaint.setColor(mCenterColor);
linepaint.setStrokeWidth(mCenterWidth /2 );
if(j == 1 || j == 10){
ruleHeigt = 50;
}else {
ruleHeigt = 30;
}
canvas.drawLine(leftMargin+mCenterWidth/2 + avagerNum * ( j - 1) ,
getMeasuredHeight() / 2 + mCenterHigh + offset / 2 - ruleHeigt,
leftMargin+mCenterWidth/2 + avagerNum *(j - 1) ,
getMeasuredHeight() / 2 + mCenterHigh + offset / 2 + mCenterWidth /2 ,linepaint);
}
}
// 绘制中间的线和数字
public void drawCenterLine(Canvas canvas){
Paint mTextPaint = new Paint();
mTextPaint.setTextSize(50);
mTextPaint.setColor(mCenterTextColor);
Rect mCenterRect = new Rect();
mTextPaint.getTextBounds(mCenterText,0,1,mCenterRect);
Log.d(TAG,"mCenterRect.height:"+mCenterRect.height());
mCenterTextHeight = mCenterRect.height();
canvas.drawText(mCenterText,getMeasuredWidth()/2 - mCenterRect.width()/2 ,getMeasuredHeight()/2,mTextPaint);
Paint paint = new Paint();
paint.setColor(mCenterColor);
paint.setStrokeWidth(mCenterWidth);
canvas.drawLine(getMeasuredWidth()/2 + mCenterWidth/2 ,getMeasuredHeight() / 2 + mCenterRect.height()+offset ,
getMeasuredWidth()/2 + mCenterWidth / 2 ,getMeasuredHeight() / 2 +
mCenterRect.height() + offset + mCenterHigh,paint);
}
}
<file_sep>/app/src/main/java/com/example/dengjx/verticalrecylerviewselector/BaseFootViewAdapter.java
package com.example.dengjx.verticalrecylerviewselector;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by dengjx on 2017/12/29.
*/
public abstract class BaseFootViewAdapter<E> extends BaseAdapter {
public static final int DEFAULT_SHOW_COUNT = 3;
protected Context mContext;
protected ListView mListView;
protected LayoutInflater inflater;
protected LinearLayout headView;
protected TextView mBtnMore;
protected ArrayList<E> mShowObjects = new ArrayList<>();
protected ArrayList<E> mAllObjects = new ArrayList<>();
protected boolean shrink = true;
private BaseFootViewAdapter(){
}
public BaseFootViewAdapter(Context context, ListView listView){
this.mListView = listView;
this.mContext = context;
inflater = LayoutInflater.from(mContext);
headView = (LinearLayout) inflater.inflate(R.layout.iv_footer_button,null);
mBtnMore = headView.findViewById(R.id.text_show);
mBtnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
changeShow();
}
});
mListView.addFooterView(headView,null,false);
}
public void setAapterData(ArrayList<E> mAllObjects){
this.mAllObjects = mAllObjects;
mShowObjects.clear();
if(mAllObjects != null){
if(mAllObjects.size() <= DEFAULT_SHOW_COUNT){
headView.setVisibility(View.GONE);
mShowObjects.addAll(mAllObjects);
}else {
headView.setVisibility(View.VISIBLE);
for(int i = 0; i < DEFAULT_SHOW_COUNT; i++){
mShowObjects.add(mAllObjects.get(i));
}
}
}
notifyDataSetChanged();
setListViewHeightBaseOnChildern(mListView);
}
@Override
public int getCount() {
int showCount = 0;
if(mShowObjects != null){
showCount = mShowObjects.size();
}
return showCount;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public E getItem(int i) {
E object = null;
if(mShowObjects != null){
object = mShowObjects.get(i);
}
return object;
}
private void changeShow() {
if(headView.getVisibility() == View.GONE){
headView.setVisibility(View.VISIBLE);
}
mShowObjects.clear();
if(shrink){
shrink = false;
mShowObjects.addAll(mAllObjects);
mBtnMore.setText("收起");
}else {
shrink = true;
for(int i = 0; i < DEFAULT_SHOW_COUNT; i++){
mShowObjects.add(mAllObjects.get(i));
}
mBtnMore.setText("查看所有的评论");
}
notifyDataSetChanged();
setListViewHeightBaseOnChildern(mListView);
}
public void setListViewHeightBaseOnChildern(ListView listView) {
if(listView == null){
return;
}
ListAdapter listAdapter = listView.getAdapter();
if(listAdapter == null){
return;
}
int totalHeight = 0;
for(int i = 0; i < listAdapter.getCount(); i++){
View listItem = listAdapter.getView(i,null,listView);
listItem.measure(0,0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() -1));
listView.setLayoutParams(params);
}
}
<file_sep>/app/src/main/java/com/example/dengjx/verticalrecylerviewselector/RulerRecylercView.java
package com.example.dengjx.verticalrecylerviewselector;
import android.content.Context;
import android.content.Loader;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
/**
* Created by dengjx on 2017/12/29.
*/
public class RulerRecylercView extends RecyclerView {
private static final String TAG = "RulerRecylercView";
// 偏移
private int deltay;
private RulerView mRulerView;
private int avagerNum;
private int leftMargin = 50;
private int revleftMargin = -50;
// 屏幕的宽度
private int mScreenWidth;
// 当前定位的数字刻度值
private int mCurNum;
private onReturnNum onreturnNum;
int curDeltay;
public RulerRecylercView(Context context) {
this(context, null);
}
boolean isFinish;
private Context context;
public RulerRecylercView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.context = context;
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
mScreenWidth = displayMetrics.widthPixels;
Log.d(TAG, "mScreenWidth:" + mScreenWidth);
avagerNum = (mScreenWidth - leftMargin * 2) / 9;
Log.d(TAG, "avagerNum:" + avagerNum);
curDeltay = mScreenWidth / 2;
}
public void setOnReturnNum(onReturnNum onReturnNum) {
this.onreturnNum = onReturnNum;
}
public interface onReturnNum {
void onNum(int num);
}
@Override
public void onScrollStateChanged(int state) {
super.onScrollStateChanged(state);
if (state == SCROLL_STATE_IDLE) {
Log.d(TAG, "delaty:" + deltay);
mCurNum = ((deltay - leftMargin) / avagerNum );
Log.d(TAG, "(deltay - leftMargin )/ avagerNum :" + ((deltay - leftMargin) / avagerNum ) * avagerNum);
int mscroll = ((deltay - leftMargin) / avagerNum ) * avagerNum - deltay + leftMargin + dptopx()/2 ;
Log.d(TAG, "mscroll:" + mscroll);
Log.d(TAG, "mCurNum:" + mCurNum);
//判断是否大于3分之2则刻度直接加1
if(mCurNum > 0 && mCurNum < 9) {
if (Math.abs(mscroll) >= (avagerNum * 2 / 3)) {
mCurNum = mCurNum + 1;
mscroll = avagerNum - Math.abs(mscroll);
}
}
Log.d(TAG, "mCurNum:" + mCurNum);
onreturnNum.onNum(mCurNum);
scrollBy(mscroll, 0);
getAdapter().notifyDataSetChanged();
}
}
@Override
public void onScrolled(int dx, int dy) {
super.onScrolled(dx, dy);
deltay = deltay + dx;
}
// dp转px 4为中间指针的宽度
public int dptopx(){
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (4 * scale + 0.5f);
}
}
<file_sep>/app/src/main/java/com/example/dengjx/verticalrecylerviewselector/RulerViewAdapter.java
package com.example.dengjx.verticalrecylerviewselector;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by dengjx on 2017/12/27.
*/
public class RulerViewAdapter extends RecyclerView.Adapter {
private static final String TAG ="RulerViewAdapter";
private Context context;
private final static int TYPE_ITEM = 1;
private final static int TYPE_HEAD_FOOT =2;
public RulerViewAdapter(Context context) {
this.context = context;
}
@Override
public int getItemViewType(int position) {
if(position == 0 || position == getItemCount() -1){
return TYPE_HEAD_FOOT;
}else {
return TYPE_ITEM;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_HEAD_FOOT){
View view = new View(context);
int headerFooterWidth = parent.getMeasuredWidth() / 2 ;
Log.d(TAG,"headerFooterWidth:"+headerFooterWidth);
RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(headerFooterWidth, 100);
view.setLayoutParams(params);
return new HeadViewHodler(view);
}else {
RulerView rulerview = new RulerView(context);
RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
300);
rulerview.setLayoutParams(params);
Log.d(TAG,"params.width:"+params.width);
Log.d(TAG,"params.height:"+params.height);
return new itemViewHolder(rulerview);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 3;
}
class HeadViewHodler extends RecyclerView.ViewHolder{
public HeadViewHodler(View itemView) {
super(itemView);
}
}
class itemViewHolder extends RecyclerView.ViewHolder{
public itemViewHolder(View itemView) {
super(itemView);
}
}
}
<file_sep>/app/src/main/java/com/example/dengjx/verticalrecylerviewselector/MainActivity.java
package com.example.dengjx.verticalrecylerviewselector;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
public class MainActivity extends AppCompatActivity implements VerticalRecyclerviewAdapter.OnItemClick {
AutoLocateHorizontalView mRecycleView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecycleView = (AutoLocateHorizontalView) findViewById(R.id.recyclerview);
VerticalRecyclerviewAdapter verticalRecyclerviewAdapter = new VerticalRecyclerviewAdapter(this);
verticalRecyclerviewAdapter.setOnItemClick(this);
if(null != verticalRecyclerviewAdapter){
mRecycleView.setInitPos(1);
mRecycleView.setAdapter(verticalRecyclerviewAdapter);
}
}
@Override
public void onItemClickListner(int postion) {
mRecycleView.updateData(postion);
}
}
<file_sep>/app/src/main/java/com/example/dengjx/verticalrecylerviewselector/FootViewAdapter.java
package com.example.dengjx.verticalrecylerviewselector;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
/**
* Created by dengjx on 2017/12/29.
*/
public class FootViewAdapter extends BaseFootViewAdapter<StationImage>{
public FootViewAdapter(Context context, ListView listView) {
super(context, listView);
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ItemHoder itemHoder = null;
if(view == null){
itemHoder = new ItemHoder();
view = inflater.inflate(R.layout.item_list,viewGroup,false);
itemHoder.mName = view.findViewById(R.id.name);
itemHoder.mContent = view.findViewById(R.id.content);
view.setTag(itemHoder);
}else {
itemHoder = (ItemHoder) view.getTag();
}
StationImage stationImage = getItem(i);
Log.d("test","stationImage.getName():" +stationImage.getName());
Log.d("test","itemHoder.mName:"+itemHoder.mName);
itemHoder.mName.setText(stationImage.getName());
itemHoder.mContent.setText(stationImage.getContent());
return view;
}
class ItemHoder{
TextView mName;
TextView mContent;
}
}
<file_sep>/app/src/main/java/com/example/dengjx/verticalrecylerviewselector/RulerActivity.java
package com.example.dengjx.verticalrecylerviewselector;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import static com.example.dengjx.verticalrecylerviewselector.RulerRecylercView.*;
/**
* Created by dengjx on 2017/12/26.
*/
public class RulerActivity extends Activity implements onReturnNum {
private static final String TAG = "RulerActivity" ;
RulerRecylercView mRulerView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ruleract);
mRulerView = findViewById(R.id.rulerview);
RulerViewAdapter rulerViewAdapter = new RulerViewAdapter(this);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
mRulerView.setLayoutManager(linearLayoutManager);
mRulerView.setAdapter(rulerViewAdapter);
mRulerView.setOnReturnNum(this);
mRulerView.smoothScrollToPosition(1);
}
@Override
public void onNum(int num) {
Log.d(TAG, "NUM :" +num);
}
}
| 51ab1e95c3b1481e817b8d8f3b927501f4bd176e | [
"Java"
] | 8 | Java | jimi9527/AutoLocationRecyclerView | bec7f09836ad58ecfe0791764c8723b6521334e7 | 315efdf056f6b9cb566cd2e7add3ae6fb6ef8cd4 | |
refs/heads/master | <file_sep>/**
*
*/
package corp.pdb.aea.data.model.enums;
/**
* @author waleed.k.al-jaradat
*
*/
public enum AlertStatusEnum {
SE("SE", "SENT", "Alert sent successfully"),
UN("UN", "UNSENT", "Alert has not been sent"),
RE("RE", "RETRY", "Retry sending Alert"),
FA("FA", "FAILED", "Alert sent failed");
private final String code;
private final String name;
private final String description;
AlertStatusEnum(final String code, final String name, final String description) {
this.code = code;
this.name = name;
this.description = description;
}
public String getCode() {
return code;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
/*
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("AlertParticipantTypeEnum");
sb.append("{code=").append(code);
sb.append(", name='").append(name).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append('}');
return sb.toString();
}
}
*/
}
<file_sep>/**
* Proprietary Software Built Off of Open-Source Software?
*/
package corp.pdb.aea.ws.endpoint;
import java.io.File;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.xml.bind.JAXBElement;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import corp.pdb.aea.util.TimestampTypeFormatter;
import corp.pdb.aea.ws.exceptions.impl.app.FileNotFoundException;
import ides.ErrorMessageDetailType;
import ides.ErrorMessageIdentifierType;
import ides.msg.filedownloadmessage.FileDownloadRequestType;
import ides.msg.filedownloadmessage.FileDownloadResponseType;
import ides.msg.soapfaultmessage.SOAPFaultType;
/**
* @author waleed.k.al-jaradat
*
*/
@Endpoint
public class FileDownloadStubEndpointImpl {
private static final Logger LOGGER = LogManager.getLogger(FileDownloadStubEndpointImpl.class);
private static final String FILE_DOWNLOAD_PACKAGE_DIRECTORY_LOCATION = "./files/outgoing/downloads/";
@Autowired
TimestampTypeFormatter timestampTypeFormatter;
@PayloadRoot(namespace="urn:ides:msg:filedownloadmessage", localPart="FileDownloadRequest")
@ResponsePayload
public JAXBElement<FileDownloadResponseType> fileDownloadRequestOperation(@RequestPayload JAXBElement<FileDownloadRequestType> fileDownloadRequest) {
LOGGER.debug("{}: Received request at FileDownloadService Endpoint (see TRACE logs for message details)", this.getClass().getSimpleName());
FileDownloadRequestType fileDownloadRequestBody = fileDownloadRequest.getValue();
LOGGER.trace("Message details: RequestSentTs=[{}], IDESTransmissionId=[{}], SendingEntity=[{}], ReceivingEntity=[{}]", fileDownloadRequestBody.getRequestSentTs(), fileDownloadRequestBody.getIDESTransmissionId(), fileDownloadRequestBody.getEntitySenderIdentifier().getCTSCountryCd(), fileDownloadRequestBody.getEntityReceiverIdentifier().getCTSCountryCd());
File mtomAttachment = new File(FILE_DOWNLOAD_PACKAGE_DIRECTORY_LOCATION + fileDownloadRequestBody.getIDESTransmissionId() + ".zip");
if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_32")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8503");
errorMessageDetailType.setErrorMessageTxt("Security - Threat detected in response");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_33")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8408");
errorMessageDetailType.setErrorMessageTxt("Failed Decryption - Incorrect AES 256 Key size");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_34")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8509");
errorMessageDetailType.setErrorMessageTxt("Security - Failed XML well formedness validation on MTOM attachment");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_35")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8400");
errorMessageDetailType.setErrorMessageTxt("Failed Decompression - Compression tool not supported");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_36")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8401");
errorMessageDetailType.setErrorMessageTxt("Failed Decompression - Compression algorithm not supported");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_37")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8402");
errorMessageDetailType.setErrorMessageTxt("Failed Decompression - Decompression Failed");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_38")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8514");
errorMessageDetailType.setErrorMessageTxt("Certificate Error - Certificate is not authorized by an approved CA");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_39")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8405");
errorMessageDetailType.setErrorMessageTxt("Failed Decryption - AES 256 Key is Blank or missing");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_40")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8407");
errorMessageDetailType.setErrorMessageTxt("Failed Decryption - Unable to decrypt key file");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_41")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8500");
errorMessageDetailType.setErrorMessageTxt("Security - Failed virus check (general)");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_42")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8512");
errorMessageDetailType.setErrorMessageTxt("Certificate Error - Certificate expired");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_43")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8502");
errorMessageDetailType.setErrorMessageTxt("Security - Failed virus check in response");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_44")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8503");
errorMessageDetailType.setErrorMessageTxt("Security - Threat detected in response");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_45")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8511");
errorMessageDetailType.setErrorMessageTxt("Certificate Error - General");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_46")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8519");
errorMessageDetailType.setErrorMessageTxt("Security - XML threat detected in response");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_47")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("1201");
errorMessageDetailType.setErrorMessageTxt("Security - Failed XML well formedness validation on MTOM attachment");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_48")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8505");
errorMessageDetailType.setErrorMessageTxt("Security - ZIP threat detected in response");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_49")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("2106");
errorMessageDetailType.setErrorMessageTxt("Security - SQL Injection threat identified in response");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_50")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("1204");
errorMessageDetailType.setErrorMessageTxt("Security - SQL Injection threat identified in MTOM attachment");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(fileDownloadRequestBody.getIDESTransmissionId().equals("FDOWNSRVCBCCLIENTIMPL_TRANSID_51")) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8507");
errorMessageDetailType.setErrorMessageTxt("Security - Failed XML well formedness validation on response");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
} else if(!mtomAttachment.exists()) {
SOAPFaultType soapFaultType = new SOAPFaultType();
ErrorMessageIdentifierType errorMessageIdentifierType = new ErrorMessageIdentifierType();
errorMessageIdentifierType.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
ErrorMessageDetailType errorMessageDetailType = new ErrorMessageDetailType();
errorMessageDetailType.setErrorMessageCd("8301");
errorMessageDetailType.setErrorMessageTxt("Requested File not found");
soapFaultType.setErrorMessageIdentifier(errorMessageIdentifierType);
soapFaultType.setErrorMessageTs(timestampTypeFormatter.generateTimestamp());
soapFaultType.getErrorMessageDetail().add(errorMessageDetailType);
FileNotFoundException exception = new FileNotFoundException(soapFaultType);
//exception.setSoapFaultType(soapFaultType);
throw exception;
}
ides.msg.filedownloadmessage.ObjectFactory factory = new ides.msg.filedownloadmessage.ObjectFactory();
FileDownloadResponseType fileDownloadResponseBody = factory.createFileDownloadResponseType();
fileDownloadResponseBody.setReceiptTs(timestampTypeFormatter.generateTimestamp());
fileDownloadResponseBody.setIDESTransmissionId(fileDownloadRequestBody.getIDESTransmissionId());
fileDownloadResponseBody.setIDESSendingTs(timestampTypeFormatter.generateTimestamp());
fileDownloadResponseBody.setBulkExchangeFile(new DataHandler(new FileDataSource(mtomAttachment)));
JAXBElement<FileDownloadResponseType> fileDownloadResponse = factory.createFileDownloadResponse(fileDownloadResponseBody);
return fileDownloadResponse;
}
}
<file_sep># Application README File
More to come... :smirk:
<file_sep>/**
* Proprietary Software Built Off of Open-Source Software?
*/
package corp.pdb.aea.data.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import corp.pdb.aea.data.model.IncomingUpload;
/**
* @author waleed.k.al-jaradat
*
*/
@Repository
public interface IncomingUploadRepository extends JpaRepository<IncomingUpload, Long>{
public IncomingUpload findByAlertId(Long alertId);
}
<file_sep>/**
* Proprietary Software Built Off of Open-Source Software?
*/
package corp.pdb.aea.service;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import corp.pdb.aea.data.model.Alert;
import corp.pdb.aea.data.model.IncomingUpload;
import corp.pdb.aea.data.model.enums.AlertStatusEnum;
import corp.pdb.aea.data.repository.AlertRepository;
import corp.pdb.aea.data.repository.IncomingUploadRepository;
import ides.EntityCommunicationTypeCdType;
/**
* @author waleed.k.al-jaradat
*
*/
@Service
public class IncomingUploadAlertService {
private Logger log = LoggerFactory.getLogger(IncomingUpload.class);
@Autowired
TransmitAlertService transmitAlertService;
@Autowired
AlertRepository alertRepository;
@Autowired
IncomingUploadRepository incomingUploadRepository;
public String transmitReadyAlerts() {
String landingPage = "";
List<Alert> alerts = alertRepository.findAll();
for(Alert alert : alerts) {
try {
if(alert.getAlertStatus().equals(AlertStatusEnum.UN) || alert.getAlertStatus().equals(AlertStatusEnum.RE)) {
landingPage = transmitAlertService.transmit(alert);
if(landingPage.equals("sendAlertSuccess")) {
alert.setAlertStatus(AlertStatusEnum.SE);
alert.setUpdatedById("INUPLDSRV");
alert.setUpdateTs(new Date());
alert = alertRepository.save(alert);
if(alert.getAlertReasonCd().equals("RC001")) {
constructAndPersistRC034Alert(alert);
}
}
}
} catch(Exception e) {
landingPage = "500";
log.error("Encountered exception {} returning {}, stacktrace below:\n{}", e.getMessage(), landingPage, e);
break;
}
}
if(landingPage.equals(""))
landingPage = "sendAlertSuccess";
return landingPage;
}
protected Alert constructAndPersistRC034Alert(Alert initialAlert) {
Alert alert = new Alert();
alert.setAlertReasonCd("RC034");
alert.setAlertStatus(AlertStatusEnum.UN);
alert.setCreatedById("INUPLDSRV");
alert.setCreateTs(new Date());
alert.setAlertRecipientTypeCd(initialAlert.getAlertRecipientTypeCd());
alert.setAlertTypeCd(initialAlert.getAlertTypeCd());
alert.setBinaryEncodingSchemeCd(initialAlert.getBinaryEncodingSchemeCd());
alert.setCompressedFileSizeKbQty(initialAlert.getCompressedFileSizeKbQty());
alert.setEntityCommunicationTypeCd(initialAlert.getEntityCommunicationTypeCd());
alert.setEntityReceiverIdentifier(initialAlert.getEntityReceiverIdentifier());
alert.setEntitySenderIdentifier(initialAlert.getEntitySenderIdentifier());
alert.setFileCreateTs(initialAlert.getFileCreateTs());
alert.setFileFormatCd(initialAlert.getFileFormatCd());
alert.setFileRevisionInd(initialAlert.getFileRevisionInd() != null ? initialAlert.getFileRevisionInd() : null);
alert.setIdesFileNm(initialAlert.getIdesFileNm());
alert.setIdesTransmissionId(initialAlert.getIdesTransmissionId());
alert.setOriginalIdesTransmissionId(initialAlert.getOriginalIdesTransmissionId() != null ? initialAlert.getOriginalIdesTransmissionId() : null);
alert.setSenderContactEmailTxt(initialAlert.getSenderContactEmailTxt() != null ? initialAlert.getSenderContactEmailTxt() : null);
alert.setSenderFileId(initialAlert.getSenderFileId());
alert.setTaxYr(initialAlert.getTaxYr());
alert = alertRepository.save(alert);
log.trace("ALERT record #{} successfully generated by {} at {}\n{}",
alert.getId(),
alert.getCreatedById(),
alert.getCreateTs(),
alert.toString());
IncomingUpload incomingUpload = incomingUploadRepository.findByAlertId(initialAlert.getId());
incomingUpload.setAlertId(alert.getId());
incomingUpload.setUpdatedById("INUPLDSRV");
incomingUpload.setUpdateTs(new Date());
incomingUpload = incomingUploadRepository.save(incomingUpload);
log.trace("INCOMING_UPLOAD record #{} successfully updated by {} with alertId=[{}] at {}",
incomingUpload.getId(),
incomingUpload.getUpdatedById(),
incomingUpload.getAlertId(),
incomingUpload.getUpdateTs());
return alert;
}
public String constructAndTransmitRC001Alert() {
String landingPage = "";
List<IncomingUpload> incomingUploads = incomingUploadRepository.findAll();
for(IncomingUpload incomingUpload : incomingUploads) {
try {
Alert alertToSend = constructAlertFromIncomingUpload(incomingUpload, "RC001", "SA");
landingPage = transmitAlertService.transmit(alertToSend);
if(landingPage.equals("500"))
break;
} catch(Exception e) {
landingPage = "500";
log.error("Encountered exception {} returning {}, stacktrace below:\n{}", e.getMessage(), landingPage, e);
break;
}
}
return landingPage;
}
public String constructAndTransmitRC034Alert() {
String landingPage = "";
List<IncomingUpload> incomingUploads = incomingUploadRepository.findAll();
for(IncomingUpload incomingUpload : incomingUploads) {
try {
Alert alertToSend = constructAlertFromIncomingUpload(incomingUpload, "RC034", "SA");
landingPage = transmitAlertService.transmit(alertToSend);
if(landingPage.equals("500"))
break;
} catch(Exception e) {
landingPage = "500";
log.error("Encountered exception {} returning {}, stacktrace below:\n{}", e.getMessage(), landingPage, e);
break;
}
}
return landingPage;
}
protected Alert constructAlertFromIncomingUpload(IncomingUpload incomingUpload, String alertReasonCd, String alertTypeCd) {
Date createDate = new Date();
Alert alert = new Alert();
alert.setAlertStatus(AlertStatusEnum.UN);
alert.setEntityCommunicationTypeCd(incomingUpload.getCommunicationTypeCd());
alert.setIdesTransmissionId(generateTransmissionId());
alert.setFileRevisionInd("N");
alert.setAlertRecipientTypeCd("CS");
alert.setAlertReasonCd(alertReasonCd);
alert.setAlertTypeCd(alertTypeCd);
alert.setEntitySenderIdentifier(incomingUpload.getEntitySenderIdentifier());
alert.setEntityReceiverIdentifier(incomingUpload.getEntityReceiverIdentifier());
alert.setSenderFileId(incomingUpload.getSenderFileId());
alert.setIdesFileNm(incomingUpload.getIdesFileNm());
alert.setTaxYr(Long.valueOf(2017));
alert.setFileCreateTs(createDate);
alert.setFileFormatCd("XML");
alert.setBinaryEncodingSchemeCd("NONE");
//TODO - add functionality where the file size of the incoming upload is determined, similar to what is done for outgoingDownload
alert.setCompressedFileSizeKbQty(Long.valueOf(110));
alert.setCreatedById("ALERTCLI");
alert.setCreateTs(createDate);
alert = alertRepository.save(alert);
return alert;
}
protected Alert constructAlertForFaultCases(String idesTransmissionId) {
Date createDate = new Date();
Alert alert = new Alert();
alert.setAlertStatus(AlertStatusEnum.SE);
alert.setEntityCommunicationTypeCd(EntityCommunicationTypeCdType.CBC.value());
alert.setIdesTransmissionId(idesTransmissionId);
alert.setFileRevisionInd("N");
alert.setAlertRecipientTypeCd("CR");
alert.setAlertTypeCd("RD");
alert.setAlertReasonCd("RC021");
alert.setEntitySenderIdentifier("CA");
alert.setEntityReceiverIdentifier("US.00");
alert.setSenderFileId("fault case senderFileId");
alert.setIdesFileNm("fault case idesFileNm");
alert.setTaxYr(Long.valueOf(2017));
alert.setFileCreateTs(createDate);
alert.setFileFormatCd("XML");
alert.setBinaryEncodingSchemeCd("NONE");
alert.setCompressedFileSizeKbQty(Long.valueOf(10));
alert.setCreatedById("ALERTCLI");
alert.setCreateTs(createDate);
alert = alertRepository.save(alert);
return alert;
}
protected String generateTransmissionId() {
String randomUUID = UUID.randomUUID().toString().replaceAll("-", "");
log.info("randomUUID={}", randomUUID);
return randomUUID;
}
}
<file_sep>//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.08.08 at 01:18:40 PM EDT
//
package ides.msg.soapfaultmessage;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import ides.ErrorMessageDetailType;
import ides.ErrorMessageIdentifierType;
/**
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><Component xmlns="urn:ides:msg:soapfaultmessage" xmlns:ides="urn:ides" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><DictionaryEntryNm> SOAP Fault exception Type</DictionaryEntryNm><MajorVersionNum>1</MajorVersionNum><MinorVersionNum>0</MinorVersionNum><VersionEffectiveBeginDt>2017-10-17</VersionEffectiveBeginDt><VersionDescriptionTxt>Initial version</VersionDescriptionTxt><DescriptionTxt>Type for message for the SOAP Fault exception</DescriptionTxt></Component>
* </pre>
*
*
* <p>Java class for SOAPFaultType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SOAPFaultType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{urn:ides}ErrorMessageIdentifier"/>
* <element ref="{urn:ides}ErrorMessageTs"/>
* <element ref="{urn:ides}ErrorMessageDetail" maxOccurs="100"/>
* </sequence>
* <attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" fixed="1.0" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SOAPFaultType", propOrder = {
"errorMessageIdentifier",
"errorMessageTs",
"errorMessageDetail"
})
public class SOAPFaultType {
@XmlElement(name = "ErrorMessageIdentifier", namespace = "urn:ides", required = true)
protected ErrorMessageIdentifierType errorMessageIdentifier;
@XmlElement(name = "ErrorMessageTs", namespace = "urn:ides", required = true)
protected String errorMessageTs;
@XmlElement(name = "ErrorMessageDetail", namespace = "urn:ides", required = true)
protected List<ErrorMessageDetailType> errorMessageDetail;
@XmlAttribute(name = "version")
protected String version;
/**
* Gets the value of the errorMessageIdentifier property.
*
* @return
* possible object is
* {@link ErrorMessageIdentifierType }
*
*/
public ErrorMessageIdentifierType getErrorMessageIdentifier() {
return errorMessageIdentifier;
}
/**
* Sets the value of the errorMessageIdentifier property.
*
* @param value
* allowed object is
* {@link ErrorMessageIdentifierType }
*
*/
public void setErrorMessageIdentifier(ErrorMessageIdentifierType value) {
this.errorMessageIdentifier = value;
}
/**
* Gets the value of the errorMessageTs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getErrorMessageTs() {
return errorMessageTs;
}
/**
* Sets the value of the errorMessageTs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setErrorMessageTs(String value) {
this.errorMessageTs = value;
}
/**
* Gets the value of the errorMessageDetail property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the errorMessageDetail property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getErrorMessageDetail().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ErrorMessageDetailType }
*
*
*/
public List<ErrorMessageDetailType> getErrorMessageDetail() {
if (errorMessageDetail == null) {
errorMessageDetail = new ArrayList<ErrorMessageDetailType>();
}
return this.errorMessageDetail;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
if (version == null) {
return "1.0";
} else {
return version;
}
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<groupId>corp.pdb.enterprise</groupId>
<artifactId>alawal-eap</artifactId>
<version>0.0.1.SNAPSHOT</version>
<packaging>jar</packaging>
<name>Al-Awal Enterprise Application Platform</name>
<description>
A Spring Boot application designed to show-off implementation(s) of a variety of Spring Boot functionalities.
Proprietary Software Built Off of Open-Source Software?
</description>
<inceptionYear>2019</inceptionYear>
<url></url>
<developers>
<developer>
<name>wkjaradat</name>
<id>jaradat-pdb</id>
<email><EMAIL></email>
<organization>PDB Corp.</organization>
</developer>
</developers>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<commons-io.version>2.1</commons-io.version>
<commons-fileupload.version>1.3.1</commons-fileupload.version>
<!-- Specifying this property sets the JAVA version for Spring Boot to use -->
<java.version>1.8</java.version>
<!-- Tells Spring Boot the JAVA version to use with the maven-compiler-plugin -->
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven-jaxb2-plugin.version>0.13.3</maven-jaxb2-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Testing Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Spring Boot Maven plugin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- Maven JAXB2 plugin -->
<!-- Configures JAXB2 to unmarshal XML objects, defined in the schemas located
in the directory that is specified in the <configuration> element below, into
JAVA class files (goal=generate) -->
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>${maven-jaxb2-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<generateDirectory>${project.basedir}/src/generated/java</generateDirectory>
<schemaDirectory>${project.basedir}/src/main/resources/schemas/SRV-CBC</schemaDirectory>
<schemaIncludes>
<include>*.wsdl</include>
</schemaIncludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>/**
* Proprietary Software Built Off of Open-Source Software?
*/
package corp.pdb.aea.data.model;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import corp.pdb.aea.data.model.enums.AlertStatusEnum;
/**
* @author waleed.k.al-jaradat
*
*/
@Entity
@Table(name="INCOMING_UPLOAD")
public class IncomingUpload {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Basic
@Column(name="COMMUNICATION_TYPE_CD", nullable=false, length=10)
private String communicationTypeCd;
@Basic
@Column(name="ENTITY_SENDER_ID", nullable=false, length=24)
private String entitySenderIdentifier;
@Basic
@Column(name="ENTITY_RECEIVER_ID", nullable=false, length=24)
private String entityReceiverIdentifier;
@Basic
@Column(name="IDES_FILE_NM", nullable=false, length=200)
private String idesFileNm;
@Basic
@Column(name="SENDER_FILE_ID", nullable=false, length=200)
private String senderFileId;
@Basic
@Column(name = "FILE_SIZE_KB_QTY", nullable = true, precision = 0, columnDefinition = "NUMBER")
private Long fileSizeKbQty;
@Basic
@Column(name="ALERT_ID", nullable=true, precision=0, columnDefinition="NUMBER")
private Long alertId;
@Column(name="ALERT_STATUS", nullable = false, length = 2, columnDefinition = "CHAR(2)")
@Enumerated(EnumType.STRING)
private AlertStatusEnum alertStatus;
@Basic
@Column(name="ALERT_SENT_TS", nullable=true, columnDefinition="TIMESTAMP(6)")
@Temporal(TemporalType.TIMESTAMP)
private Date alertSentTs;
@Basic
@Column(name="CREATED_BY_ID", nullable=false, length=24)
private String createdById;
@Basic
@Column(name="CREATE_TS", nullable=false, columnDefinition="TIMESTAMP(6)")
@Temporal(TemporalType.TIMESTAMP)
private Date createTs;
@Basic
@Column(name="UPDATED_BY_ID", nullable=true, length=24)
private String updatedById;
@Basic
@Column(name="UPDATE_TS", nullable=true, columnDefinition="TIMESTAMP(6)")
@Temporal(TemporalType.TIMESTAMP)
private Date updateTs;
/**
* @return the communicationTypeCd
*/
public String getCommunicationTypeCd() {
return communicationTypeCd;
}
/**
* @param communicationTypeCd the communicationTypeCd to set
*/
public void setCommunicationTypeCd(String communicationTypeCd) {
this.communicationTypeCd = communicationTypeCd;
}
/**
* @return the entitySenderIdentifier
*/
public String getEntitySenderIdentifier() {
return entitySenderIdentifier;
}
/**
* @param entitySenderIdentifier the entitySenderIdentifier to set
*/
public void setEntitySenderIdentifier(String entitySenderIdentifier) {
this.entitySenderIdentifier = entitySenderIdentifier;
}
/**
* @return the entityReceiverIdentifier
*/
public String getEntityReceiverIdentifier() {
return entityReceiverIdentifier;
}
/**
* @param entityReceiverIdentifier the entityReceiverIdentifier to set
*/
public void setEntityReceiverIdentifier(String entityReceiverIdentifier) {
this.entityReceiverIdentifier = entityReceiverIdentifier;
}
/**
* @return the idesFileNm
*/
public String getIdesFileNm() {
return idesFileNm;
}
/**
* @param idesFileNm the idesFileNm to set
*/
public void setIdesFileNm(String idesFileNm) {
this.idesFileNm = idesFileNm;
}
/**
* @return the senderFileId
*/
public String getSenderFileId() {
return senderFileId;
}
/**
* @param senderFileId the senderFileId to set
*/
public void setSenderFileId(String senderFileId) {
this.senderFileId = senderFileId;
}
/**
* @return the fileSizeKbQty
*/
public Long getFileSizeKbQty() {
return fileSizeKbQty;
}
/**
* @param fileSizeKbQty the fileSizeKbQty to set
*/
public void setFileSizeKbQty(Long fileSizeKbQty) {
this.fileSizeKbQty = fileSizeKbQty;
}
/**
* @return the alertId
*/
public Long getAlertId() {
return alertId;
}
/**
* @param alertId the alertId to set
*/
public void setAlertId(Long alertId) {
this.alertId = alertId;
}
/**
* @return the alertStatus
*/
public AlertStatusEnum getAlertStatus() {
return alertStatus;
}
/**
* @param alertStatus the alertStatus to set
*/
public void setAlertStatus(AlertStatusEnum alertStatus) {
this.alertStatus = alertStatus;
}
/**
* @return the alertSentTs
*/
public Date getAlertSentTs() {
return alertSentTs;
}
/**
* @param alertSentTs the alertSentTs to set
*/
public void setAlertSentTs(Date alertSentTs) {
this.alertSentTs = alertSentTs;
}
/**
* @return the createdById
*/
public String getCreatedById() {
return createdById;
}
/**
* @param createdById the createdById to set
*/
public void setCreatedById(String createdById) {
this.createdById = createdById;
}
/**
* @return the createTs
*/
public Date getCreateTs() {
return createTs;
}
/**
* @param createTs the createTs to set
*/
public void setCreateTs(Date createTs) {
this.createTs = createTs;
}
/**
* @return the updatedById
*/
public String getUpdatedById() {
return updatedById;
}
/**
* @param updatedById the updatedById to set
*/
public void setUpdatedById(String updatedById) {
this.updatedById = updatedById;
}
/**
* @return the updateTs
*/
public Date getUpdateTs() {
return updateTs;
}
/**
* @param updateTs the updateTs to set
*/
public void setUpdateTs(Date updateTs) {
this.updateTs = updateTs;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((alertId == null) ? 0 : alertId.hashCode());
result = prime * result + ((alertSentTs == null) ? 0 : alertSentTs.hashCode());
result = prime * result + ((alertStatus == null) ? 0 : alertStatus.hashCode());
result = prime * result + ((communicationTypeCd == null) ? 0 : communicationTypeCd.hashCode());
result = prime * result + ((createTs == null) ? 0 : createTs.hashCode());
result = prime * result + ((createdById == null) ? 0 : createdById.hashCode());
result = prime * result + ((entityReceiverIdentifier == null) ? 0 : entityReceiverIdentifier.hashCode());
result = prime * result + ((entitySenderIdentifier == null) ? 0 : entitySenderIdentifier.hashCode());
result = prime * result + ((fileSizeKbQty == null) ? 0 : fileSizeKbQty.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((idesFileNm == null) ? 0 : idesFileNm.hashCode());
result = prime * result + ((senderFileId == null) ? 0 : senderFileId.hashCode());
result = prime * result + ((updateTs == null) ? 0 : updateTs.hashCode());
result = prime * result + ((updatedById == null) ? 0 : updatedById.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IncomingUpload other = (IncomingUpload) obj;
if (alertId == null) {
if (other.alertId != null)
return false;
} else if (!alertId.equals(other.alertId))
return false;
if (alertSentTs == null) {
if (other.alertSentTs != null)
return false;
} else if (!alertSentTs.equals(other.alertSentTs))
return false;
if (alertStatus == null) {
if (other.alertStatus != null)
return false;
} else if (!alertStatus.equals(other.alertStatus))
return false;
if (communicationTypeCd == null) {
if (other.communicationTypeCd != null)
return false;
} else if (!communicationTypeCd.equals(other.communicationTypeCd))
return false;
if (createTs == null) {
if (other.createTs != null)
return false;
} else if (!createTs.equals(other.createTs))
return false;
if (createdById == null) {
if (other.createdById != null)
return false;
} else if (!createdById.equals(other.createdById))
return false;
if (entityReceiverIdentifier == null) {
if (other.entityReceiverIdentifier != null)
return false;
} else if (!entityReceiverIdentifier.equals(other.entityReceiverIdentifier))
return false;
if (entitySenderIdentifier == null) {
if (other.entitySenderIdentifier != null)
return false;
} else if (!entitySenderIdentifier.equals(other.entitySenderIdentifier))
return false;
if(fileSizeKbQty == null) {
if(other.fileSizeKbQty != null)
return false;
} else if(!fileSizeKbQty.equals(other.fileSizeKbQty))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (idesFileNm == null) {
if (other.idesFileNm != null)
return false;
} else if (!idesFileNm.equals(other.idesFileNm))
return false;
if (senderFileId == null) {
if (other.senderFileId != null)
return false;
} else if (!senderFileId.equals(other.senderFileId))
return false;
if (updateTs == null) {
if (other.updateTs != null)
return false;
} else if (!updateTs.equals(other.updateTs))
return false;
if (updatedById == null) {
if (other.updatedById != null)
return false;
} else if (!updatedById.equals(other.updatedById))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "IncomingUpload [id=" + id + ", communicationTypeCd=" + communicationTypeCd + ", entitySenderIdentifier=" + entitySenderIdentifier
+ ", entityReceiverIdentifier=" + entityReceiverIdentifier + ", idesFileNm=" + idesFileNm + ", senderFileId=" + senderFileId
+ ", fileSizeKbQty=" + fileSizeKbQty + ", alertId=" + alertId + ", alertStatus=" + alertStatus + ", alertSentTs=" + alertSentTs
+ ", createdById=" + createdById + ", createTs=" + createTs + ", updatedById=" + updatedById + ", updateTs=" + updateTs + "]";
}
}
<file_sep>//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.08.08 at 01:18:40 PM EDT
//
package ides.msg.fileuploadmessage;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import ides.EntityCommunicationTypeCdType;
/**
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><Component xmlns="urn:ides:msg:fileuploadmessage" xmlns:ides="urn:ides" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><DictionaryEntryNm>File Upload Response Type</DictionaryEntryNm><MajorVersionNum>1</MajorVersionNum><MinorVersionNum>0</MinorVersionNum><VersionEffectiveBeginDt>2014-06-12</VersionEffectiveBeginDt><VersionDescriptionTxt>Initial version</VersionDescriptionTxt><DescriptionTxt>Type for message for the file upload response</DescriptionTxt></Component>
* </pre>
*
*
* <p>Java class for FileUploadResponseType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="FileUploadResponseType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{urn:ides}ReceiptTs" minOccurs="0"/>
* <element ref="{urn:ides}IDESSendingTs"/>
* <element ref="{urn:ides}EntityCommunicationTypeCd"/>
* <element ref="{urn:ides}SenderFileId"/>
* <element ref="{urn:ides}IDESFileNm"/>
* </sequence>
* <attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" fixed="1.0" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "FileUploadResponseType", propOrder = {
"receiptTs",
"idesSendingTs",
"entityCommunicationTypeCd",
"senderFileId",
"idesFileNm"
})
public class FileUploadResponseType {
@XmlElement(name = "ReceiptTs", namespace = "urn:ides")
protected String receiptTs;
@XmlElement(name = "IDESSendingTs", namespace = "urn:ides", required = true)
protected String idesSendingTs;
@XmlElement(name = "EntityCommunicationTypeCd", namespace = "urn:ides", required = true)
@XmlSchemaType(name = "string")
protected EntityCommunicationTypeCdType entityCommunicationTypeCd;
@XmlElement(name = "SenderFileId", namespace = "urn:ides", required = true)
protected String senderFileId;
@XmlElement(name = "IDESFileNm", namespace = "urn:ides", required = true)
protected String idesFileNm;
@XmlAttribute(name = "version")
protected String version;
/**
* Gets the value of the receiptTs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReceiptTs() {
return receiptTs;
}
/**
* Sets the value of the receiptTs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReceiptTs(String value) {
this.receiptTs = value;
}
/**
* Gets the value of the idesSendingTs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDESSendingTs() {
return idesSendingTs;
}
/**
* Sets the value of the idesSendingTs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDESSendingTs(String value) {
this.idesSendingTs = value;
}
/**
* Gets the value of the entityCommunicationTypeCd property.
*
* @return
* possible object is
* {@link EntityCommunicationTypeCdType }
*
*/
public EntityCommunicationTypeCdType getEntityCommunicationTypeCd() {
return entityCommunicationTypeCd;
}
/**
* Sets the value of the entityCommunicationTypeCd property.
*
* @param value
* allowed object is
* {@link EntityCommunicationTypeCdType }
*
*/
public void setEntityCommunicationTypeCd(EntityCommunicationTypeCdType value) {
this.entityCommunicationTypeCd = value;
}
/**
* Gets the value of the senderFileId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSenderFileId() {
return senderFileId;
}
/**
* Sets the value of the senderFileId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSenderFileId(String value) {
this.senderFileId = value;
}
/**
* Gets the value of the idesFileNm property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDESFileNm() {
return idesFileNm;
}
/**
* Sets the value of the idesFileNm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDESFileNm(String value) {
this.idesFileNm = value;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
if (version == null) {
return "1.0";
} else {
return version;
}
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
}
<file_sep>/**
* Proprietary Software Built Off of Open-Source Software?
*/
package corp.pdb.aea.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.springframework.stereotype.Service;
/**
* @author waleed.k.al-jaradat
*
*/
@Service
public class TimestampTypeFormatter {
private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
public String generateTimestamp() {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String timeStamp = dateFormat.format(new Date());
if(!(dateFormat.getTimeZone().getID().equals("UTC")))
timeStamp += ":00";
return timeStamp;
}
}
<file_sep>/**
* Proprietary Software Built Off of Open-Source Software?
*/
package corp.pdb.aea.ws.endpoint;
import javax.xml.bind.JAXBElement;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import corp.pdb.aea.util.TimestampTypeFormatter;
import ides.msg.downloadacknowledgementmessage.DownloadAckngRequestType;
import ides.msg.downloadacknowledgementmessage.DownloadAckngResponseType;
/**
* @author waleed.k.al-jaradat
*
*/
@Endpoint
public class DownloadAcknowledgementStubEndpointImpl {
private static final Logger LOGGER = LogManager.getLogger(DownloadAcknowledgementStubEndpointImpl.class);
@Autowired
TimestampTypeFormatter timestampTypeFormatter;
@PayloadRoot(namespace="urn:ides:msg:downloadacknowledgementmessage", localPart="DownloadAckngRequest")
@ResponsePayload
public JAXBElement<DownloadAckngResponseType> downloadAckngRequestOperation(@RequestPayload JAXBElement<DownloadAckngRequestType> downloadAckngRequest) {
LOGGER.debug("{}: Received request at DownloadAckngService Endpoint (see TRACE logs for message details)", this.getClass().getSimpleName());
DownloadAckngRequestType downloadAckngRequestBody = downloadAckngRequest.getValue();
LOGGER.trace("Message details: RequestSentTs=[{}], IDESTransmissionId=[{}], EntityIdentifier=[{}], AcknowledgementType=[{}]", downloadAckngRequestBody.getRequestSentTs(), downloadAckngRequestBody.getIDESTransmissionId(), downloadAckngRequestBody.getEntityIdentifier(), downloadAckngRequestBody.getAcknowledgementTypeCd());
ides.msg.downloadacknowledgementmessage.ObjectFactory factory = new ides.msg.downloadacknowledgementmessage.ObjectFactory();
DownloadAckngResponseType downloadAckngResponseBody = factory.createDownloadAckngResponseType();
downloadAckngResponseBody.setReceiptTs(timestampTypeFormatter.generateTimestamp());
downloadAckngResponseBody.setIDESSendingTs(timestampTypeFormatter.generateTimestamp());
downloadAckngResponseBody.setIDESTransmissionId(downloadAckngRequestBody.getIDESTransmissionId());
downloadAckngResponseBody.setEntityIdentifier(downloadAckngRequestBody.getEntityIdentifier());
JAXBElement<DownloadAckngResponseType> downloadAckngResponse = factory.createDownloadAckngResponse(downloadAckngResponseBody);
return downloadAckngResponse;
}
}
<file_sep>//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.08.08 at 01:18:40 PM EDT
//
package ides.msg.idesalertmessage;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
import ides.AlertRecipientTypeCdType;
import ides.BinaryEncodingSchemeCdType;
import ides.EntityCommunicationTypeCdType;
import ides.EntityIdentifierType;
import ides.FileFormatCdType;
/**
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><Component xmlns="urn:ides:msg:idesalertmessage" xmlns:ides="urn:ides" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><DictionaryEntryNm>IDES Alert Request Type</DictionaryEntryNm><MajorVersionNum>1</MajorVersionNum><MinorVersionNum>1</MinorVersionNum><VersionEffectiveBeginDt>2018-10-18</VersionEffectiveBeginDt><VersionDescriptionTxt>1.1</VersionDescriptionTxt><DescriptionTxt>Type for message for the IDES alert request</DescriptionTxt></Component>
* </pre>
*
*
* <p>Java class for IDESAlertRequestType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="IDESAlertRequestType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{urn:ides}RequestSentTs" minOccurs="0"/>
* <element ref="{urn:ides}IDESTransmissionId"/>
* <element ref="{urn:ides}IDESSendingTs"/>
* <element ref="{urn:ides}IDESReceivedTs"/>
* <element ref="{urn:ides}IDESFileNm"/>
* <element ref="{urn:ides}AlertRecipientTypeCd"/>
* <element ref="{urn:ides}EntitySenderIdentifier"/>
* <element ref="{urn:ides}EntityReceiverIdentifier"/>
* <element ref="{urn:ides}AlertTypeCd"/>
* <element ref="{urn:ides}AlertReasonCd" minOccurs="0"/>
* <element ref="{urn:ides}EntityCommunicationTypeCd"/>
* <element ref="{urn:ides}SenderFileId" minOccurs="0"/>
* <element ref="{urn:ides}FileFormatCd"/>
* <element ref="{urn:ides}BinaryEncodingSchemeCd"/>
* <element ref="{urn:ides}FileCreateTs" minOccurs="0"/>
* <element ref="{urn:ides}TaxYear" minOccurs="0"/>
* <element ref="{urn:ides}CompressedFileSizeKBQty" minOccurs="0"/>
* <element ref="{urn:ides}FileRevisionInd" minOccurs="0"/>
* <element ref="{urn:ides}OriginalIDESTransmissionId" minOccurs="0"/>
* <element ref="{urn:ides}SenderContactEmailAddressTxt" minOccurs="0"/>
* </sequence>
* <attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" fixed="1.0" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "IDESAlertRequestType", propOrder = {
"requestSentTs",
"idesTransmissionId",
"idesSendingTs",
"idesReceivedTs",
"idesFileNm",
"alertRecipientTypeCd",
"entitySenderIdentifier",
"entityReceiverIdentifier",
"alertTypeCd",
"alertReasonCd",
"entityCommunicationTypeCd",
"senderFileId",
"fileFormatCd",
"binaryEncodingSchemeCd",
"fileCreateTs",
"taxYear",
"compressedFileSizeKBQty",
"fileRevisionInd",
"originalIDESTransmissionId",
"senderContactEmailAddressTxt"
})
public class IDESAlertRequestType {
@XmlElement(name = "RequestSentTs", namespace = "urn:ides")
protected String requestSentTs;
@XmlElement(name = "IDESTransmissionId", namespace = "urn:ides", required = true)
protected String idesTransmissionId;
@XmlElement(name = "IDESSendingTs", namespace = "urn:ides", required = true)
protected String idesSendingTs;
@XmlElement(name = "IDESReceivedTs", namespace = "urn:ides", required = true)
protected String idesReceivedTs;
@XmlElement(name = "IDESFileNm", namespace = "urn:ides", required = true)
protected String idesFileNm;
@XmlElement(name = "AlertRecipientTypeCd", namespace = "urn:ides", required = true)
@XmlSchemaType(name = "string")
protected AlertRecipientTypeCdType alertRecipientTypeCd;
@XmlElement(name = "EntitySenderIdentifier", namespace = "urn:ides", required = true)
protected EntityIdentifierType entitySenderIdentifier;
@XmlElement(name = "EntityReceiverIdentifier", namespace = "urn:ides", required = true)
protected EntityIdentifierType entityReceiverIdentifier;
@XmlElement(name = "AlertTypeCd", namespace = "urn:ides", required = true)
protected String alertTypeCd;
@XmlElement(name = "AlertReasonCd", namespace = "urn:ides")
protected String alertReasonCd;
@XmlElement(name = "EntityCommunicationTypeCd", namespace = "urn:ides", required = true)
@XmlSchemaType(name = "string")
protected EntityCommunicationTypeCdType entityCommunicationTypeCd;
@XmlElement(name = "SenderFileId", namespace = "urn:ides")
protected String senderFileId;
@XmlElement(name = "FileFormatCd", namespace = "urn:ides", required = true)
@XmlSchemaType(name = "string")
protected FileFormatCdType fileFormatCd;
@XmlElement(name = "BinaryEncodingSchemeCd", namespace = "urn:ides", required = true)
@XmlSchemaType(name = "string")
protected BinaryEncodingSchemeCdType binaryEncodingSchemeCd;
@XmlElement(name = "FileCreateTs", namespace = "urn:ides")
protected String fileCreateTs;
@XmlElement(name = "TaxYear", namespace = "urn:ides")
@XmlSchemaType(name = "gYear")
protected XMLGregorianCalendar taxYear;
@XmlElement(name = "CompressedFileSizeKBQty", namespace = "urn:ides")
protected BigInteger compressedFileSizeKBQty;
@XmlElement(name = "FileRevisionInd", namespace = "urn:ides")
protected Boolean fileRevisionInd;
@XmlElement(name = "OriginalIDESTransmissionId", namespace = "urn:ides")
protected String originalIDESTransmissionId;
@XmlElement(name = "SenderContactEmailAddressTxt", namespace = "urn:ides")
protected String senderContactEmailAddressTxt;
@XmlAttribute(name = "version")
protected String version;
/**
* Gets the value of the requestSentTs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRequestSentTs() {
return requestSentTs;
}
/**
* Sets the value of the requestSentTs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRequestSentTs(String value) {
this.requestSentTs = value;
}
/**
* Gets the value of the idesTransmissionId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDESTransmissionId() {
return idesTransmissionId;
}
/**
* Sets the value of the idesTransmissionId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDESTransmissionId(String value) {
this.idesTransmissionId = value;
}
/**
* Gets the value of the idesSendingTs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDESSendingTs() {
return idesSendingTs;
}
/**
* Sets the value of the idesSendingTs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDESSendingTs(String value) {
this.idesSendingTs = value;
}
/**
* Gets the value of the idesReceivedTs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDESReceivedTs() {
return idesReceivedTs;
}
/**
* Sets the value of the idesReceivedTs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDESReceivedTs(String value) {
this.idesReceivedTs = value;
}
/**
* Gets the value of the idesFileNm property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDESFileNm() {
return idesFileNm;
}
/**
* Sets the value of the idesFileNm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDESFileNm(String value) {
this.idesFileNm = value;
}
/**
* Gets the value of the alertRecipientTypeCd property.
*
* @return
* possible object is
* {@link AlertRecipientTypeCdType }
*
*/
public AlertRecipientTypeCdType getAlertRecipientTypeCd() {
return alertRecipientTypeCd;
}
/**
* Sets the value of the alertRecipientTypeCd property.
*
* @param value
* allowed object is
* {@link AlertRecipientTypeCdType }
*
*/
public void setAlertRecipientTypeCd(AlertRecipientTypeCdType value) {
this.alertRecipientTypeCd = value;
}
/**
* Gets the value of the entitySenderIdentifier property.
*
* @return
* possible object is
* {@link EntityIdentifierType }
*
*/
public EntityIdentifierType getEntitySenderIdentifier() {
return entitySenderIdentifier;
}
/**
* Sets the value of the entitySenderIdentifier property.
*
* @param value
* allowed object is
* {@link EntityIdentifierType }
*
*/
public void setEntitySenderIdentifier(EntityIdentifierType value) {
this.entitySenderIdentifier = value;
}
/**
* Gets the value of the entityReceiverIdentifier property.
*
* @return
* possible object is
* {@link EntityIdentifierType }
*
*/
public EntityIdentifierType getEntityReceiverIdentifier() {
return entityReceiverIdentifier;
}
/**
* Sets the value of the entityReceiverIdentifier property.
*
* @param value
* allowed object is
* {@link EntityIdentifierType }
*
*/
public void setEntityReceiverIdentifier(EntityIdentifierType value) {
this.entityReceiverIdentifier = value;
}
/**
* Gets the value of the alertTypeCd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlertTypeCd() {
return alertTypeCd;
}
/**
* Sets the value of the alertTypeCd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlertTypeCd(String value) {
this.alertTypeCd = value;
}
/**
* Gets the value of the alertReasonCd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlertReasonCd() {
return alertReasonCd;
}
/**
* Sets the value of the alertReasonCd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlertReasonCd(String value) {
this.alertReasonCd = value;
}
/**
* Gets the value of the entityCommunicationTypeCd property.
*
* @return
* possible object is
* {@link EntityCommunicationTypeCdType }
*
*/
public EntityCommunicationTypeCdType getEntityCommunicationTypeCd() {
return entityCommunicationTypeCd;
}
/**
* Sets the value of the entityCommunicationTypeCd property.
*
* @param value
* allowed object is
* {@link EntityCommunicationTypeCdType }
*
*/
public void setEntityCommunicationTypeCd(EntityCommunicationTypeCdType value) {
this.entityCommunicationTypeCd = value;
}
/**
* Gets the value of the senderFileId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSenderFileId() {
return senderFileId;
}
/**
* Sets the value of the senderFileId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSenderFileId(String value) {
this.senderFileId = value;
}
/**
* Gets the value of the fileFormatCd property.
*
* @return
* possible object is
* {@link FileFormatCdType }
*
*/
public FileFormatCdType getFileFormatCd() {
return fileFormatCd;
}
/**
* Sets the value of the fileFormatCd property.
*
* @param value
* allowed object is
* {@link FileFormatCdType }
*
*/
public void setFileFormatCd(FileFormatCdType value) {
this.fileFormatCd = value;
}
/**
* Gets the value of the binaryEncodingSchemeCd property.
*
* @return
* possible object is
* {@link BinaryEncodingSchemeCdType }
*
*/
public BinaryEncodingSchemeCdType getBinaryEncodingSchemeCd() {
return binaryEncodingSchemeCd;
}
/**
* Sets the value of the binaryEncodingSchemeCd property.
*
* @param value
* allowed object is
* {@link BinaryEncodingSchemeCdType }
*
*/
public void setBinaryEncodingSchemeCd(BinaryEncodingSchemeCdType value) {
this.binaryEncodingSchemeCd = value;
}
/**
* Gets the value of the fileCreateTs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFileCreateTs() {
return fileCreateTs;
}
/**
* Sets the value of the fileCreateTs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFileCreateTs(String value) {
this.fileCreateTs = value;
}
/**
* Gets the value of the taxYear property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getTaxYear() {
return taxYear;
}
/**
* Sets the value of the taxYear property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setTaxYear(XMLGregorianCalendar value) {
this.taxYear = value;
}
/**
* Gets the value of the compressedFileSizeKBQty property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getCompressedFileSizeKBQty() {
return compressedFileSizeKBQty;
}
/**
* Sets the value of the compressedFileSizeKBQty property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setCompressedFileSizeKBQty(BigInteger value) {
this.compressedFileSizeKBQty = value;
}
/**
* Gets the value of the fileRevisionInd property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isFileRevisionInd() {
return fileRevisionInd;
}
/**
* Sets the value of the fileRevisionInd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setFileRevisionInd(Boolean value) {
this.fileRevisionInd = value;
}
/**
* Gets the value of the originalIDESTransmissionId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOriginalIDESTransmissionId() {
return originalIDESTransmissionId;
}
/**
* Sets the value of the originalIDESTransmissionId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOriginalIDESTransmissionId(String value) {
this.originalIDESTransmissionId = value;
}
/**
* Gets the value of the senderContactEmailAddressTxt property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSenderContactEmailAddressTxt() {
return senderContactEmailAddressTxt;
}
/**
* Sets the value of the senderContactEmailAddressTxt property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSenderContactEmailAddressTxt(String value) {
this.senderContactEmailAddressTxt = value;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
if (version == null) {
return "1.0";
} else {
return version;
}
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
}
<file_sep>/**
* Proprietary Software Built Off of Open-Source Software?
*/
package corp.pdb.aea.data.model;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import corp.pdb.aea.data.model.enums.AlertStatusEnum;
/**
* @author waleed.k.al-jaradat
*
*/
@Entity
@Table(name = "ALERT")
public class Alert {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="ALERT_STATUS", nullable = false, length = 2, columnDefinition = "CHAR(2)")
@Enumerated(EnumType.STRING)
private AlertStatusEnum alertStatus;
@Basic
@Column(name = "ENTITY_COMMUNICATION_TYPE_CD", nullable = false, length = 10)
private String entityCommunicationTypeCd;
@Basic
@Column(name = "IDES_TRANSMISSION_ID", nullable = false, length = 32)
private String idesTransmissionId;
@Basic
@Column(name = "FILE_REVISION_IND", nullable = true, length = 1, columnDefinition = "CHAR(1)")
private String fileRevisionInd;
@Basic
@Column(name = "ORIGINAL_IDES_TRANSMISSION_ID", nullable = true, length = 32)
private String originalIdesTransmissionId;
@Basic
@Column(name = "ALERT_RECIPIENT_TYPE_CD", nullable = false, length = 2, columnDefinition = "CHAR(2) NOT NULL")
private String alertRecipientTypeCd;
@Basic
@Column(name = "ALERT_TYPE_CD", nullable = false, length = 5)
private String alertTypeCd;
@Basic
@Column(name = "ALERT_REASON_CD", nullable = false, length = 5)
private String alertReasonCd;
@Basic
@Column(name = "ENTITY_SENDER_ID", nullable = false, length = 24)
private String entitySenderIdentifier;
@Basic
@Column(name = "ENTITY_RECEIVER_ID", nullable = false, length = 24)
private String entityReceiverIdentifier;
@Basic
@Column(name = "SENDER_FILE_ID", nullable = false, length = 200)
private String senderFileId;
@Basic
@Column(name = "IDES_FILE_NM", nullable = false, length = 200)
private String idesFileNm;
@Basic
@Column(name = "TAX_YR", nullable = true, precision = 0, columnDefinition = "NUMBER")
private Long taxYr;
@Basic
@Column(name = "FILE_CREATE_TS", nullable = false, columnDefinition = "TIMESTAMP(6)")
@Temporal(TemporalType.TIMESTAMP)
private Date fileCreateTs;
@Basic
@Column(name = "FILE_FORMAT_CD", nullable = true, length = 10)
private String fileFormatCd;
@Basic
@Column(name = "BINARY_ENCODING_SCHEME_CD", nullable = true, length = 10)
private String binaryEncodingSchemeCd;
@Basic
@Column(name = "COMPRESSED_FILE_SIZE_KB_QTY", nullable = true, precision = 0, columnDefinition = "NUMBER")
private Long compressedFileSizeKbQty;
@Basic
@Column(name = "SENDER_CONTACT_EMAIL_TXT", nullable = true, length = 200)
private String senderContactEmailTxt;
@Basic
@Column(name="CREATED_BY_ID", nullable=false, length=24)
private String createdById;
@Basic
@Column(name="CREATE_TS", nullable=false, columnDefinition="TIMESTAMP(6)")
@Temporal(TemporalType.TIMESTAMP)
private Date createTs;
@Basic
@Column(name="UPDATED_BY_ID", nullable=true, length=24)
private String updatedById;
@Basic
@Column(name="UPDATE_TS", nullable=true, columnDefinition="TIMESTAMP(6)")
@Temporal(TemporalType.TIMESTAMP)
private Date updateTs;
/**
* @return the alertStatus
*/
public AlertStatusEnum getAlertStatus() {
return alertStatus;
}
/**
* @param alertStatus the alertStatus to set
*/
public void setAlertStatus(AlertStatusEnum alertStatus) {
this.alertStatus = alertStatus;
}
/**
* @return the entityCommunicationTypeCd
*/
public String getEntityCommunicationTypeCd() {
return entityCommunicationTypeCd;
}
/**
* @param entityCommunicationTypeCd the entityCommunicationTypeCd to set
*/
public void setEntityCommunicationTypeCd(String entityCommunicationTypeCd) {
this.entityCommunicationTypeCd = entityCommunicationTypeCd;
}
/**
* @return the idesTransmissionId
*/
public String getIdesTransmissionId() {
return idesTransmissionId;
}
/**
* @param idesTransmissionId the idesTransmissionId to set
*/
public void setIdesTransmissionId(String idesTransmissionId) {
this.idesTransmissionId = idesTransmissionId;
}
/**
* @return the fileRevisionInd
*/
public String getFileRevisionInd() {
return fileRevisionInd;
}
/**
* @param fileRevisionInd the fileRevisionInd to set
*/
public void setFileRevisionInd(String fileRevisionInd) {
this.fileRevisionInd = fileRevisionInd;
}
/**
* @return the originalIdesTransmissionId
*/
public String getOriginalIdesTransmissionId() {
return originalIdesTransmissionId;
}
/**
* @param originalIdesTransmissionId the originalIdesTransmissionId to set
*/
public void setOriginalIdesTransmissionId(String originalIdesTransmissionId) {
this.originalIdesTransmissionId = originalIdesTransmissionId;
}
/**
* @return the alertRecipientTypeCd
*/
public String getAlertRecipientTypeCd() {
return alertRecipientTypeCd;
}
/**
* @param alertRecipientTypeCd the alertRecipientTypeCd to set
*/
public void setAlertRecipientTypeCd(String alertRecipientTypeCd) {
this.alertRecipientTypeCd = alertRecipientTypeCd;
}
/**
* @return the alertTypeCd
*/
public String getAlertTypeCd() {
return alertTypeCd;
}
/**
* @param alertTypeCd the alertTypeCd to set
*/
public void setAlertTypeCd(String alertTypeCd) {
this.alertTypeCd = alertTypeCd;
}
/**
* @return the alertReasonCd
*/
public String getAlertReasonCd() {
return alertReasonCd;
}
/**
* @param alertReasonCd the alertReasonCd to set
*/
public void setAlertReasonCd(String alertReasonCd) {
this.alertReasonCd = alertReasonCd;
}
/**
* @return the entitySenderIdentifier
*/
public String getEntitySenderIdentifier() {
return entitySenderIdentifier;
}
/**
* @param entitySenderIdentifier the entitySenderIdentifier to set
*/
public void setEntitySenderIdentifier(String entitySenderIdentifier) {
this.entitySenderIdentifier = entitySenderIdentifier;
}
/**
* @return the entityReceiverIdentifier
*/
public String getEntityReceiverIdentifier() {
return entityReceiverIdentifier;
}
/**
* @param entityReceiverIdentifier the entityReceiverIdentifier to set
*/
public void setEntityReceiverIdentifier(String entityReceiverIdentifier) {
this.entityReceiverIdentifier = entityReceiverIdentifier;
}
/**
* @return the senderFileId
*/
public String getSenderFileId() {
return senderFileId;
}
/**
* @param senderFileId the senderFileId to set
*/
public void setSenderFileId(String senderFileId) {
this.senderFileId = senderFileId;
}
/**
* @return the idesFileNm
*/
public String getIdesFileNm() {
return idesFileNm;
}
/**
* @param idesFileNm the idesFileNm to set
*/
public void setIdesFileNm(String idesFileNm) {
this.idesFileNm = idesFileNm;
}
/**
* @return the taxYr
*/
public Long getTaxYr() {
return taxYr;
}
/**
* @param taxYr the taxYr to set
*/
public void setTaxYr(Long taxYr) {
this.taxYr = taxYr;
}
/**
* @return the fileCreateTs
*/
public Date getFileCreateTs() {
return fileCreateTs;
}
/**
* @param fileCreateTs the fileCreateTs to set
*/
public void setFileCreateTs(Date fileCreateTs) {
this.fileCreateTs = fileCreateTs;
}
/**
* @return the fileFormatCd
*/
public String getFileFormatCd() {
return fileFormatCd;
}
/**
* @param fileFormatCd the fileFormatCd to set
*/
public void setFileFormatCd(String fileFormatCd) {
this.fileFormatCd = fileFormatCd;
}
/**
* @return the binaryEncodingSchemeCd
*/
public String getBinaryEncodingSchemeCd() {
return binaryEncodingSchemeCd;
}
/**
* @param binaryEncodingSchemeCd the binaryEncodingSchemeCd to set
*/
public void setBinaryEncodingSchemeCd(String binaryEncodingSchemeCd) {
this.binaryEncodingSchemeCd = binaryEncodingSchemeCd;
}
/**
* @return the compressedFileSizeKbQty
*/
public Long getCompressedFileSizeKbQty() {
return compressedFileSizeKbQty;
}
/**
* @param compressedFileSizeKbQty the compressedFileSizeKbQty to set
*/
public void setCompressedFileSizeKbQty(Long compressedFileSizeKbQty) {
this.compressedFileSizeKbQty = compressedFileSizeKbQty;
}
/**
* @return the senderContactEmailTxt
*/
public String getSenderContactEmailTxt() {
return senderContactEmailTxt;
}
/**
* @param senderContactEmailTxt the senderContactEmailTxt to set
*/
public void setSenderContactEmailTxt(String senderContactEmailTxt) {
this.senderContactEmailTxt = senderContactEmailTxt;
}
/**
* @return the createdById
*/
public String getCreatedById() {
return createdById;
}
/**
* @param createdById the createdById to set
*/
public void setCreatedById(String createdById) {
this.createdById = createdById;
}
/**
* @return the createTs
*/
public Date getCreateTs() {
return createTs;
}
/**
* @param createTs the createTs to set
*/
public void setCreateTs(Date createTs) {
this.createTs = createTs;
}
/**
* @return the updatedById
*/
public String getUpdatedById() {
return updatedById;
}
/**
* @param updatedById the updatedById to set
*/
public void setUpdatedById(String updatedById) {
this.updatedById = updatedById;
}
/**
* @return the updateTs
*/
public Date getUpdateTs() {
return updateTs;
}
/**
* @param updateTs the updateTs to set
*/
public void setUpdateTs(Date updateTs) {
this.updateTs = updateTs;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((alertReasonCd == null) ? 0 : alertReasonCd.hashCode());
result = prime * result + ((alertRecipientTypeCd == null) ? 0 : alertRecipientTypeCd.hashCode());
result = prime * result + ((alertTypeCd == null) ? 0 : alertTypeCd.hashCode());
result = prime * result + ((binaryEncodingSchemeCd == null) ? 0 : binaryEncodingSchemeCd.hashCode());
result = prime * result + ((compressedFileSizeKbQty == null) ? 0 : compressedFileSizeKbQty.hashCode());
result = prime * result + ((createTs == null) ? 0 : createTs.hashCode());
result = prime * result + ((createdById == null) ? 0 : createdById.hashCode());
result = prime * result + ((entityCommunicationTypeCd == null) ? 0 : entityCommunicationTypeCd.hashCode());
result = prime * result + ((entityReceiverIdentifier == null) ? 0 : entityReceiverIdentifier.hashCode());
result = prime * result + ((entitySenderIdentifier == null) ? 0 : entitySenderIdentifier.hashCode());
result = prime * result + ((fileCreateTs == null) ? 0 : fileCreateTs.hashCode());
result = prime * result + ((fileFormatCd == null) ? 0 : fileFormatCd.hashCode());
result = prime * result + ((fileRevisionInd == null) ? 0 : fileRevisionInd.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((idesFileNm == null) ? 0 : idesFileNm.hashCode());
result = prime * result + ((idesTransmissionId == null) ? 0 : idesTransmissionId.hashCode());
result = prime * result + ((originalIdesTransmissionId == null) ? 0 : originalIdesTransmissionId.hashCode());
result = prime * result + ((senderContactEmailTxt == null) ? 0 : senderContactEmailTxt.hashCode());
result = prime * result + ((senderFileId == null) ? 0 : senderFileId.hashCode());
result = prime * result + ((taxYr == null) ? 0 : taxYr.hashCode());
result = prime * result + ((updateTs == null) ? 0 : updateTs.hashCode());
result = prime * result + ((updatedById == null) ? 0 : updatedById.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Alert))
return false;
Alert other = (Alert) obj;
if (alertReasonCd == null) {
if (other.alertReasonCd != null)
return false;
} else if (!alertReasonCd.equals(other.alertReasonCd))
return false;
if (alertRecipientTypeCd == null) {
if (other.alertRecipientTypeCd != null)
return false;
} else if (!alertRecipientTypeCd.equals(other.alertRecipientTypeCd))
return false;
if (alertTypeCd == null) {
if (other.alertTypeCd != null)
return false;
} else if (!alertTypeCd.equals(other.alertTypeCd))
return false;
if (binaryEncodingSchemeCd == null) {
if (other.binaryEncodingSchemeCd != null)
return false;
} else if (!binaryEncodingSchemeCd.equals(other.binaryEncodingSchemeCd))
return false;
if (compressedFileSizeKbQty == null) {
if (other.compressedFileSizeKbQty != null)
return false;
} else if (!compressedFileSizeKbQty.equals(other.compressedFileSizeKbQty))
return false;
if (createTs == null) {
if (other.createTs != null)
return false;
} else if (!createTs.equals(other.createTs))
return false;
if (createdById == null) {
if (other.createdById != null)
return false;
} else if (!createdById.equals(other.createdById))
return false;
if (entityCommunicationTypeCd == null) {
if (other.entityCommunicationTypeCd != null)
return false;
} else if (!entityCommunicationTypeCd.equals(other.entityCommunicationTypeCd))
return false;
if (entityReceiverIdentifier == null) {
if (other.entityReceiverIdentifier != null)
return false;
} else if (!entityReceiverIdentifier.equals(other.entityReceiverIdentifier))
return false;
if (entitySenderIdentifier == null) {
if (other.entitySenderIdentifier != null)
return false;
} else if (!entitySenderIdentifier.equals(other.entitySenderIdentifier))
return false;
if (fileCreateTs == null) {
if (other.fileCreateTs != null)
return false;
} else if (!fileCreateTs.equals(other.fileCreateTs))
return false;
if (fileFormatCd == null) {
if (other.fileFormatCd != null)
return false;
} else if (!fileFormatCd.equals(other.fileFormatCd))
return false;
if (fileRevisionInd == null) {
if (other.fileRevisionInd != null)
return false;
} else if (!fileRevisionInd.equals(other.fileRevisionInd))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (idesFileNm == null) {
if (other.idesFileNm != null)
return false;
} else if (!idesFileNm.equals(other.idesFileNm))
return false;
if (idesTransmissionId == null) {
if (other.idesTransmissionId != null)
return false;
} else if (!idesTransmissionId.equals(other.idesTransmissionId))
return false;
if (originalIdesTransmissionId == null) {
if (other.originalIdesTransmissionId != null)
return false;
} else if (!originalIdesTransmissionId.equals(other.originalIdesTransmissionId))
return false;
if (senderContactEmailTxt == null) {
if (other.senderContactEmailTxt != null)
return false;
} else if (!senderContactEmailTxt.equals(other.senderContactEmailTxt))
return false;
if (senderFileId == null) {
if (other.senderFileId != null)
return false;
} else if (!senderFileId.equals(other.senderFileId))
return false;
if (taxYr == null) {
if (other.taxYr != null)
return false;
} else if (!taxYr.equals(other.taxYr))
return false;
if (updateTs == null) {
if (other.updateTs != null)
return false;
} else if (!updateTs.equals(other.updateTs))
return false;
if (updatedById == null) {
if (other.updatedById != null)
return false;
} else if (!updatedById.equals(other.updatedById))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Alert [id=" + id + ", entityCommunicationTypeCd=" + entityCommunicationTypeCd + ", idesTransmissionId="
+ idesTransmissionId + ", fileRevisionInd=" + fileRevisionInd + ", originalIdesTransmissionId="
+ originalIdesTransmissionId + ", alertRecipientTypeCd=" + alertRecipientTypeCd + ", alertTypeCd="
+ alertTypeCd + ", alertReasonCd=" + alertReasonCd + ", entitySenderIdentifier="
+ entitySenderIdentifier + ", entityReceiverIdentifier=" + entityReceiverIdentifier + ", senderFileId="
+ senderFileId + ", idesFileNm=" + idesFileNm + ", taxYr=" + taxYr + ", fileCreateTs=" + fileCreateTs
+ ", fileFormatCd=" + fileFormatCd + ", binaryEncodingSchemeCd=" + binaryEncodingSchemeCd
+ ", compressedFileSizeKbQty=" + compressedFileSizeKbQty + ", senderContactEmailTxt="
+ senderContactEmailTxt + ", createdById=" + createdById + ", createTs=" + createTs + ", updatedById="
+ updatedById + ", updateTs=" + updateTs + "]";
}
}
<file_sep>/**
* Proprietary Software Built Off of Open-Source Software?
*/
package corp.pdb.aea.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.springframework.stereotype.Service;
/**
* @author waleed.k.al-jaradat
*
*/
@Service
public class TaxYrTypeFormatter {
private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
/*
<code>static block</code> below further initializes the formatter object, notes about <code>static blocks</code>
- if initialization of static variables requires some additional logic except the assignment
- if the initialization of static variables is error-prone and requires exception handling
- a class can have multiple static blocks
- static fields and static blocks are resolved and executed in the same order as they are present in the class
static {
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
}
*/
public TaxYrTypeFormatter() {
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
}
public String format(XMLGregorianCalendar xCal) {
return xCal.toXMLFormat();
}
public XMLGregorianCalendar parse(String v) throws DatatypeConfigurationException {
Date date;
try {
v += "-01-01T06:00:01Z";
date = formatter.parse(v);
System.out.println(date);
} catch (Exception e) {
date = new Date();
//e.printStackTrace();
System.out.println("Encountered exception parsing [" + v + "] as Date object\n" + e.getMessage());
}
GregorianCalendar gCal = new GregorianCalendar();
//gCal.setTimeZone(TimeZone.getTimeZone("UTC"));
gCal.setTimeInMillis(date.getTime());
XMLGregorianCalendar xCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gCal);
System.out.println(xCal.getYear());
return xCal;
}
}
<file_sep>drop table if exists INCOMING_UPLOAD;
create table if not exists INCOMING_UPLOAD(
ID bigint primary key auto_increment,
COMMUNICATION_TYPE_CD varchar(10) not null,
ENTITY_SENDER_ID varchar(24) not null,
ENTITY_RECEIVER_ID varchar(24) not null,
IDES_FILE_NM varchar(200) not null,
SENDER_FILE_ID varchar(200) not null,
FILE_SIZE_KB_QTY bigint,
ALERT_ID bigint,
ALERT_STATUS char(2) not null,
ALERT_SENT_TS timestamp(6),
CREATED_BY_ID varchar(24) not null,
CREATE_TS timestamp(6) not null,
UPDATED_BY_ID varchar(24),
UPDATE_TS timestamp(6)
);
drop table if exists OUTGOING_DOWNLOAD;
create table OUTGOING_DOWNLOAD(
ID bigint primary key auto_increment,
COMMUNICATION_TYPE_CD varchar(10) not null,
ENTITY_SENDER_ID varchar(24) not null,
ENTITY_RECEIVER_ID varchar(24) not null,
IDES_FILE_NM varchar(200) not null,
SENDER_FILE_ID varchar(200) not null,
FILE_LOCATION varchar(200) not null,
COMPRESSED_FILE_SIZE_KB_QTY bigint,
CREATED_BY_ID varchar(24) not null,
CREATE_TS timestamp(6) not null,
UPDATED_BY_ID varchar(24),
UPDATE_TS timestamp(6)
);
drop table if exists ALERT;
create table if not exists ALERT(
ID bigint primary key auto_increment,
ALERT_STATUS char(2) not null,
ENTITY_COMMUNICATION_TYPE_CD varchar(10) not null,
IDES_TRANSMISSION_ID varchar(32) not null,
FILE_REVISION_IND char(1),
ORIGINAL_IDES_TRANSMISSION_ID varchar(32),
ALERT_RECIPIENT_TYPE_CD char(2) not null,
ALERT_TYPE_CD varchar(5) not null,
ALERT_REASON_CD varchar(5) not null,
ENTITY_SENDER_ID varchar(24) not null,
ENTITY_RECEIVER_ID varchar(24) not null,
SENDER_FILE_ID varchar(200) not null,
IDES_FILE_NM varchar(200) not null,
TAX_YR bigint,
FILE_CREATE_TS timestamp(6),
FILE_FORMAT_CD varchar(10),
BINARY_ENCODING_SCHEME_CD varchar(10),
COMPRESSED_FILE_SIZE_KB_QTY bigint,
SENDER_CONTACT_EMAIL_TXT varchar(200),
CREATED_BY_ID varchar(24) not null,
CREATE_TS timestamp(6) not null,
UPDATED_BY_ID varchar(24),
UPDATE_TS timestamp(6)
);<file_sep>//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.08.08 at 01:18:40 PM EDT
//
package ides.msg.ctsfilestatusmessage;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><Component xmlns="urn:ides:msg:ctsfilestatusmessage" xmlns:ides="urn:ides" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><DictionaryEntryNm>CTS File Status Response Type</DictionaryEntryNm><MajorVersionNum>1</MajorVersionNum><MinorVersionNum>0</MinorVersionNum><VersionEffectiveBeginDt>2018-02-07</VersionEffectiveBeginDt><VersionDescriptionTxt>Initial version</VersionDescriptionTxt><DescriptionTxt>Type for message for the CTS File Status response</DescriptionTxt></Component>
* </pre>
*
*
* <p>Java class for CTSFileStatusResponseType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="CTSFileStatusResponseType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{urn:ides}ReceiptTs"/>
* <element ref="{urn:ides}IDESSendingTs"/>
* <element ref="{urn:ides}SenderFileId"/>
* <element ref="{urn:ides}CTSTransmissionId"/>
* <element ref="{urn:ides}CTSStatusCd"/>
* </sequence>
* <attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" fixed="1.0" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CTSFileStatusResponseType", propOrder = {
"receiptTs",
"idesSendingTs",
"senderFileId",
"ctsTransmissionId",
"ctsStatusCd"
})
public class CTSFileStatusResponseType {
@XmlElement(name = "ReceiptTs", namespace = "urn:ides", required = true)
protected String receiptTs;
@XmlElement(name = "IDESSendingTs", namespace = "urn:ides", required = true)
protected String idesSendingTs;
@XmlElement(name = "SenderFileId", namespace = "urn:ides", required = true)
protected String senderFileId;
@XmlElement(name = "CTSTransmissionId", namespace = "urn:ides", required = true)
protected String ctsTransmissionId;
@XmlElement(name = "CTSStatusCd", namespace = "urn:ides", required = true)
protected String ctsStatusCd;
@XmlAttribute(name = "version")
protected String version;
/**
* Gets the value of the receiptTs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReceiptTs() {
return receiptTs;
}
/**
* Sets the value of the receiptTs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReceiptTs(String value) {
this.receiptTs = value;
}
/**
* Gets the value of the idesSendingTs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDESSendingTs() {
return idesSendingTs;
}
/**
* Sets the value of the idesSendingTs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDESSendingTs(String value) {
this.idesSendingTs = value;
}
/**
* Gets the value of the senderFileId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSenderFileId() {
return senderFileId;
}
/**
* Sets the value of the senderFileId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSenderFileId(String value) {
this.senderFileId = value;
}
/**
* Gets the value of the ctsTransmissionId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCTSTransmissionId() {
return ctsTransmissionId;
}
/**
* Sets the value of the ctsTransmissionId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCTSTransmissionId(String value) {
this.ctsTransmissionId = value;
}
/**
* Gets the value of the ctsStatusCd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCTSStatusCd() {
return ctsStatusCd;
}
/**
* Sets the value of the ctsStatusCd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCTSStatusCd(String value) {
this.ctsStatusCd = value;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
if (version == null) {
return "1.0";
} else {
return version;
}
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
}
<file_sep>/**
* Proprietary Software Built Off of Open-Source Software?
*/
package corp.pdb.aea.service;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import corp.pdb.aea.data.model.Alert;
import corp.pdb.aea.data.model.OutgoingDownload;
import corp.pdb.aea.data.model.enums.AlertStatusEnum;
import corp.pdb.aea.data.repository.AlertRepository;
import corp.pdb.aea.data.repository.OutgoingDownloadRepository;
import ides.EntityCommunicationTypeCdType;
/**
* @author waleed.k.al-jaradat
*
*/
@Service
public class OutgoingDownloadAlertService {
@Autowired
TransmitAlertService transmitAlertService;
@Autowired
AlertRepository alertRepository;
@Autowired
OutgoingDownloadRepository outgoingDownloadRepository;
String[] errorTransmissionIds = {"FDOWNSRVCBCCLIENTIMPL_TRANSID_32", "FDOWNSRVCBCCLIENTIMPL_TRANSID_33",
"FDOWNSRVCBCCLIENTIMPL_TRANSID_34", "FDOWNSRVCBCCLIENTIMPL_TRANSID_35", "FDOWNSRVCBCCLIENTIMPL_TRANSID_36",
"FDOWNSRVCBCCLIENTIMPL_TRANSID_37", "FDOWNSRVCBCCLIENTIMPL_TRANSID_38", "FDOWNSRVCBCCLIENTIMPL_TRANSID_39",
"FDOWNSRVCBCCLIENTIMPL_TRANSID_40", "FDOWNSRVCBCCLIENTIMPL_TRANSID_41", "FDOWNSRVCBCCLIENTIMPL_TRANSID_42",
"FDOWNSRVCBCCLIENTIMPL_TRANSID_43", "FDOWNSRVCBCCLIENTIMPL_TRANSID_44", "FDOWNSRVCBCCLIENTIMPL_TRANSID_45",
"FDOWNSRVCBCCLIENTIMPL_TRANSID_46", "FDOWNSRVCBCCLIENTIMPL_TRANSID_47", "FDOWNSRVCBCCLIENTIMPL_TRANSID_48",
"FDOWNSRVCBCCLIENTIMPL_TRANSID_49", "FDOWNSRVCBCCLIENTIMPL_TRANSID_50", "FDOWNSRVCBCCLIENTIMPL_TRANSID_51"};
public String constructAndTransmit() {
String landingPage = "";
List<OutgoingDownload> outgoingDownloads = outgoingDownloadRepository.findAll();
for(OutgoingDownload outgoingDownload : outgoingDownloads) {
try {
Alert alertToSend = constructAlertFromOutgoingDownload(outgoingDownload);
landingPage = transmitAlertService.transmit(alertToSend);
if(landingPage.equals("500"))
break;
} catch(Exception e) {
landingPage = "500";
break;
}
}
return landingPage;
}
public String constructAndTransmitFaultCase() {
String landingPage = "";
for(String errorTransmissionId : errorTransmissionIds) {
try {
Alert alertToSend = constructAlertForFaultCases(errorTransmissionId);
landingPage = transmitAlertService.transmit(alertToSend);
if(landingPage.equals("500"))
break;
} catch(Exception e) {
landingPage = "500";
break;
}
}
return landingPage;
}
protected Alert constructAlertFromOutgoingDownload(OutgoingDownload outgoingDownload) {
Date createDate = new Date();
Alert alert = new Alert();
alert.setAlertStatus(AlertStatusEnum.SE);
alert.setEntityCommunicationTypeCd(outgoingDownload.getCommunicationTypeCd());
alert.setIdesTransmissionId(outgoingDownload.getIdesFileNm());
alert.setFileRevisionInd("N");
alert.setAlertRecipientTypeCd("CR");
alert.setAlertTypeCd("RD");
alert.setAlertReasonCd("RC021");
alert.setEntitySenderIdentifier(outgoingDownload.getEntitySenderIdentifier());
alert.setEntityReceiverIdentifier(outgoingDownload.getEntityReceiverIdentifier());
alert.setSenderFileId(outgoingDownload.getSenderFileId());
alert.setIdesFileNm(outgoingDownload.getIdesFileNm());
alert.setTaxYr(Long.valueOf(2017));
alert.setFileCreateTs(createDate);
alert.setFileFormatCd("XML");
alert.setBinaryEncodingSchemeCd("NONE");
alert.setCompressedFileSizeKbQty(outgoingDownload.getCompressedFileSizeKbQty());
alert.setCreatedById("ALERTCLI");
alert.setCreateTs(createDate);
alert = alertRepository.save(alert);
return alert;
}
protected Alert constructAlertForFaultCases(String idesTransmissionId) {
Date createDate = new Date();
Alert alert = new Alert();
alert.setAlertStatus(AlertStatusEnum.SE);
alert.setEntityCommunicationTypeCd(EntityCommunicationTypeCdType.CBC.name());
alert.setIdesTransmissionId(idesTransmissionId);
alert.setFileRevisionInd("N");
alert.setAlertRecipientTypeCd("CR");
alert.setAlertTypeCd("RD");
alert.setAlertReasonCd("RC021");
alert.setEntitySenderIdentifier("CA");
alert.setEntityReceiverIdentifier("US.00");
alert.setSenderFileId("fault case senderFileId");
alert.setIdesFileNm("fault case idesFileNm");
alert.setTaxYr(Long.valueOf(2017));
alert.setFileCreateTs(createDate);
alert.setFileFormatCd("XML");
alert.setBinaryEncodingSchemeCd("NONE");
alert.setCompressedFileSizeKbQty(Long.valueOf(10));
alert.setCreatedById("ALERTCLI");
alert.setCreateTs(createDate);
alert = alertRepository.save(alert);
return alert;
}
}
<file_sep>/**
* Proprietary Software Built Off of Open-Source Software?
*/
package corp.pdb.aea.ws.client;
/*import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;*/
import javax.xml.bind.JAXBElement;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ws.client.core.WebServiceTemplate;
import corp.pdb.aea.util.TimestampTypeFormatter;
/*import ides.AlertRecipientTypeCdType;
import ides.BinaryEncodingSchemeCdType;
import ides.EntityCommunicationTypeCdType;
import ides.EntityIdentifierType;
import ides.FileFormatCdType;*/
import ides.msg.idesalertmessage.IDESAlertRequestType;
import ides.msg.idesalertmessage.IDESAlertResponseType;
import ides.msg.idesalertmessage.ObjectFactory;
/**
* @author waleed.k.al-jaradat
*
*/
@Component
public class IDESAlertServiceClientImpl implements InitializingBean {
private static final Logger LOGGER = LogManager.getLogger(IDESAlertServiceClientImpl.class);
//private Map<Integer, String[]> valuesMap;
@Autowired
private WebServiceTemplate idesAlertServiceTemplate;
@Autowired
TimestampTypeFormatter timestampTypeFormatter;
public IDESAlertResponseType idesAlertRequestOperation(IDESAlertRequestType alertRequestBody) {
LOGGER.debug("Entering idesAlertRequestOperation method");
/*ObjectFactory factory = new ObjectFactory();
IDESAlertRequestType requestBody = factory.createIDESAlertRequestType();
requestBody.setRequestSentTs(timestampTypeFormatter.generateTimestamp());
//requestBody.setIDESTransmissionId("A1B2C3D4E5F6G7H8I9J0K1L2M3N4O5P6");
requestBody.setIDESSendingTs(timestampTypeFormatter.generateTimestamp());
requestBody.setIDESReceivedTs(timestampTypeFormatter.generateTimestamp());
//requestBody.setIDESFileNm("A200CharacterStringWhichSpecifiesThe.FileName");
requestBody.setAlertRecipientTypeCd(AlertRecipientTypeCdType.CS);
EntityIdentifierType senderEntityType = new EntityIdentifierType();
senderEntityType.setCTSCountryCd("US.00");
requestBody.setEntitySenderIdentifier(senderEntityType);
requestBody.setAlertTypeCd("SA");
requestBody.setAlertReasonCd("RC034");
//requestBody.setSenderFileId("A200CharacterStringWithFormat=[CountryCdSender_CountryCdReceiver_CommunicationType_MessageRefID]");
requestBody.setFileFormatCd(FileFormatCdType.XML);
requestBody.setBinaryEncodingSchemeCd(BinaryEncodingSchemeCdType.NONE);
requestBody.setFileCreateTs(timestampTypeFormatter.generateTimestamp());*/
/*try {
XMLGregorianCalendar taxYear = DatatypeFactory.newInstance().newXMLGregorianCalendar();
requestBody.setTaxYear(taxYear);
LOGGER.trace("taxYear=[{}]", taxYear.getYear());
} catch (DatatypeConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//Need to provide this as parameter
/*EntityIdentifierType receiverEntityType = new EntityIdentifierType();
receiverEntityType.setCTSCountryCd("CA");
requestBody.setEntityReceiverIdentifier(receiverEntityType);
requestBody.setEntityCommunicationTypeCd(EntityCommunicationTypeCdType.CBC);
requestBody.setCompressedFileSizeKBQty(new BigInteger("25"));
requestBody.setFileRevisionInd(false);
JAXBElement<IDESAlertRequestType> request;
JAXBElement<IDESAlertResponseType> response;
if((!this.valuesMap.isEmpty()) && (this.valuesMap != null)) {
for(int i=0; i<valuesMap.size(); i++) {
String[] valueMap = valuesMap.get(Integer.valueOf(i));
requestBody.setIDESTransmissionId(valueMap[0]);
requestBody.setIDESFileNm(valueMap[1]);
requestBody.setSenderFileId(valueMap[2]);
request = factory.createIDESAlertRequest(requestBody);
response = (JAXBElement<IDESAlertResponseType>) idesAlertServiceTemplate.marshalSendAndReceive(request);
LOGGER.trace("Received response: IDESTransmissionId=[{}], ReceiptTs=[{}]", response.getValue().getIDESTransmissionId(), response.getValue().getReceiptTs());
}
} else {
requestBody.setIDESTransmissionId("ALERTSRVCBCCLIENTIMPL_TRANSID_99");
requestBody.setIDESFileNm("ALERTSRVCBCCLIENTIMPL_TRANSID_99.tar.gz");
requestBody.setSenderFileId("ALERTSRVCBCCLIENTIMPL_TRANSID_99_SF_SEnderFileId");
requestBody.setAlertReasonCd("RC001");
request = factory.createIDESAlertRequest(requestBody);
response = (JAXBElement<IDESAlertResponseType>) idesAlertServiceTemplate.marshalSendAndReceive(request);
LOGGER.trace("Received response: IDESTransmissionId=[{}], ReceiptTs=[{}]", response.getValue().getIDESTransmissionId(), response.getValue().getReceiptTs());
}*/
ObjectFactory factory = new ObjectFactory();
JAXBElement<IDESAlertRequestType> alertRequest = factory.createIDESAlertRequest(alertRequestBody);
@SuppressWarnings("unchecked")
JAXBElement<IDESAlertResponseType> alertResponse = (JAXBElement<IDESAlertResponseType>) idesAlertServiceTemplate.marshalSendAndReceive(alertRequest);
return alertResponse.getValue();
/*IDESAlertResponseType alertResponseBody = alertResponse.getValue();
return alertResponseBody;*/
/*IDESAlertResponseType responseBody = response.getValue();
return (responseBody.getIDESTransmissionId() + ": " + responseBody.getAlertTypeCd());*/
}
@Override
public void afterPropertiesSet() throws Exception {
/*this.valuesMap = new HashMap<Integer, String[]>();
valuesMap.put(Integer.valueOf(0), new String[]{"OUTUPSRVCBCCLIENTIMPL_TRANSID_01", "US.00_CA_CBC_US2023-595d10b0ca1540d3a14fe8b594b350de.zip", "US.00_CA_CBC_US2023-595d10b0ca1540d3a14fe8b594b350de"});
valuesMap.put(Integer.valueOf(1), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_02", "US.00_DE_CBCStatus_StatusUS2018DEc8b839e5de4b42bab1b08d068bf5acad.zip", "US.00_DE_CBCStatus_StatusUS2018DEc8b839e5de4b42bab1b08d068bf5acad"});
valuesMap.put(Integer.valueOf(2), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_03", "US.00_NL_CBCStatus_StatusUS2023NLb57d1c836b6f4edaa94f40408531222a.zip", "US.00_NL_CBCStatus_StatusUS2023NLb57d1c836b6f4edaa94f40408531222a"});
valuesMap.put(Integer.valueOf(3), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_04", "US.00_NL_CBCStatus_StatusUS2023NL86f80ced1bfc47939ffb1941fd12da64.zip", "US.00_NL_CBCStatus_StatusUS2023NL86f80ced1bfc47939ffb1941fd12da64"});
valuesMap.put(Integer.valueOf(4), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_05", "US.00_DE_CBCStatus_StatusUS2018DEb525af0d34294319a05bbb58c29d683b.zip", "US.00_DE_CBCStatus_StatusUS2018DEb525af0d34294319a05bbb58c29d683b"});
valuesMap.put(Integer.valueOf(5), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_06", "US.00_DE_CBCStatus_StatusUS2018DE501813414f2d4e14871c03660683d102.zip", "US.00_DE_CBCStatus_StatusUS2018DE501813414f2d4e14871c03660683d102"});
valuesMap.put(Integer.valueOf(6), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_07", "US.00_NL_CBCStatus_StatusUS2023NLf0c9d1d42e4a4053ab56d2a9e0157335.zip", "US.00_NL_CBCStatus_StatusUS2023NLf0c9d1d42e4a4053ab56d2a9e0157335"});
valuesMap.put(Integer.valueOf(7), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_08", "US.00_DE_CBCStatus_StatusUS2018DE0d4ceb9857324b0c9649507315087069.zip", "US.00_DE_CBCStatus_StatusUS2018DE0d4ceb9857324b0c9649507315087069"});
valuesMap.put(Integer.valueOf(8), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_09", "US.00_NL_CBCStatus_StatusUS2023NL2a1e84d7175247f09f1000b5bfa8727a.zip", "US.00_NL_CBCStatus_StatusUS2023NL2a1e84d7175247f09f1000b5bfa8727a"});
valuesMap.put(Integer.valueOf(9), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_10", "US.00_DE_CBCStatus_StatusUS2018DE365da38e8b9f4347bc3b1f946c0d8e09.zip", "US.00_DE_CBCStatus_StatusUS2018DE365da38e8b9f4347bc3b1f946c0d8e09"});
valuesMap.put(Integer.valueOf(10), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_11", "US.00_NL_CBCStatus_StatusUS2023NL88c349e84a0a4f8980bf3d3c61e9305b.zip", "US.00_NL_CBCStatus_StatusUS2023NL88c349e84a0a4f8980bf3d3c61e9305b"});
valuesMap.put(Integer.valueOf(11), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_12", "US.00_NL_CBCStatus_StatusUS2023NLafe77cb293044da38d0c2eb1c9f4fbdc.zip", "US.00_NL_CBCStatus_StatusUS2023NLafe77cb293044da38d0c2eb1c9f4fbdc"});
valuesMap.put(Integer.valueOf(12), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_13", "US.00_DE_CBCStatus_StatusUS2018DEde774a7fc65a4fed9c5809d6cac475b1.zip", "US.00_DE_CBCStatus_StatusUS2018DEde774a7fc65a4fed9c5809d6cac475b1"});
valuesMap.put(Integer.valueOf(13), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_14", "US.00_DE_CBCStatus_StatusUS2018DEe0aba382af6b45f18cf474ded84b2ca3.zip", "US.00_DE_CBCStatus_StatusUS2018DEe0aba382af6b45f18cf474ded84b2ca3"});
valuesMap.put(Integer.valueOf(14), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_15", "US.00_DE_CBCStatus_StatusUS2018DE0ca53bab2e4347fdbc230849d5da2219.zip", "US.00_DE_CBCStatus_StatusUS2018DE0ca53bab2e4347fdbc230849d5da2219"});
valuesMap.put(Integer.valueOf(15), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_16", "US.00_DE_CBCStatus_StatusUS2018DE069661ec1233406b9dbd41838517d7fe.zip", "US.00_DE_CBCStatus_StatusUS2018DE069661ec1233406b9dbd41838517d7fe"});
valuesMap.put(Integer.valueOf(16), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_17", "US.00_DE_CBCStatus_StatusUS2018DE64e88d0c74d54373a0eb92b8a0469f87.zip", "US.00_DE_CBCStatus_StatusUS2018DE64e88d0c74d54373a0eb92b8a0469f87"});
valuesMap.put(Integer.valueOf(17), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_18", "US.00_DE_CBCStatus_StatusUS2018DE81e539699b064ed7a0ba5fd10ca0339b.zip", "US.00_DE_CBCStatus_StatusUS2018DE81e539699b064ed7a0ba5fd10ca0339b"});
valuesMap.put(Integer.valueOf(18), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_19", "US.00_DE_CBCStatus_StatusUS2018DEf0fac7ed646a4908a53176c4ab978cd1.zip", "US.00_DE_CBCStatus_StatusUS2018DEf0fac7ed646a4908a53176c4ab978cd1"});
valuesMap.put(Integer.valueOf(19), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_20", "US.00_DE_CBCStatus_StatusUS2018DE485adc306ce749148df971377e336f82.zip", "US.00_DE_CBCStatus_StatusUS2018DE485adc306ce749148df971377e336f82"});
valuesMap.put(Integer.valueOf(20), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_21", "US.00_DE_CBCStatus_StatusUS2018DE2acf0939fa894a4dac86139bc136e670.zip", "US.00_DE_CBCStatus_StatusUS2018DE2acf0939fa894a4dac86139bc136e670"});
valuesMap.put(Integer.valueOf(21), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_22", "US.00_DE_CBCStatus_StatusUS2018DE0f9c711ce9b94777b376206c9967ea46.zip", "US.00_DE_CBCStatus_StatusUS2018DE0f9c711ce9b94777b376206c9967ea46"});
valuesMap.put(Integer.valueOf(22), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_23", "US.00_DE_CBCStatus_StatusUS2018DE98ccd3e4c22a481bb57499e67a964926.zip", "US.00_DE_CBCStatus_StatusUS2018DE98ccd3e4c22a481bb57499e67a964926"});
valuesMap.put(Integer.valueOf(23), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_24", "US.00_DE_CBCStatus_StatusUS2018DE3f7965e224964e768c7b008d7cc11352.zip", "US.00_DE_CBCStatus_StatusUS2018DE3f7965e224964e768c7b008d7cc11352"});
valuesMap.put(Integer.valueOf(24), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_25", "US.00_DE_CBCStatus_StatusUS2018DEadce94d812874949a735a0377a3dccb9.zip", "US.00_DE_CBCStatus_StatusUS2018DEadce94d812874949a735a0377a3dccb9"});
valuesMap.put(Integer.valueOf(25), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_26", "US.00_DE_CBCStatus_StatusUS2018DEc7d9ee04a32c4a5ea62179e7c12ab792.zip", "US.00_DE_CBCStatus_StatusUS2018DEc7d9ee04a32c4a5ea62179e7c12ab792"});
valuesMap.put(Integer.valueOf(26), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_27", "US.00_DE_CBCStatus_StatusUS2018DE4b261bec0d704926b2310667e425aa12.zip", "US.00_DE_CBCStatus_StatusUS2018DE4b261bec0d704926b2310667e425aa12"});
valuesMap.put(Integer.valueOf(27), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_28", "US.00_DE_CBCStatus_StatusUS2018DE726cd7c9e61b450c855723d70a9270da.zip", "US.00_DE_CBCStatus_StatusUS2018DE726cd7c9e61b450c855723d70a9270da"});
valuesMap.put(Integer.valueOf(28), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_29", "US.00_DE_CBCStatus_StatusUS2018DE3fae67d6fa07489e930f9df9eba2f2aa.zip", "US.00_DE_CBCStatus_StatusUS2018DE3fae67d6fa07489e930f9df9eba2f2aa"});
valuesMap.put(Integer.valueOf(29), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_30", "US.00_DE_CBCStatus_StatusUS2018DE185ea7cd3fc14045bdaa636cc88de9a7.zip", "US.00_DE_CBCStatus_StatusUS2018DE185ea7cd3fc14045bdaa636cc88de9a7"});
valuesMap.put(Integer.valueOf(30), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_31", "US.00_DE_CBCStatus_StatusUS2018DEaff727463e794feeb58941fbfc421657.zip", "US.00_DE_CBCStatus_StatusUS2018DEaff727463e794feeb58941fbfc421657"});
valuesMap.put(Integer.valueOf(31), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_32", "US.00_DE_CBCStatus_StatusUS2018DEab44279939b54ded94ab118f388cb38c.zip", "US.00_DE_CBCStatus_StatusUS2018DEab44279939b54ded94ab118f388cb38c"});
valuesMap.put(Integer.valueOf(32), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_33", "US.00_DE_CBCStatus_StatusUS2018DE0ee81c2468a7420eb43a09092b9862eb.zip", "US.00_DE_CBCStatus_StatusUS2018DE0ee81c2468a7420eb43a09092b9862eb"});
valuesMap.put(Integer.valueOf(33), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_34", "US.00_DE_CBCStatus_StatusUS2018DE13df8eaf4cc34d0191eb833ae3c1ae52.zip", "US.00_DE_CBCStatus_StatusUS2018DE13df8eaf4cc34d0191eb833ae3c1ae52"});
valuesMap.put(Integer.valueOf(34), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_35", "US.00_DE_CBCStatus_StatusUS2018DEa418fed6d9024426a7e275358d8e1420.zip", "US.00_DE_CBCStatus_StatusUS2018DEa418fed6d9024426a7e275358d8e1420"});
valuesMap.put(Integer.valueOf(35), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_36", "US.00_DE_CBCStatus_StatusUS2018DE5c94f71fbf274e82ba637c61dac21ada.zip", "US.00_DE_CBCStatus_StatusUS2018DE5c94f71fbf274e82ba637c61dac21ada"});
valuesMap.put(Integer.valueOf(36), new String[]{"SMOUTSRVCBCCLIENTIMPL_TRANSID_37", "US.00_DE_CBCStatus_StatusUS2018DE79eb70f383824c4b9fdd9b8c3d5709b9.zip", "US.00_DE_CBCStatus_StatusUS2018DE79eb70f383824c4b9fdd9b8c3d5709b9"});*/
}
/**
* @return the valuesMap
*/
/*public Map<Integer, String[]> getValuesMap() {
return valuesMap;
}*/
/**
* @param valuesMap the valuesMap to set
*/
/*public void setValuesMap(Map<Integer, String[]> valuesMap) {
this.valuesMap = valuesMap;
}*/
}
<file_sep>/**
* Proprietary Software Built Off of Open-Source Software?
*/
package corp.pdb.aea.ws.config;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.xml.bind.Marshaller;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter;
import org.springframework.ws.server.endpoint.adapter.method.MarshallingPayloadMethodProcessor;
import org.springframework.ws.server.endpoint.adapter.method.MethodArgumentResolver;
import org.springframework.ws.server.endpoint.adapter.method.MethodReturnValueHandler;
import org.springframework.ws.soap.server.endpoint.SoapFaultDefinition;
import org.springframework.ws.soap.server.endpoint.SoapFaultMappingExceptionResolver;
import org.springframework.ws.config.annotation.WsConfigurationSupport;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition;
import org.springframework.ws.wsdl.wsdl11.Wsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import corp.pdb.aea.ws.exceptions.impl.app.FileNotFoundException;
import corp.pdb.aea.ws.exceptions.impl.fault.DetailSoapFaultDefinitionExceptionResolver;
/**
* @author waleed.k.al-jaradat
*
*/
@EnableWs
@Configuration
public class WsServiceEndpointsConfig extends WsConfigurationSupport {
/*
* Configuring servlet type and mapping for handling incoming web traffic
*/
@Bean
public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet mdServlet = new MessageDispatcherServlet();
mdServlet.setApplicationContext(applicationContext);
return new ServletRegistrationBean<MessageDispatcherServlet>(mdServlet, "/icmm/idt/cbc/services/*");
}
@Bean
public SoapFaultMappingExceptionResolver exceptionResolver() {
SoapFaultMappingExceptionResolver exceptionResolver = new DetailSoapFaultDefinitionExceptionResolver();
SoapFaultDefinition faultDefinition = new SoapFaultDefinition();
faultDefinition.setFaultCode(SoapFaultDefinition.SERVER);
exceptionResolver.setDefaultFault(faultDefinition);
Properties errorMappings = new Properties();
errorMappings.put(FileNotFoundException.class, SoapFaultDefinition.SERVER.toString());
exceptionResolver.setExceptionMappings(errorMappings);
exceptionResolver.setOrder(1);
return exceptionResolver;
}
@Bean(name="AccessCtsFileStatusRequestPortService")
public Wsdl11Definition ctsFileStatusServiceWsdlDefinition() {
SimpleWsdl11Definition ctsFileStatusServiceWsdl = new SimpleWsdl11Definition();
ctsFileStatusServiceWsdl.setWsdl(new ClassPathResource("/schemas/SRV-CBC/CBC-CTSFileStatusService.wsdl"));
return ctsFileStatusServiceWsdl;
}
@Bean(name="AccessDownloadAcknowledgementRequestPortService")
public Wsdl11Definition downloadAckngServiceWsdlDefinition() {
SimpleWsdl11Definition downloadAckngServiceWsdl = new SimpleWsdl11Definition();
downloadAckngServiceWsdl.setWsdl(new ClassPathResource("/schemas/SRV-CBC/CBC-DownloadAcknowledgementService.wsdl"));
return downloadAckngServiceWsdl;
}
@Bean(name="AccessFileDownloadRequestPortService")
public Wsdl11Definition fileDownloadServiceWsdlDefinition() {
SimpleWsdl11Definition fileDownloadServiceWsdl = new SimpleWsdl11Definition();
fileDownloadServiceWsdl.setWsdl(new ClassPathResource("/schemas/SRV-CBC/CBC-FileDownloadService.wsdl"));
return fileDownloadServiceWsdl;
}
@Bean(name="AccessFileUploadRequestPortService")
public Wsdl11Definition fileUploadServiceWsdlDefinition() {
SimpleWsdl11Definition fileUploadServiceWsdl = new SimpleWsdl11Definition();
fileUploadServiceWsdl.setWsdl(new ClassPathResource("/schemas/SRV-CBC/CBC-FileUploadService.wsdl"));
return fileUploadServiceWsdl;
}
@Bean(name="MSG-CTSFileStatusMessage-1.6")
public SimpleXsdSchema ctsFileStatusMessageXsdDefinition() {
SimpleXsdSchema ctsFileStatusMessageXsd = new SimpleXsdSchema();
ctsFileStatusMessageXsd.setXsd(new ClassPathResource("/schemas/SRV-CBC/MSG/MSG-CTSFileStatusMessage-1.7.xsd"));
return ctsFileStatusMessageXsd;
}
@Bean(name="MSG-DownloadAcknowledgementMessage-1.6")
public SimpleXsdSchema downloadAckngMessageXsdDefinition() {
SimpleXsdSchema downloadAckngMessageXsd = new SimpleXsdSchema();
downloadAckngMessageXsd.setXsd(new ClassPathResource("/schemas/SRV-CBC/MSG/MSG-DownloadAcknowledgementMessage-1.7.xsd"));
return downloadAckngMessageXsd;
}
@Bean(name="MSG-FileDownloadMessage-1.6")
public SimpleXsdSchema fileDownloadMessageXsdDefinition() {
SimpleXsdSchema fileDownloadMessageXsd = new SimpleXsdSchema();
fileDownloadMessageXsd.setXsd(new ClassPathResource("/schemas/SRV-CBC/MSG/MSG-FileDownloadMessage-1.7.xsd"));
return fileDownloadMessageXsd;
}
@Bean(name="MSG-FileUploadMessage-1.6")
public SimpleXsdSchema fileUploadMessageXsdDefinition() {
SimpleXsdSchema fileUploadMessageXsd = new SimpleXsdSchema();
fileUploadMessageXsd.setXsd(new ClassPathResource("/schemas/SRV-CBC/MSG/MSG-FileUploadMessage-1.7.xsd"));
return fileUploadMessageXsd;
}
@Bean(name="MSG-SOAPFaultMessage-1.6")
public SimpleXsdSchema soapFaultMessageXsdDefinition() {
SimpleXsdSchema soapFaultMessageXsd = new SimpleXsdSchema();
soapFaultMessageXsd.setXsd(new ClassPathResource("/schemas/SRV-CBC/MSG/MSG-SOAPFaultMessage-1.7.xsd"));
return soapFaultMessageXsd;
}
@Bean(name="IDES-SOAP-MSG-BASE-1.6")
public SimpleXsdSchema idesSoapBaseMessageXsdDefinition() {
SimpleXsdSchema idesSoapBaseMessageXsd = new SimpleXsdSchema();
idesSoapBaseMessageXsd.setXsd(new ClassPathResource("/schemas/SRV-CBC/MSG/IDES-SOAP-MSG-BASE-1.7.xsd"));
return idesSoapBaseMessageXsd;
}
/*@Bean
public PayloadRootAnnotationMethodEndpointMapping endpointMapping() {
return new PayloadRootAnnotationMethodEndpointMapping();
}*/
/*
* Needed for MTOM processing (i.e. MIME/XOP processing and handling)
*/
@Bean
@Override
public DefaultMethodEndpointAdapter defaultMethodEndpointAdapter() {
List<MethodArgumentResolver> argumentResolvers = new ArrayList<MethodArgumentResolver>();
argumentResolvers.add(ctsFileStatusServiceEndpointMethodProcessor());
argumentResolvers.add(downloadAckngServiceEndpointMethodProcessor());
argumentResolvers.add(fileDownloadServiceEndpointMethodProcessor());
argumentResolvers.add(fileUploadServiceEndpointMethodProcessor());
List<MethodReturnValueHandler> returnValueHandlers = new ArrayList<MethodReturnValueHandler>();
returnValueHandlers.add(ctsFileStatusServiceEndpointMethodProcessor());
returnValueHandlers.add(downloadAckngServiceEndpointMethodProcessor());
returnValueHandlers.add(fileDownloadServiceEndpointMethodProcessor());
returnValueHandlers.add(fileUploadServiceEndpointMethodProcessor());
DefaultMethodEndpointAdapter endpointAdapter = new DefaultMethodEndpointAdapter();
endpointAdapter.setMethodArgumentResolvers(argumentResolvers);
endpointAdapter.setMethodReturnValueHandlers(returnValueHandlers);
return endpointAdapter;
}
@Bean
public MarshallingPayloadMethodProcessor ctsFileStatusServiceEndpointMethodProcessor() {
return new MarshallingPayloadMethodProcessor(ctsFileStatusServiceEndpointMarshaller());
}
@Bean
public MarshallingPayloadMethodProcessor downloadAckngServiceEndpointMethodProcessor() {
return new MarshallingPayloadMethodProcessor(downloadAckngServiceEndpointMarshaller());
}
@Bean
public MarshallingPayloadMethodProcessor fileDownloadServiceEndpointMethodProcessor() {
return new MarshallingPayloadMethodProcessor(fileDownloadServiceEndpointMarshaller());
}
@Bean
public MarshallingPayloadMethodProcessor fileUploadServiceEndpointMethodProcessor() {
return new MarshallingPayloadMethodProcessor(fileUploadServiceEndpointMarshaller());
}
@Bean
public Jaxb2Marshaller soapFaultTypeMarshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("ides.msg.soapfaultmessage");
Map<String, Object> properties = new HashMap<>();
properties.put(Marshaller.JAXB_FRAGMENT, true);
marshaller.setMarshallerProperties(properties);
return marshaller;
}
@Bean
public Jaxb2Marshaller ctsFileStatusServiceEndpointMarshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("ides.msg.ctsfilestatusmessage");
return marshaller;
}
@Bean
public Jaxb2Marshaller downloadAckngServiceEndpointMarshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("ides.msg.downloadacknowledgementmessage");
return marshaller;
}
@Bean
public Jaxb2Marshaller fileDownloadServiceEndpointMarshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("ides.msg.filedownloadmessage");
marshaller.setMtomEnabled(true);
return marshaller;
}
@Bean
public Jaxb2Marshaller fileUploadServiceEndpointMarshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("ides.msg.fileuploadmessage");
marshaller.setMtomEnabled(true);
return marshaller;
}
@Bean
public CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
@Bean
public CommonsMultipartResolver filterMultipartResolver() {
final CommonsMultipartResolver resolver = new CommonsMultipartResolver();
return resolver;
}
}
<file_sep>/**
* Proprietary Software Built Off of Open-Source Software?
*/
package corp.pdb.aea.ws.endpoint;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.UUID;
import javax.activation.DataHandler;
import javax.xml.bind.JAXBElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import corp.pdb.aea.data.model.Alert;
import corp.pdb.aea.data.model.IncomingUpload;
import corp.pdb.aea.data.model.enums.AlertStatusEnum;
import corp.pdb.aea.data.repository.AlertRepository;
import corp.pdb.aea.data.repository.IncomingUploadRepository;
import corp.pdb.aea.util.TimestampTypeFormatter;
import ides.msg.fileuploadmessage.FileUploadRequestType;
import ides.msg.fileuploadmessage.FileUploadResponseType;
/**
* @author waleed.k.al-jaradat
*
*/
@Endpoint
public class FileUploadStubEndpointImpl {
private final Logger log = LoggerFactory.getLogger(FileUploadStubEndpointImpl.class);
private static final String FILE_UPLOAD_PACKAGE_DIRECTORY_LOCATION = "files/incoming/uploads/";
@Autowired
AlertRepository alertRepository;
@Autowired
IncomingUploadRepository incomingUploadRepository;
@Autowired
TimestampTypeFormatter timestampTypeFormatter;
@PayloadRoot(namespace="urn:ides:msg:fileuploadmessage", localPart="FileUploadRequest")
@ResponsePayload
public JAXBElement<FileUploadResponseType> fileUploadRequestOperation(@RequestPayload JAXBElement<FileUploadRequestType> fileUploadRequest) {
log.debug("{}: Received request at FileUploadService Endpoint (see TRACE logs for message details)", this.getClass().getName());
FileUploadRequestType fileUploadRequestBody = fileUploadRequest.getValue();
log.trace("Message details: RequestSentTs=[{}], SenderFileId=[{}], SendingEntity=[{}], ReceivingEntity=[{}], CommunicationTypeCd=[{}]", fileUploadRequestBody.getRequestSentTs(), fileUploadRequestBody.getSenderFileId(), fileUploadRequestBody.getEntitySenderIdentifier().getCTSCountryCd(), fileUploadRequestBody.getEntityReceiverIdentifier().getCTSCountryCd(), fileUploadRequestBody.getEntityCommunicationTypeCd().value());
String fileUploadPackageLocation = FILE_UPLOAD_PACKAGE_DIRECTORY_LOCATION + "" + fileUploadRequestBody.getSenderFileId() + ".zip";
log.trace("Saving upload transmission at: [{}]", fileUploadPackageLocation);
Long fileSize = saveBulkExchangeFile(fileUploadRequestBody.getBulkExchangeFile(), fileUploadPackageLocation);
log.trace("Saved upload transmission at: [{}]", fileUploadPackageLocation);
ides.msg.fileuploadmessage.ObjectFactory factory = new ides.msg.fileuploadmessage.ObjectFactory();
FileUploadResponseType fileUploadResponseBody = factory.createFileUploadResponseType();
fileUploadResponseBody.setReceiptTs(timestampTypeFormatter.generateTimestamp());
fileUploadResponseBody.setIDESSendingTs(fileUploadRequestBody.getRequestSentTs());
fileUploadResponseBody.setEntityCommunicationTypeCd(fileUploadRequestBody.getEntityCommunicationTypeCd());
fileUploadResponseBody.setSenderFileId(fileUploadRequestBody.getSenderFileId());
fileUploadResponseBody.setIDESFileNm(fileUploadRequestBody.getSenderFileId() + ".zip");
generateAndPersistIncomingUpload(fileUploadRequestBody, fileUploadResponseBody, fileSize);
JAXBElement<FileUploadResponseType> fileUploadResponse = factory.createFileUploadResponse(fileUploadResponseBody);
return fileUploadResponse;
}
protected IncomingUpload generateAndPersistIncomingUpload(
FileUploadRequestType fileUploadRequestBody, FileUploadResponseType fileUploadResponseBody, Long fileSizeKbQty) {
IncomingUpload rcrd = new IncomingUpload();
Date createDate = new Date();
rcrd.setCommunicationTypeCd(fileUploadResponseBody.getEntityCommunicationTypeCd().value());
rcrd.setEntitySenderIdentifier(fileUploadRequestBody.getEntitySenderIdentifier().getCTSCountryCd());
rcrd.setEntityReceiverIdentifier(fileUploadRequestBody.getEntityReceiverIdentifier().getCTSCountryCd());
rcrd.setIdesFileNm(fileUploadResponseBody.getIDESFileNm());
rcrd.setSenderFileId(fileUploadResponseBody.getSenderFileId());
rcrd.setFileSizeKbQty(fileSizeKbQty);
rcrd.setCreatedById("FUPLDEND");
rcrd.setCreateTs(createDate);
rcrd = generateAndPersistRC001Alert(rcrd);
rcrd = incomingUploadRepository.saveAndFlush(rcrd);
return rcrd;
}
protected IncomingUpload generateAndPersistRC001Alert(IncomingUpload incomingUpload) {
Alert rcrd = new Alert();
rcrd.setAlertStatus(AlertStatusEnum.UN);
rcrd.setAlertReasonCd("RC001");
rcrd.setAlertRecipientTypeCd("CS");
rcrd.setAlertTypeCd("SA");
rcrd.setFileFormatCd("XML");
rcrd.setBinaryEncodingSchemeCd("NONE");
rcrd.setCreatedById("FUPLDENDP");
rcrd.setFileRevisionInd("N");
rcrd.setFileCreateTs(new Date());
rcrd.setTaxYr(Long.valueOf(2019));
rcrd.setIdesTransmissionId(generateTransmissionId());
rcrd.setEntityCommunicationTypeCd(incomingUpload.getCommunicationTypeCd());
rcrd.setEntityReceiverIdentifier(incomingUpload.getEntityReceiverIdentifier());
rcrd.setEntitySenderIdentifier(incomingUpload.getEntitySenderIdentifier());
rcrd.setIdesFileNm(incomingUpload.getIdesFileNm());
rcrd.setSenderFileId(incomingUpload.getSenderFileId());
rcrd.setCompressedFileSizeKbQty(incomingUpload.getFileSizeKbQty());
rcrd.setCreateTs(incomingUpload.getCreateTs());
rcrd = alertRepository.saveAndFlush(rcrd);
incomingUpload.setAlertId(rcrd.getId());
incomingUpload.setAlertStatus(rcrd.getAlertStatus());
return incomingUpload;
}
protected String generateTransmissionId() {
String randomUUID = UUID.randomUUID().toString().replaceAll("-", "");
log.info("randomUUID={}", randomUUID);
return randomUUID;
}
protected Long saveBulkExchangeFile(DataHandler bulkExchangeFile, String locationToSaveFile) {
File file = new File(locationToSaveFile);
int i = 0;
byte[] buffer = new byte[1024];
try (InputStream inputStream = bulkExchangeFile.getInputStream()) {
try (OutputStream outputStream = new FileOutputStream(file)) {
while((i = inputStream.read(buffer, 0, buffer.length)) > 0) {
System.out.println("Writing data from BulkExchangeFile DataHandler to FileOutputStream");
outputStream.write(buffer, 0, i);
}
}
} catch (FileNotFoundException e) {
log.error("{}\n{}", e.getMessage(), e);
} catch (IOException e) {
log.error("{}\n{}", e.getMessage(), e);
} catch (Exception e) {
log.error("{}\n{}", e.getMessage(), e);
}
Long fileSizeKbQty = Long.valueOf((file.length()/1000));
log.trace("BulkExchangeFile size=[{} kb]", fileSizeKbQty);
return fileSizeKbQty;
}
}
| afb9326e753f59e2147b47da3be3cb490a4829ce | [
"Markdown",
"Java",
"Maven POM",
"SQL"
] | 20 | Java | jaradat-pdb/alawal-eap | c63e786682fb781194a1e85b126c8d39dee91164 | 1bf1e2c872b4743a932f0699937039f5a8495ca5 | |
refs/heads/master | <repo_name>dorset-college-projects/oop-eptia-2021-charp-superheroes<file_sep>/Model/SuperHero.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace SuperHeroe001.Model
{
public abstract class SuperHero
{
public string power { get; set; }
public string name { get; set; }
public SuperHero(string _name, string _power)
{
name = _name;
power = _power;
}
public override string ToString()
{
return $"Super hero: {name}, Power: {power}";
}
}
}
<file_sep>/Model/Superman.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace SuperHeroe001.Model
{
public class Superman : SuperHero
{
public Superman(string _name, string _power) : base(_name, _power)
{
}
}
}
<file_sep>/Model/Wolverine.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace SuperHeroe001.Model
{
public class Wolverine : SuperHero
{
public Wolverine(string _name, string _power) : base(_name, _power)
{
}
}
}
<file_sep>/Program.cs
using SuperHeroe001.Model;
using System;
namespace SuperHeroe001
{
class Program
{
static void Main(string[] args)
{
Batman batman = new Batman("Batman", "Dark Stuff");
Wolverine wolverine = new Wolverine("wolverine", "regenerative power");
Superman superman = new Superman("superman", "fly");
Spiderman spiderman = new Spiderman("Spiderman", "throw spider web");
//Encapsulation .....
Console.WriteLine(wolverine.ToString());
Console.WriteLine(superman);
Console.WriteLine(spiderman);
Console.WriteLine(batman);
}
}
}
<file_sep>/Model/Batman.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace SuperHeroe001.Model
{
public class Batman : SuperHero
{
public Batman(string _name, string _power) : base(_name, _power)
{
}
}
}
| 63d6849d9fb63684b3f8eb1dde6c064ce2923cc7 | [
"C#"
] | 5 | C# | dorset-college-projects/oop-eptia-2021-charp-superheroes | e3a15fa295d5e067fa4466096196a988ae110723 | cf3735e9eccf150aef1b4453b842562369d25066 | |
refs/heads/master | <file_sep>package com.base.batch.test;
import com.base.batch.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
private static Logger logger = LoggerFactory.getLogger(Test.class);
public static void main(String[] args) {
logger.info("test");
logger.info(Config.getInstance().getConfig().getString("test"));
}
}
<file_sep>package com.base.batch;
import org.apache.commons.cli.CommandLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;
public class BatchTasklet {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private String[] args;
public BatchTasklet(String[] args) {
this.args = args;
}
public void getTasksValues() {
for (Tasks task : Tasks.list()) {
logger.info("Task : {}", task.getValue());
}
}
public void execute() {
logger.info("{}", new Object[]{"Batch Base"});
CliManager cliManager = new CliManager();
CommandLine line = cliManager.startCli(args);
//help
if (line.hasOption("h")) {
cliManager.printHelp(cliManager.getOptions());
System.exit(0);
}
//version
if (line.hasOption("v")) {
cliManager.printVersion();
System.exit(0);
}
//list-tasks
if (line.hasOption("list-tasks")) {
getTasksValues();
System.exit(0);
}
//quiet mode
if (line.hasOption("q")) {
//quiet mode
}
//test mode
if (line.hasOption("t")) {
//test mode
}
//config-value
if (line.hasOption("config-value")) {
logger.info("config value");
Iterator<String> keys = Config.getInstance().getConfig().getKeys();
while(keys.hasNext()) {
String key = keys.next();
logger.info("{} => {}", new Object[]{key, Config.getInstance().getConfig().getString(key)});
}
System.exit(0);
}
//config-file
if (line.hasOption("config-file")) {
logger.info("use config file : {}", new Object[]{line.getOptionValue("config-file")});
String test = Config.getInstance().getConfig().getString("test");
logger.info("Config value : {}", new Object[]{test});
System.exit(0);
}
//test-task
if (line.hasOption("test-task")) {
logger.info("use task name : {}", new Object[]{line.getOptionValue("test-task")});
String test = Config.getInstance().getConfig().getString("test");
logger.info("Config value : {}", new Object[]{test});
System.exit(0);
}
if(line.getArgList().isEmpty()) {
cliManager.printNoInput();
System.exit(0);
}
}
}
| 350ba988b18f904c3dbce654c6ac085a1cca001a | [
"Java"
] | 2 | Java | geoffroyvergne/batch-base | 4e3b844a6f67ea62ab2245ff9dd2ae8704d20f8b | c4d748a2c271591b1de3a5983b01b504db0a1b40 | |
refs/heads/master | <file_sep>using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TreasureFinder.Models;
using System;
namespace TreasureFinder.Controllers
{
[ApiController]
[Route("api/[controller]/{itemId}")]
public class ImagesController : ControllerBase
{
private readonly TreasureFinderContext _db;
public ImagesController(TreasureFinderContext db)
{
_db = db;
}
[HttpPost]
public IActionResult Post(Image image)
{
Console.WriteLine($"image {image}");
_db.Images.Add(image);
_db.SaveChanges();
return Ok();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.IO;
using Microsoft.AspNetCore.Http;
using TreasureFinder.Models;
namespace TreasureFinder.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ItemsController : ControllerBase
{
private readonly TreasureFinderContext _db;
public ItemsController(TreasureFinderContext db)
{
_db = db;
}
private bool ItemExists(int id) => _db.Items.Any(item => item.ItemId == id);
[HttpGet]
public async Task<ActionResult<IEnumerable<Item>>> Get(string title, string description, string address, string startdate, string enddate, string condition, bool images)
{
// url?startdate=2021/12/05&enddate=2021/06/06
var query = _db.Items.AsQueryable();
if (title != null) query = query.Where(i => i.Title.Contains(title.Trim()));
if (description != null) query = query.Where(i => i.Description.Contains(description.Trim()));
if (address != null) query = query.Where(i => i.Address.Contains(address.Trim()));
if (startdate != null && enddate != null)
{
var startDate = DateTime.Parse(startdate);
var endDate = DateTime.Parse(enddate);
query = query.Where(i => i.CreatedAt >= startDate && i.CreatedAt <= endDate);
}
else if (startdate != null && enddate == null)
{
var startDate = DateTime.Parse(startdate);
query = query.Where(i => i.CreatedAt >= startDate);
}
else if (startdate == null && enddate != null)
{
var endDate = DateTime.Parse(enddate);
query = query.Where(i => i.CreatedAt <= endDate);
}
else
{
Console.WriteLine("both start date and end date are null");
}
if (condition != null) query = query.Where(i => i.Condition.Trim() == condition.Trim());
if (images == true) query = query.Where(i => i.Images.Count > 0);
query.Include(entity => entity.Images);
return await query.ToListAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<Item>> GetItem(int id)
{
var item = await _db.Items.Include(i => i.Images)
.FirstOrDefaultAsync(i => i.ItemId == id);
if (item == null)
{
return NotFound();
}
return item;
}
[HttpPost]
public async Task<ActionResult<Item>> Post(Item item)
{
item.CreatedAt = DateTime.Now;
_db.Items.Add(item);
await _db.SaveChangesAsync();
return CreatedAtAction(nameof(GetItem), new { id = item.ItemId }, item);
}
[HttpPut("{id}")]
public async Task<ActionResult<Item>> Put(int id, Item item)
{
if (id != item.ItemId) return BadRequest();
_db.Entry(item).State = EntityState.Modified;
try
{
await _db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ItemExists(id)) return NotFound();
else throw;
}
return item;
}
[HttpDelete("{id}")]
public async Task<ActionResult> DeleteItem(int id)
{
Item item = await _db.Items.FindAsync(id);
if (item == null) return NotFound();
_db.Items.Remove(item);
await _db.SaveChangesAsync();
return NoContent();
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System;
namespace TreasureFinder.Models
{
public class TreasureFinderContext : DbContext
{
public TreasureFinderContext(DbContextOptions<TreasureFinderContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Item>()
.HasMany(i => i.Images);
builder.Entity<Item>(i =>
{
i.HasData(
new
{
ItemId = 1,
Title = "Free Couch",
Description = "Free floral sectional",
Condition = "Like New",
Address = "123 Main Street",
CreatedAt = DateTime.Now,
Url = "http://www.google.com",
Dimensions = "40X115X80",
Weight = "50",
UserId = 1
});
});
}
public DbSet<Image> Images { get; set; }
public DbSet<Item> Items { get; set; }
}
}<file_sep><br>
<p align="center">
<big>|| <u><b>Treasure Finder API</b></u> ||</big>
</p>
<p align="center">Changing the world one line of code at a time.<br></p>
<p align="center">
<small>June 17th, 2021.</small><br>
<p align="center">
<a href="https://github.com/Magofna68/MessageBoard.Solution/stargazers">
<img src="https://img.shields.io/github/license/Magofna68/PierresTreats.Solution?style=plastic">
</a>
¨
<a href="https://github.com/Magofna68/MessageBoard.Solution/issues">
<img src="https://img.shields.io/github/last-commit/Magofna68/MessageBoard.Solution?style=plastic">
</a>
¨
<a href="https://linkedin.com/in/Magofna68">
<img src="https://img.shields.io/badge/-LinkedIn-black.svg?style=plastic&logo=linkedin&colorB=2867B2">
</a>
</p>
<p align="center">Contributors:<br><small><NAME>, <NAME>, <NAME>, & <NAME></small></p>
<p align="center">
<!-- Project Avatar/Logo -->
<p align="center">
</p>
<p align="center">
__________________________________________________
</p>
<br>
<p align="center"><a href="https://github.com/Magofna68">
<img src="https://avatars.githubusercontent.com/u/80496559?v=4">
</a></p>
<br>
<!-- GitHub Link -->
<!-- Project Shields -->
</p>
------------------------------
# 🌐 About the Project
## This is one of two componenets we created for our wk 14 Team Week project at Epicodus (wk 14). This is the API side; hosting the client data for consumption.
<br>
This project will provide the client the ability to create posts to get rid of free items or "freecycle".
With full CRUD functionality to post, this API as a stretch goal will be able to host user uploaded photos of the items posted.
<br>
<br>
### 🛠 Built With
* [Visual Studio Code](https://code.visualstudio.com/)
* [C#](https://docs.microsoft.com/en-us/dotnet/csharp/)
* [ASP.NET Core MVC](https://docs.microsoft.com/en-us/aspnet/core/mvc/overview?view=aspnetcore-3.1)
* [Swagger: SquashBuckle v5.6.3](https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-nswag?view=aspnetcore-3.1&tabs=visual-studio)
* [Postman](postman.com)
------------------------------
## Installation Requirements:
### 1) Install .NET Core
* On macOS:
* [Click here](https://dotnet.microsoft.com/download/thank-you/dotnet-sdk-2.2.106-macos-x64-installer)
* On Windows 10:
* [Click here](https://dotnet.microsoft.com/download/thank-you/dotnet-sdk-2.2.203-windows-x64-installer)
### 2) Install dotnet script
* Enter the command ``dotnet tool install -g dotnet-script`` in Terminal.
### 4) Install Postman
* [Download and install Postman](https://www.postman.com/downloads/).
### 5) VS Code
* i) Code Editor:
* [Download Here](https://www.npmjs.com/)
* ii) Download and install into applications folder
______________________________________________________________________________________
<br>
## Setup:
#### i) Cloning
1) Navigate to project directory
2) Click the green 'Clone or download' button to copy URL.
3) Navigate to local repository to host the file.
4) Use the following command to clone the repository to your local device:
* $ git clone '___*Copied URL*___'
5) Run the following command to enter project:
- $ cd '___*Copied URL*___'
#### ii) AppSettings
1) Create a new file in the project directory named `appsettings.json`
2) Add in the following code snippet to the new appsettings.json file and update fields in brackets:
```
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Port=[Misc_Number];database=[project_api];uid=root;pwd=[<PASSWORD>];"
}
```
#### Launch the API
1) Navigate to project directory
2) Run the command `dotnet run` to have access to the API in Postman or browser.
------------------------------
## 🛰️ API Documentation
Explore the API endpoints in Postman or a browser. You will not be able to utilize authentication in a browser.
### Using Swagger Documentation
#### i) To launch the project API with Swashbuckle, run the following command in the Terminal:
`dotnet run`
#### ii) Click on / hard code the following URL into your browser: `http://localhost:5000/swagger`
________________________________________________
________________________________________________
### Endpoints
Base URL: `https://localhost:5000`
#### HTTP Request Structure
```
GET /api/{project}
POST /api/{project}
GET /api/{project}/{id}
PUT /api/{project}/{id}
DELETE /api/{project}/{id}
```
#### Example Query w/ swagger:
```
https://localhost:5000/swagger/index.html
```
#### Sample JSON Response
```
{
"Id": 14,
"Name": "<NAME>",
"Street Address": "1111 Epicodus ln NE",
"City": "Portland",
"State": "Oregon"
"Age: "34",
}
```
..........................................................................................
<file_sep>using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Treasure.Solution.Migrations
{
public partial class RemoveItemFromImage : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "Items",
keyColumn: "ItemId",
keyValue: 1,
column: "CreatedAt",
value: new DateTime(2021, 6, 15, 12, 42, 37, 41, DateTimeKind.Local).AddTicks(3290));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "Items",
keyColumn: "ItemId",
keyValue: 1,
column: "CreatedAt",
value: new DateTime(2021, 6, 15, 10, 8, 2, 442, DateTimeKind.Local).AddTicks(9960));
}
}
}
<file_sep>using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Treasure.Solution.Migrations
{
public partial class seeddata : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.InsertData(
table: "Items",
columns: new[] { "ItemId", "Adress", "Condition", "CreatedAt", "Description", "Dimensions", "Title", "Url", "UserId", "Weight" },
values: new object[] { 1, null, "Like New", new DateTime(2021, 6, 14, 14, 29, 10, 871, DateTimeKind.Local).AddTicks(1740), "Free floral sectional", "40X115X80", "Free Couch", "http://www.google.com", 1, "50" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "Items",
keyColumn: "ItemId",
keyValue: 1);
}
}
}
<file_sep>using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Treasure.Solution.Migrations
{
public partial class AddressFieldFix : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Adress",
table: "Items",
newName: "Address");
migrationBuilder.UpdateData(
table: "Items",
keyColumn: "ItemId",
keyValue: 1,
columns: new[] { "Address", "CreatedAt" },
values: new object[] { "123 Main Street", new DateTime(2021, 6, 15, 10, 8, 2, 442, DateTimeKind.Local).AddTicks(9960) });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Address",
table: "Items",
newName: "Adress");
migrationBuilder.UpdateData(
table: "Items",
keyColumn: "ItemId",
keyValue: 1,
columns: new[] { "Adress", "CreatedAt" },
values: new object[] { null, new DateTime(2021, 6, 14, 14, 29, 10, 871, DateTimeKind.Local).AddTicks(1740) });
}
}
}
<file_sep>using System.ComponentModel.DataAnnotations.Schema;
namespace TreasureFinder.Models
{
public class Image
{
public int ImageId { get; set; }
public string ImageString { get; set; }
[ForeignKey("Item")]
public int ItemId { get; set; }
//public virtual Item Item { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
namespace TreasureFinder.Models
{
public class Item
{
public Item()
{
Images = new HashSet<Image>();
}
public int ItemId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Address { get; set; }
public string Condition { get; set; }
public DateTime CreatedAt { get; set; }
public string Url { get; set; }
public string Dimensions { get; set; }
public string Weight { get; set; }
public ICollection<Image> Images { get; set; }
public int UserId { get; set; }
}
}<file_sep>using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Treasure.Solution.Migrations
{
public partial class initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Items",
columns: table => new
{
ItemId = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Title = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true),
Description = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true),
Adress = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true),
Condition = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
Url = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true),
Dimensions = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true),
Weight = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true),
UserId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Items", x => x.ItemId);
});
migrationBuilder.CreateTable(
name: "Images",
columns: table => new
{
ImageId = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
ImageString = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true),
ItemId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Images", x => x.ImageId);
table.ForeignKey(
name: "FK_Images_Items_ItemId",
column: x => x.ItemId,
principalTable: "Items",
principalColumn: "ItemId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Images_ItemId",
table: "Images",
column: "ItemId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Images");
migrationBuilder.DropTable(
name: "Items");
}
}
}
| 95d77c42277db4de8f8600581daa486801f7e2a8 | [
"Markdown",
"C#"
] | 10 | C# | Magofna68/Treasure.Solution | 91f34109dc1c2c0c27131049c72d919a9e2863cd | 0543d758891538605600330e802d0232cf8d1bd9 | |
refs/heads/main | <file_sep>import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import {filter, map, startWith} from 'rxjs/operators';
@Component({
selector: 'app-weather',
templateUrl: './weather.component.html',
styleUrls: ['./weather.component.scss']
})
export class WeatherComponent implements OnInit {
openWeatherAPIkey= '0d3c85d44caec6a146dac4eb25c14e73';
weatherInputControl = new FormControl('London, UK')
filteredOptions: Observable<any> = new Observable();
location: string = ''
weather: Observable<{
current: {
desc: any;
temp: any;
};
daily: any[];
hourly: any[];
}>;
constructor(private http: HttpClient) {
this.weather = this.getWeatherData(51.5074, -0.1278);
// this.assignGridProp(index: number);
}
ngOnInit(): void {
}
assignGridProp(index: number){
let ele = document.getElementsByName(`weatherInfo-${index}`).forEach(x=>x.style.gridArea = `${index+1} / 1 / ${index+2} / 5;`)
}
handleAddressChange(event: any){
console.log(event)
let locationLat = event.geometry.location.lat();
let locationLng = event.geometry.location.lng();
this.location = event.formatted_address;
this.weather = this.getWeatherData(locationLat, locationLng)
}
getWeatherData(lat:number, lon:number){
return this.http.get(`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&appid=${this.openWeatherAPIkey}`).pipe(
map((res: any) => {
let weather = {
current: {
desc: res.current.weather[0].description,
temp: res.current.temp
},
daily: [...res.daily],
hourly: [...res.hourly]
}
console.log('weather: ', weather)
return weather;
// return res
})
)
}
}
| ebd3a9ec65e741f704b8c7172fb790b9aa911b7a | [
"TypeScript"
] | 1 | TypeScript | NothinButJohn/weather | 681ca354f72077adc853e3ada8d6f96932fc1f43 | 1ac006ea6660e1c93783e39dcda230fe00abcdc3 | |
refs/heads/master | <repo_name>miguelvargas/test<file_sep>/trunk/common/java/common-test/src/com/mvwsolutions/common/test/spring/TestBeanPostProcessor.java
package com.mvwsolutions.common.test.spring;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class TestBeanPostProcessor implements BeanPostProcessor {
private static Log logger = LogFactory.getLog(TestBeanPostProcessor.class);
// integration tests may want to disable this processot in order to test "real" beans
public static boolean ENABLED = true;
private Map<String, Object> classReplacementMap = new HashMap<String, Object>();
private Map<String, Object> beanReplacementMap = new HashMap<String, Object>();
public Map<String, Object> getBeanReplacementMap() {
return beanReplacementMap;
}
public void setBeanReplacementMap(Map<String, Object> beanReplacementMap) {
this.beanReplacementMap = beanReplacementMap;
}
public Map<String, Object> getClassReplacementMap() {
return classReplacementMap;
}
public void setClassReplacementMap(Map<String, Object> classReplacementMap) {
this.classReplacementMap = classReplacementMap;
}
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
Object res = getBeanImpl(bean, beanName);
return res;
}
private Object getBeanImpl(Object bean, String beanName) {
if (!ENABLED) {
return bean;
}
Object res;
res = classReplacementMap.get(bean.getClass().getName());
if (res != null) {
logger.warn("Bean (" + beanName + " - " + bean.getClass().getName()
+ ") is replaced with class ("+res.getClass().getName()+")");
} else {
res = beanReplacementMap.get(beanName);
if (res != null) {
logger.warn("Bean (" + beanName + " - " + bean.getClass().getName()
+ ") is replaced with class ("+res.getClass().getName()+")");
}
}
return res != null ? res : bean;
}
}
<file_sep>/trunk/common/java/common-web/src/com/mvwsolutions/common/web/controller/HostPortSecurityEnforcer.java
package com.mvwsolutions.common.web.controller;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
public class HostPortSecurityEnforcer implements ExtraSecurityEnforcer {
private Set<String> _remoteHostWhiteList = new HashSet<String>();
private Set<Integer> _localPortWhiteList = new HashSet<Integer>();
public void setLocalPortWhiteList(String localPortWhiteList) {
if (localPortWhiteList != null) {
StringTokenizer st = new StringTokenizer(localPortWhiteList, ",");
while (st.hasMoreTokens()) {
String s = st.nextToken();
_localPortWhiteList.add(new Integer(s));
}
}
}
public void setRemoteHostWhiteList(String remoteHostWhiteList) {
if (remoteHostWhiteList != null) {
StringTokenizer st = new StringTokenizer(remoteHostWhiteList, ",");
while (st.hasMoreTokens()) {
String s = st.nextToken();
_remoteHostWhiteList.add(s);
}
}
}
public boolean checkAccess(HttpServletRequest request) {
String remoteIp = request.getRemoteAddr();
if (_remoteHostWhiteList.size() != 0) {
if (!_remoteHostWhiteList.contains(remoteIp)) {
return false;
}
}
int localPort = request.getLocalPort();
if (_localPortWhiteList.size() != 0 && !_localPortWhiteList.contains(localPort)) {
return false;
}
return true;
}
}
<file_sep>/trunk/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mvwsolutions</groupId>
<artifactId>all</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>All projects</name>
<scm>
<connection>scm:svn:file:///var/svn/repos</connection>
<developerConnection>scm:svn:file:///var/svn/repos</developerConnection>
<tag>HEAD</tag>
</scm>
<modules>
<module>common/maven/lib-installer</module>
<module>common/maven/global-parent</module>
<module>common/java/common</module>
<module>common/java/common-server</module>
<module>common/java/common-web</module>
<module>common/java/common-test</module>
<module>common/android/dao</module>
<module>common/android/daogen</module>
<module>common/android/daogen-maven-plugin</module>
<module>common/android/DroidCommand</module>
<module>common/maven/android-parent</module>
<!-- module>examples/MapsAndDb</module -->
<module>products/in-house/DroidDateServerAPI</module>
<module>products/in-house/DroidDateServer</module>
<module>products/in-house/DroidDateClient</module>
</modules>
</project>
<file_sep>/trunk/common/android/DroidCommand/src/com/mvw/controller/CommandMappingException.java
package com.mvw.controller;
public class CommandMappingException extends Exception {
private static final long serialVersionUID = 7548673498237833035L;
public CommandMappingException(String string) {
super(string);
}
}
<file_sep>/trunk/common/java/common-web/src/com/mvwsolutions/common/web/controller/LocalPortSecurityEnforcer.java
package com.mvwsolutions.common.web.controller;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
public class LocalPortSecurityEnforcer implements ExtraSecurityEnforcer {
private Set<Integer> allowedPorts = new HashSet<Integer>();
public Set<Integer> getAllowedPorts() {
return this.allowedPorts;
}
public void setAllowedPorts(Set<Integer> allowedPorts) {
this.allowedPorts = allowedPorts;
}
public boolean checkAccess(HttpServletRequest request) {
return getAllowedPorts().contains(request.getLocalPort());
}
}
<file_sep>/trunk/common/java/common-server/src/com/mvwsolutions/common/dao/BaseDao.java
package com.mvwsolutions.common.dao;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import org.hibernate.LockMode;
import com.mvwsolutions.common.dao.SortingAndPagingDescriptor.SortingOption;
/**
* This class is the Base DAO(Data Access Object)Interface. It must be
* implemented by all data access objects (DAOs)
*
* @author : smineyev with permission, altered by Marcus
*
*/
public interface BaseDao<T, ID extends Serializable> {
/**
* This method load/retrieve a domain Object for a given id from the
* database Table
*
* @param id
* Specifies the id of the domain Object to be retrieved.
* @return the domain object instance
* @throws DataAccessException
* in case of dataaccess execution errors.
*/
public T findById(ID id) throws DataAccessException;
public <C> C findById(ID id, Class<C> expectedClass)
throws DataAccessException;
/**
* This method load/retrieve all the records for a domain Object from the
* database Table
*
* @return the list of domain-object instances
* @throws DataAccessFwException
* in case of dataaccess execution errors.
*
*/
public List<T> findAll() throws DataAccessException;
/**
* This method load/retrieve maximum number of records(specified by
* maxResults parameter) for a domain Object from the database Table.
*
* @param maxResults
* Specifies the maximum number of records to be retrieve.
* @return the list of domain-object instances
* @throws DataAccessFwException
* in case of dataaccess execution errors.
*/
public List<T> findAll(int maxResults) throws DataAccessException;
/**
* This method load/retrieve maximum number of records( the index postion of
* first record in the resultSet is specified by startIndex parameter) for a
* domain Object from the database Table.
*
* @param startIndex
* Specifies the start index of the record to be retrieve.
* @param maxResults
* Specifies the maximum number of records to be retrieve.
* @return the list of domain-object instances
* @throws DataAccessFwException
* in case of dataaccess execution errors.
*
*/
public List<T> findAll(int startIndex, int maxResults)
throws DataAccessException;
/**
* This method load/retrieve all the records for a domain Object based on
* the populated search attributes(search -parameter/values) from the
* database Table.
*
* @param exampleInstance
* Specifies the domainObject with search criteria
* @return the list of domain-object instances
* @throws DataAccessFwException
* in case of dataaccess execution errors.
*/
public List<T> findByExample(T exampleInstance)
throws DataAccessException;
public List<T> findByExample(T exampleObject, int maxResults);
public T merge(T transObj) throws DataAccessException;
/**
* This method save/update a domain object's information into the Database
* Table.
*
* @param entity
* Specifies the domain object to be save/update.
* @return the domainobject instance
* @throws DataAccessFwException
* in case of dataaccess execution errors.
*
*/
public T saveOrUpdate(T entity) throws DataAccessException;
/**
* This method remove a domain object's information from the Database Table.
*
* @param entity
* Specifies the domain object to be deleted.
* @return true if object has been deleted otherwise false
* @throws DataAccessFwException
* in case of dataaccess execution errors.
*
*/
public void delete(T entity) throws DataAccessException;
/**
* This method remove a domain object's information from the Database Table using object id.
*
* @param id
* Specifies ID of domain object to be deleted.
* @throws DataAccessFwException
* in case of dataaccess execution errors.
*
*/
public boolean deleteById(ID id) throws DataAccessException;
/**
* This method save/update a list of domain object's information into the
* Database Table.
*
* @param domainobjList
* Specifies the List of domain objects to be saved/updated.
* @return the list of domain-object instances
* @throws DataAccessFwException
* in case of dataaccess execution errors.
*
*/
public List<T> saveOrUpdateAll(List<T> domainobjList)
throws DataAccessException;
/**
* This method remove a list of domain object's information from the
* Database Table.
*
* @param domainobjList
* Specifies the list of domain objects to be deleted
* @throws DataAccessFwException
* in case of dataaccess execution errors.
*
*/
public void deleteAll(List<T> domainobjList) throws DataAccessException;
/**
* This method load/retrieve all the records for a domain Object based on
* the populated search attributes(search- parameter/values) and
* SortingAndPagingDescriptor (which contains the sorting-order, startIndex
* and pagesize for the search result) from the database Table.
*
* @param exampleObject
* Specifies the exampleObject with search criteria.
* @param pagingData
* Specifies the sorting & paging criteria.
* @return the list of domain-object instances
* @throws DataAccessFwException
* in case of dataaccess execution errors.
*/
public List<T> findByExample(T exampleObject,
SortingAndPagingDescriptor pagingData) throws DataAccessException;
public List<T> findByExample(final T exampleObject,
final SortingAndPagingDescriptor pagingDescriptor, int maxResults);
public List<T> findByExample(final T exampleObject,
final LockMode lockMode) throws DataAccessException;
public Iterator<T> iterateByExmple(final T exampleObject);
public Iterator<T> iterateByExmple(final T exampleObject,
final SortingOption so);
public Iterator<T> iterateByExmple(final T exampleObject, LockMode lockMode);
public Iterator<T> iterateByExmple(final T exampleObject,
final SortingOption... sos);
public Iterator<T> iterateByExmple(final T exampleObject,
final SortingOption so, final int internalCacheSize);
public Iterator<T> iterateByExmple(final T exampleObject,
final SortingOption so, LockMode lockMode);
public Iterator<T> iterateByExmple(final T exampleObject,
LockMode lockMode, final SortingOption... sos);
public Iterator<T> iterateByExmple(final T exampleObject,
final SortingOption[] sos, final LockMode lockMode,
final int internalCacheSize);
public void initializeLazyObject(Object obj);
// FIXME smineyev: I didn't find the way to re-attach modified data-graph to hibernate session
// (neither update, locl(NONE), relicate, refresh work)
// public void reattachModified(T entity);
public void clearCache();
public void evict(T ri);
public void flush();
}
<file_sep>/trunk/common/java/common-test/src/com/mvwsolutions/common/test/web/SpringServletTester.java
package com.mvwsolutions.common.test.web;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.LocalConnector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.servlet.DispatcherServlet;
import com.mvwsolutions.common.ComponentManager;
/**
*
* @author smineyev
*
*/
public class SpringServletTester {
private final static Log logger = LogFactory
.getLog(SpringServletTester.class);
private Server server = new Server();
private LocalConnector localConnector = new LocalConnector();
private int usageCounter;
private List<ServletContextListener> listeners = new ArrayList<ServletContextListener>();;
public SpringServletTester(ServletContextListener... extraListeners) throws IOException {
this.listeners.add(new ContextLoaderListener());
if (extraListeners != null) {
this.listeners.addAll(Arrays.asList(extraListeners));
}
try {
this.server.setSendServerVersion(false);
this.server.addConnector(localConnector);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
final String baseDir = System.getProperty("basedir");
String contextResourceBase = (baseDir == null ? "." : baseDir) + "/web";
File contentResourceBaseFile = new File(contextResourceBase);
if (contentResourceBaseFile.exists()) {
addContext(contextResourceBase, "/");
} else {
throw new FileNotFoundException("Web content folder ("
+ contentResourceBaseFile.getCanonicalPath()
+ ") doesn't exist in current project "
+ "so no default web context is created");
}
}
public void enableRemoteConnectors(int... ports) {
if (usageCounter > 0) {
throw new IllegalStateException(
"servlet container currently is in use");
}
for (int port : ports) {
if (checkIfRemoteConnectorExists(port)) {
logger.warn("Connector on port (" + port
+ ") has already been enabled");
continue;
}
SocketConnector remoteConnector = new SocketConnector();
// remoteConnector.setHost("localhost");
remoteConnector.setPort(port);
server.addConnector(remoteConnector);
logger.debug("Connector on port (" + port + ") added");
}
}
private boolean checkIfRemoteConnectorExists(int port) {
for (Connector c : server.getConnectors()) {
if (c instanceof SocketConnector) {
if (((SocketConnector) c).getPort() == port) {
return true;
}
}
}
return false;
}
public void disableRemoteConnectors() {
if (usageCounter > 0) {
throw new IllegalStateException(
"servlet container currently is in use");
}
for (Connector c : server.getConnectors()) {
if (c instanceof SocketConnector) {
server.removeConnector(c);
}
}
}
public Context addContext(String contextResourceBase, String contextPath) {
if (this.usageCounter > 0) {
throw new IllegalStateException(
"servlet container currently is in use");
}
Context context = new Context(Context.SESSIONS | Context.SECURITY);
this.server.addHandler(context);
context.setContextPath(contextPath);
context.setResourceBase(contextResourceBase);
setInitParameter(context, "contextConfigLocation", "");
setInitParameter(context, "parentContextKey",
ComponentManager.ROOT_BEAN_FACTORY_NAME);
setInitParameter(context, "locatorFactorySelector",
ComponentManager.BEAN_REF_CONTEXT_XML);
for (ServletContextListener listener: listeners) {
context.addEventListener(listener);
}
final ServletHolder servletHolder = context.getServletHandler()
.newServletHolder(DispatcherServlet.class);
servletHolder.setInitOrder(1);
servletHolder.setName("spring");
context.addServlet(servletHolder, "/spring/*");
return context;
}
public void start() throws Exception {
if (this.usageCounter == 0) {
this.server.start();
}
++this.usageCounter;
}
public void stop() throws Exception {
if (--this.usageCounter == 0) {
this.server.stop();
}
}
/* ------------------------------------------------------------ */
/**
* Get raw HTTP responses from raw HTTP requests. Multiple requests and
* responses may be handled, but only if persistent connections conditions
* apply.
*
* @param rawRequests
* String of raw HTTP requests
* @return String of raw HTTP responses
* @throws Exception
*/
public String getResponses(String rawRequests) throws Exception {
localConnector.reopen();
String responses = localConnector.getResponses(rawRequests);
return responses;
}
@SuppressWarnings("unchecked")
public static void setInitParameter(Context context, String name,
Object value) {
context.getInitParams().put(name, value);
}
}
<file_sep>/trunk/common/android/DroidCommand/src/com/mvw/controller/CommandMapping.java
package com.mvw.controller;
import com.mvw.command.Command;
import com.mvw.event.CommandEvent;
public class CommandMapping {
private CommandEvent event;
private Command command;
public CommandMapping(Command cmd, CommandEvent _event) {
event = _event;
command = cmd;
}
public CommandEvent getEvent() {
return event;
}
public void setEvent(CommandEvent event) {
this.event = event;
}
public Command getCommand() {
return command;
}
public void setCommand(Command command) {
this.command = command;
}
}
<file_sep>/trunk/common/maven/android-parent/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mvwsolutions</groupId>
<artifactId>global-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.mvwsolutions</groupId>
<artifactId>android-parent</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>Android parent pom</name>
<scm>
<connection>scm:svn:file:///var/svn/repos/common/maven/global-parent</connection>
<developerConnection>scm:svn:file:///var/svn/repos/common/maven/global-parent</developerConnection>
</scm>
<build>
<plugins>
<plugin>
<groupId>com.jayway.maven.plugins.android.generation2</groupId>
<artifactId>maven-android-plugin</artifactId>
<version>2.3.0</version>
<configuration>
<sdk>
<platform>${android-sdk-version}</platform>
</sdk>
<deleteConflictingFiles>true</deleteConflictingFiles>
</configuration>
<extensions>true</extensions>
</plugin>
<plugin>
<groupId>com.mvwsolutions.common.android</groupId>
<artifactId>daogen-maven-plugin</artifactId>
<version>1.0-SNAPSHOT</version>
<configuration>
<genOutput>gen2</genOutput> <!-- cannot use 'gen' as it's conflicting with Eclipse -->
</configuration>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- projects -->
<!-- third party libs -->
</dependencies>
</project>
<file_sep>/trunk/common/android/DroidCommand/src/com/mvw/event/EventDispatcher.java
package com.mvw.event;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EventDispatcher {
private Map<String, List<EventListener>> listeners = new HashMap<String, List<EventListener>>();
public EventDispatcher() {
super();
}
public void dispatchEvent(final CommandEvent event) {
synchronized (listeners) {
// first call all listeners
List<EventListener> elist = listeners.get(event.getType());
if (elist != null && elist.size() > 0) {
for (EventListener listener : elist) {
listener.onEvent(event);
}
}
}
}
public void addEventListener(EventListener listner, String type) {
synchronized (listeners) {
List<EventListener> list = listeners.get(type);
if (list == null) {
list = new ArrayList<EventListener>();
listeners.put(type, list);
}
list.add(listner);
}
}
public boolean removeEventListener(EventListener listener, String type) {
synchronized (listeners) {
if (!listeners.containsKey(type)) {
return false;
}
List<EventListener> list = listeners.get(type);
return list.remove(listener);
}
}
}<file_sep>/trunk/common/java/common-server/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mvwsolutions</groupId>
<artifactId>global-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.mvwsolutions.common</groupId>
<artifactId>java-common-server</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Java common server</name>
<scm>
<connection>scm:svn:file:///var/svn/repos/common/java/common-server</connection>
<developerConnection>scm:svn:file:///var/svn/repos/common/java/common-server</developerConnection>
<tag>HEAD</tag>
</scm>
<dependencies>
<!-- projects -->
<!-- third party libs -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl104-over-slf4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
</dependencies>
</project>
<file_sep>/trunk/common/java/common/src/com/mvwsolutions/common/exceptions/SecurityException.java
package com.mvwsolutions.common.exceptions;
@SuppressWarnings("serial")
public class SecurityException extends RuntimeException {
public SecurityException() {
}
public SecurityException(String msg) {
super(msg);
}
}
<file_sep>/trunk/common/android/daogen-maven-plugin/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mvwsolutions.common.android</groupId>
<artifactId>daogen-maven-plugin</artifactId>
<packaging>maven-plugin</packaging>
<version>1.0-SNAPSHOT</version>
<name>Daogen maven plugin that generates DAO from annotated beans</name>
<scm>
<connection>scm:svn:file:///var/svn/repos/common/android/daogen-maven-plugin</connection>
<developerConnection>scm:svn:file:///var/svn/repos/common/android/daogen-maven-plugin</developerConnection>
<tag>HEAD</tag>
</scm>
<build>
<directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<finalName>${artifactId}-${version}</finalName>
<testOutputDirectory>target/test-classes</testOutputDirectory>
<sourceDirectory>src</sourceDirectory>
<scriptSourceDirectory>scripts</scriptSourceDirectory>
<testSourceDirectory>test</testSourceDirectory>
<resources>
<resource>
<directory>src-res</directory>
<excludes>
<exclude>*app.properties</exclude>
</excludes>
</resource>
<resource>
<directory>src-res</directory>
<includes>
<include>*app.properties</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<testResources>
<testResource>
<directory>test-res</directory>
<excludes>
<exclude>*app.properties</exclude>
</excludes>
</testResource>
<testResource>
<directory>test-res</directory>
<includes>
<include>*app.properties</include>
</includes>
<filtering>true</filtering>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- projects -->
<dependency>
<groupId>com.mvwsolutions.common</groupId>
<artifactId>java-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.mvwsolutions.common.android</groupId>
<artifactId>daogen</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- third party libs -->
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-project</artifactId>
<version>2.2.1</version>
</dependency>
</dependencies>
</project>
<file_sep>/trunk/common/java/common-web/src/com/mvwsolutions/common/web/controller/BaseController.java
package com.mvwsolutions.common.web.controller;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;
import com.mvwsolutions.common.exceptions.AuthorizationException;
import com.mvwsolutions.common.service.CurrentUserService;
import com.mvwsolutions.common.web.util.WebUtils;
import com.mvwsolutions.common.web.view.GenericXmlView;
public abstract class BaseController<C> extends AbstractCommandController {
public static final String SESSID_COOKIE_NAME = "MVW_DROIDADTE_SESSION_ID";
public static final String SESSID_QUERY_NAME = SESSID_COOKIE_NAME;
protected boolean allowQuerySession = true;
protected CurrentUserService currentUserService;
private String successView = GenericXmlView.VIEW_NAME ;
private String failureView;
private String formView;
private Collection<ExtraSecurityEnforcer> extraSecurityEnforcers;
protected BaseController(Class<C> cmdClass) {
super(cmdClass);
setCommandName(GenericXmlView.OBJECT_MODEL);
}
@SuppressWarnings("unchecked")
public Class<C> getCmdClass() {
return getCommandClass();
}
public Collection<ExtraSecurityEnforcer> getExtraSecurityEnforcers() {
return extraSecurityEnforcers;
}
public void setExtraSecurityEnforcers(
Collection<ExtraSecurityEnforcer> extraSecurityEnforcers) {
this.extraSecurityEnforcers = extraSecurityEnforcers;
}
public CurrentUserService getCurrentUserService() {
return currentUserService;
}
public void setCurrentUserService(CurrentUserService currentUserService) {
this.currentUserService = currentUserService;
}
public boolean isAllowQuerySession() {
return allowQuerySession;
}
public void setAllowQuerySession(boolean allowQuerySession) {
this.allowQuerySession = allowQuerySession;
}
@Override
@SuppressWarnings("unchecked")
public ModelAndView handle(HttpServletRequest httpRequest,
HttpServletResponse httpResponse, Object command,
BindException errors) throws Exception {
final long startTime = System.currentTimeMillis();
preventCaching(httpResponse);
if (extraSecurityEnforcers != null) {
for (ExtraSecurityEnforcer extraSecurityEnforcer : extraSecurityEnforcers) {
if (!extraSecurityEnforcer.checkAccess(httpRequest)) {
logger.warn("Access denied (remoteHost"
+ httpRequest.getRemoteAddr() + ":"
+ httpRequest.getRemotePort() + ", enforced by: '"
+ extraSecurityEnforcer.toString() + "')");
throw new AuthorizationException("Access denied");
}
}
}
if (errors.getErrorCount() > 0) {
throw new BindException(errors);
}
final C cmd = getCmdClass().cast(command);
boolean requestAuthenticated;
boolean authenticationFailed = false;
ModelAndView res;
if (!authenticationRequired()) {
requestAuthenticated = false;
res = handleAuthenticatedRequest(httpRequest, httpResponse, cmd,
errors);
} else if (currentUserService == null) {
logger
.warn("currentUserService is not set for the controller. Request is considered unauthenticated.");
requestAuthenticated = false;
res = handleNotAuthenticatedRequest(httpRequest, httpResponse, cmd,
errors);
} else {
String sessionId = extractSessionId(httpRequest);
Long userId = null;
if( sessionId != null && !sessionId.equals("") )
userId = currentUserService.setCurrentSsoSession(new BigInteger(sessionId));
if (userId == null) {
requestAuthenticated = false;
res = handleNotAuthenticatedRequest(httpRequest, httpResponse,
cmd, errors);
} else {
requestAuthenticated = true;
res = handleAuthenticatedRequest(httpRequest, httpResponse,
cmd, errors);
}
}
if (res != null) {
final Map model = res.getModel();
model.put(GenericXmlView.REQUEST_DURATION_MODEL,
new Long(System.currentTimeMillis() - startTime));
model.put(GenericXmlView.REQUEST_AUTHENTICATED_MODEL,
requestAuthenticated);
model.put(GenericXmlView.AUTHENTICATION_FAILED_MODEL,
authenticationFailed);
}
return res;
}
protected String extractSessionId(HttpServletRequest httpRequest) {
// attempt to get from cookie
String sessionId = WebUtils.getCookieValue(httpRequest, SESSID_COOKIE_NAME);
// if, null check query string as a last resort
if (sessionId == null && allowQuerySession) {
sessionId = httpRequest.getParameter(SESSID_QUERY_NAME);
}
return sessionId;
}
@Override
protected C getCommand(HttpServletRequest request) throws Exception {
return getCmdClass().cast(super.getCommand(request));
}
protected boolean authenticationRequired() {
return true;
}
protected ModelAndView handleNotAuthenticatedRequest(
HttpServletRequest httpRequest, HttpServletResponse httpResponse,
C command, BindException errors) throws Exception {
throw new AuthorizationException(
"Permission denied (user not-authenticated)");
}
protected abstract ModelAndView handleAuthenticatedRequest(
HttpServletRequest httpRequest, HttpServletResponse httpResponse,
C command, BindException errors) throws Exception;
public static String getRemoteIP(HttpServletRequest httpRequest) {
String remoteAddr = httpRequest.getHeader("SS_CLIENT_IP");
if (remoteAddr == null) {
remoteAddr = httpRequest.getRemoteAddr();
}
return remoteAddr;
}
public String getFormView() {
return formView;
}
public void setFormView(String formView) {
this.formView = formView;
}
public String getSuccessView() {
return successView;
}
public void setSuccessView(String successView) {
this.successView = successView;
}
public String getFailureView() {
return failureView;
}
public void setFailureView(String failureView) {
this.failureView = failureView;
}
}
<file_sep>/trunk/common/maven/lib-installer/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mvwsolutions</groupId>
<artifactId>lib-installer</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>Third party lib installer</name>
<scm>
<connection>scm:svn:file:///var/svn/repos/common/maven/lib-installer</connection>
<developerConnection>scm:svn:file:///var/svn/repos/common/maven/lib-installer</developerConnection>
<tag>HEAD</tag>
</scm>
<profiles>
<profile>
<id>db-profile</id>
<activation>
<property>
<name>!fast</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>install-local-dependencies</id>
<phase>compile</phase>
<configuration>
<tasks>
<echo>Installing dependencies that do not exist in global repository ...</echo>
<exec failonerror="true" failifexecutionfails="false" executable="${basedir}/install-dependencies.sh"/>
<exec failonerror="true" failifexecutionfails="false" executable="${basedir}/install-dependencies.bat"/>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
<file_sep>/trunk/common/java/common-server/src/com/mvwsolutions/common/dao/hibernate/NulOneToManyPersister.java
package com.mvwsolutions.common.dao.hibernate;
import java.io.Serializable;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.cache.CacheConcurrencyStrategy;
import org.hibernate.cache.CacheException;
import org.hibernate.cfg.Configuration;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.mapping.Collection;
import org.hibernate.persister.collection.OneToManyPersister;
/**
* Persister that do not persist collection to DB. Needed by PlayerDataAccessService
* @author smineyev
*
*/
public class NulOneToManyPersister extends OneToManyPersister {
public NulOneToManyPersister(Collection collection,
CacheConcurrencyStrategy cache, Configuration cfg,
SessionFactoryImplementor factory) throws MappingException,
CacheException {
super(collection, cache, cfg, factory);
}
@Override
protected int doUpdateRows(Serializable id, PersistentCollection collection, SessionImplementor session) throws HibernateException {
return 0;
}
}
<file_sep>/trunk/common/java/common-server/src/com/mvwsolutions/common/dao/hibernate/BugFixDeleteEventListener.java
package com.mvwsolutions.common.dao.hibernate;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.event.EventSource;
import org.hibernate.event.def.DefaultDeleteEventListener;
import org.hibernate.persister.entity.EntityPersister;
/**
*
* bug description:
* http://opensource.atlassian.com/projects/hibernate/browse/HHH-2146
* http://lists.jboss.org/pipermail/hibernate-issues/2007-January/003099.html
*
* @author smineyev
*
*/
public class BugFixDeleteEventListener extends DefaultDeleteEventListener {
private static final long serialVersionUID = 2885464529422013461L;
@SuppressWarnings("unchecked")
protected void deleteTransientEntity(EventSource session, Object entity,
boolean cascadeDeleteEnabled, EntityPersister persister,
Set transientEntities) {
super.deleteTransientEntity(session, entity, cascadeDeleteEnabled,
persister, transientEntities == null ? new HashSet()
: transientEntities);
}
}
<file_sep>/trunk/common/java/common-web/src/com/mvwsolutions/common/web/util/WebUtils.java
package com.mvwsolutions.common.web.util;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author SMineyev
*
*/
public class WebUtils {
public static String getCookieValue(HttpServletRequest httpRequest,
String cookieName) {
Cookie cookie = getCookie(httpRequest, cookieName);
if (cookie != null)
return cookie.getValue();
return null;
}
public static Cookie getCookie(HttpServletRequest httpRequest,
String cookieName) {
final Cookie[] cookies = httpRequest.getCookies();
if (cookies == null) {
return null;
}
for (Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
public static Cookie setCookie(String name, String value,
HttpServletRequest request, HttpServletResponse response,
int expiration) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
cookie.setMaxAge(expiration);
cookie.setDomain(getDomain(request));
response.addCookie(cookie);
return cookie;
}
public static String getDomain(HttpServletRequest httpRequest) {
String domain = httpRequest.getServerName();
String[] parts = domain.split("\\.");
if (parts.length < 2) {
return domain;
} else {
domain = '.' + parts[parts.length - 2] + '.'
+ parts[parts.length - 1];
return domain;
}
}
}
<file_sep>/trunk/common/android/daogen-maven-plugin/src/com/mvwsolutions/common/android/maven/DaoGenMojo.java
package com.mvwsolutions.common.android.maven;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import com.mvwsolutions.android.daogen.FileSourceInterface;
import com.mvwsolutions.android.daogen.SourceFileGenerator;
import com.mvwsolutions.android.daogen.SourceInterface.SIException;
import com.mvwsolutions.classwriter.ClassWriter;
import com.mvwsolutions.classwriter.CodeCheckException;
import com.mvwsolutions.common.Utils;
/**
*
* @author SMineyev
* @goal run
*/
public class DaoGenMojo extends AbstractMojo {
/** @parameter default-value="${project}" */
private MavenProject mavenProject;
// /** @parameter default-value="gen" */
// private String genOutput;
public void execute() throws MojoExecutionException {
getLog().info(
"Project output: "
+ mavenProject.getBuild().getOutputDirectory());
final File genOutputDir = new File(mavenProject.getBuild().getSourceDirectory());
getLog().info("Generated files will be placed into: " + genOutputDir.getAbsolutePath());
Utils.traverseFileTree(new File(mavenProject.getBuild()
.getOutputDirectory()), new Utils.FileVisitor() {
@Override
public void visit(File file) {
if (!file.isDirectory() && file.getName().endsWith(".class")) {
try {
processClassFile(file, genOutputDir);
} catch (Exception e) {
getLog().error(
"Unable to process class file: "
+ file.getAbsolutePath(), e);
}
}
}
});
}
private void processClassFile(File classFile, File outputDir)
throws FileNotFoundException, IOException, CodeCheckException,
SIException {
getLog().info(outputDir.getAbsolutePath() +" , " + classFile.getAbsolutePath());
ClassWriter cw = new ClassWriter();
cw.readClass(new FileInputStream(classFile));
boolean generated = new SourceFileGenerator(new FileSourceInterface(
outputDir)).generate(cw);
if (generated) {
getLog().info(
"DAO class (" + outputDir.getAbsolutePath() + ") was generated for "
+ classFile.getAbsolutePath());
}
}
}
<file_sep>/trunk/common/maven/global-parent/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mvwsolutions</groupId>
<artifactId>global-parent</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>Maven global parent project</name>
<scm>
<connection>scm:svn:file:///var/svn/repos/common/maven/global-parent</connection>
<developerConnection>scm:svn:file:///var/svn/repos/common/maven/global-parent</developerConnection>
</scm>
<!-- repositories>
<repository>
<id>mvn2</id>
<name>Maven2 central repository</name>
<url>http://repo2.maven.org/maven2</url>
</repository>
<repository>
<id>sun-java</id>
<name>sun-java</name>
<url>http://download.java.net/maven/2/</url>
</repository>
<repository>
<id>jboss</id>
<name>jboss</name>
<url>http://repository.jboss.org/maven2/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>tlc</id>
<name>Maven codehouse</name>
<url>http://snapshots.repository.codehaus.org</url>
</pluginRepository>
<pluginRepository>
<id>tlc</id>
<name>Maven codehouse</name>
<url>http://cropwiki.irri.org/m2repo/</url>
</pluginRepository>
<pluginRepository>
<id>mvn2</id>
<name>Maven2 central repository</name>
<url>http://repo2.maven.org/maven2</url>
</pluginRepository>
</pluginRepositories -->
<profiles>
<profile>
<id>dev-test-profile</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<failIfNoTests>false</failIfNoTests>
<forkMode>once</forkMode>
<!-- -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y -->
<argLine>-Xmx512M -server -da</argLine>
<disableXmlReport>false</disableXmlReport>
<excludes>
<exclude>**/*ExtendedTest.java</exclude>
</excludes>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>extended-test-profile</id>
<activation>
<property>
<name>extendedTest</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<failIfNoTests>false</failIfNoTests>
<forkMode>once</forkMode>
<!-- -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y -->
<argLine>-DextendedTest -Xmx512M -server -da</argLine>
<disableXmlReport>true</disableXmlReport>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<finalName>${artifactId}-${version}</finalName>
<testOutputDirectory>target/test-classes</testOutputDirectory>
<sourceDirectory>src</sourceDirectory>
<scriptSourceDirectory>scripts</scriptSourceDirectory>
<testSourceDirectory>test</testSourceDirectory>
<resources>
<resource>
<directory>src-res</directory>
<!-- excludes>
<exclude>*app.properties</exclude>
</excludes -->
</resource>
<!-- resource>
<directory>src-res</directory>
<includes>
<include>*app.properties</include>
</includes>
<filtering>true</filtering>
</resource -->
</resources>
<testResources>
<testResource>
<directory>test-res</directory>
<!-- excludes>
<exclude>*app.properties</exclude>
</excludes -->
</testResource>
<!-- testResource>
<directory>test-res-f</directory>
<includes>
<include>*app.properties</include>
</includes>
<filtering>true</filtering>
</testResource -->
</testResources>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>gen2</source> <!-- can not use 'gen' as it's conflicting with eclipse -->
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>buildnumber-maven-plugin</artifactId>
<version>1.0-beta-4</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>create</goal>
</goals>
</execution>
</executions>
<configuration>
<doCheck>false</doCheck>
<doUpdate>false</doUpdate>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webResources>
<resource>
<directory>${basedir}/web</directory>
</resource>
</webResources>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
<manifestEntries>
<SVN-revision>${buildNumber}</SVN-revision>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<!-- manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest -->
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
<manifestEntries>
<SVN-revision>${buildNumber}</SVN-revision>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>android</groupId>
<artifactId>android</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>android</groupId>
<artifactId>android</artifactId>
<version>1.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>android</groupId>
<artifactId>android</artifactId>
<version>1.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>android</groupId>
<artifactId>android</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>android</groupId>
<artifactId>android</artifactId>
<version>2.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>android</groupId>
<artifactId>android</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.android</groupId>
<artifactId>maps</artifactId>
<version>3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.android</groupId>
<artifactId>maps</artifactId>
<version>4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.android</groupId>
<artifactId>maps</artifactId>
<version>5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.android</groupId>
<artifactId>maps</artifactId>
<version>6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.android</groupId>
<artifactId>maps</artifactId>
<version>7</version>
<scope>provided</scope>
</dependency>
<!-- Exclusions in dependencies bellow are becuase of wrong version format f eclipse artefacts.
See http://jira.codehaus.org/browse/MNG-3518 -->
<dependency>
<groupId>org.eclipse.equinox</groupId>
<artifactId>common</artifactId>
<version>3.3.0-v20070426</version>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>jface</artifactId>
<version>3.3.0-I20070606-0010</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>app</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse</groupId>
<artifactId>swt</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.core</groupId>
<artifactId>commands</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>osgi</artifactId>
<version>3.3.0-v20070530</version>
</dependency>
<dependency>
<groupId>org.eclipse.ui</groupId>
<artifactId>workbench</artifactId>
<version>3.3.0-I20070608-1100</version>
<exclusions>
<exclusion>
<groupId>org.eclipse</groupId>
<artifactId>jface</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.core</groupId>
<artifactId>expressions</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse</groupId>
<artifactId>swt</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.jface</groupId>
<artifactId>databinding</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.core</groupId>
<artifactId>databinding</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.eclipse.core</groupId>
<artifactId>runtime</artifactId>
<version>3.3.100-v20070530</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>app</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.eclipse.core</groupId>
<artifactId>resources</artifactId>
<version>3.3.0-v20070604</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>app</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.eclipse.equinox</groupId>
<artifactId>registry</artifactId>
<version>3.3.0-v20070522</version>
</dependency>
<dependency>
<groupId>org.eclipse.core</groupId>
<artifactId>jobs</artifactId>
<version>3.3.0-v20070423</version>
</dependency>
<dependency>
<groupId>org.eclipse.swt.win32.win32</groupId>
<artifactId>x86</artifactId>
<version>3.3.0-v3346</version>
</dependency>
<dependency>
<groupId>org.eclipse.jdt</groupId>
<artifactId>core</artifactId>
<version>3.3.0-v_771</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>common</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.simpleframework</groupId>
<artifactId>simple-xml</artifactId>
<version>2.3.2</version>
<exclusions>
<exclusion>
<groupId>stax</groupId>
<artifactId>stax</artifactId>
</exclusion>
<exclusion>
<groupId>stax</groupId>
<artifactId>stax-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.7.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.4.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.3.0.ga</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl104-over-slf4j</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-support</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>quartz</groupId>
<artifactId>quartz</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-oxm</artifactId>
<version>1.5.9</version>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-oxm-tiger</artifactId>
<version>1.5.9</version>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-oxm-tiger</artifactId>
<version>1.5.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-servlet-tester</artifactId>
<version>6.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<scope>provided</scope>
<version>2.0</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<scope>provided</scope>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.12</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
<file_sep>/trunk/common/java/common-web/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mvwsolutions</groupId>
<artifactId>global-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.mvwsolutions.common</groupId>
<artifactId>java-common-web</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Java common web</name>
<scm>
<connection>scm:svn:file:///var/svn/repos/common/java/common-web</connection>
<developerConnection>scm:svn:file:///var/svn/repos/common/java/common-web</developerConnection>
<tag>HEAD</tag>
</scm>
<dependencies>
<!-- projects -->
<dependency>
<groupId>com.mvwsolutions.common</groupId>
<artifactId>java-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- third party libs -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-oxm-tiger</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl104-over-slf4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
</dependencies>
</project>
<file_sep>/trunk/common/java/common-test/src/com/mvwsolutions/common/test/web/SpringServletTestCase.java
package com.mvwsolutions.common.test.web;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.mortbay.jetty.testing.HttpTester;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mvwsolutions.common.Utils;
import com.mvwsolutions.common.web.xml.Response;
/**
*
* @author smineyev
*
*/
public class SpringServletTestCase {
private static final Logger logger = LoggerFactory
.getLogger(SpringServletTestCase.class);
protected static SpringServletTester tester;
protected HttpTester httpRequest;
protected HttpTester httpResponse;
@BeforeClass
public static void startServletTester() throws Exception {
tester = new SpringServletTester();
tester.start();
}
@Before
public final void beforeRequest() {
this.httpRequest = new HttpTester();
this.httpResponse = new HttpTester();
}
protected final HttpTester sendRequest(String uri) throws Exception {
final boolean post = this.httpRequest.getContent() != null;
this.httpRequest.setMethod(post ? "POST" : "GET");
this.httpRequest.setURI(uri);
this.httpRequest.setVersion("HTTP/1.1");
this.httpRequest.addHeader("Host", "tester");
if (post) {
this.httpRequest.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
}
final String request = this.httpRequest.generate();
logger.debug("(!) request: " + request);
String rawHttpResponse = tester.getResponses(request);
logger.debug("(!) response: " + rawHttpResponse);
this.httpResponse.parse(rawHttpResponse);
return this.httpResponse;
}
public void postViaRemoteConnector(String url, String body, String cookies) {
try {
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
try {
if (body != null) {
StringRequestEntity sre = new StringRequestEntity(body, "",
"UTF-8");
postMethod.setRequestEntity(sre);
}
// for (Map.Entry<String, String> entry : cookies.entrySet()) {
// postMethod.addRequestHeader("Cookie", entry.getKey() + "="
// + entry.getValue());
// }
if (cookies != null && cookies.length() > 0) {
postMethod.addRequestHeader("Cookie", cookies);
}
httpResponse.setStatus(httpClient.executeMethod(postMethod));
httpResponse.setContent(new String(
postMethod.getResponseBody(), "UTF-8"));
} finally {
postMethod.releaseConnection();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected String getResponseCookie(String cName) {
Map<String, String> cookieMap = getCockies();
return cookieMap.get(cName);
}
protected Map<String, String> getCockies() {
Map<String, String> cookieMap = new HashMap<String, String>();
String cookiesStr = httpResponse.getHeader("Set-Cookie");
List<String> cookies = Utils.tokenize(cookiesStr, ";");
for (String cockie : cookies) {
int p = cockie.indexOf('=');
if (p != -1) {
String name = cockie.substring(0, p);
String value = cockie.substring(p + 1);
cookieMap.put(name, value);
}
}
return cookieMap;
}
protected final <T> T getResponse(Class<T> expectedResponseClass,
Class... classesToBeBound) {
Assert.assertEquals("Bad HTTP response code: " + this.httpResponse.getStatus()
+ ", content: " + this.httpResponse.getReason(), 200,
this.httpResponse.getStatus());
Assert.assertNotNull("Response is empty: " + this.httpResponse.getStatus()
+ " " + this.httpResponse.getReason(), this.httpResponse
.getContent());
final Class[] classes = new Class[classesToBeBound.length + 2];
classes[0] = Response.class;
classes[1] = expectedResponseClass;
System.arraycopy(classesToBeBound, 0, classes, 2,
classesToBeBound.length);
final String content = this.httpResponse.getContent();
Object responseObject;
try {
final Serializer unmarshaller = new Persister();
responseObject = unmarshaller.read(Response.class, content);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (responseObject.getClass() == expectedResponseClass) {
return expectedResponseClass.cast(responseObject);
} else {
if (responseObject.getClass() != Response.class) {
Assert.fail("Actual response is neither instance of "
+ Response.class.getName() + " nor "
+ expectedResponseClass.getName());
}
}
Response response = (Response) responseObject;
if (expectedResponseClass == Response.class) {
return expectedResponseClass.cast(responseObject);
}
// to move on and extract result object we need to make sure that
// request is successful
Assert.assertNotNull("Result object is null", response);
Assert.assertTrue("HTTP request failed, the cause: " + response.getError(),
response.isSuccess());
Assert.assertTrue("Response is " + response.getResultObject() + ", but "
+ expectedResponseClass.getName() + " expected",
expectedResponseClass.isInstance(response.getResultObject()));
return expectedResponseClass.cast(response.getResultObject());
}
@After
public final void afterResponse() {
this.httpRequest = null;
this.httpResponse = null;
}
@AfterClass
public static void stopServletTester() throws Exception {
if (tester != null) {
tester.stop();
tester = null;
}
}
}
<file_sep>/trunk/common/android/DroidCommand/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mvwsolutions</groupId>
<artifactId>global-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.mvwsolutions.common.android</groupId>
<artifactId>DroidCommand</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Andriod common Command Framework</name>
<scm>
<connection>scm:svn:file:///var/svn/repos/common/android/DroidCommand</connection>
<developerConnection>scm:svn:file:///var/svn/repos/common/android/DroidCommand</developerConnection>
<tag>HEAD</tag>
</scm>
<dependencies>
<!-- projects -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
</project>
<file_sep>/trunk/common/android/DroidCommand/src/com/mvw/event/CommandEvent.java
package com.mvw.event;
public abstract class CommandEvent {
public abstract String getType();
// default to async
private SYNC_TYPE syncType = SYNC_TYPE.Async;
public boolean isAsync() {
if (syncType == SYNC_TYPE.Async) {
return true;
} else {
return false;
}
}
public CommandEvent() {
}
public CommandEvent(SYNC_TYPE syncType) {
super();
this.syncType = syncType;
}
public enum SYNC_TYPE {
Async, Sync
}
}
<file_sep>/trunk/common/android/DroidCommand/test/com/mvw/command/TestCommand.java
package com.mvw.command;
import com.mvw.controller.CommandControllerTest;
import com.mvw.event.CommandEvent;
public class TestCommand extends Command {
@Override
public void execute(CommandEvent event) {
synchronized (CommandControllerTest.lock) {
CommandControllerTest.commandRan = true;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
CommandControllerTest.threadCount.decrementAndGet();
CommandControllerTest.lock.notify();
}
return;
}
}
| 39cb4ca5ed94c65da3ee2871cd55bc4bd0524545 | [
"Java",
"Maven POM"
] | 25 | Java | miguelvargas/test | 18cef14a1e382bd6ae0d35f131ed6bc8f3f7101e | 6c92d3a54ba2636a82c1fe3a05f8659cc2422cfc | |
refs/heads/master | <repo_name>mybb-de/MyBB-Merge-German<file_sep>/global.lang.php
<?php
/**
* German language pack for MyBB Merge 1.8
* Deutsches Sprachpaket für das MyBB Merge System 1.8
* (c) 2017 MyBB.de
*
* Author/Autor: https://www.mybb.de/
* License/Lizenz: GNU Lesser General Public License, Version 3
*/
$l['next'] = "Weiter";
$l['version'] = "Version";
$l['none'] = "Kein";
$l['please_wait'] = "Bitte warten...";
$l['welcome'] = "Willkommen";
$l['pause'] = "Pause";
$l['error'] = "Fehler";
$l['warning'] = "Warnung";
$l['completed'] = "Abgeschlossen";
$l['dependencies'] = "Abhängigkeiten";
$l['resume'] = "Fortsetzen";
$l['run'] = "Starten";
$l['cleanup'] = "Aufräumen";
$l['yes'] = "Ja";
$l['no'] = "Nein";
$l['download'] = "Herunterladen";
$l['redirecting'] = "Weiterleitungen...";
$l['dont_wait'] = "Bitte klicken Sie hier, wenn Sie nicht länger warten wollen.";
$l['back'] = "zurück";
$l['found_error'] = "Fehler aufgetreten";
$l['loading_data'] = "Daten aus der Datenbank laden...";
$l['done'] = "Fertig";
// Modules, english names are hardcoded. Uncomment this for your language
// Descriptions are added as "module_{key}_desc, however the current ones doesn't have a description
// Singular versions are added as "module_{key}_singular
$l['module_db_configuration'] = 'Datenbankkonfiguration';
$l['module_db_configuration_singular'] = 'Datenbankkonfiguration';
$l['module_usergroups'] = 'Benutzergruppen';
$l['module_usergroups_singular'] = 'Benutzergruppe';
$l['module_users'] = 'Benutzer';
$l['module_users_singular'] = 'Benutzer';
$l['module_categories'] = 'Kategorien';
$l['module_forums'] = 'Foren';
$l['module_forums_singular'] = 'Forum';
$l['module_forumperms'] = 'Forenberechtigungen';
$l['module_forumperms_singular'] = 'Forenberechtigung';
// Yes, this is used twice as the key used for automatic detection is different sometimes. Will be fixed in a later release
$l['module_forum_permissions'] = 'Forenberechtigungen';
$l['module_forum_permissions_singular'] = 'Forenberechtigung';
$l['module_moderators'] = 'Moderatoren';
$l['module_moderators_singular'] = 'Moderator';
$l['module_threads'] = 'Themen';
$l['module_threads_singular'] = 'Thema';
$l['module_posts'] = 'Beiträge';
$l['module_posts_singular'] = 'Beitrag';
$l['module_attachments'] = 'Attachments';
$l['module_attachments_singular'] = 'Attachment';
$l['module_polls'] = 'Umfragen';
$l['module_polls_singular'] = 'Umfrage';
// Yes, this is used twice as the key used for automatic detection is different sometimes. Will be fixed in a later release
$l['module_poll_votes'] = 'Umfragen';
$l['module_poll_votes_singular'] = 'Umfrage';
$l['module_pollvotes'] = 'Stimmen';
$l['module_pollvotes_singular'] = 'Stimme';
$l['module_privatemessages'] = 'Private Nachrichten';
$l['module_privatemessages_singular'] = 'Private Nachricht';
// Yes, this is used twice as the key used for automatic detection is different sometimes. Will be fixed in a later release
$l['module_private_messages'] = 'Private Nachrichten';
$l['module_private_messages_singular'] = 'Private Nachricht';
$l['module_events'] = 'Termine';
$l['module_events_singular'] = 'Termin';
$l['module_icons'] = 'Icons';
$l['module_icons_singular'] = 'Icon';
$l['module_smilies'] = 'Smilies';
$l['module_smilies_singular'] = 'Smilie';
$l['module_settings'] = 'Einstellungen';
$l['module_settings_singular'] = 'Einstellung';
$l['module_attachtypes'] = 'Attachment-Typen';
$l['module_attachtypes_singular'] = 'Attachment-Typ';
$l['module_categories_singular'] = 'Kategorie';
$l['creating_fields'] = "Erstelle Felder zur Verfolgung des Imports (Dies kann eine Weile dauern)...";
$l['creating_table'] = "{1} Tabellen erstellt.";
$l['creating_columns'] = "Füge {1} Spalten {2} zur Tabelle {3} hinzu";
$l['indexpage_require'] = "Das MyBB Merge System benötigt MyBB 1.8 zur Ausführung.";
$l['welcomepage_description'] = "Willkommen beim MyBB Merge System. Das MyBB Merge System wurde entworfen um Foren, die eine unterstützte Foren-Software verwenden, in MyBB 1.8 zu importieren. Außerdem können Sie mehrere Foren zu einem MyBB <i>zusammenzufügen</i>.<br /><br />Sie finden eine detailierte Anleitung zum Merge System in unserer Dokumentation: ";
$l['welcomepage_mergesystem'] = "Merge System";
$l['welcomepage_anonymousstat'] = "Anonyme Statistik über Serverspezifikationen an die MyBB Group schicken";
$l['welcomepage_informations'] = "Welche Informationen werden gesendet?";
$l['welcomepage_closeboard'] = "Forum während Import schließen";
$l['welcomepage_note'] = "Das MyBB Merge System kann <u><strong>nicht</strong></u> dafür verwendet werden um MyBB-Forum zu aktualisieren oder zu verknüpfen. Außerdem sollten sie sicherstellen, dass alle Modifikationen und Plugins, die den Import beeinflussen können, in beiden Foren (Ihrem alten und Ihrem neuen Forum) <strong>deaktiviert</strong> wurden, bevor Sie das MyBB Merge System ausführen. Es wird zudem <strong>dringend</strong> empfohlen ein Backup beider Foren anzufertigen, bevor Sie fortfahren.";
$l['welcomepage_pleasenote'] = "Bitte beachten Sie";
$l['requirementspage_check'] = "Prüfung der Voraussetzungen";
$l['requirementspage_req'] = "Voraussetzungen";
$l['requirementspage_uptodate'] = "Aktuell";
$l['requirementspage_outofdatedesc'] = "Ihr MyBB Merge System ist veraltet! Das MyBB Merge System wird möglicherweise nicht funktionieren bis Sie es aktualisieren. Aktuelle Version:
";
$l['requirementspage_outofdate'] = "Veraltet";
$l['requirementspage_mergeoutofdate'] = "Ihre Version des Merge System ist veraltet";
$l['requirementspage_unabletocheck'] = "Prüfung fehlgeschlagen";
$l['requirementspage_unabletocheckdesc'] = "Die Version konnte nicht überprüft werden";
$l['requirementspage_chmoduploads'] = "Das Attachment-Verzeichnis (/uploads/) ist nicht beschreibbar. Bitte passen Sie ";
$l['requirementspage_chmoduploads2'] = " die Berechtigungen an, damit die Dateien geschrieben werden können.";
$l['requirementspage_chmod'] = "Das Attachment-Verzeichnis (/uploads/) ist nicht beschreibbar. Bitte passen Sie ";
$l['requirementspage_notwritable'] = "Nicht beschreibbar";
$l['requirementspage_attnotwritable'] = "Attachment-Verzeichnis nicht beschreibbar";
$l['requirementspage_attwritable'] = "Beschreibbar";
$l['requirementspage_attwritabledesc'] = "Attachment-Verzeichnis beschreibbar";
$l['requirementspage_reqfailed'] = "Prüfung der Voraussetzungen fehlgeschlagen:";
$l['requirementspage_mergeversion'] = "Merge System Version:";
$l['requirementspage_attwritabledesc2'] = "Attachment-Verzeichnis beschreibbar:";
$l['requirementspage_checkagain'] = "Wenn Sie bereit sind, klicken Sie \"Erneut prüfen\" um erneut zu prüfen.";
$l['requirementspage_congrats'] = "Herzlichen Glückwunsch, alle Voraussetzungen werden erfüllt! Klicken Sie \"Weiter\" um Fortzufahren.
";
$l['boardspage_welcome'] = "Vielen Dank, dass Sie MyBB gewählt haben. Dieser Assistent wird Sie durch den Prozess zum Import Ihres Forums ins MyBB führen.";
$l['boardspage_boardselection'] = "Foren-Auswahl";
$l['boardspage_boardselectiondesc'] = "Bitte wählen Sie die Software aus, die Sie importieren möchten.";
$l['module_selection'] = "Modul-Auswahl";
$l['module_selection_select'] = "Bitte wählen Sie ein Modul zur Ausführung aus.";
$l['module_selection_import'] = "Importiert {1} ";
$l['module_selection_cleanup_desc'] = "Nachdem Sie die gewünschten Module ausgeführt haben, fahren Sie mit dem nächsten Schritt fort. Beim Aufräumen werden alle temporär für den Import benötigten Daten gelöscht.";
$l['database_configuration'] = "Datenbank-Konfiguration";
$l['database_settings'] = "Datenbank-Einstellungen";
$l['database_engine'] = "Datenbank-Engine";
$l['database_path'] = "Datenbank-Pfad";
$l['database_host'] = "Datenbank-Host";
$l['database_user'] = "Datenbank-Benutzername";
$l['database_pw'] = "Datenbank-Passwort";
$l['database_name'] = "Datenbank-Name";
$l['database_table_settings'] = "Tabelleneinstellungen";
$l['database_table_prefix'] = "Tabellenpräfix";
$l['database_table_encoding'] = "Tabellenkodierung";
$l['database_utf8_thead'] = "UTF-8 kodieren";
$l['database_utf8_desc'] = "Sollten Nachrichten automatisch zu UTF8 konvertiert werden?:<br /><small>Deaktivieren Sie diese Option, falls nach dem Import<br />merkwürdige Zeichen in Beiträgen erscheinen.</small>";
$l['database_click_next'] = "Nachdem Sie überprüft haben, dass alle Angaben stimmen, klicken Sie Weiter um Fortzufahren.";
$l['database_exit'] = "Konfiguration verlassen";
$l['database_check_success'] = "Datenbank-Einstellungen überprüfen... <span style=\"color: green\">Erfolgreich.</span>";
$l['database_success'] = "Datenbank erfolgreich konfiguriert und Verbindung hergestellt.";
$l['database_details'] = "Bitte geben Sie die Datenbank-Einstellung für die {1} Installation an, die Sie importieren möchten.";
$l['wbb_installationnumber'] = "Installationsnummer";
$l['wbb_installationnumber_desc'] = "Welche Installationsnummer wurde bei der Installation gewählt?";
$l['column_length_check'] = 'Prüfe, ob alle Daten in die MyBB-Datenbank passen...';
$l['column_length_checking'] = 'Prüfe Spalte {1} in der Tabelle {2}';
$l['per_screen_config'] = "Auswahl der Optionen";
$l['per_screen'] = "Bitte wählen Sie, wie viele {1} in einem Schritt importiert werden sollen";
$l['per_screen_label'] = "{1} in einem Schritt importieren";
$l['per_screen_autorefresh'] = "Wollen Sie automatisch bis zum Abschluss zum nächsten Schritt weitergeleitet werden?";
$l['stats_in_progress'] = "{1} {2} werden gerade importiert. Es sind noch {3} {2} und {4} weitere Seiten übrig.";
$l['stats'] = "Es werden {1} {2} importiert.";
$l['progress'] = "Einfügen von {1} #{2}";
$l['progress_merging_user'] = "Benutzer #{1} mit Benutzer #{2} zusammengefügt";
$l['progress_settings'] = "Einfügen von {1} {2} von Ihrer Datenbank {3}";
$l['progress_none_left'] = "Es sind keine {1} mehr zu importieren. Bitte klicken Weiter um Fortzufahren.";
$l['progress_none_left_settings'] = "Es sind keine {1} zu aktualisieren. Bitte klicken Weiter um Fortzufahren.";
$l['import_successfully'] = "{1} erfolgreich importiert.";
$l['module_post_rebuilding'] = "Zähler werden erneuert";
$l['module_post_rebuild_counters'] = "<br />\nInterne Zähler werden erneuert...(Das könnte eine Weile dauern)<br />";
$l['module_post_rebuilding_thread'] = "Themenzähler werden erneuert...";
$l['module_post_thread_counter'] = "Zähler von Thema #{1} werden erneuert";
$l['module_post_rebuilding_forum'] = "Forenzähler werden erneuert...";
$l['module_post_forum_counter'] = "Zähler von Forum #{1} werden erneuert";
$l['module_post_rebuilding_user_post'] = "Benutzerbeitragszähler werden erneuert...";
$l['module_post_user_counter'] = "Zähler von Benutzer #{1} werden erneuert";
$l['module_post_rebuilding_user_thread'] = "Benutzerthemenzähler werden erneuert...";
$l['module_settings_updating'] = "Einstellungen {1} werden aktualisiert";
$l['module_attachment_link'] = "Bitte geben Sie den Link zu Ihrem {1} Attachment-Verzeichnis sein";
$l['module_attachment_label'] = "Link (URL) zu Ihrem Attachment-Verzeichnis<br /><span class='smalltext'>Wenn möglich, verwenden Sie einen relativen oder absoluten Pfad. Beachten Sie, dass das <b>merge</b>-Verzeichnis als Arbeitsverzeichnis verwendet wird</span>";
$l['module_attachment_error'] = "Fehler beim Übertragung des Attachments (ID: {1})";
$l['module_attachment_not_found'] = "Fehler, Attachment könnte nicht gefunden werden (ID: {1})";
$l['module_attachment_create_thumbnail'] = 'Thumbnails für übertragene Attachment automatisch erstellen';
$l['module_attachment_create_thumbnail_note'] = 'Beachten Sie, dass die Thumbnails neu erstellt werden müssen, wenn die Thumbnail-Größe geändert wurde. Wenn das Einstellungs-Modul noch nicht ausgeführt wurde oder Sie die Einstellung nicht geändert haben, sollten Sie Nein wählen.';
$l['attmodule_ipadress'] = "Verwenden Sie nicht \"localhost\" in der URL. Bitte nutzen Sie Ihre öffenliche IP-Adresse (Stellen Sie sicher, dass Port 80 in Ihrer Firewall und Ihrem Router geöffnet sind).";
$l['attmodule_ipadress2'] = "Verwenden Sie nichz \"127.0.0.1\" in der URL. Bitte nutzen Sie Ihre öffenliche IP-Adresse (Stellen Sie sicher, dass Port 80 in Ihrer Firewall und Ihrem Router geöffnet sind).";
$l['module_avatar_link'] = "Please type in the link to your {1} avatar directory";
$l['module_avatar_label'] = "Link (URL) to your forum avatar directory<br /><span class='smalltext'>If possible use a relative or absolute path. Note that the <b>merge</b> directory is used as working directory</span>";
$l['module_avatar_error'] = "Error transfering the avatar (ID: {1})";
$l['module_avatar_not_found'] = "Error could not find the avatar (ID: {1})";
$l['upload_not_writeable'] = 'Das Upload-Verzeichnis ({1}) ist nicht beschreibbar. Bitte passen Sie die <a href="https://www.mybb.de/doku/installationaktualisierung/installation/" target="_blank">Dateirechte</a> an, damit das Verzeichnis beschreibar ist.';
$l['download_not_readable'] = 'Das Verzeichnis konnte nicht eingelesen werden. Bitte passen Sie die <a href="https://www.mybb.de/doku/installationaktualisierung/installation/" target="_blank">Dateirechte</a> an, damit das Verzeichnis beschreibar ist, und stellen Sie sicher, dass die URL korrekt ist. Falls Sie weiterhin Probleme feststellen, probieren Sie den vollständigen Systempfad (z.B.: /var/www/htdocs/path/to/your/old/forum/uploads/ oder C:/path/to/your/old/forum/upload/). Sorgen Sie außerdem dafür, dass der Zugriff nicht durch eine htaccess gesperrt ist.';
$l['removing_table'] = "Tabelle {1} wird entfernt.";
$l['removing_columns'] = "Spalte {1} wird von der Tabelle {2} entfernt";
$l['cleanup_header'] = "MyBB Merge System - Letzter Schritt: Aufräumen";
$l['cleanup_notice'] = "Durchführung der abschließenden Säuberung und Wartung (Dies könnte eine Weile dauern)...";
$l['finish_completion'] = "Abgeschlossen";
$l['finish_head'] = '<p>Der Import ist abschlossen. Sie können nun Ihr <a href="../">MyBB</a> oder das <a href="../{1}/index.php">Admin-CP</a> besuchen.</p>
<p>Bitte entfernen Sie dieses Verzeichnis, falls Sie keinen weiteren Import planen.</p>';
$l['finish_whats_next_head'] = "Wie geht es nun weiter?";
$l['finish_whats_next'] = 'Da ist unmöglich ist alles Berechtigungen, Einstellungen und Zähler zu importieren, prüfen Sie bitte folgende Optionen auf Korrektheit:
<ul>
<li>Alle <a href="../{1}/index.php?module=config">Einstellungen</a> überprüfen</li>
<li>Überprüfen Sie die <a href="../{1}/index.php?module=forum">Foren</a> und <a href="../{1}/index.php?module=user-groups">Benutzergruppen</a>-Berechtigungen</li>
</ul>';
$l['finish_report1'] = "Sie können im Folgenden einen detailierten Bereich des Konvertiers in verschiedenen Formaten herunterladen.";
$l['finish_report2'] = "Erstellung des Berichts";
$l['finish_report_type'] = "Bitte wählen Sie das Format des Berichts.";
$l['finish_report_type_txt'] = "Textdatei";
$l['finish_report_type_html'] = "HTML-Datei (im Browser betrachtbar)";
$l['warning_innodb'] = "Die Tabelle \"{1}\" ist im InnoDB-Format. Wir empfehlen diese Tabellen in MyISAM-Format zu konverieren, da es sonst zu erheblichen Verzögerungen beim Ausführen des Merge System kommen kann.";
$l['error_no_admin'] = 'Nur Administratoren können das Merge System ausführen. Bitte kehren Sie zur Startseite zurück und melden sich als Administrator an.';
$l['error_invalid_board'] = "Das ausgewählte Modul ist nicht vorhanden.";
$l['error_js_off'] = 'Sie scheinen Javascript deaktiviert zu haben. Das MyBB Merge System benötigt Javascript zur korrekten Funktion. Sobald Sie Javascript aktiviert haben, laden Sie diese Seite neu.';
$l['error_list'] = "Das MyBB Merge System hat folgende Probleme festgestellt";
$l['error_click_next'] = "Sobald Sie die Probleme gelöst haben, klicken Sie unten \"Weiter\".";
$l['error_database_relative'] = "Sie können keine relativen URLs für die SQLite-Datenbank verwenden. Bitte verwenden Sie einen kompletten Dateisystempfad (z.B.: /home/user/database.db) für Ihre SQLite-Datenbank.";
$l['error_database_invalid_engine'] = "Sie haben eine ungültige Datenbank-Engine gewählt. Bitte wähle Sie eine Engine aus der folgenden Liste.";
$l['error_database_cant_connect'] = "Die Verbindung zum Datenbankserver unter '{1}' konnte mit dem angegebenen Benutzernamen und Passwort nicht hergestellt werden. Sind Host und Benutzerdaten korrekt?";
$l['error_database_wrong_table'] = "Die Datenbank {1} konnte nicht unter '{2}' gefunden werden. Bitte stellen Sie sicher, dass {1} mit dem gewählten Tabellenpräfix in Ihrer Datenbank existiert.";
$l['error_database_list'] = "Es ist mindestens ein Fehler mit den eingegebenen Datenbank-Informationen aufgetreten";
$l['error_database_continue'] = "Sobald die Fehler gelöst sind, können Sie mit der Konvertierung fortfahren.";
$l['error_database_non_supported'] = 'Leider unterstützt Ihr Server keine der benötigten Datenbank-Erweiterungen';
$l['error_column_length_desc'] = 'Die alte Datenbank enthält Daten, die nicht automatisch importiert werden können. Eine ausführliche Beschreibung des Problem kann in <a href="http://docs.mybb.com/1.8/merge/column-length-check/">Dokumentation</a> gefunden werden.';
$l['error_column_length_table'] = 'Die Daten in den folgenden Spalten der Tabelle <b>{1}</b> werden gekürzt';
$l['error_column_length'] = '- {1} (Maximale Länge: {2})';
$l['loginconvert_title'] = "MyBB Merge System - Passwort-Konvertierung einrichten";
$l['loginconvert_message'] = " <div class=\"error\">\n
<h3>Fehler</h3>
Das Merge System kann nicht fortgesetzt werden, solange Sie die Datei loginconvert.php (aus dem Verzeichnis des Merge System) nicht in das Verzeichnis inc/plugins Ihres Forums kopiert wird.\n
</div>
<p>Weitere Informationen können <a href=\"http://docs.mybb.com/1.8/merge/running/#loginconvert.php-plugin\" target=\"_blank\">hier</a> gefunden werden.</p>
<p>Sobald die Datei hochgeladen worden ist, klicken Sie auf Weiter.</p>";
$l['report_txt'] = 'MyBB Merge System - Import-Bericht
--------------------------------------------------------
Willkommen beim Bericht des MyBB Merge System. Dieser
Bericht zeigt Ihnen eine kurze Übersicht über die
Ausführung des Systems.
Allgemein
-------
Forum importiert: {1}
Import gestartet: {2}
Import beendet: {3}
Datenbankabfrage-Statistik
-------------------------
Abfragen an MyBB-Datenbank: {4}
Abfragen an alte Datenbank: {5}
Gesamtdauer: {6}
Module
-------
Die folgenden Module des Konverters wurden ausgeführt:
{7}
Import-Statistik
-----------------
Das MyBB Merge System hat Folgendes Ihres Forums {8} importiert:
{9}
Fehler
------
Die folgenden Fehler wurden bei der Ausführung aufgezeichnet:
{10}
Probleme?
---------
Die Tabelle "mybb_debuglogs" Ihrer Datenbank enthält
Debug-Informationen zur Ausführung. Bei Problemen können Sie
sich an das Support-Forum wenden: https://www.mybb.de/forum/
--------------------------------------------------------
Generiert: {11}';
$l['report_html'] = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>MyBB Merge System > Import-Bericht</title>
<style type="text/css">
body {
font-family: Verdana, Arial, sans-serif;
font-size: 12px;
background: #efefef;
color: #000000;
margin: 0;
}
#container {
margin: auto auto;
width: 780px;
background: #fff;
border: 1px solid #ccc;
padding: 20px;
}
h1 {
font-size: 25px;
margin: 0;
background: #ddd;
padding: 10px;
}
h2 {
font-size: 18px;
margin: 0;
padding: 10px;
background: #efefef;
}
h3 {
font-size: 14px;
clear: left;
border-bottom: 1px dotted #aaa;
padding-bottom: 4px;
}
ul, li {
padding: 0;
}
#general p, #modules p, #import p, ul, li, dl {
margin-left: 30px;
}
dl dt {
float: left;
width: 300px;
padding-bottom: 10px;
font-weight: bold;
}
dl dd {
padding-bottom: 10px;
}
#footer {
border-top: 1px dotted #aaa;
padding-top: 10px;
font-style: italic;
}
.float_right {
float: right;
}
</style>
</head>
<body>
<div id="container">
<h1>MyBB Merge System</h1>
<h2>Import-Bericht</h2>
<p>Willkommen beim Bericht des MyBB Merge System. Dieser Bericht zeigt Ihnen eine kurze Übersicht über die Ausführung des Systems.</p>
<div id="general">
<h3>Allgemeine Statistik</h3>
<p>{1} in Ihr Forum importiert.</p>
<dl>
<dt>Import gestartet</dt>
<dd>{2}</dd>
<dt>Import beendet</dt>
<dd>{3}</dd>
</dl>
</div>
<div id="database">
<h3>Datenbankabfrage-Statistik</h3>
<dl>
<dt>Abfragen an MyBB-Datenbank</dt>
<dd>{4}</dd>
<dt>Abfragen an {8}-Datenbank</dt>
<dd>{5}</dd>
<dt>Gesamtdauer</dt>
<dd>{6}</dd>
</dl>
</div>
<div id="modules">
<h3>Module</h3>
<p>Die folgenden Module des Konverters wurden ausgeführt:</p>
<ul>
{7}
</ul>
</div>
<div id="import">
<h3>Import-Statistik</h3>
<p>Das MyBB Merge System hat Folgendes Ihres Forums {8} importiert:</p>
<dl>
{9}
</dl>
</div>
<div id="errors">
<h3>Errors</h3>
<p>Die folgenden Fehler wurden bei der Ausführung aufgezeichnet:</p>
<ul>
{10}
</ul>
</div>
<div id="problems">
<h3>Probleme?</h3>
<p>Die Tabelle "mybb_debuglogs" Ihrer Datenbank enthält Debug-Informationen zur Ausführung. Bei Problemen können Sie sich an das <a href="https://www.mybb.de/forum/" target="_blank">Support-Forum</a> wenden.</p>
</div>
<div id="footer">
<div class="float_right">MyBB © 2002-{12} MyBB Group</div>
<div>Generiert {11}</div>
</div>
</div>
</body>
</html>';
| 8f2a2a318a3bb4218a0d99ff78b33d9b704b246e | [
"PHP"
] | 1 | PHP | mybb-de/MyBB-Merge-German | aa1f8af957e795ed3e2f907c80fa0d887e28a970 | c4b617c1b6cbd9828158906f5a314eaa7270bd11 | |
refs/heads/master | <repo_name>zjuchenlong/Coding<file_sep>/java/algorithms/ch2/SelectionSort.java
package ch2;
import edu.princeton.cs.algs4.*;
public class SelectionSort {
public static void sort(Comparable[] a)
{//sort a[] into increasing order
int N = a.length;
for(int i=0;i< N;i++)
{
int min = i;
for(int j=i+1; j< N;j++)
if(less(a[j], a[min]))
min = j;
exch(a, i, min);
}
}
private static boolean less(Comparable w, Comparable v)
{
return w.compareTo(v) < 0;
}
private static void exch(Comparable[] a, int i, int j)
{
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static void show(Comparable[] a)
{
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println(" ");
}
private static boolean isSorted(Comparable[] a)
{
for(int i=1;i<a.length;i++)
if(less(a[i], a[i-1]))
return false;
return true;
}
public static void main(String[] args)
{
String[] a = In.readStrings();
sort(a);
assert isSorted(a);
show(a);
}
}
<file_sep>/java/algorithms/ch1/Bag.java
package ch1;
import java.util.Iterator;
import edu.princeton.cs.algs4.StdIn;
public class Bag<Item> implements Iterable<Item> {
private Node first;
private int N;
private class Node
{
Item item;
Node next;
}
public void add(Item item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
N++;
}
public int size()
{
return N;
}
public Iterator<Item> iterator()
{
return new listIterator();
}
private class listIterator implements Iterator<Item>
{
private Node current = first;
public boolean hasNext() {return current!=null;}
public Item next()
{
Item item = current.item;
current = current.next;
return item;
}
public void remove() {}
}
public static void main(String[] args)
{
Bag<Double> bag = new Bag<Double>();
while(!StdIn.isEmpty())
{
bag.add(StdIn.readDouble());
}
double sum = 0.0;
for(double i:bag)
{
sum += i;
System.out.println(i);
}
System.out.println("Sum of the number are "+sum);
}
}
<file_sep>/java/algorithms/ch1/UFQuickUnion.java
package ch1;
import edu.princeton.cs.algs4.StdIn;
public class UFQuickUnion {
private int[] id; // id store the root number of this node
private int count;
public UFQuickUnion(int N)
{
count = N;
id = new int[N];
for(int i=0;i<N;i++)
id[i] = i;
}
public int count() {return count;}
public boolean connected(int p, int q)
{
return find(p) == find(q);
}
//for the worst case, the number of array access is 1 plus
// twice the depth of the node corresponding to the given site
public int find(int p)
{
while(p != id[p])
p = id[p];
return p;
}
public void union(int p, int q)
{
int pRoot = find(p);
int qRoot = find(q);
if(pRoot == qRoot) return;
id[pRoot] = qRoot;
count--;
}
public static void main(String[] args)
{
int N = StdIn.readInt();
UFQuickUnion uf = new UFQuickUnion(N);
while(!StdIn.isEmpty())
{
int p = StdIn.readInt();
int q = StdIn.readInt();
if(uf.connected(p, q))
continue;
uf.union(p,q);
System.out.println(p + " " + q);
}
System.out.println(uf.count() + " components.");
}
}
<file_sep>/java/algorithms/ch2/ShellSort.java
package ch2;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.In;
public class ShellSort {
public static void sort(Comparable[] a)
{
int N = a.length;
int h =1;
while(h < N/3)
h = 3 * h + 1; // 1, 4, 13, 40, 121, 364, 1093, ...
while(h >= 1)
{ //h-sort the array
for(int i=h; i<N; i++)
{
for(int j=i; j >=h && less(a[j], a[j-h]); j -=h)
exch(a, j, j-h);
}
h = h/3;
}
}
private static boolean less(Comparable w, Comparable v)
{
return w.compareTo(v) < 0;
}
private static void exch(Comparable[] a, int i, int j)
{
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static boolean isSorted(Comparable[] a)
{
for(int i=1;i<a.length;i++)
if(less(a[i], a[i-1]))
return false;
return true;
}
private static void show(Comparable[] a)
{
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println(" ");
}
public static void main(String[] args)
{
String[] a = In.readStrings();
sort(a);
assert isSorted(a);
show(a);
}
}
<file_sep>/python/sparse/sparse_csr_matrix.py
import numpy as np
def matrix2csr(matrix):
assert matrix.ndim == 2, "matrix convert to csr_matrix should be 2 dimension"
data = []
indices = []
indptr = []
indptr.append(0)
for row in matrix:
for index, elem in enumerate(row):
if elem != 0:
data.append(elem)
indices.append(index)
indptr.append(len(indices))
return np.array(data), np.array(indices), np.array(indptr)
# there is no shape parameter, so the shape is derived from indices
def csr2matrix(data, indices, indptr):
assert len(data) == len(indices), "data lenght should same as indices"
row_num = len(indptr) - 1
col_num = np.max(indices) + 1 # because col i index is start from 0
rval = np.zeros((row_num, col_num), dtype = data.dtype)
for row_index in xrange(row_num):
rval[row_index, indices[indptr[row_index]:indptr[row_index + 1]]] \
= data[indptr[row_index]:indptr[row_index + 1]]
return rval
mat = np.array([[1, 0, 2], [0, 0, 3], [4, 5, 6]])
print mat
data, indices, indptr = matrix2csr(mat)
recover = csr2matrix(data, indices, indptr)
print recover
| 7804ac47fdcbd080279c107b7d54e68a778b64d6 | [
"Java",
"Python"
] | 5 | Java | zjuchenlong/Coding | d57ce3b5fe253e4acf410427e153370a59ac0a96 | 3140e9d6ff030aa1331698a200c3881b39e505cf | |
refs/heads/master | <repo_name>chuckdishmon/patrick-temp<file_sep>/src/reducers/user/user.test.js
import * as types from '../../ActionTypes';
import users from './';
const unauthState = { status: 'UNAUTH', access: 'guest' };
it('should be defined', () => {
expect(users).not.toBe(undefined);
});
it('should initialize state if left undefined', () => {
const action = { type: '@@INIT' };
const nextState = users(undefined, action);
expect(nextState).toEqual(unauthState);
});
it('should subscribe to LOGIN_SUCCESS and add user details', () => {
const prevState = { status: 'PENDING' };
const action = {
type: 'LOGIN_SUCCESS',
user: {
name: 'Pat',
access: 'admin',
token: '<PASSWORD>'
}
};
const expectedState = {
...action.user,
status: 'AUTH'
};
const nextState = users(prevState, action);
expect(nextState).toEqual(expectedState);
});
it('should subscribe to LOGIN_PENDING and update user status', () => {
const prevState = unauthState;
const action = {
type: 'LOGIN_PENDING'
};
const expectedState = {
status: 'PENDING'
};
const nextState = users(prevState, action);
expect(nextState).toEqual(expectedState);
});
it('should subscribe to LOGIN_FAILURE and update user status', () => {
const prevState = { status: 'PENDING' };
const action = {
type: 'LOGIN_FAILURE'
};
const nextState = users(prevState, action);
expect(nextState).toEqual(unauthState);
});
<file_sep>/src/containers/RSVPForm/RSVPFormComponent.js
import React from 'react';
import { Field } from 'redux-form';
const Form = ({ handleSubmit, reset }) => {
const submit = (e) => {
handleSubmit(e);
reset();
}
return (
<form onSubmit={ submit }>
<div>
<label htmlFor="name">username</label>
<Field name="name" component="input" type="text" />
</div>
<div>
<label htmlFor="password">password</label>
<Field name="password" component="input" type="text" />
</div>
<button type="submit">RSVP</button>
</form>
);
};
export default Form;
<file_sep>/src/containers/App/index.js
import React from 'react';
import { Match } from 'react-router';
import AdminOnly from '../../hocs/AdminOnly';
import LandingPage from '../LandingPage';
import GuestManagement from '../GuestManagement';
export default (props) => (
<div>
<Match exactly pattern='/' component={ LandingPage } />
<Match pattern='/guest-management' component={ AdminOnly(GuestManagement) }/>
</div>
);
| 5ecda15c130bc90263f32f57743722ddd9316d8d | [
"JavaScript"
] | 3 | JavaScript | chuckdishmon/patrick-temp | ff279ba5f8961b9a20e5f53cfff88bced1f4c5aa | be1192ddea46960134d925c2489a60cf91a8ac6f | |
refs/heads/master | <file_sep>package com.itech.test.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "category")
public class SportCategory {
@Id
@GeneratedValue
private Long category_id;
private String category_name;
@OneToOne(mappedBy = "sportCategory")
private Student student;
@OneToMany(mappedBy = "sportCategory", cascade = CascadeType.ALL)
private Set<Sport> sports = new HashSet<Sport>();
public Long getCategory_id() {
return category_id;
}
public void setCategory_id(Long category_id) {
this.category_id = category_id;
}
public String getCategory_name() {
return category_name;
}
public void setCategory_name(String category_name) {
this.category_name = category_name;
}
public Set<Sport> getSports() {
return sports;
}
public void setSports(Set<Sport> sports) {
this.sports = sports;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
<file_sep>package com.itech.test.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.itech.test.entity.Sport;
import com.itech.test.service.StudentSportService;
@RestController
@RequestMapping(value = "/rest")
public class StudentSportController {
@Autowired
private StudentSportService sportService;
@RequestMapping(value = "/getCategory/{studentId}")
public @ResponseBody
String getSportCategory(@PathVariable Long studentId) {
return sportService.getSportCategory(studentId);
}
@RequestMapping(value = "/getSportList/{studentId}")
public @ResponseBody
List<String> getSportList(@PathVariable Long studentId) {
List<String> sportNames = null;
List<Sport> sports = sportService.getSportList(studentId);
if (sports != null && sports.size() > 0) {
sportNames = new ArrayList<String>();
for (Sport sport : sports) {
sportNames.add(sport.getSport_name());
}
}
return sportNames;
}
}
<file_sep>package com.itech.test.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.itech.test.dao.StudentSportDAO;
import com.itech.test.entity.Sport;
@Service
public class StudentSportServiceImpl implements StudentSportService{
@Autowired
private StudentSportDAO sportDAO;
@Transactional
public String getSportCategory(Long studentId) {
return sportDAO.getSportCategory(studentId);
}
@Transactional
public List<Sport> getSportList(Long studentId) {
return sportDAO.getSportList(studentId);
}
}
<file_sep># springhibernate_poc
spring hibernate rest intergarion
<file_sep>package com.itech.test.dao;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.itech.test.entity.Sport;
import com.itech.test.entity.SportCategory;
import com.itech.test.entity.Student;
@Repository
public class StudentSportDAOImpl implements StudentSportDAO {
@Autowired
private SessionFactory sessionFactory;
public String getSportCategory(Long studentId) {
String sportCategory = null;
Student student = (Student) sessionFactory.getCurrentSession().get(
Student.class, studentId);
if (null != student) {
SportCategory category = student.getSportCategory();
if (category != null) {
sportCategory = category.getCategory_name();
}
}
return sportCategory;
}
public List<Sport> getSportList(Long studentId) {
Set<Sport> sports = null;
Student student = (Student) sessionFactory.getCurrentSession().get(
Student.class, studentId);
if (null != student) {
sports = student.getSports();
}
List<Sport> list = new ArrayList<Sport>(sports);
return list;
}
}
| c6e8b2bf197019352734960ccdbe50ab085583cd | [
"Markdown",
"Java"
] | 5 | Java | rampalrao/springhibernate_poc | 62840546c86292f6e9e52b77eb0e96cf2a94198d | 986f9426916355f119b0ea58eff47435dae7027e | |
refs/heads/master | <repo_name>KleeGroup-BaseCamp/HomeDuino<file_sep>/HomeDuino.ino
/*
* HomeAgain - Main Home Duino
*
*
*
*
*/
//#define MOISTURE_SENSOR
//#define MOISTURE_PIN 1
#define TEMPERATURE_SENSOR
#define TEMPERATURE_PIN 0
//#define PRESENCE_SENSOR
//#define PRESENCE_PIN 2
#ifdef TEMPERATURE_SENSOR
int temperatureAnalog ;
float temperatureValue;
int temperatureB=3975; //B value of the thermistor
float temperatureResistance;
#endif
#ifdef MOISTURE_SENSOR
int moistureAnalog;
#endif
#ifdef PRESENCE_SENSOR
int presence;
int lastPresence;
boolean presenceInit = false;
#endif
void setup(){
Serial.begin(9600);
#ifdef MOISTURE_SENSOR
// Serial.println("Initializing moisture sensor");
pinMode(MOISTURE_PIN, INPUT);
#endif
#ifdef TEMPERATURE_SENSOR
// Serial.println("Initializing temperature sensor");
pinMode(TEMPERATURE_PIN, INPUT);
#endif
#ifdef PRESENCE_SENSOR
// Serial.println("Initializing presence sensor");
pinMode(PRESENCE_PIN, INPUT);
#endif PRESENCE_SENSOR
pinMode(13, OUTPUT);
}
void loop(){
digitalWrite(13, HIGH);
delay(1000);
#ifdef TEMPERATURE_SENSOR
temperatureAnalog=analogRead(TEMPERATURE_PIN);
temperatureResistance=(float)(1023-temperatureAnalog)*10000/temperatureAnalog; //get the resistance of the sensor;
temperatureValue=1/(log(temperatureResistance/10000)/temperatureB+1/298.15)-273.15;//convert to temperature via datasheet ;
send("TEMP", "temperature.celsius", temperatureValue);
// Serial.print("temperature=temperature.celsius=");
// Serial.println(temperatureValue);
#endif
#ifdef MOISTURE_SENSOR
moistureAnalog=analogRead(MOISTURE_PIN);
send("MOISTURE", "moisture", moistureAnalog);
// Serial.print("moisture=moisture=");
// Serial.println(moistureAnalog);
#endif
#ifdef PRESENCE_SENSOR
presence = digitalRead(PRESENCE_PIN);
if(!presenceInit){
presenceInit = true;
// Serial.print("presence=presence=");
// Serial.println(presence);
send("PRESENCE", "presence", presence);
lastPresence=presence;
}
else if(presence != lastPresence){
// Serial.print("presence=presence=");
// Serial.println(presence);
send("PRESENCE", "presence", presence);
}
#endif PRESENCE_SENSOR
digitalWrite(13, LOW);
delay(1000);
}
void send(String id, String unit, int value){
Serial.println(id + "=" + unit + "=" + String(value, DEC));
}
| 21e14bf2217a49335dd2ecd04bc59888f057eee6 | [
"C++"
] | 1 | C++ | KleeGroup-BaseCamp/HomeDuino | 99d45c9a6ab5989696f96c5ec2cdcbb752bfe723 | a5b8844beb39914a6ef7744ec8ac381300f694c9 | |
refs/heads/master | <file_sep>package com.javabk.han;
import java.util.Scanner;
import java.lang.String;
public class QuanXe {
public static void main(String[] args) {
int[] args1 = new int[]{1,2,3,4,5,6,7,8};
Scanner scn = new Scanner(System.in);
String vitri;
char[] args2 = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
String[][] arr = new String[8][8];
for (int i = 0; i < args1.length; i++) {
for (int j = 0; j < args2.length; j++) {
arr[i][j] = args1[i] + String.valueOf(args2[j]);
System.out.print(arr[i][j]);
if (j == arr.length - 1) System.out.println();
//-------------------------------------
}
}
vitri=scn.next();
for(int i=0;i<args1.length;i++) {
if(args1[i]!=(int)vitri.charAt(0)-48) System.out.print(args1[i]+String.valueOf(vitri.charAt(1))+"\t");
}
for(int i=0;i<args2.length;i++){
if(args2[i]!=vitri.charAt(1)) System.out.print(String.valueOf(vitri.charAt(0))+args2[i]+"\t");
}
}
}
<file_sep> package com.javabk.thu;
import java.util.Scanner;
public class CauLenhLap {
public static void soNguyenTo(){
Scanner scanner = new Scanner(System.in);
int number =2;
int demSoNguyenTo= 0;
while (demSoNguyenTo<20){
for (int i = 2; i <number -1 ; i++) {
if (number%i ==0){
number++;
i=2;
}
}
System.out.println(number + " ");
demSoNguyenTo++;
number++;
}
}
public static void hienThiCacLoaiHinh(){
Scanner scanner = new Scanner(System.in);
System.out.println("Menu");
System.out.println("1. Print the rectangle");
System.out.println("2. Print the square triangle");
System.out.println("3. Print isosceles triangle");
System.out.println("0. Exit");
System.out.println("Enter your choice: ");
while (true) {
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Draw the square");
System.out.println("* * * * * *");
System.out.println("* * * * * *");
System.out.println("* * * * * *");
System.out.println("* * * * * *");
break;
case 2:
System.out.println("Draw the triangle");
System.out.println("******");
System.out.println("*****");
System.out.println("****");
System.out.println("***");
System.out.println("**");
System.out.println("*");
break;
case 3:
System.out.println("Draw the rectangle");
System.out.println("* * * * * ");
System.out.println(" * * * * ");
System.out.println(" * * * ");
System.out.println(" * ");
break;
case 0:
System.exit(0);
default:
System.out.println("No choice!");
}
}
}
public static void soNguyenToNhoHon100() {
Scanner scanner = new Scanner( System.in);
System.out.println("Các số nguyên tố nhỏ hơn 100 là: ");
for (int i = 0; i < 100; i++) {
if (kiemtrasonguyen(i)) {
System.out.print(i + " ");
}
}
}
public static boolean kiemtrasonguyen(int n) {
if (n < 2) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void UCLN(){
Scanner scanner = new Scanner(System.in);
int a,b;
System.out.println("nhap so nguyen duong a la:");
a = scanner.nextInt();
System.out.println("nhap so nguyen duong b la:");
b = scanner.nextInt();
a = Math.abs(a);
b = Math.abs(b);
if (a ==0 || b==0);
while (a != b) {
if (a > b)
a = a - b;
else
b = b - a;
}
System.out.println("UCLN:" +a);
}
}
<file_sep>package com.ateach.pdf2.collectionFrameWork.hashandtree;
import java.util.Map;
import java.util.TreeMap;
public class TreeMapTest {
static void insertAndPrint(TreeMap<Integer, String> map) {
int[] array = {1, -1, 0, 2, -2};
for (int x : array) {
map.put(x, Integer.toString(x));
}
for (int k : map.keySet()) {
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main(String[] args) {
// TreeMap<Integer, String> map = new TreeMap<Integer, String>();
// insertAndPrint(map);
TreeMap<Integer, Integer> hv = new TreeMap<Integer, Integer>();
hv.put(1, 7);
hv.put(5, 9);
hv.put(4, 3);
for (Map.Entry v : hv.entrySet()) {
System.out.println("value: " + v.getValue()+ "key "+v.getKey());
}
}
}
<file_sep>package com.javabk.khai;
import java.util.Scanner;
public class TimGiaTriNhoNhatTrongMang {
public static void main(String[] args) {
int[] array = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("Nhap gia tri cho mang :");
for (int i = 0; i < array.length; i++) {
array[i] = sc.nextInt();
}
int a = array[0];
for (int i = 0; i < array.length; i++){
if (a > array[i]) {
a = array[i];
}
}
System.out.println("Gia tri nho nhat trong mang la : \t" +a);
}
}
<file_sep>package com.ateach.pdf2.oop.usequizabstractvsinterface.fruit;
import com.ateach.pdf2.oop.usequizabstractvsinterface.edible.Edible;
public abstract class Fruit implements Edible {
}
<file_sep>package com.javabk.khai;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Method {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Bai tap chuoi Pentagonal");
int n;
System.out.println("Nhap so n");
n = scan.nextInt();
System.out.println("Chuoi Pentagonal: ");
Pentagonal(n);
System.out.println("------------------------------");
System.out.println("Bai tap tong cac phan tu trong 1 so");
System.out.println("Nhap so nguyen: ");
int x = scan.nextInt();
System.out.println("Tong cac so trong so nguyen la: ");
System.out.println(sumDigits(x));
System.out.println("-------------------------------------");
System.out.println("Bai tap sao xep 3 so thuc");
System.out.println("Nhap 3 so thuc");
double n1, n2, n3;
n1 = scan.nextDouble();
n2 = scan.nextDouble();
n3 = scan.nextDouble();
System.out.println("sap xep 3 so: ");
displaySortedNumbers(n1, n2, n3);
System.out.println("\n--------------------------------------");
System.out.println("Bai tap ve so doi xung");
System.out.println("Nhap mot so a bat ky: ");
int a = scan.nextInt();
System.out.println("So dao nguoc cua so x: " + reverse(a));
System.out.println("Xet tinh doi xung cua x: " + isPalindrome(a));
System.out.println("--------------------------------------");
System.out.println("Bai tap chuyen doi tu feet qua metters");
System.out.println("Nhap so feet con chuyen: ");
double feet = scan.nextDouble();
System.out.println(feet + " feet = " + feetToMeter(feet) + " metters");
System.out.println("Nhap so metters can chuyen: ");
double metters = scan.nextDouble();
System.out.println(metters + " metters = " + meterToFeet(metters) + " feet");
System.out.println("---------------------------------------");
System.out.println("Kiem tra so nguyen to");
System.out.println("Nhap mot so can kiem tra: ");
int soNT=scan.nextInt();
System.out.println("So vua nhap la so nguyen to: "+isPrime(soNT));
System.out.println("--------------------------------------");
System.out.println("Bai tap hien thi ma tran nhi phan");
System.out.println("Nhap canh cua ma tran");
int canh=scan.nextInt();
System.out.println("Ma tran nhi phan "+canh+"x"+canh+" :");
printMatrix(canh);
System.out.println("-------------------------------------");
System.out.println("Bai tap dem so ki tu trong chuoi");
System.out.println("Nhap vao 1 chuoi");
String s=scan.nextLine();
System.out.println("So ki tu trong chuoi la: "+countLetters(s));
System.out.println("----------------------------------------");
System.out.println("Bai tap dem so ngay tu nam XXXX den nam YYYY ");
System.out.println("Nhap nam thu 1: ");
int year1=scan.nextInt();
System.out.println("Nhap nam thu 2: ");
int year2= scan.nextInt();
System.out.println("So ngay trong khoang thoi gian tu nam "+year1+" den nam "+year2+" la: "+countNumberOfDaysInYeartoYear(year1,year2)+" ngay");
System.out.println("--------------------------------------------");
}
public static void Pentagonal(int x) {
int pen;
for (int i = 1; i < x; i++) {
pen = i * (3 * i - 1) / 2;
System.out.print(pen + ", ");
}
System.out.println(x * (x * 3 - 1) / 2);
}
public static long sumDigits(long n) {
int count = 0;
while (n > 0) {
count += n % 10;
n = n / 10;
}
return count;
}
public static void displaySortedNumbers(double num1, double num2, double num3) {
double temp;
if (num1 > num2) {
temp = num1;
num1 = num2;
num2 = temp;
}
if (num2 > num3) {
temp = num2;
num2 = num3;
num3 = temp;
}
if (num1 > num2) {
temp = num1;
num1 = num2;
num2 = temp;
}
System.out.print(num1 + ",");
System.out.print(num2 + ",");
System.out.print(num3);
}
public static int reverse(int number) {
int count = 0;
while (number > 0) {
count = count * 10 + number % 10;
number /= 10;
}
return count;
}
public static boolean isPalindrome(int number) {
if (reverse(number) == number) return true;
else return false;
}
public static double feetToMeter(double feet) {
return 0.305 * feet;
}
public static double meterToFeet(double meter) {
return meter * 3.279;
}
public static boolean isPrime(int number){
int count=0;
for (int i=1;i<Math.sqrt(number);i++){
if (number%i==0){
count+=1;
}
}
if (count==1) return true;
else return false ;
}
public static void printMatrix(int n){
int[][] matrix=new int[n][n];
Random rand = new Random();
for (int i =0;i<matrix.length;i++){
for (int j=0;j<matrix[i].length;j++){
matrix[i][j]=rand.nextInt(2);
}
}
for (int i=0;i<matrix.length;i++)
System.out.println(Arrays.toString(matrix[i]));
}
public static int countLetters(String s){
int count=0;
for (int i=0;i<s.length();i++){
count+=1;
}
return count;
}
public static boolean ktNamNhuan(int year) {
if (year % 4 == 0 && year % 100 != 0) {
return true;
}
else{
if (year % 400 == 0 && year % 100 == 0) {
return true;
}
else {
return false;
}
}
}
public static int numberOfDaysInAYear(int year){
int day;
if (ktNamNhuan(year)){
day=366;
}
else day=365;
return day;
}
public static int countNumberOfDaysInYeartoYear(int year1, int year2){
int count=0;
for (int i=year1;i<=year2;i++){
count+=numberOfDaysInAYear(i);
}
return count;
}
}
<file_sep>package com.ateach.pdf1.quizz.reviewPf1;
public class ArrayMax {
int arrayMaximalAdjacentDifference(int[] inputArray) {
int max=0;
for( int i = 1 ; i < inputArray.length ; i++ ){
max = Math.max(max, Math.abs(inputArray[i] - inputArray[i-1]));
}
return max;
}
}
<file_sep>package com.ateach.pdf1.basic.method;
public class BaiTap {
/* #1. Given the string, check if it is a palindrome.*/
public static boolean isPalindrome(String str) {
boolean isPa = false;
System.out.println(str.length());
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != str.charAt(str.length() - i - 1)) {
isPa = false;
break;
} else {
isPa = true;
}
}
return isPa;
}
/* #2.Given n and firstNumber, find the number which is written in the radially opposite position to firstNumber.*/
/* #3. After they became famous, the CodeBots all decided to move to a new building and live together.
The building is represented by a rectangular matrix of rooms. Each cell in the matrix contains
an integer that represents the price of the room. Some rooms are free (their cost is 0),
but that's probably because they are haunted, so all the bots are afraid of them. That is why any room
that is free or is located anywhere below a free room in the same column is not considered suitable for
the bots to live in. Help the bots calculate the total price of all the rooms that are suitable for them.*/
public static int giaPhong() {
int[][] rooms = {{0, 1, 1, 2},
{0, 5, 0, 0},
{2, 0, 3, 3}};
int sum = 0;
for (int cot = 0; cot < rooms[0].length; cot++) {
for (int hang = 0; hang < rooms.length; hang++) {
if (rooms[hang][cot] == 0) {
break;
} else {
sum = sum + rooms[hang][cot];
}
}
}
return sum;
}
}
<file_sep>package com.ateach.pdf2.oop.exercise;
public class Quiz1 {
final void useFinal(){
System.out.println("final method");
}
void nonUseFinal(){
System.out.println("non filnal method");
}
}
class Exam extends Quiz1{
}<file_sep>package com.ateach.pdf2.oop.exercise;
interface Quiz5a {
int id = 100; //must initialed
//protected String name;
//private String name;
public String name = "name";
}
interface Quiz5b {
String address = "DN";
}
class TestQuiz5 {
public static void main(String[] args) {
System.out.println(Quiz5a.id);
}
}
//c.
class implementTwoInterface implements Quiz5a, Quiz5b {
public static void main(String[] args) {
System.out.println("id: " + Quiz5a.id + "address: " + Quiz5b.address);
}
}
// d.
abstract class AbsClass implements Quiz5b {
abstract void show();
}
<file_sep>package com.ateach.pdf1.project.furamaStruct;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.Scanner;
public class FuramaProject {
private static Scanner scn = new Scanner(System.in);
static final String TIME_OPEN = "9PM";
public static void main(String[] args) {
VillaManager vl = new VillaManager();
int enter;
do{
System.out.println("-------------------MENU--------------------");
System.out.println("* 1. Check in *");
System.out.println("* 2. Swimming Pool Opening Times *");
System.out.println("* 3. Service *");
System.out.println("* 3.1. Swimming Pool Service *");
System.out.println("* 3.2. Rent day *");
System.out.println("* 4. ManagerPerson Villa *");
System.out.println("* 4.1. Add new bed and swimming pool*");
System.out.println("* 4.2. Display info villa *");
System.out.println("* 0. Exit *");
System.out.println("* 4. Continues *");
System.out.println("-------------------------------------------");
System.out.print(" Please choose: ");
String choose = scn.next();
switch (choose){
case "1":
System.out.println("Enter name of customer: ");
String customerName = scn.next();
System.out.println("Enter age of customer: ");
int customerAge = scn.nextInt();
System.out.println("Enter V (Villa) or H(House)");
String type = scn.next();
System.out.println("Enter day");
int day = scn.nextInt();
infoCustomer(customerName,customerAge);
caculatorForRent(type.toUpperCase(),day);
break;
case "2":
swimmingPoolOpenTimes(TIME_OPEN);
break;
case "3.1":
System.out.println("Enter time (format: hh:mm): ");
String time = scn.next();
swimmingPoolService(time);
break;
case "3.2":
System.out.println("Enter money");
float money = scn.nextFloat();
System.out.println("Enter V (Villa) or H(House)");
String types = scn.next();
dayForRent(types.toUpperCase(), money);
break;
case "4.1":
System.out.println("Enter total villa in furamaOop resort");
int total = scn.nextInt();
vl.addNewVilla(total);
break;
case "4.2":
vl.displayVillaInfo();
break;
default:
System.out.println("Please enter valid number:");
break;
}
System.out.println("Enter 0 to exit - enter 4 to continues");
enter = scn.nextInt();
}while (enter != 0);
}
public static void infoCustomer(String name, int age){
System.out.println("-----------Check in info-----------");
System.out.println("Name:\t" + name);
System.out.println("Age:\t "+ age);
}
public static void swimmingPoolOpenTimes(String time ){
System.out.println("Swimming pool open at: "+time);
}
public static void swimmingPoolService(String time ){
LocalTime localTime = LocalTime.parse(time, DateTimeFormatter.ofPattern("HH:mm"));
int hour = localTime.get(ChronoField.CLOCK_HOUR_OF_DAY);
int minute = localTime.get(ChronoField.MINUTE_OF_HOUR);
int mSum = 9*60;
int cSum = hour * 60 + minute;
int rTime = mSum - cSum;
String message ="";
if(rTime !=0){
int hTime = rTime/60;
int mTime = rTime%60;
if(hTime != 0 && mTime !=0){
message = message + hTime +" house " +mTime +" minutes";
}else if(hTime == 0 && mTime !=0){
message = message + mTime +" minutes";
}
System.out.println("Please wait " + message);
}else{
System.out.println("Welcome!!!");
}
}
public static void caculatorForRent(String type, int date){
switch (type){
case "V":
System.out.println("You pay "+rentCharge(type, date)+" USD/" +date+" days");
break;
case "H":
System.out.println("You pay "+rentCharge(type, date)+"USD/" +date+" days");
break;
default:
System.out.println("No service");
break;
}
}
public static float rentCharge(String type, int date){
float cost = 0;
if (type.equals("V")){
cost = 10*(float)date;
}else if(type.equals("H")){
cost = 5*(float)date;
}
return cost;
}
public static void dayForRent(String type, float money){
switch (type){
case "V" :
System.out.println("You have "+ (int)money/10+" days ");
break;
case "H":
System.out.println("You have "+(int)money/5+" days");
break;
}
}
}
<file_sep>package com.ateach.pdf2.oop.staticexample.example1;
public class ExampleStatic {
int schoolId = 111;
static String schoolName = "Oxford";
void schoolInfo(){
System.out.println("id" + schoolId + "name "+ schoolName);
}
}
class Manager {
public static void main(String[] args) {
System.out.println(ExampleStatic.schoolName);
ExampleStatic ex = new ExampleStatic();
ex.schoolInfo();
System.out.println(ex.schoolId);
// System.out.println(ex.);
}
}
<file_sep>package com.javabk.dung;
import java.util.Scanner;
public class XoaPhanTu {
static Scanner sc = new Scanner(System.in);
public static void xoaPhanTuVaoMang(){
int kichThuoc;
boolean kiemTra;
//Nhập mảng
do {
System.out.print("Nhap so phan tu cua mang: 1");
kichThuoc = sc.nextInt();
if (kichThuoc <= 0) {
kiemTra = true;
} else kiemTra = false;
} while (kiemTra);
int[] array = new int[kichThuoc];
System.out.println("Nhap lan luot cac phan tu trong mang: ");
nhapMang(array);
//Nhập giá trị cần xóa và kiểm tra có bao nhiêu giá trị đó trong mảng
int soCanXoa, count=0;
boolean ktSoCanXoa = true;
do {
System.out.print("Nhập giá trị cần xóa ");
soCanXoa = sc.nextInt();
for (int i = 0; i < array.length; i++) {
if (soCanXoa == array[i]) {
ktSoCanXoa = false;
count++;
}
}
if (ktSoCanXoa == true) {
System.out.println("Không tồn tại số " + soCanXoa + " trong mảng. Vui lòng nhập lại");
}
} while (ktSoCanXoa);
//Tiến hành xóa
int doDaiMoi = array.length-count;
int[] arrayMoi = new int[doDaiMoi];
int j=0;
for(int xetMangMoi=0; xetMangMoi<arrayMoi.length; xetMangMoi++){
if (soCanXoa != array[j]){
arrayMoi[xetMangMoi]=array[j];
}else {
j++;
arrayMoi[xetMangMoi] = array[j];
}
j++;
}
//In ra mảng sau khi xóa
System.out.println("Mảng sau khi xóa là:");
for (int scan : arrayMoi) {
System.out.print(scan + " ");
}
}
public static void nhapMang(int[] mang){
for (int i=0; i<mang.length; i++){
mang[i] = sc.nextInt();
}
}
}
<file_sep>package com.ateach.pdf2.oop.packageexample.package2;
import com.ateach.pdf2.oop.packageexample.package1.*; // path access to package 1
public class ClassOfPackage2 {
public static void main(String[] args) {
ClassOfPackage1 objPk1 = new ClassOfPackage1();
System.out.println(objPk1.variablePackage1);
objPk1.info();
}
}
<file_sep>package com.javabk.han.newpkg;
public class Recusiver1 {
public static void main(String[] srgs) {
System.out.println(Sum(3));
}
public static float Sum(float n) {
if (n == 1)
return 1;
float tong =(1 / n) + Sum(n - 1);
return tong;
}
}
<file_sep>package com.ateach.pdf2.fileExample;
import java.io.File;
import java.util.*;
public class FinePercentVowel {
public static void readContentFromFile(int n) {
String pathName = "E:\\testfile\\vowel.txt";
File fl = new File(pathName);
ArrayList<String> sr = new ArrayList<>();
try {
Scanner sc = new Scanner(fl);
while (sc.hasNextLine()) {
sr.add(sc.nextLine());
}
} catch (Exception e) {
e.printStackTrace();
}
String[] st = new String[sr.size()];
for (int i = 0; i < sr.size(); i++) {
st[i] = sr.get(i);
}
for (int j = 0; j < st.length; j++) {
System.out.println("Line " + (j + 1));
fineVowel(st[j], n);
System.out.println();
}
}
public static void fineVowel(String st, int n) {
String[] stn = new String[st.length() - n];
for (int i = 0; i < st.length() - n; i++) {
System.out.println(st);
stn[i] = st.charAt(i) + "" + st.charAt(i + 1) + "" + st.charAt(i + 2);
int total = 0;
for (int j = 0; j < stn[i].length() - 1; j++) {
if (stn[i].charAt(j) == 'a' || stn[i].charAt(j) == 'e' || stn[i].charAt(j) == 'i' || stn[i].charAt(j) == 'o' || stn[i].charAt(j) == 'u' || stn[i].charAt(j) == 'y') {
total = total + 1;
}
}
System.out.println(stn[i] + " (freq = " + total + "/3 = " + (float) total / 3 * 100 + ")");
}
}
public static void main(String[] args) {
readContentFromFile(3);
}
}
<file_sep>package com.ateach.designpattern.stragety;
public interface QuackBehavior {
public void quack();
}
<file_sep>package com.ateach.pdf1.basic.vonglap;
public class SoNguyenTo {
// TODO code application logic here
public static void inRaSoNguyenTo(){
for(int i = 0; i < 20; i ++){
if(kiemTraSoNguyenTo2(i)){
System.out.println(i);
}
}
}
public static boolean kiemTraSoNguyenTo(int n){
if( n == 0 || n == 1) return false;
for(int i = 2; i<= n -1; i ++){
if ( n % i == 0) return false;
}
return true;
}
public static boolean kiemTraSoNguyenTo2(int n)
{
// Neu n < 2 thi khong phai la SNT
if (n < 2){
return false;
}
// Neu n = 2 la SNT
if (n == 2){
return true;
}
// Neu n la so chan thi ko phai la SNT
if (n % 2 == 0){
return false;
}
// Lap qua cac so le
for (int i = 3; i < (n - 1); i += 2){
if (n % i == 0){
return false;
}
}
return true;
}
}
<file_sep>package com.ateach.pdf2.oop.accessexample.privateaccess;
class PrivateAcess {
private int data = 40;
private void msg() {
System.out.println("Hello java");
}
}
class Simple {
public static void main(String args[]) {
PrivateAcess obj = new PrivateAcess();
// System.out.println(obj.data); // can't access to field private
// obj.msg(); //// can't access to method private
// we will access private method and field through geter and setter;
}
}<file_sep>package com.ateach.pdf2.oop.usequizabstractvsinterface.animal;
public abstract class Animal {
public abstract String makeSound();
}
<file_sep>package com.ateach.pdf2.collectionFrameWork.stackandqueu;
import java.util.ArrayList;
import java.util.Stack;
class StackCls {
public static void main(String[] args) {
Stack<Integer> st = new Stack<Integer>();
st.push(1);
st.push(2);
st.push(3);
for (Integer i : st) {
System.out.println(i);
}
// System.out.println(st.toArray().toString());
System.out.println("pop method: " + st.pop()); // Trả về phần tử đầu tiên của Stack, Và xóa nó ra khỏi stack
System.out.println("peek method: " + st.peek()); //Trả về phần tử đầu tiên của Stack, nhưng không xóa nó ra khỏi stack
// System.out.println("serarh"+st.search(1));
//
for (Integer i : st) {
System.out.println(i);
}
}
}
<file_sep>package com.ateach.pdf2.oop.grocery;
public class Condition implements DiscountCondition{
private String nameOfCustomer;
private String discountName;
private double discountAmount;
public Condition(String nameOfCustomer, String discountName, double discountAmount) {
this.nameOfCustomer = nameOfCustomer;
this.discountName = discountName;
this.discountAmount = discountAmount;
}
public boolean willGetDiscount(){
return nameOfCustomer != null && nameOfCustomer.equals(discountName);
}
@Override public String getNameOfCondition() {
return "Condition";
}
public double getDiscountAmount() {
return discountAmount;
}
}
<file_sep>package com.ateach.pdf1.project.furamaOop;
public class SwinmmingPool {
}
<file_sep>package com.ateach.pdf1.project.furamaStruct;
import java.util.Scanner;
public class VillaManager {
static int[][] villa = null;
public static void addNewVilla(int totalVilla) {
villa = new int[totalVilla][2];
Scanner scn = new Scanner(System.in);
for (int i = 0; i < villa.length; i++) {
System.out.println("Enter total bed & total swimming pool of villa " + (i + 1));
for (int j = 0; j < villa[i].length; j++) {
villa[i][j] = scn.nextInt();
}
}
}
public static void displayVillaInfo() {
System.out.println("villa ----------Bed----Swimming pool");
for (int i = 0; i < villa.length; i++) {
System.out.print("Villa " + (i + 1) + "\t\t\t");
for (int j = 0; j < villa[i].length; j++) {
System.out.print(villa[i][j] + "\t\t\t");
}
System.out.println();
}
}
}
<file_sep>package com.ateach.pdf2.orderAgo;
public class SortArrayCharacter {
String[] sortByLength(String[] inputArray) {
int i, j, k;
String swap;
for (i = 0; i < inputArray.length; i++)
{
for (j = i; j < inputArray.length; j++)
{
if (inputArray[i].length() > inputArray[j].length())
{
for (k = j; k > i; k--)
{
swap = inputArray[k];
inputArray[k] = inputArray[k-1];
inputArray[k-1] = swap;
}
}
}
}
return inputArray;
}
}
<file_sep>package com.ateach.pdf1.quizz.reviewPf1;
public class almostIncreasingSequence {
boolean almostIncreasingSequence(int[] sequence) {
boolean issq = true;
for(int i = 0; i <sequence.length-1; i ++){
if((sequence[i+1]-sequence[i]) ==1){
issq = true;
}else{
issq = false;
break;
}
}
return issq;
}
}
<file_sep>//package com.ateach.pdf1.basic.array;
//
//import org.junit.jupiter.api.Test;
//
//import java.util.Arrays;
//
//class ContructArrayTest {
//
// @Test
// void constructArray() {
// ContructArray ct = new ContructArray();
// System.out.println(Arrays.toString(ct.constructArray(7)));
//
//
// }
//}<file_sep>package com.ateach.pdf2.oop.accessexample.defaultaccess.defaultpackage1;
public class DefaultClassPackge1 {
int data = 10; // default modifier field (default access modifier field)
void msg() { // default modifier method (default access modifier method)
System.out.println("Hello");
}
}
// access default modifier because DefaultInPackage in same package
// with DefaultClassPackge1 have default modifier field and method default modifier
class DefaultInPackage {
public static void main(String args[]) {
DefaultClassPackge1 obj = new DefaultClassPackge1();
System.out.println(obj.data);
obj.msg();
}
}
<file_sep>package com.javabk.khai;
import java.util.Scanner;
public class XoaPhanTuTrongMang {
public static void main(String[] args) {
int[] array = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("Nhap gia tri cho mang :");
for (int i = 0; i < array.length; i++) {
array[i] = sc.nextInt();
}
int x, a = 0, b = 0 ;
System.out.println("Nhap phan tu muon xoa :");
x = sc.nextInt();
for (int i = 0; i < array.length; i++) {
if (x == array[i]) {
a = i;
break;
}
}
for (int i = a; i < array.length; i++){
if(i == array.length-1){
array[i] = 0;
break;
}
b = array[i + 1];
array[i] = b;
}
for (int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
}
}
<file_sep>package com.javabk.han;
public class SuitableRoom {
public static void main(String[] args) {
System.out.println(suitableRoom());
}
public static int suitableRoom() {
int[][] args = new int[][]{{1, 1, 1, 0},
{0, 5, 0, 5},
{2, 1, 3, 10}};
int sum = 0;
for (int i = 0; i < args.length; i++) {
for (int j = 0; j < args.length; j++) {
if (args[i][j] == 0) {
if ((i + 1) > args.length - 1){
continue;
} else{
args[i + 1][j] = 0;
}
}
sum += args[i][j];
}
}
return sum;
}
}
<file_sep>//package com.ateach.pdf2.oop.random;
//
//import org.junit.jupiter.api.Test;
//
//class RandomOopTest {
//
// @Test
// void getRandomValue() {
// RandomOop ob = new RandomOop(1000);
// ob.getRandomValue();
// }
//}<file_sep>package com.ateach.pdf2.fileInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreams {
public static void main(String[] args) {
String data = "This is an example of writing data to a file.";
File file = new File("outfile.txt");
try {
java.io.FileOutputStream fileOutputStream = new java.io.FileOutputStream(file);
fileOutputStream.write(data.getBytes());
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>package com.ateach.pdf2.collectionFrameWork.stackandqueu;
import java.util.Stack;
class Parentheses {
private static final char L_PAREN = '(';
private static final char R_PAREN = ')';
private static final char L_BRACE = '{';
private static final char R_BRACE = '}';
private static final char L_BRACKET = '[';
private static final char R_BRACKET = ']';
//mystack = {(
// String st1 = "[()]{()}{}";
public static boolean checkParen(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == L_PAREN)
stack.push(L_PAREN);
else if (s.charAt(i) == L_BRACE)
stack.push(L_BRACE);
else if (s.charAt(i) == L_BRACKET)
stack.push(L_BRACKET);
else if (s.charAt(i) == R_PAREN) {
if (stack.pop() != L_PAREN)
return false;
} else if (s.charAt(i) == R_BRACE) {
if (stack.pop() != L_BRACE)
return false;
} else if (s.charAt(i) == R_BRACKET) {
if (stack.pop() != L_BRACKET)
return false;
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
String st1 = "[()]{()}{}";
String st2 = "({})[]";
String st3 = "(){}";
System.out.println(checkParen(st3));
}
}
<file_sep>package com.javabk.khai;
import java.util.Arrays;
public class CongMang2Chieu {
public static void main(String[] args) {
int[][] arr1=new int[][]{{1,5,9},{3,6,4},{7,2,8}};
int[][] arr2=new int[][]{{2,6,9},{1,7,3},{5,4,1}};
int[][] arr=new int[3][3];
System.out.println("Mang 1: ");
for (int i=0;i<arr1.length;i++){
System.out.println(Arrays.toString(arr1[i]));
}
System.out.println("Mang 2: ");
for (int i=0;i<arr1.length;i++) {
System.out.println(Arrays.toString(arr2[i]));
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = arr1[i][j]+arr2[i][j];
}
}
System.out.println("Cong 2 mang: ");
for (int i =0;i<arr.length;i++) {
System.out.println(Arrays.toString(arr[i]));
}
}
}
<file_sep>package com.ateach.pdf2.oop.abstraction.quizz;
abstract class Hinh {
}
abstract class DaGiac extends Hinh {
}
class Tron extends Hinh {
}
class TamGiac extends DaGiac {
}
class ChuNhat extends DaGiac {
}
class Test2 {
public static void main(String[] args) {
Hinh h1 = new Tron();
Hinh h2 = new TamGiac();
Hinh h3 = new ChuNhat();
DaGiac h4 = (DaGiac) h2;
Tron h6 = (Tron) h1;
h2 = h3;
Hinh h5 = h1;
}
}
<file_sep>package com.javabk.dao;
import java.util.Scanner;
public class DienTichHinh {
public static void dienTinhHinhTron(){
System.out.println("Tinh dien tich va chu vi hinh tron");
Float r;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Nhap ban kinh");
r = sc.nextFloat();
}
while (r<0);
Float Dientich = ((314*r*r)/100);
System.out.println("Dien tich hinh tron la:" + Dientich);
Float d;
do {
System.out.println("Nhap duong kinh");
d = sc.nextFloat();
}
while (d<0);
Float Chuvi = ((314*d)/100);
System.out.println("Chu vi hinh tron la:" + Chuvi);
}
}
<file_sep>package com.ateach.designpattern.stragety;
public class Speak implements QuackBehavior{
@Override
public void quack() {
System.out.println("Speak...");
}
}
<file_sep>package com.ateach.pdf1.quizz.reviewPf1;
public class RotateArray {
int[][] rotateImage(int[][] a) {
int[][] rotate = new int[a.length][a.length];
int index = 0;
for (int i = a.length - 1; i >= 0; i--) {
for (int j = 0; j < a.length; j++) {
rotate[j][index] = a[i][j];
}
index++;
}
return rotate;
}
}
<file_sep>package com.javabk.khai;
import java.util.Scanner;
public class ChenPhanTuVaoMang {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] array = new int[10];
int[] array2 = new int[11];
int x,index,a;
System.out.println("Nhap gia tri mang");
for (int i = 0; i < array.length; i++){
array[i] = sc.nextInt();
}
System.out.println("Nhap so can chen :");
x = sc.nextInt();
System.out.println("Nhap vi tri can chen:");
index = sc.nextInt();
for (int i = 0; i < array.length; i++){
array2[i] = array[i];
}
if (index <= -1 || index >= array.length-1){
System.out.println("Khong the chen duoc phan tu vao mang");
}
else {
for(int i = index; i < array2.length; i++) {
if (i == array2.length-1){
array2[i] = x;
break;
}
a = array2[i];
array2[i] = x;
x = a;
}
for (int i = 0; i < array2.length; i++){
System.out.println(array2[i]);
}
}
}
}
<file_sep>package com.ateach.pdf1.quizz.reviewPf1;
public class isLucky {
boolean isLucky(int n) {
String num = Integer.toString(n); //1234 -?"1234"
int x = 0;
int sum1 = 0;
int sum2 = 0;
if(num.length()%2 == 0) {
x = num.length()/2;
for(int i=0; i<x ;i++) {
sum1 += Character.getNumericValue(num.charAt(i));
}
for(int i=x; i<num.length() ;i++) {
sum2 += Character.getNumericValue(num.charAt(i));
}
if (sum1 == sum2) {
return true;
}else {
return false;
}
}
return false;
}
}
<file_sep>package com.ateach.pdf2.orderAgo;
public class SelectionSort {
public static void sort(int[] array) {
for (int i = 0; i < array.length; i++) {
int max = array[i]; // Lưu phần tử lớn nhất
int index = i; // lưu vị trí chứa phần tử lớn nhất
for (int j = i + 1; j < array.length; j++) {
if(max < array[j]){
max = array[j];
index = j;
}
}
// Nếu chỉ số đã thay đổi, ta sẽ hoán vị
if(index != i){
int temp = array[i];
array[i] = array[index];
array[index] = temp;
}
}
}
}
<file_sep>package com.ateach.pdf2.collectionFrameWork.arraylinkedlist;
import java.util.ArrayList;
import java.util.Stack;
public class MergeList {
public static void main(String[] args) {
ArrayList<Integer> l1 = new ArrayList<Integer>();
l1.add(3);
l1.add(4);
l1.add(5);
ArrayList<Integer> l2 = new ArrayList<Integer>();
l2.add(3);
l2.add(4);
l2.add(5);
ArrayList<Integer> lnew = new ArrayList<Integer>();
lnew.addAll(l1);
lnew.addAll(l2);
System.out.println(lnew.toString());
Stack<Integer> stack = new Stack<Integer>();
}
}
<file_sep>package com.ateach.medium;
public class KhachHang {
static public int id;
public String hoTen;
int soDienThoai;
public void show(){
System.out.println(soDienThoai);
}
}
class QuanLy{
public static void main(String[] args) {
KhachHang obj = new KhachHang();
System.out.println(obj.hoTen);
System.out.println(obj.soDienThoai);
}
}
<file_sep>package com.javabk.ha;
import java.util.Scanner;
public class TimUoc {
public static void UCLN(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
System.out.println(" Nhập vào số a");
a = scanner.nextInt();
System.out.println("Nhập vào số b");
b= scanner.nextInt();
a = Math.abs(a);
b = Math.abs(b);
if(a==0 || b==0)
{
System.out.println(" no greatest common factor");
System.out.println("Done !");
}
while ( a!= b)
{
if(a>b)
{
a=a-b;
}
else
{
b=b-a;
}
}
System.out.println(" Greatest common factor: " + a );
}
}
<file_sep>package com.ateach.pdf2.oop.exercise;
abstract class Quiz3 {
public void methodNonAbstract() {
System.out.println("This is method non Abstract");
}
abstract void methodAbstract();
}
abstract class Quiz4 {
final int id = 100;
static String name;
String address;
protected void methodProtected() {
}
private void methodPrivate() {
}
public void methodPublic() {
}
}
//class testInheritanceQ3Q4 extends Quiz3,Quiz4 {
class testInheritanceQ3Q4 extends Quiz3 {
void methodAbstract() {
System.out.println("this's content");
}
}<file_sep>package com.javabk.han;
public class CircleOfNumber {
public static void main(String[] args) {
circleOfNumber(10,2);
}
public static int circleOfNumber(int n,int firstNumber){
int ketqua;
if ((firstNumber + (n / 2)) > n) {
ketqua = firstNumber + (n / 2);
} else {
ketqua = (firstNumber + (n / 2)) % n;
}
System.out.println(ketqua);
return ketqua;
}
}
<file_sep>package com.ateach.pdf2.oop.student;
public class StudentManagerTest {
public static void main(String[] args) {
StudentManager studentManager = new StudentManager();
studentManager.displayAll();
Student andy = new Student("Andy", 23);
studentManager.add(andy);
System.out.println("added " + andy.getInfomation());
studentManager.displayAll();
studentManager.find("Andy");
}
}
<file_sep>package com.ateach.pdf2.oop.grocery;
public class ReadyMadeCake extends Cake {
private final String[] SUPPORTED_DISCOUNT_CONDITIONS = {"Condition"};
public int quantity;
public ReadyMadeCake(String name, double rate,int quantity) {
super(name, rate);
this.quantity = quantity;
}
public ReadyMadeCake(Cake cake){
super(cake);
if (cake instanceof ReadyMadeCake) {
this.quantity = ((ReadyMadeCake) cake).quantity;
}
}
public double calcPrice () {
return rate * quantity;
}
@Override public double getPrice() {
return calcPrice();
}
@Override public double getDiscount(DiscountCondition[] discountConditions) {
double discountAmount = 0;
if(quantity > 5){
discountAmount += DISCOUNT_IN_PERCENT/100*this.getPrice();
}
//We should not check the discount condition if it is empty
if(discountConditions == null || discountConditions.length ==0 ){
return discountAmount;
}
for (DiscountCondition discountCondition : discountConditions) {
if(supportDiscountCondition(discountCondition)){
/**
* We are at ReadyMadeCake class, we know how to calculate the discount for these items
*/
if(discountCondition instanceof Condition){
Condition nameOfCustomerCondition = (Condition) discountCondition;
if(nameOfCustomerCondition.willGetDiscount()){
discountAmount += nameOfCustomerCondition.getDiscountAmount();
}
}
}
}
return discountAmount;
}
@Override public String getInfo() {
return toString() + ", price: " + getPrice();
}
@Override public boolean supportDiscountCondition(DiscountCondition discountCondition) {
for (String supported_discount_condition : SUPPORTED_DISCOUNT_CONDITIONS) {
if( supported_discount_condition.equals(discountCondition.getNameOfCondition())){
return true;
}
}
return false;
}
public String toString () {
return super.toString() + "\t" + quantity +" (eggs)";
}
}<file_sep># JavaCoreBK
JavaCore
<file_sep>package com.ateach.pdf2.oop.random;
import java.util.Random;
public class RandomOop {
public int seed;
public RandomOop(int seeds) {
this.seed = seeds;
}
public void getRandomValue(){
Random random1 = new Random(this.seed);
for (int i = 0; i < 50; i++) {
System.out.print(random1.nextInt(100) + " ");
}
}
}
<file_sep>package com.ateach.pdf2.oop.exercise;
//a....
abstract class AbClss1{
abstract void method1();
abstract void method2();
}
abstract class AbClss2 extends AbClss1{
abstract void method3();
abstract void method4();
}
//public class Quiz6 extends AbClss{
//
//}
//b...
class AbChild extends AbClss2{
void method1() {
System.out.println("Contents of method2");
}
void method2() {
System.out.println("Contents of method2");
}
void method3() {
System.out.println("Contents of method2");
}
void method4() {
System.out.println("Contents of method2");
}
}
<file_sep>package com.ateach.pdf1.basic.array2D;
import java.util.Scanner;
public class ThaoTacVoiArray2D {
public static void array2D(){
// gan truc tiep
int[][] rating = new int [][]{{8,9,7,10},{8,7,7,10},{9,5,7,10}};
Scanner scn = new Scanner(System.in);
// gan gian tiep
int[][] assignValue = new int[3][4];
for (int i=0; i<assignValue.length;i++){
for(int j=0;j<assignValue[i].length;j++){
System.out.println("Gia tri dong: "+i+" cot:"+j);
assignValue[i][j] = scn.nextInt();
}
}
System.out.println("mang in ra: ");
for (int i=0; i<3; i++){
for(int j=0; j<4; j++){
System.out.print(assignValue[i][j]+ " ");
}
System.out.println();
}
int sum= 0;
for(int j=0; j<assignValue.length; j++){
sum = sum + assignValue[j][3];
}
System.out.println("gia tri:"+sum);
double trungBinh = sum/3;
System.out.println(trungBinh);
}
public static void inMang(int arrs[][]){
System.out.println("mang in ra: ");
for (int i=0; i<arrs.length; i++){
for(int j=0; j<arrs[i].length; j++){
System.out.print(arrs[i][j]+ " ");
}
System.out.println();
}
}
public static void duongCheoThuNhat(){
int[][] arrgs = new int[][]{{1,2,4},{5,6,8},{9,6,3}};
int sum = 0;
// cach 1
for(int i = 0; i<arrgs.length;i++){
for(int j=0; j<arrgs[i].length; j++){
if(i==j){
sum =sum+arrgs[i][j];
}
}
}
//cach 2
// for(int i = 0; i<arrgs.length;i++){
// sum = sum + arrgs[i][i];
// }
System.out.println("tong duong cheo 1: "+sum);
}
public static void duongCheoThuHai(){
int[][] arr2d = new int[][]{{1,2,4},{5,6,8},{9,6,3}};
int sum1 = 0;
for(int k = 0; k < arr2d.length; k++){
sum1 = sum1 + arr2d[k][arr2d.length-k-1]; // vi du k = 0 thi hang 0 cot 3(arr2d.length = 3)-0(k=0)-1 ->arr[0][2] + arr[1][1]+ arr[2][0]
}
System.out.println("Tong duong cheo 2: "+sum1);
}
// cach 2 tinh tong 2 duong cheo
public static void tongHaiDuongCheo(){
int[][] arr2d = new int[][]{{1,2,4},{5,6,8},{9,6,3}};
int sum = 0;
for (int i = 0; i<arr2d.length; i++){
sum = sum + arr2d[i][i]+arr2d[i][arr2d.length-i-1];
}
System.out.println(" tong hai duong cheo: "+sum);
}
public static void congHaiMaTran (){
int [][] maTran1 = new int[][]{{2,3,4},{1,1,1},{6,5,2}};
int [][] maTran2 = new int[][]{{1,6,7},{3,4,6},{2,3,2}};
int [][] maTran3 = new int[3][3];
for(int i = 0; i<maTran1.length; i++){
for(int j = 0; j<maTran1[i].length; j++){
maTran3[i][j] = maTran1[i][j] + maTran2[i][j];
}
}
inMang(maTran3);
}
}
<file_sep>package com.ateach.pdf2.collectionFrameWork.hashandtree;
import java.util.HashMap;
import java.util.Map;
public class HashMapTest {
static void insertAndPrint(HashMap<Integer, String> map)
{
int[] array= {1, -1, 0, 2,-2};
for (int x: array)
{
map.put(x, Integer.toString(x));
}
for (int k: map.keySet())
{
System.out.print(k + ", ");
}
}
// Driver method to test above method
public static void main (String[] args)
{
HashMap<String,String> map1 = new HashMap<String,String>();
map1.put("a","Anchor");
map1.put("b","Anchor");
map1.put(null,"value null");
// map1.put("b","value null");
for (Map.Entry x: map1.entrySet()){
System.out.println("key: " +x.getKey()+" value: "+x.getValue());
}
// HashMap<Integer, String> map = new HashMap<Integer, String>();
// insertAndPrint(map);
}
}
<file_sep>//package com.ateach.pdf2.oop.abstraction.example1;
//
//// <NAME>
//public class Boss extends Employee {
//
// private int workingHours;
//
// public Boss(String name, int paymentPerHour, int workingHours) {
// super(name, paymentPerHour);
// this.workingHours = workingHours;
// }
//
//
// public int calculateSalaryBossCuaThu() {
// return getPaymentPerHour() * workingHours;
// }
//}<file_sep>package com.javabk.khai;
import java.util.Scanner;
public class GopHaiMang {
public static void main(String[] args) {
int[] array1 = new int[5];
int[] array2 = new int[5];
Scanner sc = new Scanner(System.in);
System.out.println("Nhap gai tri cho mang 1 :");
for (int i = 0; i<array1.length; i++){
array1[i] = sc.nextInt();
}
System.out.println("Nhap gai tri cho mang 2 :");
for (int i = 0; i<array1.length; i++){
array2[i] = sc.nextInt();
}
int[] array3 = new int[array1.length + array2.length];
System.out.println("Gia tri cua mang 3 :");
for (int i = 0; i<array3.length; i++){
if(i < array1.length) {
array3[i] = array1[i];
}
else {
if (i >= array1.length){
array3[i] = array2[i - array1.length];
}
}
System.out.print(array3[i]+"\t");
}
}
}
<file_sep>package com;
class Cha {
private String khoVang = "";
Cha(String khoVang) {
System.out.println("dsfdsfdfdsf");
this.khoVang = khoVang;
}
private void display(){
System.out.println(khoVang );
}
}
<file_sep>package com.ateach.pdf2.fileInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
public static void main(String[] args) {
File file=new File("file.txt");
try {
FileInputStream fileInputStream=new FileInputStream(file);
int b;
while((b=fileInputStream.read())!=-1){
System.out.print((char)b);
}
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>package com.ateach.pdf1.basic.array2D;
import java.util.Scanner;
public class BanCo {
public static void duongDiQuanXe() {
String[] chieuNgang = {"a", "b", "c", "d", "e", "f", "g", "h"};
String[] chieuDoc = {"1", "2", "3", "4", "5", "6", "7", "8"};
String[][] banCoMoi = new String[8][8];
for (int i = 0; i < chieuNgang.length; i++) {
for (int j = chieuDoc.length - 1; j >= 0; j--) {
String giaTri = chieuNgang[i] + "" + chieuDoc[j];
banCoMoi[i][j] = giaTri;
}
}
inMang(banCoMoi);
System.out.println(" Nhap vi tri cua quan xe: ");
Scanner scn = new Scanner(System.in);
String viTriXe = scn.next();
int soViTri = Integer.parseInt(viTriXe.substring(0, 1));
System.out.println(soViTri);
//duyet qua cot
for (int i = 0; i < banCoMoi.length; i++) {
System.out.print(banCoMoi[i][soViTri - 1] + " ");
}
//duyet qua dong
for (int i = 0; i < banCoMoi.length; i++) {
System.out.print(banCoMoi[soViTri - 1][i] + " ");
}
}
public static void inMang(String arrs[][]) {
System.out.println("mang in ra: ");
for (int i = 0; i < arrs.length; i++) {
for (int j = 0; j < arrs[i].length; j++) {
System.out.print(arrs[i][j] + " ");
}
System.out.println();
}
}
}
<file_sep>package com.ateach.pdf2.oop.account;
import java.text.SimpleDateFormat;
import java.util.Date;
class AccountTest {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
Account ac = new Account();
ac.setId(111);
ac.setBalance(20);
ac.setDateCreated(date);
ac.setAnnualInterestRate(4.5); // lai suat 1 nam 4.5$
ac.withdraw(2.5); // rut 2.5$
ac.deposit(3); // them vao 3$
System.out.println("Account id: "+ac.getId());
System.out.println("Date create account: " + formatter.format(ac.getDateCreated()));
System.out.println("Balance: " + ac.getBalance());
System.out.println("Monthly Interest Rate: " + ac.getMonthlyInterestRate());
}
}<file_sep>package com.javabk.liem;
import java.util.Random;
import java.util.Scanner;
public class LenhDieuKien {
public static void cauLenhDieuKien(){
System.out.println("Hello World!");
Scanner sc = new Scanner(System.in);
int Count,Count2,SoTron ;
double Sprtt = Math.sqrt(100);
SoTron = (int)(Sprtt);
boolean IS;
int[] SoNguyenTo;
int CountArray = 0;
for (Count=2;Count<=100;Count++) {
//System.out.println("");
IS = true;
Sprtt = Math.sqrt(Count);
SoTron = (int) (Sprtt);
for (Count2 = 2; Count2 < Count; Count2++) {
if (Count % Count2 == 0) {
IS = false;
break;
}
}
if (IS == true) {
System.out.println("Số " + Count + " là số nguyên tố");
}
}
}
public static void xoSo(){
Scanner sc = new Scanner(System.in);
int So_nhap_vao;
do {
System.out.print("Vui lòng nhập số có 2 chữ số : ");
So_nhap_vao = sc.nextByte();
} while ((So_nhap_vao<0)||(So_nhap_vao>100));
Random rd = new Random();
int na = 100;
int rds = rd.nextInt(na);
System.out.println("Số Random là : " + rds);
int So_nhap_vao_thu_nhat_la = So_nhap_vao / 10;
int So_nhap_vao_thu_hai_la = So_nhap_vao % 10;
int So_rds_thu_nhat_la = rds / 10;
int So_rds_thu_hai_la = rds % 10;
if ((So_nhap_vao_thu_nhat_la == So_rds_thu_nhat_la) && (So_nhap_vao_thu_hai_la == So_rds_thu_hai_la)){
System.out.println("Phần thưởng của bạn là 10 000$");
}
else if ((So_nhap_vao_thu_nhat_la == So_rds_thu_hai_la) && (So_rds_thu_nhat_la == So_nhap_vao_thu_hai_la)){
System.out.println("Phần thưởng của bạn là 3000$");
}
else if ((So_nhap_vao_thu_nhat_la == So_rds_thu_nhat_la) || (So_nhap_vao_thu_hai_la == So_rds_thu_hai_la)||
(So_nhap_vao_thu_nhat_la == So_rds_thu_hai_la) || (So_rds_thu_nhat_la == So_nhap_vao_thu_hai_la)){
System.out.println("Phần thưởng của bạn là 1000$");
}
else {
System.out.println("Phần thưởng của bạn là 0$. Chúc mừng bạn");
}
}
public static void giaiPhuongTrinh(){
Scanner sc = new Scanner(System.in);
System.out.println("Vui lòng nhập lần lượt 3 hệ số a, b, c");
System.out.print("Vui lòng nhập số A : ");
float a = sc.nextFloat();
System.out.print("Vui lòng nhập số B : ");
float b = sc.nextFloat();
System.out.print("Vui lòng nhập số C : ");
float c = sc.nextFloat();
float Nghiem1;
if(a == 0){
if(b == 0 &&(c!=0)){
System.out.println("Phương trình vô nghiệm");
}
else if((b!=0)&&(c!=0) ){
Nghiem1 = -b/c;
System.out.print("Phương Trình Có 1 nghiệm là : " + Nghiem1);
}
else if(( b == 0 )&&(c==0) ){
System.out.println("Phương trình có vô số nghiệm");
}
}
else {
float Delta= b*b - 4*a*c;
if (Delta < 0){
System.out.println("Phương trình Vô nghiệm");
}
else if(Delta == 0 ){
System.out.println("Phương trình có nghiệm kép : " + -b/(2*a));
}
else if(Delta > 0 ){
double Can_2_cua_delta = Math.sqrt(Delta);
double Nghiem_1 = (-b + Can_2_cua_delta)/(2*a);
double Nghiem_2 = (-b - Can_2_cua_delta)/(2*a);
System.out.println("Phương trình có 2 nghiệm lần lượt là : " + Nghiem_1 + " , " + Nghiem_2);
}
}
}
}
<file_sep>package com.ateach.pdf1.basic.TDD;
public class Calculator {
public int add(int x, int y) {
// throw new UnsupportedOperationException("not support operation");
return x - y;
}
public int sub(int x, int y){
return x - y;
}
}
<file_sep>package com.javabk.ha;
import java.util.Scanner;
public class GopMang {
public static void gopMang(){
Scanner scn = new Scanner(System.in);
int i,j;
int m,n;
int[] arrayA = new int[100];
int[] arrayB = new int[100];
int[] arrayC = new int[arrayA.length+arrayB.length];
for(i=0;i<arrayA.length;i++){
}
}
}
<file_sep>package com.ateach.pdf1.basic.array;
public class ContructArray {
int[] constructArray(int size) {
int[] arr = new int[size];
arr[0] = 1;
arr[1] = 7;
for(int i = 2; i< size-1;i++){
arr[i] = i ;
arr[i+1] = (size) -1;
}
return arr;
}
}
<file_sep>package com.ateach.pdf2.oop.accessexample.publicaccess;
public class PublicAcess {
// access every where. every package. it open for all
}
<file_sep>package com.ateach.pdf2.oop.polymorphism.example1;
/**
* This represents payment interface
*/
interface Payment {
public void pay();
}<file_sep>package com.ateach.pdf2.collectionFrameWork.stackandqueu;
import java.util.LinkedList;
import java.util.Queue;
public class Queus {
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<>();
q.add(1);
q.add(2);
q.add(3);
for (Integer i : q) {
System.out.println(i);
}
System.out.println("peek method: " + q.peek()); //Lấy phần tử ở đầu tiên hàng đợi nhưng không xóa
System.out.println("poll method: " + q.poll());//Lấy phần từ đầu tiên của hàng đợi và xóa nó ra khỏi hàng đợi
for (Integer i : q) {
System.out.println(i);
}
// System.out.println();
}
}
<file_sep>package com.ateach.pdf2.oop.accessexample.protectedaccess;
public class ProtectedAcess {
// we will come back in lesson inheritance
}
<file_sep>package com.ateach.pdf2.orderAgo;
public class OrderTree {
int[] sortByHeight(int[] a) {
for(int i = 0; i < a.length - 1; i++){
if(a[i] != -1){
int smallest = i;
for(int j = i + 1; j < a.length; j++){
if(a[j] != -1){
if(a[smallest] > a[j]){
smallest = j;
}
}
}
int temp = a[smallest];
a[smallest] = a[i];
a[i] = temp;
}
}
return a;
}
}
<file_sep>package com.ateach.pdf2.oop.exercise;
public class Quiz2 {
static String name = "<NAME>";
String address = "Codegym Da nang";
}
class Test{
public static void main(String[] args) {
// access static field
// access non-static filed
}
}<file_sep>package com.ateach.pdf1.basic.method;
public class ThamBienThamTri {
public static void goiHam(){
// int giaTriGoc = 10;
// truyenThamTri(giaTriGoc);
// System.out.println("Gia tri sau khi goi: "+ giaTriGoc);
int [] mangGoc = {400,500};
System.out.println("Gia tri ban dau: " + mangGoc[0] + " " +mangGoc[1]);
truyenThamChieu(mangGoc);
System.out.println("Gia tri sau khi goi ham: "+ mangGoc[0] + " "+ mangGoc[1]);
}
static void truyenThamTri(int bien)
{
bien = 20;
}
static void truyenThamChieu(int mang[]){
mang[0] = 200;
mang[1] = 100;
}
}
<file_sep>package com.ateach.pdf2.oop.inheritance.person;
import java.util.Scanner;
public class Student extends Person{
private String program;
private int year;
private double fee;
public String getProgram() {
return program;
}
public void setProgram(String program) {
this.program = program;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double getFee() {
return fee;
}
public void setFee(double fee) {
this.fee = fee;
}
public Student(){
super();
program = "";
year = 0;
fee = 0.0;
}
public Student(String name, String address, String program, int year, double fee) {
super(name,address);
this.program = program;
this.year = year;
this.fee = fee;
}
public void addInfoStudent(){
super.addInfo();
Scanner sc = new Scanner(System.in);
System.out.println("Enter program: ");
program = sc.next();
System.out.println("Enter year(int): ");
year = sc.nextInt();
System.out.println("Enter fee (double): ");
fee = sc.nextDouble();
}
public String toString(){
return "Student info: "+super.toString()+", program: "+program+ ", year: "+year + ", fee: "+fee +"";
}
}
<file_sep>package com.ateach.pdf2.oop.onlyabstract.animal;
public class Tiger extends Animal {
@Override
public String makeSound() {
return "Tiger: roarrrrr!";
}
public String howToEat() {
return "could be fried";
} // tiger khong can co phuong thuc nay, nhung vi abstrac nen phai khai bao
}
| 2104fbd5133c90ba58320f25425c97b24567a7eb | [
"Markdown",
"Java"
] | 72 | Java | tinh1408/JavaCoreBK | 6e3e29de3e27b21ba29a854ec66d8cbb24be4d34 | b7af696fe97c1706334be2d6cf9de768ef92a7cc | |
refs/heads/master | <file_sep>/* exercici 5 nivell-2 */
function ex5() {
var str = "Una dirección de correo electrónico es la dirección que utiliza para recibir y enviar correos electrónicos. Se muestra a los destinatarios de sus correos\
electrónicos para que sepan quién le envió un correo electrónico.Cada dirección de correo\
electrónico sólo se puede asignar una vez en todo el mundo y, por lo tanto, está disponible exclusivamente para usted.No puede cambiar las direcciones de correo\
electrónico, pero puede eliminarlas en cualquier momento.Una dirección de\
correo electrónico consiste en el signo @(arroba), el nombre de usuario delante y el dominio detrás, por ejemplo, <EMAIL>: La parte del dominio\
depende del dominio bajo el cual se crea la dirección de correo electrónico:\
en nuestro ejemplo es ionos.es.Esta información varía de proveedor a proveedor, por lo que una parte del dominio también puede ser gmail.com o gmx.es si utiliza\
una dirección de correo electrónico de estos proveedores.Si ha registrado\
su propio dominio, por ejemplo, www.el-nombre-de-sus-sueños.es, las direcciones de correo electrónico que configura para el dominio lo tienen como parte del dominio( <EMAIL> o <EMAIL> ).\
El nombre de usuario es la parte de una dirección de correo electrónico que puede seleccionar libremente en la medida de lo posible. Puede, por ejemplo, utilizar su\
propio nombre o el nombre o departamento de una empresa.Si utiliza una\
dirección de correo electrónico con un proveedor de correo como gmail.com o gmx.es, es posible que la combinación con la parte del dominio deseada ya esté\
registrada.En este caso, deberá considerar alternativas para el nombre de usuario\
de su dirección de correo electrónico.Si utiliza su propio dominio, estas restricciones no se aplican porque sólo usted puede crear direcciones de correo\
electrónico que coincidan con su propio dominio.En resumen, [email protected]\
es un email.";
let myRegex = /([\w\.-]+)@([\u00f1\u00d1\w\.-]+)/gim;
let mailArr = str.match(myRegex);
let mailNoRep = [];
for (let i = 0; i < mailArr.length; i++) {
let mail = mailArr[i];
if (!mailNoRep.includes(mailArr[i].toLocaleLowerCase())) {
mailNoRep.push(mail);
}
}
console.log(mailNoRep);
return mailNoRep;
}<file_sep># React
Este repositorio tiene la función de ir guardando los ejercicios que voy haciendo para la ITAcademy en el itinerario de REACT.
<file_sep><!DOCTYPE html>
<html lang="ca">
<head>
<meta charset="UTF-8">
<title>Flex práctica</title>
<meta name="viewport" content="width=device-width, initial-scale=1 shrink-to-fit=no">
<link rel="stylesheet" href="styles.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,400;0,700;1,400&display=swap" rel="stylesheet">
</head>
<body>
<div class="madre">
<header class="header">
<div class="menu">
<div class="logo">
<img src="img/Material activitat Flex nivell 2-logo.png" alt="logo empresa" class="img">
</div>
<nav class="nav">
<ul>
<li><a href="#">Inicio</a></li>
<li><a href="#">Rutas</a></li>
<li><a href="#">Hoteles</a></li>
<li><a href="#">Vuelos</a></li>
<li><a href="#">Contacto</a></li>
</ul>
</nav>
<div class="social"></div>
</div>
<div class="texto-principal">
<h1>"Disfruta de la experiencia de otros viajeros"</h1>
</div>
</header>
<section>
<div class="articulos">
<article class="article">
<img class="article-image" src="img/escultura.jpg" alt="escultura de personas pegadas a la pared">
<h4><time datetime="2021-12-08">8 de desembre 2021</time></h4>
<h3>CULTURA</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing 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.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</article>
<article class="article">
<img class="article-image" src="img/aceite.jpg" alt="Aceite de oliva cayendo">
<h4><time datetime="2021-12-08">8 de desembre 2021</time></h4>
<h3>GASTRONOMÍA</h3>Lorem ipsum dolor sit amet, consectetur adipiscing 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. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</article>
<article class="article">
<img src="img/adventure.jpg" alt="Mujer en Kayak en un lago con montaña nevada de fondo" class="article-image">
<h4><time datetime="2021-12-08">8 de desembre 2021</time></h4>
<h3>AVENTURA</h3>Lorem ipsum dolor sit amet, consectetur adipiscing 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. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</article>
<article class="article">
<img src="img/nubes.jpg" alt="nubes sobre la cordillera de los andes nevada" class="article-image">
<h4><time datetime="2021-12-08">8 de desembre 2021</time></h4>
<h3>EMOCIÓN</h3>Lorem ipsum dolor sit amet, consectetur adipiscing 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. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<aside class="aside">
<div class="publicida">At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia
deserunt mollitia animi, id est laborum et dolorum fuga. </div>
<div class="publicida">At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia
deserunt mollitia animi, id est laborum et dolorum fuga. </div>
</aside>
</section>
<footer class="footer">
<nav class="pie"></nav>
</footer>
</div>
</body>
</html><file_sep># itinerari-react-itacademy
exercicis Sprint 1 setmanes del 22 de febrer al 5 de març<file_sep>/* exercici 1 */
function ex1n3() {
let myName = document.getElementById("nom1").value;
nom = [];
for (let i = 0; i < myName.length; i++) {
console.log(myName[i]);
nom += myName[i] + '<br>';
document.getElementById("ex1n3").innerHTML = nom;
}
}
/* exercici 2 */
/* creació de mapa */
function ex2n3() {
const vocals = new Map([
["a", "a"],
["e", "e"],
["i", "i"],
["o", "o"],
["u", "u"]
]);
const numbers = new Map([
['0'],
['1'],
['2'],
['3'],
['4'],
['5'],
['6'],
['7'],
['8'],
['9']
]);
let myName = document.getElementById("nom2").value;
let myNameLower = myName.toLowerCase();
console.log(myNameLower)
nom = [];
for (let i = 0; i < myNameLower.length; i++) {
if (vocals.has(myNameLower[i])) {
console.log("He trobat la Vocal: " + myNameLower[i]);
nom.push("He trobat la Vocal: " + '<b>' + myNameLower[i] + '</b>' + '.' +
'<br>');
} else if (numbers.has(myNameLower[i])) {
console.log("Els noms de persona no contenen números com el " + myNameLower[i]);
nom.push("Els noms de persona no contenen números com el " +
'<b>' + myNameLower[i] + '</b>' + '.' + '<br>');
} else {
console.log("He trobat la Consonant " + myNameLower[i]);
nom.push("He trobat la Consonant " + '<b>' + myNameLower[i] + '</b>' + '.' + '<br>');
}
}
document.getElementById('ex2n3').innerHTML = nom.join('');
}
/* exercici 3 */
function ex3n3() {
let myName = document.getElementById("nom3").value;
let mapName = new Map();
for (let i = 0; i < myName.length; i++) {
let v = 1;
if (mapName.has(myName[i])) {
v = mapName.get(myName[i]);
mapName.set(myName[i], v + 1);
} else {
mapName.set(myName[i], v)
}
}
let resultat = "";
for (let [key, value] of mapName) {
resultat += (key + ' = ' + value + "<br>");
}
document.getElementById('ex3n3').innerHTML = resultat;
}
/* exercici 4 */
function ex4n3() {
let nom = document.getElementById("nom4").value;
let cognom = document.getElementById("cognom4").value;
let nomCognom = [];
for (let i = 0; i < nom.length; i++) {
nomCognom.push(nom[i]);
}
nomCognom.push("--");
for (let i = 0; i < cognom.length; i++) {
nomCognom.push(cognom[i]);
}
document.getElementById("ex4n3").innerHTML = nomCognom.join(", ");
}
function ex5n3() {
let resultat = ex5();
document.getElementById("ex5n3").innerHTML = resultat.join("<br>");
} | 5e0033e47609a6f0d988b148d8a8753a3b9162bc | [
"JavaScript",
"HTML",
"Markdown"
] | 5 | JavaScript | Olivermusico/React | 6742dd22de156ac779fc86e362891c0b960cfcc1 | 1dc8bc1ffb34966a211dafb3fac8de56cfad11da | |
refs/heads/main | <file_sep>/*
* @Author: CL
* @Date: 2021-05-14 15:52:06
* @LastEditTime: 2021-07-02 16:29:04
* @Description:
*/
const btnStart = document.querySelector(".btnStart"), //开始按钮
btnLaunch = document.querySelector(".btnLaunch"), //发射按钮
btnLand = document.querySelector(".btnLand"), //着陆按钮
fire = document.querySelector(".fire"),
rockets = document.querySelector(".rockets"),
shadow = document.querySelector(".shadow"),
txtLaunch = document.querySelector(".btnLaunch span"),
txtLand = document.querySelector(".btnLand span"),
txtStart = document.querySelector(".btnStart span");
/**
* 开始点火
*/
btnStart.addEventListener("click", openFire);
/**
* 发射
*/
btnLaunch.addEventListener("click", launch);
/**
* 着陆
*/
btnLand.addEventListener("click", land);
/**
* 点火
*/
function openFire() {
//如果开始按钮已经有了active,class,则证明此时是有火的,点击就要去掉火,移除activeclass
if (btnStart.classList.contains("active")) {
fire.classList.remove("burn"); //去火
btnStart.classList.remove("active"); //改变背景样式
txtStart.innerText = "start"; //文本
} else {
fire.classList.add("burn");
btnStart.classList.add("active");
txtStart.innerText = "停止";
}
}
/**
* 熄火
*/
function burn() {
fire.classList.remove("burn");
rockets.classList.remove("land");
shadow.style.opacity = "0.2";
// buttons
btnLand.classList.remove("active");
btnLand.classList.add("disable");
btnLand.disabled = true;
// 着陆按钮文本
txtLand.innerText = "着陆";
}
/**
* 发射
*/
function launch() {
btnStart.classList.add("disable");
fire.classList.add("burn");
rockets.classList.remove("land");
rockets.classList.add("launch");
rockets.removeEventListener("animationend", burn);
shadow.style.opacity = "0";
//按钮
btnLaunch.classList.add("active");
btnStart.disabled = true;
btnStart.classList.remove("active");
btnLand.classList.remove("active");
btnLand.classList.remove("disable");
btnLand.disabled = false;
//文本
txtLaunch.innerText = "发射";
txtStart.innerText = "开始";
txtLand.innerText = "着落";
}
/**
* 着陆
*/
function land() {
//飞船
rockets.classList.remove("launch");
rockets.classList.add("land");
rockets.addEventListener("animationend", burn); //熄火显示
// 按钮
btnLaunch.classList.remove("active");
btnLand.classList.add("active");
btnStart.classList.remove("disable");
btnStart.disabled = false;
// 按钮文本
txtLand.innerText = "着陆";
txtLaunch.innerText = "发射";
}
<file_sep># zc-demos
仓库主要存储一些日常编写的demo
## games
> 存放使用使用JS编写的游戏
## display
> 存放一些比较好的实现效果
- [x] rockets launch: (缅怀两弹元勋钱老)火箭发射
- [x] 自由飞翔的小鸟

### font(文字效果)
- [x] 文字粒子效果
- [x] `background-clip:text` 实现 `hover` 文字填充效果

- [x] 跃动的文字

| 7d74694d5dff55a54bb18713ce495c3cde6a85be | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | li1961201449/zc-demos | 2ef1161b5fad82f0a5c3d29c1e1b5be2e9e60824 | 1133a39c2ca1e1fad2166eba40a7567f4d199a19 | |
refs/heads/master | <repo_name>Techbot/Niburu-Online<file_sep>/inc/salir.php
<?php
include("config.php");
$playerID = $_POST['id_local'];
$localPos = mysql_query("UPDATE personajes SET online = '0' WHERE id = '".$playerID."'");
?><file_sep>/inc/mover.php
<?php
include("config.php");
$playerID = $_POST['id_local'];
$posy = $_POST['posy'];
$posx = $_POST['posx'];
if ($posy != ""){
$localPos = mysql_query("UPDATE personajes SET posy = '".$posy."', online = '1' WHERE id = '".$playerID."'");
}
if ($posx != ""){
$localPos = mysql_query("UPDATE personajes SET posx = '".$posx."', online = '1' WHERE id = '".$playerID."'");
}
?><file_sep>/index.php
<?php session_start(); ?>
<html>
<head>
<title>Niburu Online - 2D MMORPG basado en PHP y jQuery</title>
</head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<link rel="stylesheet" href="css/estilo.css" type="text/css" media="screen">
<body>
<div style="position:absolute; top:-10px; z-index:-10; width:100%; height:90%;">
<img src="http://www.deviantart.com/download/65228468/2D_RPG_game_background_by_willowWISP.jpg" style="width:100%;"/>
</div>
<?php if (!isset($_SESSION["s_usuario"])){ ?>
<style>body { overflow:hidden; }</style>
<div id="login" style="position:absolute; left:50%; margin-left:-100px; margin-top:10px;">
<div style="position:relative; left:-10px;"><h1>Iniciar Sesión</h1></div>
<script src="js/jquery.uniform.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
$(function(){
$("input, textarea, select, button").uniform();
});
</script>
<link rel="stylesheet" href="css/uniform.default.css" type="text/css" media="screen">
<form name="login" method="post" action="login.php">
<ul>
<li><label>Usuario:</label><input type="text" name="usuario"/> <input type="submit" value="Entrar"/></li>
<li><label>Contraseña</label><input type="password" name="contra"/></li>
</ul>
<div style="font-size:12px; text-align:center;"><a href="#">Registrar Nuevo Usuario</a></div>
</form>
</div>
<?php } else { ?>
<script>
$(document).ready(function() {
//document.getElementById("chat").scrollTop=document.getElementById("chat").scrollHeight
});
</script>
<div id="juego">
</div>
<div style="width:700px; left:50%; margin-left:-350px; height:70px; margin-top:5px; position:relative;">
<div id="chat">Conectando...</div>
<input id="message" type="text" size="80" onkeyup="keyup(event);" />
<input type="button" value="Enviar" onclick="chat_write();" /><br />
<div style="width:100%; height:20px;"></div>
</div>
<script language="JavaScript" type="text/javascript" src="chat.php"></script>
<?php } ?>
</body>
</html>
<script type="text/javascript" src="js/principal.js"></script>
<?php if (isset($_SESSION['s_usuario'])){
if (isset($_POST['personaje'])){ $_SESSION['s_personaje'] = $_POST['personaje']; }
?>
<script>
$(window).unload( function () {
$.post("inc/salir.php", { id_local: usuarioID } );
//alert("Gracias por jugar!");
} );
login = true;
usuarioID = <?php echo $_SESSION['s_personaje']; ?>;
</script>
<?php } ?><file_sep>/salir.php
<?php
session_start();
include("inc/config.php");
$localPos = mysql_query("UPDATE personajes SET online = '0' WHERE id = '".$_SESSION['s_id']."'");
session_destroy();
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script language="javascript">
$(document).ready(function() {
location.href="index.php";
});
</script><file_sep>/inc/main.php
<?php
include("config.php");
session_start();
// El Mapa xD
echo "<style>
#juego{
width:700px;
height:500px;
background:url(img/pasto2.jpg);
position:relative;
left:50%;
margin-left:-350px;
}
</style>";
// Mostrar el jugador local
$localPos = mysql_query("SELECT * FROM personajes WHERE id = '".$_GET['id']."'");
$localPos = mysql_fetch_array($localPos);
$local_div = "
<style>
.localDiv{
width: 30px;
height: 30px;
background:url(img/cabeza.png) no-repeat;
position:absolute;
left:".$localPos['posx']."px;
top:".$localPos['posy']."px;
}
</style>
";
// Nombre del personaje para la sesión.
$_SESSION['s_personaje_nombre'] = $localPos['nombre'];
echo $local_div."<div class='localDiv' id='".$localPos['id']."'><div style='position:absolute; width:70px; text-align:center; font-size:12px; left:-20px; top:-18px; color:#000;'><b>".$_SESSION['s_personaje_nombre']."</b></div></div>";
// Mostrar otros jugadores conectados
$otros = mysql_query("SELECT * FROM personajes WHERE online = '1'");
while ($otro = mysql_fetch_array($otros)){
if ($otro['id'] != $_GET['id']){
echo "<div id='".$otro['id']."' style='position:absolute; width:30px; height:30px; background:url(img/cabeza.png) no-repeat; left: ".$otro['posx']."; top: ".$otro['posy']."; color:#000;'><div style='position:absolute; width:70px; text-align:center; font-size:12px; left:-20px; top:-18px;'>".$otro['nombre']."</div></div>";
}
}
?><file_sep>/inc/config.php
<?php
$user="root";
$host="localhost";
$password="";
$database = "NiburujQuery";
$con = mysql_connect($host,$user,$password) or die("Error al conectar al Servidor.");
$db = mysql_select_db($database,$con) or die ("Error al seleccionar base de datos.");
?><file_sep>/js/principal.js
// Teclas del juego
var KEY = {
// Jugador 1
UP: 38,
DOWN: 40,
LEFT: 37,
RIGHT: 39,
ENTER: 13
}
var areaHeight = parseInt($("#juego").height());
var areaWidth = parseInt($("#juego").width());
var usuarioID = "";
var login = false;
var niburu = {}
// Un arreglo para guardar las teclas presionadas
niburu.pressedKeys = [];
$(function(){
// Intervalo del Game Loop en milisegundos
niburu.timer = setInterval(gameloop,100);
// Guarda si una tecla está presionada en la variable "pressedKeys"
$(document).keydown(function(e){
niburu.pressedKeys[e.keyCode] = true;
});
$(document).keyup(function(e){
niburu.pressedKeys[e.keyCode] = false;
});
});
// Función llamada cada ciertos milisegundos
function gameloop()
{
if (login == true){
moverPlayer();
$("#juego").load("inc/main.php?id=" + usuarioID);
}
}
function moverPlayer()
{
// Usando el "Timer" comprobamos cada milisegundo si está oprimida.
if (niburu.pressedKeys[KEY.UP]) // Flecha arriba
{
// Mover jugador 2 hacia arriba
var top = parseInt($("#" + usuarioID).css("top"));
// Limitar movimiento sin salir del área
if (top >= 10){
$("#" + usuarioID).css("top",top-10);
$.post("inc/mover.php", { posy: parseInt($("#" + usuarioID).css("top")), id_local: usuarioID } );
}
}
if (niburu.pressedKeys[KEY.DOWN]) // Flecha abajo
{
// Mover jugador 2 hacia abajo
var top = parseInt($("#" + usuarioID).css("top"));
// Limitar jugador hacia abajo
if ((parseInt($("#" + usuarioID).css("top"))) <= (areaHeight - (parseInt($("#" + usuarioID).css("height")) + 10))){
$("#" + usuarioID).css("top",top+10);
$.post("inc/mover.php", { posy: parseInt($("#" + usuarioID).css("top")), id_local: usuarioID } );
}
}
if (niburu.pressedKeys[KEY.LEFT]) // Flecha arriba
{
// Mover jugador 2 hacia arriba
var left = parseInt($("#" + usuarioID).css("left"));
// Limitar movimiento sin salir del área
if (left >= 10){
$("#" + usuarioID).css("left",left-10);
$.post("inc/mover.php", { posx: parseInt($("#" + usuarioID).css("left")), id_local: usuarioID } );
}
}
if (niburu.pressedKeys[KEY.RIGHT]) // Flecha abajo
{
// Mover jugador 2 hacia abajo
var left = parseInt($("#" + usuarioID).css("left"));
// Limitar jugador hacia abajo
if ((parseInt($("#" + usuarioID).css("left"))) <= (areaWidth - (parseInt($("#" + usuarioID).css("width")) + 10))){
$("#" + usuarioID).css("left",left+10);
$.post("inc/mover.php", { posx: parseInt($("#" + usuarioID).css("left")), id_local: usuarioID } );
}
}
}<file_sep>/login.php
<?php
session_start();
include("inc/config.php");
if (!isset($_SESSION["s_usuario"])) {
$usuario = $_POST['usuario'];
$password = $_POST["<PASSWORD>"];
$result = mysql_query("SELECT * FROM usuarios WHERE usuario='".$usuario."'");
if($row = mysql_fetch_array($result)){
if($row["password"] == $password){
$_SESSION["s_usuario"] = $row['usuario'];
$_SESSION["s_id"] = $row['id'];
//Elimina el siguiente comentario si quieres que re-dirigir automáticamente a index.php
echo "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script><script>
$(document).ready(function() {
location.href='./login.php';
});
</script></html>";
}else{
echo 'Contraseña incorrecta...';
echo "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script><script>
$(document).ready(function() {
location.href='./index.php';
});
</script></html>";
}
} else{
echo '<html><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script><body>Datos incorrectos, redirigiendo al inicio....</body>';
echo "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script><script>
$(document).ready(function() {
location.href='./index.php';
});
</script></html>";
}
@mysql_free_result($result);
mysql_close();
} else {
?>
<html>
<head>
<title>Niburu Online - Elige tu personaje</title>
</head>
<body style="overflow:hidden;">
<div style="position:absolute; z-index:-1; width:100%; height:100%;">
<img src="http://www.deviantart.com/download/65228468/2D_RPG_game_background_by_willowWISP.jpg" style="width:100%;"/>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<link rel="stylesheet" href="css/estilo.css" type="text/css" media="screen">
<script src="js/jquery.uniform.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
$(function(){
$("input, textarea, select, button").uniform();
});
</script>
<link rel="stylesheet" href="css/uniform.default.css" type="text/css" media="screen">
<div id="elegir" style="position:relative; left:50%; margin-left:-150px; top:20px;">
<form name="personaje" method="post" action="index.php">
<ul>
<li>
<label>Elige un personaje:</label>
<select name="personaje" style="width:200px;">
<option value="todas" selected>Selecciona un Personaje</option>
<?php $personajes = mysql_query("SELECT * FROM personajes WHERE id_usuario = '".$_SESSION["s_id"]."'");
while ($pers = mysql_fetch_array($personajes)){
?>
<option value="<?php echo $pers['id'] ?>"><?php echo $pers['nombre'] ?></option>
<?php } ?>
</select> <input type="submit" value="Seleccionar"/>
</li>
</ul>
</form>
</div>
</body>
</html>
<?php } ?> | 6731d3bb797f0cefc28ef7fd21256aaae4142fcd | [
"JavaScript",
"PHP"
] | 8 | PHP | Techbot/Niburu-Online | 0956b75f9304813bec42bc1ef177ac09314937a8 | 6171be9027a585c1956678996ca666af2f062f1d | |
refs/heads/master | <repo_name>NickSmithNYC/ruby-intro-to-arrays-lab-001-prework-web<file_sep>/lib/intro_to_arrays.rb
def instantiate_new_array
[]
end
def array_with_two_elements
[0, 1]
end
def first_element(array)
taylor_swift = ["Welcome to New York", 1]
taylor_swift[0]
end
def third_element(array)
array = ["Welcome to New York", 1, "Style"]
array[2]
end
def last_element(array)
array = ["Welcome to New York", 1, "Out of The Woods"]
array[-1]
end
def first_element_with_array_methods(array)
south_east_asia = ["Thailand", 1]
array.shift
end
def last_element_with_array_methods(array)
south_east_asia = ["Thailand", "Myanmar"]
south_east_asia.pop
end
def length_of_array(array)
south_east_asia = ["Thailand", "Myanmar", 2, 3, 4, 5, 6, 7]
south_east_asia.count
end | fc10a5b4394f795a9bb7877bdab7cf90e55e9efd | [
"Ruby"
] | 1 | Ruby | NickSmithNYC/ruby-intro-to-arrays-lab-001-prework-web | 5cd494e5708bf9fb7061a7706e82343ef385f1fe | 70653fc94fff6862b0048ac78cbaf136deb4a1ef | |
refs/heads/master | <repo_name>eat-code/ico<file_sep>/post-format/content-image.php
<?php if( is_single() ): ?>
<article id="post-<?php the_ID(); ?>" <?php post_class('icocrypt-post melody-single-post single-content-flat'); ?>>
<?php else: ?>
<article id="post-<?php the_ID(); ?>" <?php post_class('icocrypt-post melody-single-post melody-index-post'); ?>>
<?php endif; ?>
<?php if ( has_post_thumbnail() && !is_single() ){ ?>
<div class="blog-details-img">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('melody-gallery', array('class' => 'img-fluid')); ?></a>
</div>
<?php } ?>
<div class="icocrypt-blog-content clearfix">
<?php if (is_single()) { ?>
<div class="thm-post-top">
<!-- Content Single Top -->
<?php get_template_part( 'post-format/content-single-top' ); ?>
<div class="melody-single-post-feature text-center">
<?php the_post_thumbnail('melody-large', array('class' => 'img-fluid')); ?>
</div>
</div>
<div class="row">
<div class="col">
<div class="entry-blog">
<?php
get_template_part( 'post-format/entry-content-blog' );
?>
</div> <!--/.entry-meta -->
</div>
</div>
<?php } ?>
<!-- Content Single Bottom -->
<?php get_template_part( 'post-format/content-single-bottom' ); ?>
<?php if(get_theme_mod( 'blog_read_more', false )) { ?>
<?php if(!is_single()){ ?>
<?php if ( get_theme_mod( 'blog_continue_en', true ) ) { ?>
<?php if ( get_theme_mod( 'blog_continue', 'Read More' ) ) { ?>
<a class="btn btn-read-more" href="<?php the_permalink(); ?>"><i class="fa fa-arrow-right"></i></a>
<?php } ?>
<?php }?>
<?php }?>
<?php }?>
</div>
</article><!--/#post-->
<file_sep>/404.php
<?php
/*
*Template Name: 404 Page Template
*/
get_header('alternative');
$bg_img = get_theme_mod( '404_bg_img', get_parent_theme_file_uri( 'images/404.jpg' ) );
$error_img = get_theme_mod( '404_img', get_parent_theme_file_uri( 'images/404.png' ) );
$html = esc_html( '<a href="http://www.example.com/">A link</a>');
?>
<div class="text-center icocrypt-error-wrapper" style="background-image: url(<?php echo $bg_img; ?>)">
<!-- <h1 class="error-title"><?php echo esc_html(get_theme_mod( '404_title', esc_html__('Page not found', 'icocrypt'))); ?></h1> -->
<div class="error-img">
<img src="<?php echo $error_img; ?>" alt="">
</div>
<p class="error-message"><?php echo esc_html(get_theme_mod( '404_description', '' )); ?></p>
<div class="error-button">
<p><?php echo __('Sorry, we cant find the page you are looking for '.'</br>'.'
Click '.'<a href="'.home_url('/').'">here</a>'.' to come back to home page.', 'icocrypt'); ?></p>
</div>
</div>
<?php get_footer('alternative'); ?><file_sep>/post-format/entry-content-blog.php
<!-- Single Page content -->
<div class="entry-summary clearfix">
<?php
if ( is_single() ) {
the_content();
}
wp_link_pages( array(
'before' => '<div class="page-links"><span class="page-links-title">' . esc_html__( 'Pages:', 'icocrypt' ) . '</span>',
'after' => '</div>',
'link_before' => '<span>',
'link_after' => '</span>',
) );
?>
</div> <!-- //.entry-summary -->
<div class="row single-social-share">
<?php if ( get_theme_mod( 'blog_tags_single', true ) && get_the_tag_list() ) { ?>
<div class="col-md-7 single-tag">
<?php echo get_the_tag_list(); ?>
</div>
<?php } ?>
<div class="col-md-5 text-md-right">
<span class="d-inline-block single-share-text"><?php echo esc_attr__( 'Share', 'icocrypt' ); ?></span>
<span class="d-inline-block"><?php get_template_part( 'post-format/social-buttons' ); ?></span>
</div>
</div>
<div class="single-author-meta">
<div class="media">
<div class="thm-author-img" title="Written by <?php echo get_the_author_meta('display_name'); ?>" data-toggle="tooltip">
<?php echo get_avatar( get_the_author_meta( 'ID' ) , 90 ); ?>
</div>
<div class="media-body">
<div class="row">
<div class="col-md-6 col-9 single-user-info">
<a href="<?php the_permalink(); ?>"><h4 class="mt-0"> <?php the_author_posts_link(); ?></h4></a>
</a>
<?php
echo get_the_author_meta('description');
?>
</div>
<div class="col-md-6 col-3 text-right">
<?php $user_follow = get_the_author_meta('follow'); ?>
<a href="<?php echo $user_follow; ?>" class="btn btn-follow" target="_blank"><?php echo esc_attr__( 'Follow', 'icocrypt' );; ?></a>
</div>
</div>
</div>
</div>
</div>
<?php
if ( is_singular( 'post' ) ){
$count_post = esc_attr( get_post_meta( $post->ID, '_post_views_count', true) );
if( $count_post == ''){
$count_post = 1;
add_post_meta( $post->ID, '_post_views_count', $count_post);
}else{
$count_post = (int)$count_post + 1;
update_post_meta( $post->ID, '_post_views_count', $count_post);
}
} ?>
<div class="usehlhdkjs">
<?php if ( get_theme_mod( 'blog_single_comment_en', true ) ) {
if ( comments_open() || get_comments_number() ) {
comments_template();
}
} ?>
</div>
<file_sep>/footer.php
<?php if ( get_theme_mod( 'footer_en', true )) { ?>
<footer id="footer-wrap">
<div class="container">
<div class="row clearfix">
<?php if ( get_theme_mod( 'copyright_en', true )) { ?>
<div class="col-sm-12 col-md-6">
<div class="footer-copyright">
<?php if( get_theme_mod( 'copyright_en', true ) ) { ?>
<?php echo wp_kses_post(balanceTags( get_theme_mod( 'copyright_text', '© 2018 IcoCryopt. All Rights Reserved.') )); ?>
<?php } ?>
</div> <!-- col-md-6 -->
</div> <!-- end footer-copyright -->
<?php } ?>
<?php if(get_theme_mod( 'copyright_en', true )){ ?>
<div class="col-sm-12 col-md-6 text-md-right">
<?php }else{ ?>
<div class="col-sm-12 col-md-12 text-center">
<?php }?>
<?php if ( has_nav_menu( 'footer' ) ) { ?>
<div class="footer-menu">
<?php wp_nav_menu(
array(
'theme_location' => 'footer',
'container' => false,
'menu_class' => 'footer-nav'
)
); ?>
</div>
<?php } ?>
</div>
</div><!--/.row clearfix-->
</div><!--/.container-->
</footer><!--/#footer-wrap-->
<?php } ?>
</div> <!-- #page -->
<?php wp_footer(); ?>
</body>
</html>
<file_sep>/post-format/content.php
<?php if( is_single() ): ?>
<article id="post-<?php the_ID(); ?>" <?php post_class('icocrypt-post icocrypt-single-post single-content-flat'); ?>>
<?php else: ?>
<article id="post-<?php the_ID(); ?>" <?php post_class('icocrypt-post icocrypt-single-post icocrypt-index-post'); ?>>
<?php endif; ?>
<?php if ( has_post_thumbnail() && !is_single() ){ ?>
<div class="blog-details-img">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('icocrypt-gallery', array('class' => 'img-fluid')); ?>
</a>
</div>
<?php } ?>
<div class="icocrypt-blog-content clearfix">
<?php if (is_single()) { ?>
<div class="thm-post-top">
<!-- Content Single Top -->
<?php get_template_part( 'post-format/content-single-top' ); ?>
<div class="icocrypt-single-post-feature text-center">
<?php the_post_thumbnail('icocrypt-large', array('class' => 'img-fluid')); ?>
</div>
</div>
<div class="row">
<div class="col">
<div class="entry-blog">
<?php
get_template_part( 'post-format/entry-content-blog' );
?>
</div> <!--/.entry-meta -->
</div>
</div>
<?php } ?>
<!-- Content Single Bottom -->
<?php get_template_part( 'post-format/content-single-bottom' ); ?>
<?php if(get_theme_mod( 'blog_read_more', false )) { ?>
<?php if(!is_single()){ ?>
<?php if ( get_theme_mod( 'blog_continue_en', true ) ) { ?>
<?php if ( get_theme_mod( 'blog_continue', 'Read More' ) ) { ?>
<a class="btn btn-read-more" href="<?php the_permalink(); ?>"><i class="fa fa-arrow-right"></i></a>
<?php } ?>
<?php }?>
<?php }?>
<?php }?>
</div>
</article><!--/#post-->
| ef7ea5f42b50290561a492e289fd590583519a4f | [
"PHP"
] | 5 | PHP | eat-code/ico | 71f04e1553a24e4b70e18839ccfa9075a1c92c8c | 63f8fb7678483bfe8a603d60e8b5c1f10d123b60 | |
refs/heads/master | <repo_name>jmpolitzer/use-api-request<file_sep>/src/useApiRequest/index.js
import { useReducer, useCallback } from "react";
import { handleFetching, handleSuccess, handleError } from "./actions";
import buildReducer from "./reducer";
function useApiRequest({ axios, key, debug }) {
const initialState = {
fetching: [],
resources: {},
errors: {}
};
const reducer = useCallback(buildReducer(debug), [key]);
const [state, dispatch] = useReducer(reducer, initialState);
const replaceParams = (url, response) => {
const matches = url.match(/\{{.*?\}}/g);
if (matches && matches.length > 0) {
const params = matches.map(match =>
match.replace("{{", "").replace("}}", "")
);
return matches.reduce((acc, match, i) => {
const param = params[i].split(".").reduce((pAcc, fragment, j) => {
return pAcc[fragment];
}, response);
return acc.replace(match, param);
}, url);
} else {
return url;
}
};
const onError = (resource, error) => {
dispatch(handleError(resource, error));
};
const makeApiRequest = (config, prevResponse) => {
const resource = Object.keys(config)[0];
const { next, isNext, url, ...rest } = config[resource];
const request = { ...rest, url: replaceParams(url, prevResponse) };
if (!isNext) dispatch(handleFetching([resource]));
axios
.request(request)
.then(response => {
if (next) {
const nextConfig = { [resource]: { ...next, isNext: true } };
makeApiRequest(nextConfig, response);
} else {
dispatch(handleSuccess([resource], { [resource]: response }));
}
})
.catch(e => onError([resource], { [resource]: e }));
};
const makeApiRequests = config => {
const resources = Object.keys(config);
dispatch(handleFetching(resources));
Promise.all(
resources.map(key =>
axios.request({
...config[key],
headers: {
resourceKey: key
}
})
)
)
.then(responses => {
const response = resources.reduce((acc, resource, i) => {
acc[resource] = responses[i];
return acc;
}, {});
dispatch(handleSuccess(resources, response));
})
.catch(e => {
const resource = e.config.headers.resourceKey;
return onError(resources, { [resource]: e });
});
};
return { state, makeApiRequest, makeApiRequests };
}
export default useApiRequest;
<file_sep>/src/useApiRequest/reducer.js
import logger from './helpers/logger'
const filterFetching = (action, state) =>
state.fetching.filter(
resource => !action.payload.resource.includes(resource)
)
const filterResourcesOrErrors = (resource, resources) => {
const r = Object.keys(resources).reduce((acc, res) => {
if (!resource.includes(res)) {
acc[res] = resources[res]
}
return acc
}, {})
return r
}
function createReducer() {
return function(state, action) {
const { resource } = action.payload
switch (action.type) {
case `${resource}/FETCHING`:
return {
fetching: [...state.fetching, action.payload.resource].reduce(
(acc, val) => acc.concat(val),
[]
),
resources: filterResourcesOrErrors(
action.payload.resource,
state.resources
),
errors: filterResourcesOrErrors(action.payload.resource, state.errors)
}
case `${resource}/SUCCESS`:
return {
fetching: filterFetching(action, state),
resources: {
...state.resources,
...action.payload.response
},
errors: filterResourcesOrErrors(action.payload.resource, state.errors)
}
case `${resource}/ERROR`:
return {
fetching: filterFetching(action, state),
resources: filterResourcesOrErrors(
action.payload.resource,
state.resources
),
errors: {
...state.errors,
...action.payload.error
}
}
}
}
}
function buildReducer(debug) {
const reducer = createReducer()
/* istanbul ignore next */
if (debug === true && process.env.NODE_ENV === 'development') {
return logger(reducer)
} else {
return reducer
}
}
export default buildReducer
<file_sep>/README.md
# use-api-request
> A simple React hook for making network requests using Axios.
[](https://www.npmjs.com/package/use-api-request)
[](https://github.com/prettier/prettier)
[](https://travis-ci.com/jmpolitzer/use-api-request)
[](https://coveralls.io/github/jmpolitzer/use-api-request?branch=master)
## Install
```
npm install --save use-api-request
```
## Example
```javascript
import axios from 'axios';
import { useApiRequest } from 'use-api-request';
function MyComponent() {
const apiConfig = {
axios: axios.create({
baseURL: "https://whereami.com/"
}),
key: "example",
debug: true
};
const { state, makeApiRequest } = useApiRequest(apiConfig);
const { fetching, resources: { posts }, errors } = state;
const requestConfig = {
posts: {
url: "/posts"
}
};
return (
<>
<button onClick={() => makeApiRequest(requestConfig)}>Get Posts</button>
<>
{fetching.includes("posts") && <div>fetching</div>}
{posts.data.length > 0 && posts.data.map(post =>
<div key={post.id}>{post.title}</div>) }
{errors.posts && <div>{errors.posts.message}</div>}
</>
</>
);
}
```
## Usage
1. Pass a config object with an Axios instance and a unique `key` string into `useApiRequest`. The Axios instance takes the exact same configurations as specified in the [documentation](https://www.npmjs.com/package/axios). Optionally include a `debug` flag if you'd like to see redux-like logging in your console.
2. Create a request object -- again, refer to the [Axios documentation](https://www.npmjs.com/package/axios) for examples -- and pass it into `makeApiRequest`. Note that this library uses `Axios.request()` under the hood. The request object is nothing more than an Axios request config object assigned to a resource key of your choosing. So, if you name the key `things`, you will find `things` many times within the state object. See below for more details.
3. Call `makeApiRequest` and look for your response on the resources key of the `state` object provided by `useApiRequest`.
## Features
Make a single request:
```javascript
const singleRequestConfig = {
posts: {
url: "/posts"
}
};
makeApiRequest(singleRequestConfig);
```
Make multiple concurrent requests:
```javascript
const concurrentRequestsConfig = {
albums: {
url: "/albums"
},
users: {
url: "/users"
}
};
makeApiRequests(concurrentRequestsConfig);
```
Make a sequential request (dependent variables are wrapped in double curly brackets and will always be properties of `data`):
```javascript
const sequentialRequestConfig = {
userPosts: {
url: "/posts/1",
next: {
url: "/posts?userId={{data.userId}}"
}
}
};
makeApiRequest(sequentialRequestConfig);
```
## API
```javascript
const { state, makeApiRequest, makeApiRequests } = useApiRequest(apiConfig);
const { fetching, resources, errors } = state;
```
`fetching` - array of strings corresponding to the resource key(s) used in the request config
`resources` - object of successful responses; each response can be found under the key used in the request config, and each response contains the entire response generated by Axios
`errors` - object of errors; each error can be found under the key used in the request config, and each error contains the entire error generated by Axios
## License
MIT © [jmpolitzer](https://github.com/jmpolitzer)
<file_sep>/src/useApiRequest/__mocks__/componentMock.js
import React from 'react'
import { useApiRequest } from '../../index'
/* eslint-disable-next-line react/prop-types */
function ComponentMock({ axios }) {
const apiConfig = {
axios: axios,
key: 'testing',
debug: true
}
const { state, makeApiRequest, makeApiRequests } = useApiRequest(apiConfig)
const {
fetching,
resources: { things, thangs, thingThangs },
errors
} = state
const thingsRequest = {
things: {
url: '/things'
}
}
const multiRequest = {
thangs: {
url: '/thangs'
},
things: {
url: '/things'
}
}
const sequentialRequest = {
thingThangs: {
url: '/things/2',
next: {
url: '/thangs?thingId={{data.id}}'
}
}
}
return (
<div>
<button onClick={() => makeApiRequest(thingsRequest)}>Get Things</button>
<button onClick={() => makeApiRequests(multiRequest)}>
Get Multiple Resources
</button>
<button onClick={() => makeApiRequest(sequentialRequest)}>
Get ThingThangs
</button>
{fetching.includes('things') && (
<div data-testid='fetching-things'>fetching things</div>
)}
{things &&
things.data.length > 0 &&
things.data.map(thing => (
<div data-testid='thing' key={thing.id}>
{thing.text}
</div>
))}
{errors.things && (
<div data-testid='things-error'>{errors.things.message}</div>
)}
{fetching.includes('thangs') && (
<div data-testid='fetching-thangs'>fetching multiple resources</div>
)}
{thangs &&
thangs.data.length > 0 &&
thangs.data.map(thang => (
<div data-testid='thang' key={thang.id}>
{thang.text}
</div>
))}
{errors.thangs && (
<div data-testid='thangs-error'>{errors.thangs.message}</div>
)}
{fetching.includes('thingThangs') && (
<div data-testid='fetching-thingThangs'>fetching thingThangs</div>
)}
{thingThangs &&
thingThangs.data.length > 0 &&
thingThangs.data.map(thingThang => (
<div data-testid='thingThang' key={thingThang.id}>
{thingThang.text}
</div>
))}
</div>
)
}
export default ComponentMock
<file_sep>/src/index.js
import useApiRequest from "./useApiRequest";
export { useApiRequest };
| d4f0ff9955d7b87d0b5b202f375d138e8ec55928 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | jmpolitzer/use-api-request | 6c6506e5a045a515653cf439fd8377ce0daf3404 | d4c322e016a4a77c05f3e68e8fa2ac73173196d2 | |
refs/heads/master | <file_sep>class CreateTeamsCardsJoinTable < ActiveRecord::Migration[5.1]
def change
create_join_table :teams, :cards
end
end
<file_sep>class Card < ApplicationRecord
belongs_to :list
has_and_belongs_to_many :teams
end
<file_sep>class ListSerializer < ActiveModel::Serializer
attributes :id, :name, :cards
def cards
cards = object.cards.map do |c|
{
id: c.id,
teams: teams(c),
title: c.title
}
end
return cards
end
def teams(card)
teams = card.teams.map { |t| {id: t.id, name: t.name} }
end
end<file_sep>class Team < ApplicationRecord
has_and_belongs_to_many :cards
end
<file_sep>class List < ApplicationRecord
has_many :cards
end
<file_sep>class CardSerializer < ActiveModel::Serializer
attributes :id, :title, :teams
def teams
teams = object.teams.map { |t| {id: t.id, name: t.name} }
end
end<file_sep>Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :teams
resources :cards do
member do
get 'add_team/:team_id', to: "cards#add_team"
get 'rem_team/:team_id', to: "cards#rem_team"
end
end
resources :posts
resources :lists
end
end
match '*path', via: [:options], to: lambda {|_| [204, { 'Content-Type' => 'text/plain' }]}
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
<file_sep>class Api::V1::CardsController < ApplicationController
before_action :set_card, only: [:show, :update, :destroy, :add_team, :rem_team]
before_action :set_team, only: [:add_team, :rem_team]
# GET /cards
def index
@cards = Card.all
render json: @cards
end
# GET /cards/1
def show
render json: @card
end
# POST /cards
def create
@card = Card.new(card_params)
if @card.save
render json: @card, status: :created
else
render json: @card.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /cards/1
def update
if @card.update(card_params)
render json: @card
else
render json: @card.errors, status: :unprocessable_entity
end
end
def add_team
@card.teams << @team
render json: @card, status: :created
end
def rem_team
@card.teams = @card.teams.select{|t| !t.eql?(@team)}
render json: @card, status: :created
end
# DELETE /cards/1
def destroy
@card.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_card
@card = Card.find(params[:id])
end
def set_team
@team = Team.find(params[:team_id])
end
# Only allow a trusted parameter "white list" through.
def card_params
params.require(:card).permit(:title, :list_id)
end
end
| 74dadc3adc6728a388527a2b2dbc563470c458bb | [
"Ruby"
] | 8 | Ruby | mhadzakaria/api_trilli | 24b38e0bea281a68c85828645e52db2638f2d219 | a534c0245e75a2354f5e00232a68c5f6f88caf12 | |
refs/heads/master | <repo_name>BenjamLC/node-irc<file_sep>/reso-irc-server/app.js
const express = require('express');
const app = express();
server = app.listen(3001, function(){
console.log('server listening on port 3001');
});
const io = require('socket.io')(server);
const irc = require('irc');
let ircConf = {
server: 'chat.freenode.net',
globalChannel: '#conserto-reso-test'
};
let users = [];
io.on('connection', function (socket) {
socket.emit('GET_NICKNAME');
let client;
socket.on('NICKNAME', function (nickname) {
client = new irc.Client(ircConf.server, nickname, {
autoConnect: false
});
client.nickname = nickname;
client.addListener('error', function (message) {
console.log('error: ', message)
});
client.connect(() => {
client.join(ircConf.globalChannel, () => {
client.addListener('message' + ircConf.globalChannel, function (author, content) {
socket.emit('MESSAGE', {
author: author,
content: content
});
});
socket.emit('CONNECTED');
});
});
});
socket.on('SAY', function (content) {
if (client) {
client.say(ircConf.globalChannel, content);
socket.emit('MESSAGE', {
author: client.nickname,
content: content
});
}
});
socket.on('disconnect', function () {
client.part(ircConf.globalChannel, () => {
client.disconnect();
});
});
});
let watchClient = new irc.Client(ircConf.server, 'bot_watch', {
autoConnect: false
});
watchClient.addListener('error', function (message) {
console.log('error: ', message)
});
watchClient.connect(() => {
watchClient.join(ircConf.globalChannel, () => {
watchClient.addListener('names' + ircConf.globalChannel, (nicknames) => {
users = [];
for (let nickname in nicknames) {
if (nicknames.hasOwnProperty(nickname) && nickname !== 'bot_watch') {
users.push({ nickname: nickname });
}
}
io.emit("USER_LIST_UPDATE", users);
});
watchClient.addListener('join' + ircConf.globalChannel, () => {
watchClient.send('NAMES', ircConf.globalChannel);
});
watchClient.addListener('part' + ircConf.globalChannel, () => {
watchClient.send('NAMES', ircConf.globalChannel);
});
watchClient.addListener('kick' + ircConf.globalChannel, () => {
watchClient.send('NAMES', ircConf.globalChannel);
});
watchClient.addListener('kill', () => {
watchClient.send('NAMES', ircConf.globalChannel);
});
watchClient.addListener('quit', () => {
watchClient.send('NAMES', ircConf.globalChannel);
});
});
});
| 22388a3ab5c2b738d7b5100bc1688ff05e6a7485 | [
"JavaScript"
] | 1 | JavaScript | BenjamLC/node-irc | 65a97eb2e2c369487256733c0c5411d8ae765a08 | 958781743d8e3c2209e38a1a842a2f856a50b7fa | |
refs/heads/master | <repo_name>gillstrom/brwsr<file_sep>/index.js
'use strict';
module.exports = function () {
var browsers = {
'Google Chrome': require('is-chrome'),
'Internet Explorer': require('is-iexplorer'),
'Microsoft Edge': require('is-edge')(),
'Mozilla Firefox': require('is-firefox'),
Opera: require('is-opera'),
Safari: require('is-safari')
};
var ret = Object.keys(browsers).filter(function (key) {
return browsers[key];
});
return ret.length ? ret[0] : null;
};
<file_sep>/readme.md
# brwsr
> Get current browser
*User agent sniffing is [considered](https://developer.mozilla.org/en-US/docs/Browser_detection_using_the_user_agent) bad practice and should be avoided if possible.*
## Install
```
$ npm install --save brwsr
```
## Usage
```js
var brwsr = require('brwsr');
console.log(brwsr());
//=> 'Google Chrome'
```
## License
MIT © [<NAME>](http://github.com/gillstrom)
| 4a067879155ba1dc441c0d6f9126cb1fc5aa2470 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | gillstrom/brwsr | 15a1946fbacc1c393b652132b6488955d2307462 | 4c8eb5737375107c97dd1ecac24220374e747f25 | |
refs/heads/dev | <file_sep>import { GraphQLClient } from 'graphql-request';
export const client = new GraphQLClient('https://graphql.anilist.co/');
<file_sep>import { CmdCategory } from '@prisma/client';
import { kaguya_sleep_gif } from '../../shared/assets';
import { baseEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
const goodnight = new Command({
name: 'goodnight',
description: 'Greets goodnight.',
category: CmdCategory.FUN,
aliases: ['gn'],
args: [{ name: 'user', optional: true, multi: true }],
async execute({ channel, mentions, author }) {
let message;
if (!mentions.users.size) {
message = `Goodnight!`;
} else {
const userNames: string[] = [];
mentions.users.forEach((user) => userNames.push(user.toString()));
message =
userNames.length > 1
? `**${author.username}** wishes ${userNames
.slice(0, userNames.length - 1)
.join(', ')} and ${userNames[
userNames.length - 1
].toString()} goodnight!`
: `${author.toString()} wishes ${userNames[0].toString()} goodnight!`;
}
channel.send(
baseEmbed().setDescription(message).setImage(kaguya_sleep_gif),
);
},
});
export default goodnight;
<file_sep>import type { Client } from 'discord.js';
type IActivityUpdater = (client: Client) => void;
export function setGuildCount(client: Client) {
const guildCount = client.guilds.cache.size;
client.user
?.setActivity({
name: `amogus in ${guildCount} ${
guildCount === 1 ? 'server' : 'servers'
}`,
type: 'PLAYING',
})
.catch((err) => console.error(err));
}
export function setHelp(client: Client) {
client.user
?.setActivity({
name: `ck;help`,
type: 'PLAYING',
})
.catch((err) => console.error(err));
}
export function setChikatto(client: Client) {
client.user
?.setActivity({
name: `<NAME>`,
type: 'LISTENING',
})
.catch((err) => console.error(err));
}
export function setUserCount(client: Client) {
const userCount = client.guilds.cache.reduce((acc, guild) => {
return acc + guild.memberCount;
}, 0);
client.user
?.setActivity({
name: `with ${userCount} ${userCount === 1 ? 'user' : 'users'}`,
type: 'PLAYING',
})
.catch((err) => console.error(err));
}
export const activityUpdaters: IActivityUpdater[] = [
setGuildCount,
setHelp,
setChikatto,
setUserCount,
];
<file_sep>import { CmdCategory } from '@prisma/client';
import { balloonGame } from '../../games/balloon';
import { checkAndBlock } from '../../games/utils/manageState';
import { lightErrorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
const balloon = new Command({
name: 'balloon',
aliases: ['bl'],
args: [],
category: CmdCategory.GAMES,
description: 'Chika hands you a balloon and you must pump it.',
async execute(message) {
checkAndBlock(balloonGame, message).then(
() => balloonGame.pregame(message),
(err) => message.channel.send(lightErrorEmbed(err)),
);
},
});
export default balloon;
<file_sep>import type { Redis } from 'ioredis';
export async function pubGuildCount(redis: Redis, count: number) {
try {
return redis.publish('guild-count-update', count.toString());
} catch (err) {
return console.error(err);
}
}
export async function updateGuildList(redis: Redis, ids: string[]) {
try {
// we'll use the 'inGuilds' key
return redis.set('inGuilds', JSON.stringify(ids));
} catch (err) {
return console.error(err);
}
}
<file_sep>import { CmdCategory } from '@prisma/client';
import { stripIndents } from 'common-tags';
import ms from 'ms';
import { userProvider } from '../../data/providers/userProvider';
import { getCooldown, setCooldown } from '../../lib/cooldownManager';
import { endOfToday } from '../../lib/time';
import { ribbon_emoji } from '../../shared/assets';
import { baseEmbed, lightErrorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
const daily = new Command({
name: 'daily',
category: CmdCategory.CURRENCY,
args: [],
description: 'Collect your daily dose of ribbons.',
async execute(message) {
const { author, channel } = message;
const pttl = await getCooldown(author.id, this.name);
if (pttl) {
channel.send(
lightErrorEmbed(
stripIndents`You've already collected today's ribbons!
Please wait **${ms(pttl)}** before collecting again.`,
),
);
return;
}
const toAward = Math.floor(Math.random() * 200 + 100);
channel.send(
baseEmbed().setDescription(
`**+ ${toAward}** ribbons ${ribbon_emoji} for **${author.username}**!`,
),
);
const nowStamp = Date.now();
const cooldown = endOfToday() - nowStamp;
setCooldown(author.id, this.name, cooldown);
userProvider.incrRibbons(author, toAward);
},
});
export default daily;
<file_sep>import he from 'he';
export const parseHtml = (s: string) =>
he.decode(s.replace(/(<([^>]+)>)/gi, ''));
export const truncate = (s: string, max: number, byWord = false) => {
if (byWord) {
const words = s.split(' ');
if (words.length < max) return s;
return `${words.slice(0, max).join(' ')} ...`;
}
if (s.length <= max) return s;
return `${s.substring(0, max)} ...`;
};
export const wrapText = (s: string) =>
s.replace(/(?![^\n]{1,40}$)([^\n]{1,40})\s/g, '$1\n');
export const groupNum = new Intl.NumberFormat('en-US', { useGrouping: true });
export const withAnd = (words: string[]) => {
if (words.length === 1) return words[0];
if (words.length === 2) return `${words[0]} and ${words[1]}`;
return `${words
.slice(0, words.length - 1)
.map((word) => `${word},`)
.join(' ')} and ${words[words.length - 1]}`;
};
<file_sep>import { CmdCategory } from '@prisma/client';
import { lightErrorEmbed, withAuthorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { sendMusicOnlyInGuild, trackLinkAndDuration } from './utils/embeds';
const resume = new Command({
name: 'resume',
args: [],
category: CmdCategory.MUSIC,
description: 'Resume playback.',
async execute(message) {
const { client, channel, guild, author } = message;
if (!guild) {
sendMusicOnlyInGuild(channel);
return;
}
const audioUtils = client.cache.audioUtils.get(guild.id);
if (!audioUtils?.dispatcher.paused) {
channel.send(lightErrorEmbed('There is nothing to resume...'));
return;
}
audioUtils.dispatcher.resume();
const { title, url, duration } = audioUtils.nowPlaying!;
channel.send(
withAuthorEmbed(author)
.setTitle(`:arrow_forward: Resumed`)
.setDescription(trackLinkAndDuration(title, url, duration)),
);
},
});
export default resume;
<file_sep>import type { Client, ClientEvents } from 'discord.js';
interface Event {
name: keyof ClientEvents;
once: boolean;
listener: (client: Client, ...args: any[]) => Promise<void>;
}
export type { Event };
<file_sep>import { CmdCategory } from '@prisma/client';
import { redisQueue } from '../../data/redisClient';
import { lightErrorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { sendMusicOnlyInGuild, sendRepeat } from './utils/embeds';
const repeat = new Command({
name: 'repeat',
aliases: ['rp'],
category: CmdCategory.MUSIC,
description: 'Repeats the current track once.',
args: [],
async execute(message) {
const { client, channel, guild, author } = message;
if (!guild) {
sendMusicOnlyInGuild(channel);
return;
}
const audioUtils = client.cache.audioUtils.get(guild.id);
if (!audioUtils) {
channel.send(lightErrorEmbed('Nothing is playing now!'));
return;
}
sendRepeat(channel, { videoData: audioUtils.nowPlaying, author });
redisQueue.lpush(guild.id, JSON.stringify(audioUtils.nowPlaying));
},
});
export default repeat;
<file_sep>import { CmdCategory } from '@prisma/client';
import { lightErrorEmbed, sendNotInGuild } from '../../shared/embeds';
import { Command } from '../../types/command';
import { setCooldown } from '../../lib/cooldownManager';
import { sendSearchResults } from './utils/embeds';
import { createResultSelectListener } from './utils/listener';
import { searchVideo } from './utils/youtube';
const search = new Command({
name: 'search',
description: 'Search for a track on YouTube',
args: [{ name: 'search_string', multi: true }],
category: CmdCategory.MUSIC,
channelCooldown: 15000,
async execute(message, args) {
const { channel, client, guild } = message;
if (!guild) {
sendNotInGuild(channel);
return;
}
setCooldown(channel.id, this.name, this.channelCooldown!);
const results = await searchVideo(args.join(' '));
if (!results) {
channel.send(lightErrorEmbed('Your search received no results.'));
return;
}
sendSearchResults(channel, results);
const resultSelectListener = createResultSelectListener(results, {
channelId: channel.id,
guildId: guild.id,
});
const timeoutCallback = () => {
client.removeListener('message', resultSelectListener);
};
client.on('message', resultSelectListener);
client.setTimeout(timeoutCallback, this.channelCooldown!);
},
});
export default search;
<file_sep>import Discord from 'discord.js';
import { setIntervals } from './init/cron';
import { genFullHelpEmbed } from './init/fullHelpEmbed';
import { initialClientCache } from './init/initialClientCache';
import { loadCommands } from './init/loadCommands';
import { loadEventListeners } from './init/loadEventListeners';
import { seedCommands } from './init/seedCommands';
import { setHelp } from './lib/activityUpdaters';
const main = () => {
// instantiate the client
const client = new Discord.Client();
// login to the gateway, and set our status
client.login(process.env.APP_TOKEN).then(() => setHelp(client));
// load commands
client.commands = loadCommands();
// seed commands to our database
seedCommands(client.commands);
// generates help message based on commands
client.commandsHelp = genFullHelpEmbed(client.commands);
// creates a "cache" object
client.cache = initialClientCache;
// apply event listeners
loadEventListeners(client);
client.setMaxListeners(2048);
// "cron-like" jobs
setIntervals(client);
};
process.on('unhandledRejection', (err) => {
console.error(`!!!!! An error has made it to index.ts !!!!!\n`, err);
throw err;
});
main();
<file_sep>import type { Client } from 'discord.js';
import fs from 'fs';
import path from 'path';
import { Event } from '../types/event';
export const loadEventListeners = (client: Client) => {
const eventFiles = fs
.readdirSync(path.join(__dirname, '..', 'events'))
.filter((filename) => filename.endsWith('.js'));
eventFiles.forEach((file) => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const event: Event = require(`../events/${file}`).default;
if (event.once) {
client.once(event.name, async (...args) =>
event.listener(client, ...args),
);
} else {
client.on(event.name, async (...args) => event.listener(client, ...args));
}
});
};
<file_sep>import { commaListsAnd } from 'common-tags';
import { redis } from '../data/redisClient';
import { Event } from '../types/event';
import { updateGuildList } from './lib/guild';
const ready: Event = {
name: 'ready',
once: true,
async listener(client) {
console.log('Chika bot is ready.');
// set guilds in redis
const { cache } = client.guilds;
const ids = cache.map((guild) => guild.id);
await updateGuildList(redis, ids);
console.log(commaListsAnd`We are in ${cache.map((guild) => guild.name)}.`);
},
};
export default ready;
<file_sep>import type { Snowflake } from 'discord.js';
import { forCooldown, redis } from '../data/redisClient';
export const setCooldown = (id: Snowflake, command: string, ms: number) =>
redis.set(forCooldown(`${id}:${command}`), command, 'px', ms);
export const getCooldown = async (id: Snowflake, command: string) => {
// returns in milliseconds
const ttl = await redis.pttl(forCooldown(`${id}:${command}`));
if (ttl <= 0) {
return 0;
}
return ttl;
};
<file_sep>NODE_ENV=
APP_TOKEN=
BOT_USER_ID=
REDISCLOUD_URL=
DATABASE_URL=
HUGGING_FACE_CHIKA=
HUGGING_FACE_CHIKA_KEY=
HUGGING_FACE_KAGUYA=
HUGGING_FACE_KAGUYA_KEY=
ANILIST_SCHEMA=<file_sep>import type { Client, StreamDispatcher, VoiceConnection } from 'discord.js';
import { v4 } from 'uuid';
import ytdl from 'ytdl-core';
import ytpl from 'ytpl';
import ytsr, { Video } from 'ytsr';
import { forNowPlaying, redis } from '../../../data/redisClient';
import { CriticalError } from '../../../shared/errors';
import { GenericChannel } from '../../../types/command';
import { AudioUtils, QueueItem } from '../../../types/queue';
import { sendCannotPlay, sendNowPlaying } from './embeds';
import { secToString } from './helpers';
import type { createFinishListener } from './listener';
const YOUTUBE_URL_RE = /^(https?:\/\/)?((www\.)?youtube\.com|youtu\.?be)\/.+$/;
export const searchVideo = async (
title: string,
maxResults = 10,
): Promise<QueueItem[] | null> => {
const vFilter = (await ytsr.getFilters(title)).get('Type')!.get('Video')!;
const videos = (await ytsr(vFilter.url!, { limit: maxResults }))
.items as Video[];
if (videos.length === 0) return null;
return videos.map(
(video): QueueItem => ({
id: v4(),
title: video.title,
duration: video.duration!,
thumbnailURL: video.bestThumbnail.url!,
url: video.url,
}),
);
};
export const playFromYt = async (
connection: VoiceConnection,
url: string,
): Promise<StreamDispatcher> => {
try {
const dispatcher = await ytdl.getInfo(url).then((info) => {
return connection.play(
ytdl.downloadFromInfo(info, {
filter: 'audioonly',
quality: 'highestaudio',
highWaterMark: 1 << 25,
}),
);
});
return dispatcher;
} catch (err) {
console.error(err);
if (err.statusCode >= 400) {
throw new Error('YouTube has blocked us, or something bad has happened.');
} else {
throw err;
}
}
};
export const validateArgs = async (
args: string[],
): Promise<QueueItem | null> => {
if (YOUTUBE_URL_RE.test(args[0])) {
const [url] = args;
if (!ytdl.validateURL(url)) return null;
let res: ytdl.videoInfo;
try {
res = await ytdl.getBasicInfo(url);
} catch (err) {
return null;
}
const { videoDetails } = res;
if (!videoDetails) return null;
return {
id: v4(),
title: videoDetails.title,
duration: secToString(parseInt(videoDetails.lengthSeconds, 10)),
url: videoDetails.video_url,
thumbnailURL: videoDetails.thumbnails[0].url,
};
}
const res = await searchVideo(args.join(' '), 1);
if (!res) return null;
return { ...res[0] };
};
interface PlaylistMetadata {
title: string;
thumbnailURL: string;
url: string;
}
export const parsePlaylist = (
res: ytpl.Result,
): [PlaylistMetadata, QueueItem[]] => {
const metadata: PlaylistMetadata = {
title: res.title,
url: res.url,
thumbnailURL: res.bestThumbnail.url!,
};
const items = res.items.map(
(item): QueueItem => ({
id: v4(),
url: item.shortUrl,
title: item.title,
thumbnailURL: item.bestThumbnail.url!,
duration: item.duration!,
}),
);
return [metadata, items];
};
interface playThisParams {
client: Client;
channel: GenericChannel;
guildId: string;
onFinish: ReturnType<typeof createFinishListener>;
}
export const playThis = async (
connection: VoiceConnection,
videoData: QueueItem,
{ client, channel, guildId, onFinish }: playThisParams,
): Promise<void> => {
try {
const dispatcher = await playFromYt(connection, videoData.url);
redis.set(forNowPlaying(guildId), JSON.stringify(videoData));
sendNowPlaying(channel, videoData);
const newAudioUtils: AudioUtils = {
connection,
dispatcher,
nowPlaying: videoData,
};
dispatcher.on('finish', onFinish);
client.cache.audioUtils.set(guildId, newAudioUtils);
} catch (err) {
sendCannotPlay(channel, videoData.title, videoData.url);
connection.disconnect();
if (err instanceof CriticalError) throw err;
}
};
<file_sep>import { CmdCategory } from '@prisma/client';
import { guildProvider } from '../../data/providers/guildProvider';
import { isAdmin } from '../../lib/validateMessages';
import { baseEmbed, sendNotInGuild } from '../../shared/embeds';
import { Command } from '../../types/command';
const prefix = new Command({
name: 'set-prefix',
args: [{ name: 'new_prefix' }],
category: CmdCategory.UTILITY,
description: "Set a new prefix for Chika. You'll need to be an admin.",
async execute(message, args) {
const { channel, guild } = message;
if (!guild) {
sendNotInGuild(channel);
return;
}
if (!isAdmin(message)) return;
const [newPrefix] = args;
guildProvider.setPrefix(guild.id, newPrefix);
channel.send(
baseEmbed().setDescription(`Chika's prefix is now **${newPrefix}**`),
);
},
});
export default prefix;
<file_sep>import { TextChannel } from 'discord.js';
import { mock } from 'jest-mock-extended';
import * as Embeds from '../shared/embeds';
import { Command } from '../types/command';
import { validateArgsCount } from './validateArgsCount';
jest.mock('discord.js');
jest.mock('../shared/embeds');
describe('#validateArgsCount', () => {
const mockCommand = mock<Command>();
const mockChannel = mock<TextChannel>();
const embedErrorSpy = jest.spyOn(Embeds, 'lightErrorEmbed');
const channelSendSpy = jest.spyOn(mockChannel, 'send');
beforeEach(() => {
embedErrorSpy.mockClear();
channelSendSpy.mockClear();
});
describe('for command with no params', () => {
beforeEach(() => {
mockCommand.args = [];
});
it('should return null if any args submitted', () => {
expect(validateArgsCount(mockCommand, ['1', '2'], mockChannel)).toBe(
null,
);
expect(validateArgsCount(mockCommand, ['1'], mockChannel)).toBe(null);
expect(embedErrorSpy).toBeCalledTimes(2);
expect(channelSendSpy).toBeCalledTimes(2);
});
it('should return [] if no args submitted', () => {
const args: string[] = [];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
});
describe('for command with N mono-required params', () => {
beforeEach(() => {
mockCommand.args = [{ name: 'arg1' }, { name: 'arg2' }];
});
it('should return null if args < N', () => {
expect(validateArgsCount(mockCommand, ['1'], mockChannel)).toBe(null);
expect(embedErrorSpy).toBeCalledTimes(1);
expect(channelSendSpy).toBeCalledTimes(1);
});
it('should return null if args > N', () => {
expect(validateArgsCount(mockCommand, ['1', '2', '3'], mockChannel)).toBe(
null,
);
expect(embedErrorSpy).toBeCalledTimes(1);
expect(channelSendSpy).toBeCalledTimes(1);
});
it('should return args if args = N', () => {
const args = ['1', '2'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
});
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
describe('for command with N mono-optional params only', () => {
beforeEach(() => {
mockCommand.args = [
{ name: 'arg1', optional: true },
{ name: 'arg2', optional: true },
];
});
it('should return args if no args submitted', () => {
const args: string[] = [];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
it('should return args if args < N', () => {
const args = ['1'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
it('should return args if args = N', () => {
const args = ['1', '2'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
it('should return null if args > N', () => {
const args = ['1', '2', '3'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(null);
expect(embedErrorSpy).toBeCalledTimes(1);
expect(channelSendSpy).toBeCalledTimes(1);
});
});
describe('for command with N mono-required and M mono-optional params', () => {
beforeEach(() => {
mockCommand.args = [
{ name: 'arg1' },
{ name: 'arg2' },
{ name: 'arg3', optional: true },
{ name: 'arg4', optional: true },
];
});
it('should return null if args < N', () => {
expect(validateArgsCount(mockCommand, ['1'], mockChannel)).toBe(null);
expect(embedErrorSpy).toBeCalledTimes(1);
expect(channelSendSpy).toBeCalledTimes(1);
});
it('should return args if args = N', () => {
const args = ['1', '2'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
it('should return args if N < args <= N + M', () => {
const args3 = ['1', '2', '3'];
expect(validateArgsCount(mockCommand, args3, mockChannel)).toBe(args3);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
const args4 = ['1', '2', '3', '4'];
expect(validateArgsCount(mockCommand, args4, mockChannel)).toBe(args4);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
it('should return null if args > N', () => {
expect(
validateArgsCount(mockCommand, ['1', '2', '3', '4', '5'], mockChannel),
).toBe(null);
expect(embedErrorSpy).toBeCalledTimes(1);
expect(channelSendSpy).toBeCalledTimes(1);
});
});
describe('for command with N multi-required params', () => {
beforeEach(() => {
mockCommand.args = [
{ name: 'arg1', multi: true },
{ name: 'arg2', multi: true },
];
});
it('should return null if args < N', () => {
expect(validateArgsCount(mockCommand, [], mockChannel)).toBe(null);
expect(validateArgsCount(mockCommand, ['1'], mockChannel)).toBe(null);
expect(embedErrorSpy).toBeCalledTimes(2);
expect(channelSendSpy).toBeCalledTimes(2);
});
it('should return args if args >= N', () => {
let args = ['1', '2'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
args = ['1', '2', '3'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
});
describe('for command with N multi-optional params', () => {
beforeEach(() => {
mockCommand.args = [
{ name: 'arg1', multi: true, optional: true },
{ name: 'arg2', multi: true, optional: true },
];
});
it('should return args if no args submitted', () => {
const args: string[] = [];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
it('should return args if args < N', () => {
const args = ['1'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
it('should return args if args = N', () => {
const args = ['1', '2'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
it('should return args if args > N', () => {
const args = ['1', '2', '3', '4'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
});
describe('for command with N multi-required and M multi-optional params', () => {
beforeEach(() => {
mockCommand.args = [
{ name: 'arg1', multi: true },
{ name: 'arg2', multi: true },
{ name: 'arg3', multi: true, optional: true },
{ name: 'arg4', multi: true, optional: true },
];
});
it('should return null if no args submitted', () => {
const args: string[] = [];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(null);
expect(embedErrorSpy).toBeCalledTimes(1);
expect(channelSendSpy).toBeCalledTimes(1);
});
it('should return null if args < N', () => {
const args = ['1'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(null);
expect(embedErrorSpy).toBeCalledTimes(1);
expect(channelSendSpy).toBeCalledTimes(1);
});
it('should return args if args = N', () => {
const args = ['1', '2'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
it('should return args if N < args < N + M', () => {
const args = ['1', '2', '3'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
it('should return args if args = N + M', () => {
const args = ['1', '2', '3', '4'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
it('should return args if args > N + M', () => {
const args = ['1', '2', '3', '4', '5'];
expect(validateArgsCount(mockCommand, args, mockChannel)).toBe(args);
expect(embedErrorSpy).toBeCalledTimes(0);
expect(channelSendSpy).toBeCalledTimes(0);
});
});
describe('for command with >=1 mono-required/mono-optional and 0 multi', () => {
it('should return null if 0 args given', () => {
mockCommand.args = [{ name: 'arg1' }, { name: 'arg2', optional: true }];
expect(validateArgsCount(mockCommand, [], mockChannel)).toBe(null);
expect(embedErrorSpy).toBeCalledTimes(1);
expect(channelSendSpy).toBeCalledTimes(1);
});
it('should return null if too many args are given', () => {
mockCommand.args = [{ name: 'arg3', optional: true }];
expect(
validateArgsCount(mockCommand, ['1', '2', '3', '4'], mockChannel),
).toBe(null);
expect(embedErrorSpy).toBeCalledTimes(1);
expect(channelSendSpy).toBeCalledTimes(1);
});
});
describe('for commands with no optionals params', () => {
describe('and exactly 1 mono-required param', () => {
it('should return null if 0 args given', () => {
mockCommand.args = [{ name: 'arg1' }];
expect(validateArgsCount(mockCommand, [], mockChannel)).toBe(null);
expect(embedErrorSpy).toBeCalledTimes(1);
expect(channelSendSpy).toBeCalledTimes(1);
});
});
});
});
<file_sep>const padTimeZero = (chunk: number): string =>
`${chunk <= 9 ? `0${chunk}` : chunk}`;
export const secToString = (sec: number): string => {
if (sec < 60) return `00:${padTimeZero(sec)}`;
if (sec > 60 && sec < 3600)
return `${padTimeZero(Math.floor(sec / 60))}:${padTimeZero(sec % 60)}`;
const subHour = sec % 3600;
const ss = subHour % 60;
const mm = (subHour - ss) / 60;
const hh = Math.floor(sec / 3600);
return `${padTimeZero(hh)}:${padTimeZero(mm)}:${padTimeZero(ss)}`;
};
export const stringToSec = (min: string): number => {
const [hh, mm, ss] = min.split(':');
if (ss) {
return 3600 * parseInt(hh, 10) + 60 * parseInt(mm, 10) + parseInt(ss, 10);
}
if (mm) {
return 60 * parseInt(hh, 10) + parseInt(mm, 10);
}
return parseInt(hh, 10);
};
<file_sep>import { CmdCategory } from '@prisma/client';
import { balloonProvider } from '../../data/providers/balloonProvider';
import {
baseEmbed,
lightErrorEmbed,
sendNotInGuild,
} from '../../shared/embeds';
import { Command } from '../../types/command';
const balloonMax = new Command({
name: 'balloon-max',
aliases: ['bl-max'],
category: CmdCategory.GAMES,
description:
"Check or set the upper bound for balloons' volumes in this server.",
args: [{ name: 'new_max', optional: true }],
async execute(message, args) {
const { channel, guild } = message;
if (!guild) {
sendNotInGuild(channel);
return;
}
const [_newMax] = args;
if (!_newMax) {
const currMax = await balloonProvider.getMax(guild.id);
channel.send(
baseEmbed().setDescription(`Current max volume: **${currMax}**`),
);
return;
}
const newMax = parseInt(_newMax, 10);
if (Number.isNaN(newMax)) {
channel.send(lightErrorEmbed(`Please give me a valid number!`));
return;
}
const currMin = await balloonProvider.getMin(guild.id);
if (newMax < currMin) {
channel.send(
lightErrorEmbed(
`The current min is **${currMin}**.
Please set a max below that, or lower the min.`,
),
);
return;
}
if (newMax <= 0) {
channel.send(
lightErrorEmbed('Volume is a *non-negative scalar* ლ(´ڡ`ლ)'),
);
return;
}
await balloonProvider.setMax(newMax, guild.id);
channel.send(
baseEmbed().setDescription(
`The maximum balloon volume has been set to **${newMax}**!
This will apply on the next game.`,
),
);
},
});
export default balloonMax;
<file_sep>export const DEFAULT_PREFIX = 'ck;';
export const DEFAULT_PREFIX_RE = /^ck;/i;
export const GLOBAL_RIBBONS = 'global';
<file_sep>import { CmdCategory } from '.prisma/client';
import { Command } from '../../types/command';
import { dashboardLink } from './embeds/dashboardLinkEmbed';
const dashboard = new Command({
name: 'dashboard',
aliases: ['dbd'],
description: 'Get a link to the dashboard app',
args: [],
category: CmdCategory.UTILITY,
async execute(ctx) {
const { channel } = ctx;
channel.send(dashboardLink);
},
});
export default dashboard;
<file_sep>import { shuffle } from './shuffle';
describe('#shuffle', () => {
const testArr = [1, 2, 3, 4, 5];
it('should not mutate the original array', () => {
shuffle(testArr);
expect(testArr).toEqual([1, 2, 3, 4, 5]);
});
it('should shuffle lol', () => {
expect(shuffle(testArr)).not.toEqual(testArr);
});
});
<file_sep>/*
Warnings:
- Made the column `commandId` on table `Arg` required. This step will fail if there are existing NULL values in that column.
*/
-- AlterTable
ALTER TABLE "Arg" ALTER COLUMN "commandId" SET NOT NULL;
-- AlterTable
ALTER TABLE "Command" ADD COLUMN "aliases" TEXT[];
-- AlterTable
ALTER TABLE "Shiritori" ADD COLUMN "minLen" INTEGER;
<file_sep>> ### Chika joins Discord
>
> _Hi Chika, thanks for joining us here. Would you like to introduce yourself?_
> <br/><br/>
> **<NAME>**: Oh hi!! didn't see you there. I was playing Amogus with Kei. But thanks for having me here.
> <br/><br/>
> _I see, so what can you do as a Discord bot?_
> <br/><br/>
> **<NAME>**: You know, I can't compete with the likes of MEE6 or Mudae, but I'm trying my best anyway. You can refer to the banner below for a list of commands.
> <br/><br/>
> _That's great that you're trying your best! I heard you have an IQ of 3?_
> <br/><br/>
> **<NAME>**: I think so. Is that bad?
> <br/><br/>
> _No, it's great._
> <br/><br/>
> **<NAME>**: Haha okay. Anyway, I'll bring the entire Shuchi'in Tabletop Game Club to Discord some day. Please stay tuned!
> ### Introduction
>
> Chika doesn't seem to care for moderation. She is all about dat entertainment value.
> <br/><br/>
> Stream music with Chika, or enjoy a few rounds of Shiritori and Balloon with your friends. More games are being developed!
> <br/><br/>
> You can also have a chat with Chika using `ck;chika`. This costs _ribbons_, the de-facto currency for Chika bot. Please note that this feature is completely experimental now.
> ### Usage
>
> Chika's default prefix is `ck;` and this is customizable per-server. Here are the commands as of 23 Jun 2021.
> <br/><br/>
> 
> <br/><br/>
> We hope that you'll have lots of fun with Chika bot!
<file_sep>import { PrismaClient } from '.prisma/client';
import { Snowflake } from 'discord.js';
import { Redis } from 'ioredis';
import { DEFAULT_PREFIX } from '../../shared/constants';
import { prisma } from '../prismaClient';
import { forBlockedCommands, forPrefix, redis } from '../redisClient';
export class GuildProvider {
constructor(
private readonly prisma: PrismaClient,
private readonly redis: Redis,
) {}
async getPrefix(guildId: Snowflake) {
const ping = await this.redis.get(forPrefix(guildId));
if (ping) {
this.redis.expire(forPrefix(guildId), 60);
return ping;
}
return this.prisma.guild
.findUnique({
where: { guildId },
select: { prefix: true },
})
.then((res) => {
let prefix = res?.prefix;
if (!prefix) prefix = DEFAULT_PREFIX;
this.redis.set(forPrefix(guildId), prefix, 'ex', 60);
return prefix;
});
}
async setPrefix(guildId: Snowflake, prefix: string) {
redis.set(forPrefix(guildId), prefix, 'ex', 60);
await this.prisma.guild.upsert({
create: { guildId, prefix },
update: { prefix },
where: { guildId },
});
}
getBlockedCommands(guildId: Snowflake): Promise<string[]> {
return this.redis.smembers(forBlockedCommands(guildId));
}
async isBlocked(guildId: Snowflake, name: string): Promise<boolean> {
const res = await this.redis.sismember(forBlockedCommands(guildId), name);
return Boolean(res);
}
blockCommand(guildId: Snowflake, name: string): Promise<number> {
return redis.sadd(forBlockedCommands(guildId), name);
}
unblockCommand(guildId: Snowflake, name: string): Promise<number> {
return redis.srem(forBlockedCommands(guildId), name);
}
}
export const guildProvider = new GuildProvider(prisma, redis);
<file_sep>import { setCooldown, getCooldown } from './cooldownManager';
import { forCooldown, redis } from '../data/redisClient';
afterAll(() => {
return redis.quit();
});
describe('cooldownManager', () => {
const setSpy = jest.spyOn(redis, 'set');
const pttlSpy = jest.spyOn(redis, 'pttl');
beforeEach(() => {
setSpy.mockReset();
pttlSpy.mockReset();
});
describe('#setCooldown', () => {
it('calls set once', () => {
setCooldown('id', 'command', 10);
expect(setSpy).toBeCalledTimes(1);
});
it('calls set with correct params', () => {
setCooldown('id', 'command', 10);
expect(setSpy).toBeCalledWith(
forCooldown('id:command'),
'command',
'px',
10,
);
});
});
describe('#getCooldown', () => {
it('calls get once', () => {
getCooldown('id', 'command');
expect(pttlSpy).toBeCalledTimes(1);
});
it('calls set with correct params', () => {
getCooldown('id', 'command');
expect(pttlSpy).toBeCalledWith(forCooldown('id:command'));
});
it('returns 0 if key already expired or has no ttl set (-1 or -2)', () => {
pttlSpy.mockResolvedValueOnce(-1);
return getCooldown('id', 'command').then((res) => {
expect(res).toBe(0);
});
});
it('returns ttl if ttl is found', () => {
pttlSpy.mockResolvedValueOnce(1000);
return getCooldown('id', 'command').then((res) => {
expect(res).toBe(1000);
});
});
});
});
<file_sep>export const DEFAULT_MIN_BALLOON = 20;
export const DEFAULT_MAX_BALLOON = 500;
<file_sep>import { secToString, stringToSec } from './helpers';
describe('#stringToSec', () => {
describe('given HH:MM:SS', () => {
it('should convert correctly', () => {
expect(stringToSec('05:20:30')).toEqual(19230);
});
});
describe('given MM:SS', () => {
it('should convert correctly', () => {
expect(stringToSec('10:10')).toEqual(610);
});
});
describe('given SS', () => {
it('should convert correctly', () => {
expect(stringToSec('47')).toEqual(47);
});
});
});
describe('#secToString', () => {
describe('given less than a minute', () => {
it('should convert correctly', () => {
expect(secToString(50)).toEqual('00:50');
});
});
describe('given more than a minute, less than an hour', () => {
it('should convert correctly', () => {
expect(secToString(320)).toEqual('05:20');
});
});
describe('given more than an hour', () => {
it('should convert correctly', () => {
expect(secToString(19230)).toEqual('05:20:30');
});
});
});
<file_sep>export const EXIT_GAME_RE = /^;stopgame$/i;
export const EXIT_GAME = ';stopgame';
<file_sep>import type { Collection, User } from 'discord.js';
import { GameState } from '../../../types/gameState';
interface BalloonState extends GameState {
players: Collection<string, User>;
tolerance: number;
currentVolume: number;
}
export type { BalloonState };
<file_sep>import {
cryingEmbed,
lightErrorEmbed,
peekingEmbed,
} from '../../shared/embeds';
import { GenericChannel } from '../../types/command';
export const sendNoGameSelectedError = async (channel: GenericChannel) => {
channel.send(lightErrorEmbed('Tell me which game you wanna play, yo.'));
};
export const sendTaggedSelfError = async (channel: GenericChannel) => {
channel.send(
peekingEmbed().setTitle('...').setDescription(`Do you have no friends.`),
);
};
export const sendUnknownGameError = async (
gameName: string,
channel: GenericChannel,
) => {
channel.send(
lightErrorEmbed(`Sorry...I don't know how to play **${gameName}**.`),
);
// TODO return a list of playable games
};
export const sendGameCrashedError = async (channel: GenericChannel) => {
channel.send(
cryingEmbed()
.setTitle('what the heck')
.setDescription('The game crashed for some reason.'),
);
};
export const sendInGame = async (channel: GenericChannel) =>
channel.send(
lightErrorEmbed(
'There is a game being played in this channel!\nPlease wait till the current game is finished.',
),
);
<file_sep>import { CmdCategory } from '@prisma/client';
import { lightErrorEmbed, withAuthorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { sendMusicOnlyInGuild, toUrlString } from './utils/embeds';
import { createFinishListener } from './utils/listener';
const skip = new Command({
name: 'skip',
description: 'Skip the current track.',
args: [],
category: CmdCategory.MUSIC,
async execute(message) {
const { channel, guild, client, author } = message;
if (!guild) {
sendMusicOnlyInGuild(channel);
return;
}
const audioUtils = client.cache.audioUtils.get(guild.id);
if (!audioUtils) {
channel.send(lightErrorEmbed('There is no track to skip.'));
return;
}
channel.send(
withAuthorEmbed(author).setDescription(
`Skipping **${toUrlString(
audioUtils.nowPlaying.title,
audioUtils.nowPlaying.url,
40,
)}**`,
),
);
if (!audioUtils.dispatcher.paused) {
audioUtils.dispatcher.end();
return;
}
// a paused track cannot emit 'finish' for some reason
// we'll do this manually
createFinishListener(guild, {
channel,
client,
})();
},
});
export default skip;
<file_sep>import { lightErrorEmbed } from '../../../shared/embeds';
import { GenericChannel } from '../../../types/command';
export const sendNotFoundError = (s: string, channel: GenericChannel) =>
channel.send(lightErrorEmbed(`I couldn't find any info for **${s}**.`));
<file_sep>import type { VoiceChannel, VoiceConnection } from 'discord.js';
export const tryToConnect = async (
channel: VoiceChannel,
): Promise<VoiceConnection | null> =>
channel
.join()
.then((conn) => conn)
.catch(() => null);
<file_sep>import type { Message } from 'discord.js';
import { lightErrorEmbed } from '../../shared/embeds';
import { Game } from '../../types/game';
import { sendTaggedSelfError } from './embeds';
// mentions should only work for strictly 2 player games
export const validateMentions = (message: Message, game: Game) => {
const { mentions, channel, author } = message;
const taggedCount = mentions.users.size;
if (!taggedCount) {
return true;
}
const isTwoPlayer = game.minPlayerCount === 2 && game.maxPlayerCount === 2;
if (!isTwoPlayer && taggedCount > 0) {
channel.send(
lightErrorEmbed(`You can only tag another player for 2-player games.`),
);
return false;
}
if (isTwoPlayer && taggedCount !== 1) {
channel.send(
lightErrorEmbed(
`Please tag only one other user to play **${game.displayTitle}** with.`,
),
);
return false;
}
if (process.env.NODE_ENV !== 'development') {
if (isTwoPlayer && mentions.users.first()!.id === author.id) {
sendTaggedSelfError(channel);
return false;
}
}
return true;
};
<file_sep>declare namespace NodeJS {
export interface ProcessEnv {
NODE_ENV: string;
APP_TOKEN: string;
BOT_USER_ID: string;
DATABASE_URL: string;
REDISCLOUD_URL: string;
HUGGING_FACE_CHIKA: string;
HUGGING_FACE_KAGUYA: string;
HUGGING_FACE_CHIKA_KEY: string;
HUGGING_FACE_KAGUYA_KEY: string;
ANILIST_SCHEMA: string;
}
}
<file_sep>export const MAX_TAKE = 20;
<file_sep>import { CmdCategory } from '@prisma/client';
import { shiritoriGame } from '../../games/shiritori';
import { Command } from '../../types/command';
const shiritoriRules = new Command({
name: 'shiritori-rules',
aliases: ['sh-rules'],
args: [],
category: CmdCategory.GAMES,
description: 'Check the rules for Shiritori.',
async execute(message) {
const { channel } = message;
channel.send(shiritoriGame.rules);
},
});
export default shiritoriRules;
<file_sep>import { CmdCategory } from '@prisma/client';
import { balloonProvider } from '../../data/providers/balloonProvider';
import {
baseEmbed,
lightErrorEmbed,
sendNotInGuild,
} from '../../shared/embeds';
import { Command } from '../../types/command';
const balloonMin = new Command({
name: 'balloon-min',
aliases: ['bl-min'],
category: CmdCategory.GAMES,
description:
"Check or set the lower bound for balloons' volumes in this server.",
args: [{ name: 'new_min', optional: true }],
async execute(message, args) {
const { channel, guild } = message;
if (!guild) {
sendNotInGuild(channel);
return;
}
const [_newMin] = args;
if (!_newMin) {
const currMin = await balloonProvider.getMin(guild.id);
channel.send(
baseEmbed().setDescription(`Current min volume: **${currMin}**`),
);
return;
}
const newMin = parseInt(_newMin, 10);
if (Number.isNaN(newMin)) {
channel.send(lightErrorEmbed(`Please give me a valid number!`));
return;
}
const currMax = await balloonProvider.getMax(guild.id);
if (newMin > currMax) {
channel.send(
lightErrorEmbed(
`The current max is **${currMax}**.
Please set a min below that, or raise the max.`,
),
);
return;
}
if (newMin <= 0) {
channel.send(
lightErrorEmbed('Volume is a *non-negative scalar* ლ(´ڡ`ლ)'),
);
return;
}
await balloonProvider.setMin(newMin, guild.id);
channel.send(
baseEmbed().setDescription(
`The minimum balloon volume has been set to **${newMin}**!
This will apply on the next game.`,
),
);
},
});
export default balloonMin;
<file_sep>import { PrismaClient } from '@prisma/client';
import type { Redis } from 'ioredis';
import {
DEFAULT_SHIRITORI_HAND,
DEFAULT_SHIRITORI_MIN_LEN,
} from '../../games/shiritori/utils/defaults';
import { prisma as prismaClient } from '../prismaClient';
import {
forShiritoriHand,
forShiritoriMinLen,
redis,
redis as redisClient,
} from '../redisClient';
export class ShiritoriProvider {
constructor(
private readonly prisma: PrismaClient,
private readonly redis: Redis,
) {}
async setMinLen(guildId: string, minLen: number) {
if (minLen < 0) throw new Error('Min length cannot be negative.');
await this.prisma.guild
.upsert({
where: { guildId },
update: {
shiritori: {
upsert: { update: { minLen }, create: { minLen } },
},
},
create: {
guildId,
shiritori: { create: { minLen } },
},
})
.then(() =>
this.redis.set(forShiritoriMinLen(guildId), minLen, 'ex', 60),
);
}
async getMinLen(guildId?: string) {
if (!guildId) return DEFAULT_SHIRITORI_MIN_LEN;
const ping = await redis.get(forShiritoriMinLen(guildId));
if (ping) {
this.redis.expire(forShiritoriMinLen(guildId), 60);
return parseInt(ping, 10);
}
return this.prisma.shiritori
.findUnique({
where: { guildId },
select: { minLen: true },
})
.then((res) => {
const minLen = res?.minLen || DEFAULT_SHIRITORI_MIN_LEN;
this.redis.set(forShiritoriMinLen(guildId), minLen, 'ex', 60);
return minLen;
});
}
async setHandSize(guildId: string, handSize: number) {
if (handSize <= 0) throw new Error('Hand size must be at least one.');
await this.prisma.guild
.upsert({
where: { guildId },
update: {
shiritori: {
upsert: {
update: { handSize },
create: { handSize },
},
},
},
create: { guildId, shiritori: { create: { handSize } } },
})
.then(() => redis.set(forShiritoriHand(guildId), handSize, 'ex', 60));
}
async getHandSize(guildId: string) {
const ping = await redis.get(forShiritoriHand(guildId));
if (ping) {
redis.expire(forShiritoriHand(guildId), 60);
return parseInt(ping, 10);
}
return this.prisma.shiritori
.findUnique({
where: { guildId },
select: { handSize: true },
})
.then((res) => {
const handSize = res?.handSize || DEFAULT_SHIRITORI_HAND;
redis.set(forShiritoriHand(guildId), handSize, 'ex', 60);
return handSize;
});
}
}
export const shiritoriProvider = new ShiritoriProvider(
prismaClient,
redisClient,
);
<file_sep>import { CmdCategory } from '.prisma/client';
import { stripIndents } from 'common-tags';
import _ from 'lodash';
import { blogKey, redis } from '../../data/redisClient';
import { setCooldown } from '../../lib/cooldownManager';
import { sendPaginated } from '../../lib/sendPaginated';
import { baseEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { blogPage } from './utils/embeds';
import { IBlogPost } from './utils/types';
const blog = new Command({
name: 'blog',
args: [],
description: 'Read the Chika blog.',
category: CmdCategory.FUN,
channelCooldown: 10000,
async execute(context) {
const { channel } = context;
// retrieve blog posts
const posts: IBlogPost[] = await redis
.lrange(blogKey, 0, -1)
.then((posts) => posts.map((post) => JSON.parse(post)));
if (posts.length < 1) {
sendPaginated(channel, [
baseEmbed().setTitle('ChikaSpot').setDescription(stripIndents`
...no posts here...ᕙ(⇀‸↼‶)ᕗ
post something on the blog with \`post\`!`),
]);
}
// split into individual embeds
const pages = _.chunk(posts, 5).map((_posts) => blogPage(_posts));
// send as paginated
sendPaginated(channel, pages, { timeout: 60000 });
setCooldown(channel.id, this.name, this.channelCooldown!);
},
});
export default blog;
<file_sep>-- DropForeignKey
ALTER TABLE "Arg" DROP CONSTRAINT "Arg_commandId_fkey";
-- AddForeignKey
ALTER TABLE "Arg" ADD FOREIGN KEY ("commandId") REFERENCES "Command"("id") ON DELETE CASCADE ON UPDATE CASCADE;
<file_sep>import type { StreamDispatcher, VoiceConnection } from 'discord.js';
interface QueueItem {
id: string;
url: string;
title: string;
thumbnailURL: string;
duration: string;
}
interface AudioUtils {
connection: VoiceConnection;
dispatcher: StreamDispatcher;
nowPlaying: QueueItem;
}
export type { QueueItem, AudioUtils };
<file_sep>import { MessageEmbed, User } from 'discord.js';
import { chika_pink, kaguya_red } from '../../../shared/assets';
import {
baseEmbed,
detectiveEmbed,
lightErrorEmbed,
} from '../../../shared/embeds';
import type { ChatbotChar, IBlogPost } from './types';
import relativeTime from 'dayjs/plugin/relativeTime';
import dayjs from 'dayjs';
dayjs.extend(relativeTime);
export const avatarEmbed = (user: User): MessageEmbed =>
baseEmbed()
.setImage(user.displayAvatarURL({ dynamic: true }))
.setFooter(`${user.tag}'s avatar`);
const applyColor = (embed: MessageEmbed, char: ChatbotChar) => {
switch (char) {
case 'ck':
embed.setColor(chika_pink);
break;
case 'ka':
embed.setColor(kaguya_red);
break;
default:
embed.setColor(chika_pink);
break;
}
return embed;
};
export const chatbotLoadingError = (char: ChatbotChar) => {
const embed = new MessageEmbed()
.setDescription(
`Thanks for chatting with me! Please give me a minute to get ready.`,
)
.setFooter('(The API takes a moment to load sometimes lol)');
return applyColor(embed, char);
};
export const chatbotTimeoutError = (char: ChatbotChar) => {
const embed = lightErrorEmbed(
'I ran into an error while thinking of a reply.',
);
return applyColor(embed, char);
};
export const chatbotLimitError = (char: ChatbotChar) => {
const embed = lightErrorEmbed(
"Sorry! I'll be hibernating for the rest of the month. (ღ˘⌣˘ღ)",
).setFooter(
"(The free API I'm using has a 30k character limit per month lol)",
);
return applyColor(embed, char);
};
export const blogPage = (posts: IBlogPost[]): MessageEmbed => {
return detectiveEmbed()
.setTitle('ChikaSpot')
.addFields(
posts.map((post) => ({
name: post.message,
value: `${post.author} • ${dayjs(post.time).fromNow()}`,
})),
);
};
<file_sep>import { redis } from '../data/redisClient';
import type { Event } from '../types/event';
import { pubGuildCount, updateGuildList } from './lib/guild';
const guildCreate: Event = {
name: 'guildDelete',
once: false,
listener: async (client) => {
const { cache: guilds } = client.guilds;
await pubGuildCount(redis, guilds.size);
// update the list in redis
const ids = guilds.map((guild) => guild.id);
await updateGuildList(redis, ids);
},
};
export default guildCreate;
<file_sep>import { Collection, Message, User } from 'discord.js';
import _ from 'lodash';
import { userProvider } from '../../../data/providers/userProvider';
import { prisma } from '../../../data/prismaClient';
import { forRibbons, redis } from '../../../data/redisClient';
import { sendPopped } from './embeds';
export const postGameBalloon = async (
message: Message,
players: Collection<string, User>,
) => {
const { channel, author: popper } = message;
const winners = players.filter((user) => user.id !== popper.id);
const popperStock = await userProvider.getRibbons(popper);
const winAmt = Math.floor(Math.random() * 20 + 20);
const isBankrupt = winAmt * winners.size > popperStock;
sendPopped(channel, { popper, isBankrupt, winAmt });
await prisma
.$transaction(
winners.map((winner) =>
prisma.user.upsert({
where: { userId: winner.id },
update: { ribbons: { increment: winAmt } },
create: { userId: winner.id, tag: winner.tag, ribbons: winAmt },
select: { userId: true, ribbons: true },
}),
),
)
.then((res) =>
redis.mset(
..._.flattenDeep(
res.map((_res) => [forRibbons(_res.userId), _res.ribbons]),
),
),
);
userProvider.decrRibbons(popper, winAmt * winners.size);
};
<file_sep>import _ from 'lodash';
import {
FuzzyDate,
Maybe,
MediaSource,
MediaStatus,
} from '../../../generated/anilist';
import { unknown_png } from '../../../shared/assets';
import { baseEmbed } from '../../../shared/embeds';
import { parseHtml } from '../../../lib/typography';
interface mangaEmbedParams {
title: string | null | undefined;
description: string | null | undefined;
status: MediaStatus | null | undefined;
averageScore: number | null | undefined;
coverImage: string | null | undefined;
genres: Maybe<string>[] | null | undefined;
source: MediaSource | null | undefined;
startDate: FuzzyDate | null | undefined;
endDate: FuzzyDate | null | undefined;
volumes: number | null | undefined;
chapters: number | null | undefined;
}
export function parseFuzzyDate(date?: FuzzyDate | null): string {
if (!date) {
return '?';
}
const { year, month, day } = date;
if (!year && !month && !day) {
return '?';
}
return `${day || '?'}-${month || '?'}-${year || '?'}`;
}
export const mangaInfoEmbed = (info: mangaEmbedParams) => {
const {
coverImage,
title,
description,
status,
genres,
source,
averageScore,
startDate,
endDate,
chapters,
volumes,
} = info;
return baseEmbed()
.setThumbnail(coverImage || unknown_png)
.setTitle(title)
.setDescription(
description ? parseHtml(description) : `*No description for this manga.*`,
)
.addFields([
{
name: ':pencil: Status',
value: status
? _.startCase(status.replace(/_/g, ' ').toLowerCase())
: '?',
inline: true,
},
{
name: ':calendar: Published',
value: `From **${parseFuzzyDate(startDate)}** to **${parseFuzzyDate(
endDate,
)}**`,
inline: true,
},
{
name: ':ramen: Sauce',
value: source
? _.startCase(source.replace(/_/g, ' ').toLowerCase())
: '?',
inline: true,
},
])
.addField(':shinto_shrine: Genres', genres?.join(', ') || ':question:')
.addFields([
{ name: ':books: Volumes', value: volumes || '?', inline: true },
{
name: ':newspaper2: Chapters',
value: chapters || '?',
inline: true,
},
{
name: ':star: Rating',
value: averageScore ? `${averageScore}/100` : '?',
inline: true,
},
]);
};
<file_sep>import type { Message, User } from 'discord.js';
import { Guild } from 'discord.js';
import { sendNotAdmin, sendNotInGuild } from '../shared/embeds';
import type { GenericChannel } from '../types/command';
interface validateMessageOptions {
channelId?: string;
channel?: GenericChannel;
channels?: GenericChannel[];
guild?: Guild;
guildId?: string;
author?: User;
authors?: User[];
content?: RegExp;
minLen?: number;
maxLen?: number;
}
export const filterMessage = (
message: Message,
options: validateMessageOptions,
): Message | null => {
const {
channel,
channels,
channelId,
guild,
guildId,
author,
authors,
content,
minLen,
maxLen,
} = options;
if (author && author.id !== message.author.id) return null;
if (
authors &&
!authors.map((_author) => _author.id).includes(message.author.id)
)
return null;
if (content && !content.test(message.content)) return null;
if (minLen && message.content.length < minLen) return null;
if (maxLen && message.content.length > maxLen) return null;
if (channel && channel.id !== message.channel.id) return null;
if (
channels &&
!channels.map((_channel) => _channel.id).includes(message.channel.id)
)
return null;
if (channelId && message.channel.id !== channelId) return null;
if (guild && guild.id !== message.guild?.id) return null;
if (guildId && message.guild?.id !== guildId) return null;
return message;
};
export const isAdmin = (message: Message) => {
const { member, channel } = message;
if (!member) {
sendNotInGuild(channel);
return false;
}
if (!member.hasPermission('ADMINISTRATOR')) {
sendNotAdmin(channel);
return false;
}
return true;
};
<file_sep>import { CmdCategory } from '@prisma/client';
import axios from 'axios';
import { userProvider } from '../../data/providers/userProvider';
import { forChikaInput, forChikaResponse } from '../../data/redisClient';
import { sendInsufficientRibbons } from '../../shared/embeds';
import { Command } from '../../types/command';
import {
cacheInput,
cacheResponse,
genChatData,
handleHuggingFaceError,
} from './utils/chatbot';
const chika = new Command({
name: 'chika',
aliases: ['ck'],
args: [{ name: 'your_message', multi: true }],
category: CmdCategory.FUN,
description:
'Chat with Chika. Be careful though, her IQ drops below 3 at times. This costs ribbons.',
async execute(message, args) {
const { channel, author } = message;
const text = args.join(' ');
const ribbonCost = text.length;
const ribbonStock = await userProvider.getRibbons(author);
if (ribbonCost > ribbonStock) {
sendInsufficientRibbons(channel, ribbonCost, ribbonStock);
return;
}
const data = await genChatData(channel.id, {
input: forChikaInput,
response: forChikaResponse,
text,
});
axios
.post(process.env.HUGGING_FACE_CHIKA, data, {
headers: {
Authorization: `Bearer ${process.env.HUGGING_FACE_CHIKA_KEY}`,
},
})
.then((res) => {
const reply = res.data.generated_text;
channel.send(`> ${text}\n${reply}`);
cacheInput(channel.id, text, forChikaInput);
cacheResponse(channel.id, reply, forChikaResponse);
userProvider.decrRibbons(author, ribbonCost);
})
.catch((err) => {
handleHuggingFaceError(channel, err, 'ck', text);
});
},
});
export default chika;
<file_sep>import { CmdCategory } from '@prisma/client';
import type { DMChannel, Message, NewsChannel, TextChannel } from 'discord.js';
type GenericChannel = TextChannel | DMChannel | NewsChannel;
interface CommandArg {
name: string;
optional?: boolean;
multi?: boolean;
}
interface ICommand {
name: string;
description: string;
category: CmdCategory;
args: CommandArg[];
execute(message: Message, args: string[]): Promise<void>;
aliases?: string[];
channelCooldown?: number;
userCooldown?: number;
}
export class Command implements ICommand {
name: string;
description: string;
category: CmdCategory;
usage: string;
args: CommandArg[];
execute: (message: Message, args: string[]) => Promise<void>;
aliases?: string[];
channelCooldown?: number;
userCooldown?: number;
constructor({
name,
description,
category,
args,
aliases,
channelCooldown,
userCooldown,
execute,
}: ICommand) {
this.name = name;
this.description = description;
this.category = category;
this.args = args;
this.aliases = aliases;
this.channelCooldown = channelCooldown;
this.userCooldown = userCooldown;
this.execute = execute;
this.usage = this.genUsage();
}
genUsage(): string {
return `${this.name} ${this.args
.map((arg) => {
if (!arg.optional) return `<${arg.name}>`;
if (arg.optional && !arg.multi) return `[${arg.name}]`;
return `[${arg.name} ...]`;
})
.join(' ')}`;
}
}
export type { GenericChannel };
<file_sep>import Discord from 'discord.js';
import { Command } from './command';
import { Game } from './game';
import { AudioUtils } from './queue';
interface DiscordClientCache {
audioUtils: Discord.Collection<string, AudioUtils>;
inGameStates: Discord.Collection<string, string>; // map ID to game title
}
declare module 'discord.js' {
export interface Client {
commands: Discord.Collection<string, Command>;
commandsHelp: Discord.MessageEmbed;
games: Discord.Collection<string, Game>;
gamesList: string[];
cache: DiscordClientCache;
}
}
<file_sep>import { CmdCategory } from '@prisma/client';
import { lightErrorEmbed, sendNotInGuild } from '../../shared/embeds';
import { Command } from '../../types/command';
const boot = new Command({
name: 'boot',
description: 'Boot Chika from the voice channel. Queue is not cleared.',
category: CmdCategory.MUSIC,
args: [],
async execute(message) {
const { guild, client, channel } = message;
if (!guild) {
sendNotInGuild(channel);
return;
}
const audioUtils = client.cache.audioUtils.get(guild.id);
if (!audioUtils?.connection) {
channel.send(lightErrorEmbed(`Bruv I'm not even in a voice channel.`));
return;
}
audioUtils.connection.disconnect();
channel.send(lightErrorEmbed(`I've left the voice channel.`));
client.cache.audioUtils.delete(guild.id);
},
});
export default boot;
<file_sep>import { CmdCategory } from '@prisma/client';
import type { Collection, EmbedFieldData, MessageEmbed } from 'discord.js';
import { baseEmbed, detectiveEmbed } from '../shared/embeds';
import type { Command } from '../types/command';
import { stripIndents } from 'common-tags';
export const genFullHelpEmbed = (
commands: Collection<string, Command>,
): MessageEmbed => {
const categoryMap: Record<CmdCategory, Command[]> = {} as any;
commands.forEach((command) => {
if (categoryMap[command.category]) {
categoryMap[command.category].push(command);
} else {
categoryMap[command.category] = [command];
}
});
const fields: EmbedFieldData[] = [];
Object.keys(categoryMap).forEach((category) => {
const cmds = categoryMap[category as CmdCategory].map(
(command) => `\`${command.name}\``,
);
fields.push({
name: tagEmoji(category as CmdCategory),
value: cmds.join(', '),
});
});
return detectiveEmbed().setTitle('Chika Commands').addFields(fields);
};
export const helpExtraInfo = baseEmbed().addField(
'Some notes',
stripIndents`
• Chika's default prefix is **ck;**
• For more info about a specific command, use \`help <command>\`
• Chika's [dashboard](https://dashboard.chikawara.xyz) is ready! Currently open to admins only.`,
);
function tagEmoji(category: CmdCategory) {
switch (category) {
case 'CURRENCY':
return ':moneybag: Currency';
case 'FUN':
return ':coffee: Fun';
case 'GAMES':
return ':video_game: Game';
case 'MUSIC':
return ':headphones: Music';
case 'UTILITY':
return ':satellite: Utility';
default:
return ':coffee: Fun';
}
}
<file_sep>-- DropForeignKey
ALTER TABLE "Balloon" DROP CONSTRAINT "Balloon_guildId_fkey";
-- DropForeignKey
ALTER TABLE "Shiritori" DROP CONSTRAINT "Shiritori_guildId_fkey";
-- AlterTable
ALTER TABLE "Balloon" ALTER COLUMN "guildId" SET DATA TYPE TEXT,
ALTER COLUMN "minVol" DROP NOT NULL,
ALTER COLUMN "maxVol" DROP NOT NULL;
-- AlterTable
ALTER TABLE "Shiritori" ALTER COLUMN "guildId" SET DATA TYPE TEXT,
ALTER COLUMN "handSize" DROP NOT NULL;
-- AddForeignKey
ALTER TABLE "Shiritori" ADD FOREIGN KEY ("guildId") REFERENCES "Guild"("guildId") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Balloon" ADD FOREIGN KEY ("guildId") REFERENCES "Guild"("guildId") ON DELETE CASCADE ON UPDATE CASCADE;
<file_sep>import { commaListsAnd, stripIndents } from 'common-tags';
import type { User } from 'discord.js';
import { MessageEmbed } from 'discord.js';
import { GenericChannel } from '../types/command';
import {
chika_crying_png,
chika_detective_png,
chika_peeking_png,
chika_pink,
chika_pointing_png,
chika_rap_png,
ribbon_emoji,
} from './assets';
export const baseEmbed = () => new MessageEmbed().setColor(chika_pink);
export const cryingEmbed = () => baseEmbed().setThumbnail(chika_crying_png);
export const detectiveEmbed = () =>
baseEmbed().setThumbnail(chika_detective_png);
export const peekingEmbed = () => baseEmbed().setThumbnail(chika_peeking_png);
export const pointingEmbed = () => baseEmbed().setThumbnail(chika_pointing_png);
export const rappingEmbed = () => baseEmbed().setThumbnail(chika_rap_png);
export const lightErrorEmbed = (msg: string) =>
baseEmbed().setDescription(`:broken_heart: ${msg}`);
export const lightOkEmbed = (msg: string) =>
baseEmbed().setDescription(`:magic_wand: ${msg}`);
export const badCommandsEmbed = (...cmds: string[]) =>
lightErrorEmbed(
stripIndents(commaListsAnd`
I couldn't understand these commands: ${cmds.map((cmd) => `**${cmd}**`)}
To get a list of all the commands I know, use \`help\``),
);
export const genericErrorEmbed = () =>
cryingEmbed()
.setTitle('Oh no!')
.setDescription('I ran into an unknown error while running your request.');
export const withAuthorEmbed = (author: User) =>
baseEmbed().setFooter(
`Requested by ${author.tag}`,
author.displayAvatarURL({ size: 32, dynamic: false }),
);
export const sendNotInGuild = async (channel: GenericChannel) =>
channel.send(lightErrorEmbed('This command can only be used in a server!'));
export const sendInsufficientRibbons = (
channel: GenericChannel,
cost: number,
stock: number,
) =>
channel.send(
lightErrorEmbed(
stripIndents`
You don't have enough ribbons!
You need **${cost}** ${ribbon_emoji}, but only have **${stock}** ${ribbon_emoji}.`,
),
);
export const sendNotAdmin = (channel: GenericChannel) =>
channel.send(lightErrorEmbed(`Only admins can use that command!`));
export const sendBlockedCommand = (channel: GenericChannel, command: string) =>
channel.send(
lightErrorEmbed(`Command **${command}** has been disabled in this server.`),
);
<file_sep>import type { MessageEmbed, MessageReaction, User } from 'discord.js';
import { GenericChannel } from '../types/command';
import { left_arrow, right_arrow } from '../shared/assets';
import dayjs from 'dayjs';
interface sendPaginatedOptions {
leftEmoji?: string;
rightEmoji?: string;
timeout?: number;
}
// NOTE: need permissions to delete the reactions afterwards
export const sendPaginated = (
channel: GenericChannel,
pages: MessageEmbed[],
options?: sendPaginatedOptions,
) => {
const leftEmoji = options?.leftEmoji || left_arrow;
const rightEmoji = options?.rightEmoji || right_arrow;
const timeout = options?.timeout || 30000; // half a minute by default
let on = 0; // page number
const maxOn = pages.length - 1;
channel
.send(pages[on].setFooter(footer(1, maxOn + 1)))
.then(async (message) => {
await message.react(left_arrow).then(() => message.react(right_arrow));
const filter = (reaction: MessageReaction, user: User) =>
(reaction.emoji.name === leftEmoji ||
reaction.emoji.name === rightEmoji) &&
!user.bot;
const collector = message.createReactionCollector(filter, {
time: timeout,
dispose: true,
});
const reactHandler = (reaction: MessageReaction) => {
switch (reaction.emoji.name) {
case left_arrow:
on = on === 0 ? maxOn : on - 1;
break;
case right_arrow:
on = on === maxOn ? 0 : on + 1;
break;
default:
break;
}
message.edit(pages[on].setFooter(footer(on + 1, maxOn + 1)));
};
collector.on('remove', reactHandler);
collector.on('collect', reactHandler);
collector.on('end', () => {
if (!message.deleted) {
message.reactions.removeAll().catch((err) => console.error(err));
}
});
});
};
function footer(curr: number, total: number) {
return `${curr}/${total} • ${dayjs().format(
'ddd h:ma',
)}, Chika Standard Time`;
}
<file_sep>import { CmdCategory } from '@prisma/client';
import { userProvider } from '../../data/providers/userProvider';
import { groupNum } from '../../lib/typography';
import { ribbon_emoji } from '../../shared/assets';
import { baseEmbed, lightErrorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
const give = new Command({
name: 'give',
args: [{ name: 'user' }, { name: 'amount' }],
description: `Be charitable and give another user some ribbons.`,
category: CmdCategory.CURRENCY,
aliases: ['donate'],
async execute(message, args) {
const { author, channel, mentions } = message;
const beneficiary = mentions.users.first();
if (!beneficiary) {
channel.send(lightErrorEmbed(`Tag someone to give ${ribbon_emoji} to!`));
return;
}
if (beneficiary.bot) {
channel.send(
lightErrorEmbed(
`**${beneficiary.tag}** is a bot and does not care for ${ribbon_emoji}...`,
),
);
return;
}
const donation = parseInt(args[args.length - 1], 10);
if (Number.isNaN(donation)) {
channel.send(lightErrorEmbed(`Please use a valid number!`));
return;
}
const benefactorStock = await userProvider.getRibbons(author);
if (donation > benefactorStock) {
channel.send(
lightErrorEmbed(
`LOL you're too poor to do that! You only have ${benefactorStock} ${ribbon_emoji}.`,
),
);
return;
}
userProvider.incrRibbons(beneficiary, donation);
userProvider.decrRibbons(author, donation);
channel.send(
baseEmbed().setDescription(
`**${beneficiary.username}** has received **${groupNum.format(
donation,
)}** ${ribbon_emoji} from ${author.username}!`,
),
);
},
});
export default give;
<file_sep>import { CmdCategory } from '.prisma/client';
import { ishigami_cake_png } from '../../shared/assets';
import { baseEmbed, lightErrorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { withAnd } from '../../lib/typography';
const birthday = new Command({
name: 'birthday',
aliases: ['bd'],
args: [{ name: 'user' }, { name: 'more_users', optional: true, multi: true }],
category: CmdCategory.FUN,
description: 'Wish your m8s a happy birthday.',
execute: async (message) => {
const { author, mentions, channel } = message;
if (!mentions.users.size) {
channel.send(lightErrorEmbed('Tag someone in your birthday wish!'));
return;
}
const births = mentions.users.map((user) => user.toString());
channel.send(
baseEmbed()
.setDescription(
`${author.toString()} realizes that ${withAnd(births)} ${
births.length === 1 ? 'has' : 'have'
} aged one year since 365 days ago.`,
)
.setImage(ishigami_cake_png)
.setFooter('Happy Birthday!!'),
);
},
});
export default birthday;
<file_sep>import Redis, { KeyType } from 'ioredis';
const withPrefix = (keyPrefix: string) =>
new Redis(process.env.REDISCLOUD_URL, {
keyPrefix: `${keyPrefix}:`,
});
export const redis = new Redis(process.env.REDISCLOUD_URL);
export const redisQueue = withPrefix('queue');
export type redisPrefixer = (key: KeyType) => string;
export const forNowPlaying = (guildId: KeyType) => `nowplaying:${guildId}`;
export const forPrefix = (key: KeyType) => `prefix:${key}`;
export const forBlockedCommands = (guildId: string) => `blocked:${guildId}`;
export const forRibbons = (key: KeyType) => `ribbons:${key}`;
export const forBalloonMin = (key: KeyType) => `balloon:min:${key}`;
export const forBalloonMax = (key: KeyType) => `balloon:max:${key}`;
export const forShiritoriMinLen = (key: KeyType) => `shiritori:minlen:${key}`;
export const forShiritoriHand = (key: KeyType) => `shiritori:hand:${key}`;
export const forChikaInput = (key: KeyType) => `chika:input:${key}`;
export const forChikaResponse = (key: KeyType) => `chika:response:${key}`;
export const forKaguyaInput = (key: KeyType) => `kaguya:input:${key}`;
export const forKaguyaResponse = (key: KeyType) => `kaguya:response:${key}`;
export const forCooldown = (key: KeyType) => `cooldown:${key}`;
export const blogKey = 'blog';
<file_sep>import { CmdCategory } from '@prisma/client';
import { lightErrorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { sendMusicOnlyInGuild, sendNowPlaying } from './utils/embeds';
const nowPlaying = new Command({
name: 'now-playing',
aliases: ['np'],
args: [],
description: 'Show the currently playing track.',
category: CmdCategory.MUSIC,
async execute(message) {
const { guild, client, channel } = message;
if (!guild) {
sendMusicOnlyInGuild(channel);
return;
}
const audioUtils = client.cache.audioUtils.get(guild.id);
if (!audioUtils?.nowPlaying) {
channel.send(lightErrorEmbed('The sound of silence.'));
return;
}
sendNowPlaying(channel, audioUtils.nowPlaying, {
streamTime: audioUtils.dispatcher.streamTime,
});
},
});
export default nowPlaying;
<file_sep>-- CreateTable
CREATE TABLE "User" (
"id" SERIAL NOT NULL,
"userId" TEXT NOT NULL,
"username" TEXT NOT NULL,
"ribbons" INTEGER NOT NULL,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Guild" (
"id" SERIAL NOT NULL,
"guildId" TEXT NOT NULL,
"prefix" TEXT,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Shiritori" (
"id" SERIAL NOT NULL,
"guildId" INTEGER NOT NULL,
"handSize" INTEGER NOT NULL,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Balloon" (
"id" SERIAL NOT NULL,
"guildId" INTEGER NOT NULL,
"minVol" INTEGER NOT NULL,
"maxVol" INTEGER NOT NULL,
PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "User.userId_unique" ON "User"("userId");
-- CreateIndex
CREATE UNIQUE INDEX "Guild.guildId_unique" ON "Guild"("guildId");
-- CreateIndex
CREATE UNIQUE INDEX "Shiritori.guildId_unique" ON "Shiritori"("guildId");
-- CreateIndex
CREATE UNIQUE INDEX "Balloon.guildId_unique" ON "Balloon"("guildId");
-- AddForeignKey
ALTER TABLE "Shiritori" ADD FOREIGN KEY ("guildId") REFERENCES "Guild"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Balloon" ADD FOREIGN KEY ("guildId") REFERENCES "Guild"("id") ON DELETE CASCADE ON UPDATE CASCADE;
<file_sep>import type { Collection, User } from 'discord.js';
import { ribbon_emoji } from '../../../shared/assets';
import { baseEmbed, lightErrorEmbed } from '../../../shared/embeds';
import { GenericChannel } from '../../../types/command';
import { groupNum } from '../../../lib/typography';
import { toListString } from '../../music/utils/embeds';
export const sendRibbonStock = (
channel: GenericChannel,
stock: Collection<User, string | null>,
) => {
const lines = stock.map(
(count, user) => `${user.toString()}: ${count || 0} ${ribbon_emoji}`,
);
channel.send(
baseEmbed().setDescription(toListString(lines, { noNum: true })),
);
};
export const sendTop = (
channel: GenericChannel,
top: {
tag: string;
ribbons: number;
}[],
options?: { locale?: string; thumbnail?: string | null },
) => {
const lines = top.map(
({ tag, ribbons }) =>
`**${tag}**: ${groupNum.format(ribbons)} ${ribbon_emoji}`,
);
const partialEmbed = baseEmbed()
.setTitle(`Wealth Gap in ${options?.locale || 'za Warudo'} :yen:`)
.setDescription(toListString(lines))
.setFooter(`Showing top ${lines.length}`);
channel.send(
options?.thumbnail
? partialEmbed.setThumbnail(options.thumbnail)
: partialEmbed,
);
};
export const sendExceededMaxTake = (channel: GenericChannel) =>
channel.send(lightErrorEmbed('I can only fetch a maximum of 20 results.'));
<file_sep>import { mocked } from 'ts-jest/utils';
import {
DEFAULT_MAX_BALLOON,
DEFAULT_MIN_BALLOON,
} from '../../games/balloon/utils/defaults';
import { prisma } from '../prismaClient';
import { forBalloonMax, forBalloonMin, redis } from '../redisClient';
import { BalloonProvider } from './balloonProvider';
jest.mock('../redisClient');
const mockRedis = mocked(redis, true);
const balloonProvider = new BalloonProvider(prisma, mockRedis);
afterEach(async () => {
await prisma.guild.deleteMany();
mockRedis.set.mockReset();
});
afterAll(async () => {
await prisma.$disconnect();
});
describe('#setMin', () => {
test('uses upsert', async () => {
const upsert = jest.spyOn(prisma.guild, 'upsert');
await balloonProvider.setMin(10, '1');
expect(upsert).toBeCalledTimes(1);
upsert.mockRestore();
});
test('caches minVol to redis with 60 seconds ttl', async () => {
const upsert = jest.spyOn(prisma.guild, 'upsert');
await balloonProvider.setMin(10, '1');
expect(mockRedis.set).toBeCalledWith(forBalloonMin('1'), 10, 'ex', 60);
upsert.mockRestore();
});
test('throws an error if negative volume provided', () => {
return expect(balloonProvider.setMin(-1, '1')).rejects.toThrow();
});
describe('guild does not exist in db', () => {
test('creates the guild with balloon settings applied', async () => {
const _guild = await prisma.guild.findUnique({ where: { guildId: '1' } });
expect(_guild).toBeNull(); // check null
await balloonProvider.setMin(10, '1');
const res = await prisma.balloon.findUnique({
where: { guildId: '1' },
select: { minVol: true },
});
expect(res?.minVol).toBe(10);
});
});
describe('guild exists in db', () => {
describe('without minVol', () => {
beforeEach(async () => {
await prisma.guild.create({ data: { guildId: '1' } });
});
test('creates a minVol for the guild', async () => {
await balloonProvider.setMin(10, '1');
const res = await prisma.balloon.findUnique({
where: { guildId: '1' },
select: { minVol: true },
});
expect(res?.minVol).toBe(10);
});
});
describe('with minVol', () => {
beforeEach(async () => {
await prisma.guild.create({
data: { guildId: '1', balloon: { create: { minVol: 10 } } },
});
});
test('updates minVol', async () => {
await balloonProvider.setMin(20, '1');
const res = await prisma.balloon.findUnique({
where: { guildId: '1' },
select: { minVol: true },
});
expect(res?.minVol).toBe(20);
});
});
});
});
describe('#getMin', () => {
describe('finds in redis', () => {
beforeEach(() => {
mockRedis.get.mockResolvedValueOnce('10');
});
test('should not hit db', async () => {
const findUnique = jest.spyOn(prisma.balloon, 'findUnique');
await balloonProvider.getMin('1');
expect(findUnique).not.toBeCalled();
findUnique.mockRestore();
});
test('return value from redis as int', async () => {
const res = await balloonProvider.getMin('1');
expect(res).toBe(10);
});
test('sets 60 seconds ttl', async () => {
await balloonProvider.getMin('1');
expect(mockRedis.expire).toBeCalledWith(forBalloonMin('1'), 60);
});
});
describe('could not find in redis', () => {
beforeEach(() => {
mockRedis.get.mockResolvedValueOnce(null);
});
describe('exists in db', () => {
beforeEach(async () => {
await prisma.guild.create({
data: { guildId: '1', balloon: { create: { minVol: 1 } } },
});
});
test('returns the value from db', async () => {
const res = await balloonProvider.getMin('1');
expect(res).toBe(1);
});
test('caches the value in redis', async () => {
await balloonProvider.getMin('1');
expect(mockRedis.set).toBeCalledWith(forBalloonMin('1'), 1, 'ex', 60);
});
});
describe('does not exist in db', () => {
test('returns the default', async () => {
const res = await balloonProvider.getMin('1');
expect(res).toBe(DEFAULT_MIN_BALLOON);
});
test('caches the value in redis', async () => {
await balloonProvider.getMin('1');
expect(mockRedis.set).toBeCalledWith(
forBalloonMin('1'),
DEFAULT_MIN_BALLOON,
'ex',
60,
);
});
});
});
});
describe('#setMax', () => {
test('uses upsert', async () => {
const upsert = jest.spyOn(prisma.guild, 'upsert');
await balloonProvider.setMax(10, '1');
expect(upsert).toBeCalledTimes(1);
upsert.mockRestore();
});
test('caches maxVol to redis with 60 seconds ttl', async () => {
const upsert = jest.spyOn(prisma.guild, 'upsert');
await balloonProvider.setMax(10, '1');
expect(mockRedis.set).toBeCalledWith(forBalloonMax('1'), 10, 'ex', 60);
upsert.mockRestore();
});
test('throws an error if negative volume provided', () => {
return expect(balloonProvider.setMax(-1, '1')).rejects.toThrow();
});
describe('guild does not exist in db', () => {
test('creates the guild with balloon settings applied', async () => {
const _guild = await prisma.guild.findUnique({ where: { guildId: '1' } });
expect(_guild).toBeNull(); // check null
await balloonProvider.setMax(10, '1');
const res = await prisma.balloon.findUnique({
where: { guildId: '1' },
select: { maxVol: true },
});
expect(res?.maxVol).toBe(10);
});
});
describe('guild exists in db', () => {
describe('without maxVol', () => {
beforeEach(async () => {
await prisma.guild.create({ data: { guildId: '1' } });
});
test('creates a maxVol for the guild', async () => {
await balloonProvider.setMax(10, '1');
const res = await prisma.balloon.findUnique({
where: { guildId: '1' },
select: { maxVol: true },
});
expect(res?.maxVol).toBe(10);
});
});
describe('with maxVol', () => {
beforeEach(async () => {
await prisma.guild.create({
data: { guildId: '1', balloon: { create: { maxVol: 10 } } },
});
});
test('updates maxVol', async () => {
await balloonProvider.setMax(20, '1');
const res = await prisma.balloon.findUnique({
where: { guildId: '1' },
select: { maxVol: true },
});
expect(res?.maxVol).toBe(20);
});
});
});
});
describe('#getMax', () => {
describe('finds in redis', () => {
beforeEach(() => {
mockRedis.get.mockResolvedValueOnce('10');
});
test('should not hit db', async () => {
const findUnique = jest.spyOn(prisma.balloon, 'findUnique');
await balloonProvider.getMax('1');
expect(findUnique).not.toBeCalled();
findUnique.mockRestore();
});
test('return value from redis as int', async () => {
const res = await balloonProvider.getMax('1');
expect(res).toBe(10);
});
test('sets 60 seconds ttl', async () => {
await balloonProvider.getMax('1');
expect(mockRedis.expire).toBeCalledWith(forBalloonMax('1'), 60);
});
});
describe('could not find in redis', () => {
beforeEach(() => {
mockRedis.get.mockResolvedValueOnce(null);
});
describe('exists in db', () => {
beforeEach(async () => {
await prisma.guild.create({
data: { guildId: '1', balloon: { create: { maxVol: 1 } } },
});
});
test('returns the value from db', async () => {
const res = await balloonProvider.getMax('1');
expect(res).toBe(1);
});
test('caches the value in redis', async () => {
await balloonProvider.getMax('1');
expect(mockRedis.set).toBeCalledWith(forBalloonMax('1'), 1, 'ex', 60);
});
});
describe('does not exist in db', () => {
test('returns the default', async () => {
const res = await balloonProvider.getMax('1');
expect(res).toBe(DEFAULT_MAX_BALLOON);
});
test('caches the value in redis', async () => {
await balloonProvider.getMax('1');
expect(mockRedis.set).toBeCalledWith(
forBalloonMax('1'),
DEFAULT_MAX_BALLOON,
'ex',
60,
);
});
});
});
});
<file_sep>import { CmdCategory } from '@prisma/client';
import { balloonGame } from '../../games/balloon';
import { Command } from '../../types/command';
const balloonRules = new Command({
name: 'balloon-rules',
aliases: ['bl-rules'],
args: [],
category: CmdCategory.GAMES,
description: 'Check the rules for Balloon.',
async execute(message) {
const { channel } = message;
channel.send(balloonGame.rules);
},
});
export default balloonRules;
<file_sep>interface ChatbotInput {
inputs: {
past_user_inputs?: string[];
generated_responses?: string[];
text: string;
};
}
type ChatbotChar = 'ck' | 'ka';
interface IBlogPost {
author: string; // Discord tag
time: number; // unix timestamp
message: string;
}
export type { ChatbotInput, ChatbotChar, IBlogPost };
<file_sep>import { CmdCategory } from '@prisma/client';
import { redisQueue } from '../../data/redisClient';
import { Command } from '../../types/command';
import {
sendAddedToQueue,
sendMusicOnlyInGuild,
sendNoVideo,
} from './utils/embeds';
import { validateArgs } from './utils/youtube';
const insert = new Command({
name: 'insert',
aliases: ['addd'],
category: CmdCategory.MUSIC,
description: 'Inserts a track to the front of the queue.',
args: [{ name: 'url_or_title', multi: true }],
async execute(message, args) {
const { channel, guild, author } = message;
if (!guild) {
sendMusicOnlyInGuild(channel);
return;
}
const videoData = await validateArgs(args);
if (!videoData) {
sendNoVideo(channel, args.join(' '));
return;
}
redisQueue.lpush(guild.id, JSON.stringify(videoData));
sendAddedToQueue(channel, { videoData, author });
},
});
export default insert;
<file_sep>import { PrismaClient } from '.prisma/client';
import type { User } from 'discord.js';
import { Redis } from 'ioredis';
import { prisma as prismaClient } from '../prismaClient';
import { forRibbons, redis as redisClient } from '../redisClient';
export class UserProvider {
constructor(
private readonly prisma: PrismaClient,
private readonly redis: Redis,
) {}
async getRibbons(user: User) {
const ping = await this.redis.get(forRibbons(user.id));
if (ping) {
this.redis.expire(forRibbons(user.id), 60);
return parseInt(ping, 10);
}
return this.prisma.user
.findUnique({
where: { userId: user.id },
select: { ribbons: true },
})
.then((res) => {
const ribbons = res?.ribbons || 0;
this.redis.set(forRibbons(user.id), ribbons, 'ex', 60);
return ribbons;
});
}
async incrRibbons(user: User, incrby: number) {
if (incrby < 0) throw new Error('Got a negative value to increment.');
return this.prisma.user
.upsert({
where: { userId: user.id },
update: { ribbons: { increment: incrby } },
create: { userId: user.id, tag: user.tag, ribbons: incrby },
})
.then((_user) =>
this.redis.set(forRibbons(user.id), _user.ribbons, 'ex', 60),
);
}
async decrRibbons(user: User, decrby: number) {
if (decrby < 0) throw new Error('Received negative decrby value.');
await this.prisma
.$transaction([
this.prisma.$executeRaw<number>`
INSERT INTO "User" ("userId", tag, ribbons)
VALUES (${user.id}, ${user.tag}, ${0})
ON CONFLICT ("userId") DO UPDATE
SET ribbons =
CASE
WHEN "User".ribbons < ${decrby} THEN ${0}
ELSE "User".ribbons - ${decrby}
END;`,
this.prisma.user.findUnique({
where: { userId: user.id },
select: { ribbons: true },
}),
])
.then((_res) => {
const [, res] = _res;
const ribbons = res?.ribbons || 0;
this.redis.set(forRibbons(user.id), ribbons, 'ex', 60);
});
}
async getGlobalTopRibbons(take = 10) {
return this.prisma.user.findMany({
take,
orderBy: { ribbons: 'desc' },
select: { tag: true, ribbons: true },
});
}
async getTopRibbonsForUsers(members: User[], take = 10) {
const IDs = members.map((member) => member.id);
return this.prisma.user.findMany({
take,
select: { ribbons: true, tag: true },
where: { userId: { in: IDs } },
orderBy: { ribbons: 'desc' },
});
}
}
export const userProvider = new UserProvider(prismaClient, redisClient);
<file_sep>import { CmdCategory } from '@prisma/client';
import { shiritoriProvider } from '../../data/providers/shiritoriProvider';
import {
baseEmbed,
lightErrorEmbed,
sendNotInGuild,
} from '../../shared/embeds';
import { Command } from '../../types/command';
const shiritoriMinLen = new Command({
name: 'shiritori-minlen',
aliases: ['sh-min'],
args: [{ name: 'new_min', optional: true }],
category: CmdCategory.GAMES,
description: 'Check or set the minimum word length in Shiritori.',
async execute(message, args) {
const { channel, guild } = message;
if (!guild) {
sendNotInGuild(channel);
return;
}
const [_newMin] = args;
if (!_newMin) {
const currMin = await shiritoriProvider.getMinLen(guild.id);
channel.send(
baseEmbed().setDescription(`Current min word length: **${currMin}**`),
);
return;
}
const newMin = parseInt(_newMin, 10);
if (Number.isNaN(newMin)) {
channel.send(lightErrorEmbed(`Please give me a valid number!`));
return;
}
if (newMin < 0) {
channel.send(lightErrorEmbed(`Bruh.`));
return;
}
await shiritoriProvider.setMinLen(guild.id, newMin);
channel.send(
baseEmbed().setDescription(
`The minimum word length for Shiritori has been set to **${newMin}**!
This will apply on the next game.`,
),
);
},
});
export default shiritoriMinLen;
<file_sep>import { Message } from 'discord.js';
import { guildProvider } from '../data/providers/guildProvider';
import { validateArgsCount } from '../lib/validateArgsCount';
import { isOnCooldown } from '../lib/validateCooldowns';
import { DEFAULT_PREFIX } from '../shared/constants';
import { badCommandsEmbed, sendBlockedCommand } from '../shared/embeds';
import { CriticalError } from '../shared/errors';
import { Event } from '../types/event';
// TODO: add better arg validation
// check arg types too
const message: Event = {
name: 'message',
once: false,
async listener(client, message: Message) {
const { guild, content, author, channel } = message;
if (author.bot) return;
// check prefix
let prefix = DEFAULT_PREFIX;
if (guild) {
prefix = await guildProvider.getPrefix(guild.id);
}
const prefixRe = new RegExp(`^${prefix}`, 'i');
if (!prefixRe.test(content)) return;
// check if command exists
const args = content.split(/ +/);
const sentCommand = args.shift()?.toLowerCase().replace(prefix, '');
if (!sentCommand) return;
const command = client.commands.find(
(_command) =>
_command.name === sentCommand ||
!!_command.aliases?.includes(sentCommand),
);
if (!command) {
channel.send(badCommandsEmbed(sentCommand));
return;
}
// check if command is blocked
if (guild) {
const isBlocked = await guildProvider.isBlocked(guild.id, command.name);
if (isBlocked) {
sendBlockedCommand(channel, command.name);
return;
}
}
// check argument count
if (!validateArgsCount(command, args, channel)) return;
if (await isOnCooldown(message, command)) return;
try {
command.execute(message, args);
} catch (err) {
console.error(err);
if (err instanceof CriticalError) throw err;
}
},
};
export default message;
<file_sep>import { CmdCategory } from '@prisma/client';
import { redisQueue } from '../../data/redisClient';
import { lightErrorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { QueueItem } from '../../types/queue';
import { tryToConnect } from './utils/client';
import {
sendAddedToQueue,
sendMusicOnlyInGuild,
sendNotInVoiceChannel,
sendNoVideo,
sendNoVoicePermissions,
} from './utils/embeds';
import { createFinishListener } from './utils/listener';
import { playThis, validateArgs } from './utils/youtube';
const play = new Command({
name: 'play',
aliases: ['tunes'],
args: [{ name: 'url_or_title', multi: true, optional: true }],
category: CmdCategory.MUSIC,
description: 'Let Chika play some music from YouTube for you.',
async execute(message, args) {
const { channel, member, guild, client, author } = message;
if (!guild) {
sendMusicOnlyInGuild(channel);
return;
}
if (!member?.voice.channel) {
sendNotInVoiceChannel(channel);
return;
}
const next = await redisQueue.lpop(guild.id);
const audioUtils = client.cache.audioUtils.get(guild.id);
// they called ck;play with no args
if (args.length === 0) {
if (!next) {
channel.send(
lightErrorEmbed('There are no songs in the queue for me to play.'),
);
return;
}
if (audioUtils) {
channel.send(lightErrorEmbed("I'm already playing some music!"));
return;
}
const connection = await tryToConnect(member.voice.channel);
if (!connection) {
sendNoVoicePermissions(channel);
return;
}
connection.on('disconnect', () =>
client.cache.audioUtils.delete(guild.id),
);
const nextData = JSON.parse(next) as QueueItem;
playThis(connection, nextData, {
channel,
client,
guildId: guild.id,
onFinish: createFinishListener(guild, {
client,
channel,
}),
});
return;
}
if (next) redisQueue.lpush(guild.id, next); // push next track back
const videoData = await validateArgs(args);
if (!videoData) {
sendNoVideo(channel, args.join(' '));
return;
}
// there's a song playing
// push to the redis queue
if (audioUtils) {
redisQueue.rpush(guild.id, JSON.stringify(videoData));
sendAddedToQueue(channel, { videoData, author });
return;
}
// nothing is playing now
// start playing
const connection = await tryToConnect(member.voice.channel);
if (!connection) {
sendNoVoicePermissions(channel);
return;
}
connection.on('disconnect', () => client.cache.audioUtils.delete(guild.id));
playThis(connection, videoData, {
channel,
client,
guildId: guild.id,
onFinish: createFinishListener(guild, { channel, client }),
});
},
});
export default play;
<file_sep>import type { Message } from 'discord.js';
import ms from 'ms';
import { lightErrorEmbed } from '../shared/embeds';
import type { Command } from '../types/command';
import { getCooldown } from './cooldownManager';
export const isOnCooldown = async (
message: Message,
command: Command,
): Promise<boolean> => {
const { channel, author } = message;
if (command.channelCooldown) {
const pttl = await getCooldown(channel.id, command.name);
if (pttl) {
channel.send(
lightErrorEmbed(
`Please wait ${ms(pttl)} before using **${
command.name
}** in this channel again.`,
),
);
return true;
}
}
if (command.userCooldown) {
const pttl = await getCooldown(author.id, command.name);
if (pttl) {
message.channel.send(
lightErrorEmbed(
`**${author.username}**, please wait ${ms(pttl)} before using **${
command.name
}** again.`,
),
);
return true;
}
}
return false;
};
<file_sep>import { endOfToday, secToWordString } from './time';
describe('#secToWordString', () => {
describe('given exact hour', () => {
it('should return hour only', () => {
expect(secToWordString(3600)).toEqual('1h');
});
});
describe('given exact minute', () => {
it('should return minute only', () => {
expect(secToWordString(300)).toEqual('5min');
});
});
describe('given exact second', () => {
it('should return second only', () => {
expect(secToWordString(45)).toEqual('45s');
});
});
describe('given mix of hours, minutes, and seconds', () => {
it('should convert correctly', () => {
expect(secToWordString(19230)).toEqual('5h 20min 30s');
});
});
});
describe('#endOfToday', () => {
const dateSpy = jest.spyOn(Date.prototype, 'setHours').mockReturnValue(420);
beforeEach(() => {
dateSpy.mockClear();
});
it('should call Date with 23, 59, 59, 999', () => {
endOfToday();
expect(dateSpy).toBeCalledTimes(1);
expect(dateSpy).toBeCalledWith(23, 59, 59, 999);
});
it('should call valueOf and return a number', () => {
expect(endOfToday()).toBe(420);
});
});
<file_sep>import { CmdCategory } from '@prisma/client';
import { userProvider } from '../../data/providers/userProvider';
import { ribbon_emoji } from '../../shared/assets';
import { baseEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
const ribbon = new Command({
name: 'ribbon',
description: 'Check how many ribbons you or another user has.',
args: [{ name: 'user', optional: true }],
category: CmdCategory.CURRENCY,
aliases: ['r'],
async execute(message) {
const { mentions, author, channel } = message;
const user = mentions.users.first() || author;
const stock = await userProvider.getRibbons(user);
channel.send(
baseEmbed().setDescription(
`**${user.tag}** has **${stock}** ${ribbon_emoji}`,
),
);
},
});
export default ribbon;
<file_sep>import { Client, Guild, Message } from 'discord.js';
import { forNowPlaying, redis, redisQueue } from '../../../data/redisClient';
import { GenericChannel } from '../../../types/command';
import { QueueItem } from '../../../types/queue';
import { sendAddedToQueue, sendFinishedAllTracks } from './embeds';
import { playThis } from './youtube';
interface createFinishListenerParams {
channel: GenericChannel;
client: Client;
}
export function createFinishListener(
guild: Guild,
{ channel, client }: createFinishListenerParams,
) {
const onFinish = async () => {
const audioUtils = client.cache.audioUtils.get(guild.id)!;
if (!audioUtils) return;
redisQueue
.lpop(guild.id)
.then(async (res) => {
if (!res) {
sendFinishedAllTracks(channel);
audioUtils.dispatcher.destroy();
audioUtils.connection.disconnect();
redis.del(forNowPlaying(guild.id));
return;
}
const nextData = JSON.parse(res) as QueueItem;
playThis(audioUtils.connection, nextData, {
channel,
client,
guildId: guild.id,
onFinish,
});
})
.catch((err) => console.error(err));
};
return onFinish;
}
interface createResultSelectListenerParams {
channelId: string;
guildId: string;
}
export const createResultSelectListener = (
results: QueueItem[],
{ channelId, guildId }: createResultSelectListenerParams,
) => {
const resultSelectListener = async (message: Message) => {
const { content, channel, author } = message;
if (channelId !== channel.id) return;
const index = parseInt(content, 10);
if (Number.isNaN(index) || index > results.length) return;
const selectedTrack = results[index - 1];
redisQueue.rpush(guildId, JSON.stringify(selectedTrack));
sendAddedToQueue(channel, { videoData: selectedTrack, author });
};
return resultSelectListener;
};
<file_sep>export const endOfToday = () => new Date().setHours(23, 59, 59, 999);
export const secToWordString = (sec: number): string => {
const h = Math.floor(sec / 3600);
const subHour = sec % 3600;
const s = subHour % 60;
const m = (subHour - s) / 60;
return `${h ? `${h}h` : ''} ${m ? `${m}min` : ''} ${s ? `${s}s` : ''}`.trim();
};
<file_sep>import { lightErrorEmbed } from '../shared/embeds';
import { Command, GenericChannel } from '../types/command';
export function validateArgsCount(
command: Command,
args: string[],
channel: GenericChannel,
): string[] | null {
let softMax = 0;
let hasNoMulti = true;
command.args.forEach((arg) => {
if (!arg.optional) softMax += 1;
if (arg.optional && !arg.multi) softMax += 1;
if (arg.multi) hasNoMulti = false;
});
const min = command.args.filter((arg) => !arg.optional).length;
const hasNoOptional = min === command.args.length;
const provided = args.length;
// only non-optional args
// but either failed to give exact or gave too little
if (
hasNoOptional &&
((hasNoMulti && provided !== min) || (!hasNoMulti && provided < min))
) {
channel.send(
lightErrorEmbed(
`Command **${command.name}** expected ${min} ${
min === 1 ? 'argument' : 'arguments'
} but got ${provided}.
Use \`help ${command.name}\` to see usage info.`,
),
);
return null;
}
// has optional but gave less than min
if (!hasNoOptional && provided < min) {
channel.send(
lightErrorEmbed(
`Command **${command.name}** expected at least ${min} ${
min === 1 ? 'argument' : 'arguments'
} but got ${provided}.
Use \`help ${command.name}\` to see usage info.`,
),
);
return null;
}
// has optional and no multi and gave more than soft cap
if (!hasNoOptional && hasNoMulti && provided > softMax) {
channel.send(
lightErrorEmbed(
`Command **${command.name}** expected at most ${softMax} ${
softMax === 1 ? 'argument' : 'arguments'
} but got ${provided}.
Use \`help ${command.name}\` to see usage info.`,
),
);
return null;
}
return args;
}
<file_sep>import { CmdCategory } from '@prisma/client';
import { getSdk } from '../../generated/anilist';
import { Command } from '../../types/command';
import { charInfoEmbed } from './embeds/charInfoEmbed';
import { sendNotFoundError } from './embeds/errors';
import { client } from './graphql/aniListClient';
const char = new Command({
name: 'char',
aliases: ['character'],
args: [{ name: 'character', multi: true }],
category: CmdCategory.UTILITY,
description: 'Search for an animanga character.',
async execute(message, args) {
const { channel } = message;
const charName = args.join(' ');
const sdk = getSdk(client);
sdk
.searchChar({ charName })
.then((result) => {
if (!result.Character) {
sendNotFoundError(charName, channel);
return;
}
const { name, image, age, gender, description, dateOfBirth, siteUrl } =
result.Character;
channel.send(
charInfoEmbed({
englishName: name?.full,
japName: name?.native,
image: image?.large,
gender,
description,
age,
dateOfBirth,
siteUrl,
}),
);
})
.catch((err) => {
console.error(err);
sendNotFoundError(charName, channel);
});
},
});
export default char;
<file_sep>import { shuffle } from '../../../lib/shuffle';
export const genCardsString = (chars: string[]): string => {
// helper function to produce alphabet emojis
let generated = '';
chars.forEach((char) => {
generated += `:regional_indicator_${char}: `;
});
return generated;
};
export const genInitialCards = (size: number) => {
const allChars: string[] = [];
for (let i = 0; i < 26; i += 1) {
allChars.push(String.fromCharCode(i + 97));
}
const shuffled = shuffle(allChars);
return {
p1Cards: shuffled.slice(0, size),
p2Cards: shuffled.slice(size, 2 * size),
startingChar: shuffled[2 * size + 1],
};
};
<file_sep>import { Shiritori } from './shiritori';
export const shiritoriGame: Readonly<Shiritori> = new Shiritori();
<file_sep>import type { Collection, Snowflake, User } from 'discord.js';
import { GameState } from '../../../types/gameState';
// TODO game timeout on inactivity
interface ShiritoriState extends GameState {
p1: User;
p2: User;
cards: Collection<Snowflake, string[]>;
startingChar: string;
minLen: number;
}
export type { ShiritoriState };
<file_sep>import { CmdCategory } from '@prisma/client';
import { userProvider } from '../../data/providers/userProvider';
import { lightErrorEmbed, sendNotInGuild } from '../../shared/embeds';
import { Command } from '../../types/command';
import { MAX_TAKE } from './utils/defaults';
import { sendExceededMaxTake, sendTop } from './utils/embeds';
const top = new Command({
name: 'top',
args: [{ name: 'take', optional: true, multi: false }],
category: CmdCategory.CURRENCY,
description: 'Hunt down the richest in this server.',
aliases: ['richest'],
async execute(message, args) {
const { channel, guild } = message;
if (!guild) {
sendNotInGuild(channel);
return;
}
let take;
const [count] = args;
if (count) {
const _take = parseInt(count, 10);
if (Number.isNaN(_take)) {
channel.send(lightErrorEmbed('Gimme a number yo.'));
return;
}
if (_take > MAX_TAKE) {
sendExceededMaxTake(channel);
return;
}
take = _take;
}
const guildMembers = (await guild.members.fetch()).map(
(member) => member.user,
);
userProvider.getTopRibbonsForUsers(guildMembers, take).then((res) =>
sendTop(channel, res, {
locale: guild.name,
thumbnail: guild.iconURL({ dynamic: true, size: 128 }),
}),
);
},
});
export default top;
<file_sep>import { Balloon } from './balloon';
export const balloonGame: Readonly<Balloon> = new Balloon();
<file_sep>import { CmdCategory } from '.prisma/client';
import { blindUnblock } from '../../games/utils/manageState';
import { lightErrorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
const stopGame = new Command({
name: 'stop-game',
aliases: ['sg'],
args: [],
category: CmdCategory.GAMES,
description: 'Exit from the current game in session.',
execute: async (ctx) => {
const { channel, author } = ctx;
blindUnblock(ctx).then(
() => {
channel.send(
lightErrorEmbed(`**${author.username}** has stopped the game.`),
);
},
(err) => channel.send(lightErrorEmbed(err)),
);
},
});
export default stopGame;
<file_sep>
<p>
<a><img alt="ci" src="https://github.com/shinomiya-corp/chika/actions/workflows/ci.yml/badge.svg"/></a>
<a href="https://codecov.io/gh/shinomiya-corp/chika"> <img src="https://codecov.io/gh/shinomiya-corp/chika/branch/dev/graph/badge.svg?token=<KEY>"/> </a>
<a href="https://codeclimate.com/github/shinomiya-corp/chika-bot/maintainability"><img src="https://api.codeclimate.com/v1/badges/b8793d37cbbbde8f1e96/maintainability" /></a>
<a href="https://www.chikawara.xyz"><img alt="Website" src="https://img.shields.io/website?url=https%3A%2F%2Fwww.chikawara.xyz"></a>
<a><img alt="GitHub" src="https://img.shields.io/github/license/shinomiya-corp/chika"></a>
<a href="https://discord.com/api/oauth2/authorize?client_id=843481025459519528&permissions=540018688&scope=bot"><img alt="Invite" src="https://img.shields.io/static/v1?logo=discord&label=invite&message=Chika&color=f2d5da"></a>
<p/>
# discord.js bot for Chika
Hayasaka is best girl, so it puzzles myself why I chose Chika as a template for the bot. But we've gone too far to turn back now. If I started this project from scratch today, I'd use a tool like [Nx](https://github.com/nrwl/nx) and put everything in a mono-repo. But I was dumb and divided this project into: the bot itself (this page), [server](https://github.com/shinomiya-corp/chika-server), [landing page](https://github.com/immanuelhume/chika-next), [dashboard](https://github.com/immanuelhume/chika-dashboard), and even a repo just for a freakin prisma [schema file and migrations](https://github.com/shinomiya-corp/chika-schema).
## Features
- 🎮 Games from the manga (Shiritori and Balloon(?))
- More are coming soon<sup>TM</sup>
- 🎧 Simple music streaming
- 🦜 An unintelligent AI chatbot for Kaguya and Chika
- I don't know anything about ML but hey it kinda works
- 💰 Global currency system
- ...and some others probably, see the full list [here](https://www.chikawara.xyz/commands)
## Run Locally
Clone the project
```bash
git clone https://github.com/shinomiya-corp/chika.git
```
Install dependencies
```bash
cd chika && yarn
```
Build and run (requires node v14.16.1 for music to work, idk why lol)
```bash
yarn tsc && node dist/index.js
```
## Environment Variables
To run this project, you'll need to add the following environment variables to your .env file
`APP_TOKEN`, `BOT_USER_ID` (from Discord's developer portal)
`DATABASE_URL`, `REDISCLOUD_URL` (pointing to a postgres and redis instance)
`HUGGING_FACE_CHIKA`, `HUGGING_FACE_CHIKA_KEY`, `HUGGING_FACE_KAGUYA`, `HUGGING_FACE_KAGUYA_KEY` (from hosting the ML stuff on huggingface.co)
`ANILIST_SCHEMA` (it's just https://graphql.anilist.co)
## Roadmap
- Web dashboard in NextJS 🥢
- Integrate [uwu](https://github.com/Daniel-Liu-c0deb0t/uwu) into a command
- 30% test cov pls
## Screenshots
Here are some bruh moments



## Feedback
If you have any feedback or spot bugs, please raise an issue on GitHub.
<file_sep>import { baseEmbed } from '../../../shared/embeds';
export const dashboardLink = baseEmbed().setDescription(
'[Here you go!](https://dashboard.chikawara.xyz)',
);
<file_sep>import Discord, { Collection } from 'discord.js';
import type { AudioUtils } from '../types/queue';
export const initialClientCache: Discord.Client['cache'] = {
audioUtils: new Collection<string, AudioUtils>(),
inGameStates: new Collection<string, string>(),
};
<file_sep>import type { User } from 'discord.js';
import { ribbon_emoji } from '../../../shared/assets';
import { baseEmbed } from '../../../shared/embeds';
import { GenericChannel } from '../../../types/command';
export const sendPopped = (
channel: GenericChannel,
info: { popper: User; isBankrupt: boolean; winAmt: number },
) => {
const { popper, isBankrupt, winAmt } = info;
channel.send(
baseEmbed()
.setTitle(`Boom, yo! :boom:`)
.setDescription(
`
The balloon bursts in **${popper.username}**'s face!
${
isBankrupt
? `**${popper.username}** is bankrupt!\nEveryone else receives **+ ${winAmt}** ${ribbon_emoji}, sponsored by the Chika Bank.`
: `**${popper.username}** pays everyone else **${winAmt}** ${ribbon_emoji}.`
}
`,
),
);
};
<file_sep>import { CmdCategory } from '@prisma/client';
import ytpl from 'ytpl';
import { redisQueue } from '../../data/redisClient';
import { cryingEmbed, withAuthorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { sendMusicOnlyInGuild, toUrlString } from './utils/embeds';
import { parsePlaylist } from './utils/youtube';
const addPlaylist = new Command({
name: 'add-playlist',
aliases: ['ap'],
category: CmdCategory.MUSIC,
description: 'Add a YouTube playlist to the queue.',
args: [{ name: 'playlist_url' }],
async execute(message, args) {
const { guild, channel, author } = message;
if (!guild) {
sendMusicOnlyInGuild(channel);
return;
}
const [playlistURL] = args;
ytpl(playlistURL)
.then((res) => {
const [playlistMetadata, videos] = parsePlaylist(res);
redisQueue.rpush(
guild.id,
...videos.map((video) => JSON.stringify(video)),
);
channel.send(
withAuthorEmbed(author)
.setTitle('Added Playlist')
.setDescription(
`${toUrlString(
playlistMetadata.title,
playlistMetadata.url,
40,
)}`,
)
.setThumbnail(playlistMetadata.thumbnailURL),
);
})
.catch(() =>
channel.send(
cryingEmbed()
.setTitle('Sorry...')
.setDescription(
`I couldn't find a playlist at ${toUrlString(
playlistURL,
playlistURL,
40,
)}`,
)
.addField('\u200b', 'It might be a private playlist?'),
),
);
},
});
export default addPlaylist;
<file_sep>import type { Message } from 'discord.js';
import { chika_beating_yu_gif, white_check_mark } from '../../../shared/assets';
import { baseEmbed } from '../../../shared/embeds';
import { filterMessage } from '../../../lib/validateMessages';
import { isGameActive, unblock } from '../../utils/manageState';
import type { Shiritori } from '../shiritori';
import { checkWord } from './checkWord';
import { shiritoriPlayerCardsEmbed } from './embeds';
import type { ShiritoriState } from './types';
export const createOnceShiritoriListener = (
state: ShiritoriState,
game: Readonly<Shiritori>,
) => {
const shiritoriListener = async (message: Message) => {
const { author, content, channel, client } = message;
const onRejectListener = createOnceShiritoriListener(state, game);
const reject = () => client.once('message', onRejectListener);
if (
!filterMessage(message, {
channelId: state.channelId,
authors: [state.p1, state.p2],
content: new RegExp(`^${state.startingChar}`, 'i'),
minLen: state.minLen,
})
) {
reject();
return;
}
if (!isGameActive(game, message)) return;
const playerCards = state.cards.get(author.id)!;
const lastChar = content[content.length - 1];
if (!playerCards.includes(content[content.length - 1])) {
reject();
return;
}
const isValidWord = await checkWord(content);
if (!isValidWord) {
reject();
return;
}
channel.send(`I accept **${content}**! ${white_check_mark}`);
playerCards.splice(playerCards.indexOf(lastChar), 1); // it's valid, pop that word out
if (playerCards.length === 0) {
channel.send(
baseEmbed()
.setDescription(
`**${author.username}** defeats **${
author.id === state.p1.id ? state.p2.username : state.p1.username
}!**`,
)
.setImage(chika_beating_yu_gif),
);
unblock(game, message);
return;
}
client.once('message', createOnceShiritoriListener(state, game));
channel
.send(shiritoriPlayerCardsEmbed(state))
.then(() => channel.send(`:regional_indicator_${lastChar}:`));
state.startingChar = lastChar;
};
return shiritoriListener;
};
<file_sep>import { GraphQLClient } from 'graphql-request';
import * as Dom from 'graphql-request/dist/types.dom';
import gql from 'graphql-tag';
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = {
[K in keyof T]: T[K];
};
export type MakeOptional<T, K extends keyof T> = Omit<T, K> &
{ [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> &
{ [SubKey in K]: Maybe<T[SubKey]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
/** ISO 3166-1 alpha-2 country code */
CountryCode: any;
/** 8 digit long date integer (YYYYMMDD). Unknown dates represented by 0. E.g. 2016: 20160000, May 1976: 19760500 */
FuzzyDateInt: any;
Json: any;
};
/** Notification for when a activity is liked */
export type ActivityLikeNotification = {
__typename?: 'ActivityLikeNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The id of the user who liked to the activity */
userId: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The id of the activity which was liked */
activityId: Scalars['Int'];
/** The notification context text */
context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The liked activity */
activity?: Maybe<ActivityUnion>;
/** The user who liked the activity */
user?: Maybe<User>;
};
/** Notification for when authenticated user is @ mentioned in activity or reply */
export type ActivityMentionNotification = {
__typename?: 'ActivityMentionNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The id of the user who mentioned the authenticated user */
userId: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The id of the activity where mentioned */
activityId: Scalars['Int'];
/** The notification context text */
context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The liked activity */
activity?: Maybe<ActivityUnion>;
/** The user who mentioned the authenticated user */
user?: Maybe<User>;
};
/** Notification for when a user is send an activity message */
export type ActivityMessageNotification = {
__typename?: 'ActivityMessageNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The if of the user who send the message */
userId: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The id of the activity message */
activityId: Scalars['Int'];
/** The notification context text */
context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The message activity */
message?: Maybe<MessageActivity>;
/** The user who sent the message */
user?: Maybe<User>;
};
/** Replay to an activity item */
export type ActivityReply = {
__typename?: 'ActivityReply';
/** The id of the reply */
id: Scalars['Int'];
/** The id of the replies creator */
userId?: Maybe<Scalars['Int']>;
/** The id of the parent activity */
activityId?: Maybe<Scalars['Int']>;
/** The reply text */
text?: Maybe<Scalars['String']>;
/** The amount of likes the reply has */
likeCount: Scalars['Int'];
/** If the currently authenticated user liked the reply */
isLiked?: Maybe<Scalars['Boolean']>;
/** The time the reply was created at */
createdAt: Scalars['Int'];
/** The user who created reply */
user?: Maybe<User>;
/** The users who liked the reply */
likes?: Maybe<Array<Maybe<User>>>;
};
/** Replay to an activity item */
export type ActivityReplyTextArgs = {
asHtml?: Maybe<Scalars['Boolean']>;
};
/** Notification for when a activity reply is liked */
export type ActivityReplyLikeNotification = {
__typename?: 'ActivityReplyLikeNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The id of the user who liked to the activity reply */
userId: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The id of the activity where the reply which was liked */
activityId: Scalars['Int'];
/** The notification context text */
context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The liked activity */
activity?: Maybe<ActivityUnion>;
/** The user who liked the activity reply */
user?: Maybe<User>;
};
/** Notification for when a user replies to the authenticated users activity */
export type ActivityReplyNotification = {
__typename?: 'ActivityReplyNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The id of the user who replied to the activity */
userId: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The id of the activity which was replied too */
activityId: Scalars['Int'];
/** The notification context text */
context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The liked activity */
activity?: Maybe<ActivityUnion>;
/** The user who replied to the activity */
user?: Maybe<User>;
};
/** Notification for when a user replies to activity the authenticated user has replied to */
export type ActivityReplySubscribedNotification = {
__typename?: 'ActivityReplySubscribedNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The id of the user who replied to the activity */
userId: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The id of the activity which was replied too */
activityId: Scalars['Int'];
/** The notification context text */
context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The liked activity */
activity?: Maybe<ActivityUnion>;
/** The user who replied to the activity */
user?: Maybe<User>;
};
/** Activity sort enums */
export enum ActivitySort {
Id = 'ID',
IdDesc = 'ID_DESC',
}
/** Activity type enum. */
export enum ActivityType {
/** A text activity */
Text = 'TEXT',
/** A anime list update activity */
AnimeList = 'ANIME_LIST',
/** A manga list update activity */
MangaList = 'MANGA_LIST',
/** A text message activity sent to another user */
Message = 'MESSAGE',
/** Anime & Manga list update, only used in query arguments */
MediaList = 'MEDIA_LIST',
}
/** Activity union type */
export type ActivityUnion = TextActivity | ListActivity | MessageActivity;
/** Notification for when an episode of anime airs */
export type AiringNotification = {
__typename?: 'AiringNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The id of the aired anime */
animeId: Scalars['Int'];
/** The episode number that just aired */
episode: Scalars['Int'];
/** The notification context text */
contexts?: Maybe<Array<Maybe<Scalars['String']>>>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The associated media of the airing schedule */
media?: Maybe<Media>;
};
/** Score & Watcher stats for airing anime by episode and mid-week */
export type AiringProgression = {
__typename?: 'AiringProgression';
/** The episode the stats were recorded at. .5 is the mid point between 2 episodes airing dates. */
episode?: Maybe<Scalars['Float']>;
/** The average score for the media */
score?: Maybe<Scalars['Float']>;
/** The amount of users watching the anime */
watching?: Maybe<Scalars['Int']>;
};
/** Media Airing Schedule. NOTE: We only aim to guarantee that FUTURE airing data is present and accurate. */
export type AiringSchedule = {
__typename?: 'AiringSchedule';
/** The id of the airing schedule item */
id: Scalars['Int'];
/** The time the episode airs at */
airingAt: Scalars['Int'];
/** Seconds until episode starts airing */
timeUntilAiring: Scalars['Int'];
/** The airing episode number */
episode: Scalars['Int'];
/** The associate media id of the airing episode */
mediaId: Scalars['Int'];
/** The associate media of the airing episode */
media?: Maybe<Media>;
};
export type AiringScheduleConnection = {
__typename?: 'AiringScheduleConnection';
edges?: Maybe<Array<Maybe<AiringScheduleEdge>>>;
nodes?: Maybe<Array<Maybe<AiringSchedule>>>;
/** The pagination information */
pageInfo?: Maybe<PageInfo>;
};
/** AiringSchedule connection edge */
export type AiringScheduleEdge = {
__typename?: 'AiringScheduleEdge';
node?: Maybe<AiringSchedule>;
/** The id of the connection */
id?: Maybe<Scalars['Int']>;
};
export type AiringScheduleInput = {
airingAt?: Maybe<Scalars['Int']>;
episode?: Maybe<Scalars['Int']>;
timeUntilAiring?: Maybe<Scalars['Int']>;
};
/** Airing schedule sort enums */
export enum AiringSort {
Id = 'ID',
IdDesc = 'ID_DESC',
MediaId = 'MEDIA_ID',
MediaIdDesc = 'MEDIA_ID_DESC',
Time = 'TIME',
TimeDesc = 'TIME_DESC',
Episode = 'EPISODE',
EpisodeDesc = 'EPISODE_DESC',
}
export type AniChartHighlightInput = {
mediaId?: Maybe<Scalars['Int']>;
highlight?: Maybe<Scalars['String']>;
};
export type AniChartUser = {
__typename?: 'AniChartUser';
user?: Maybe<User>;
settings?: Maybe<Scalars['Json']>;
highlights?: Maybe<Scalars['Json']>;
};
/** A character that features in an anime or manga */
export type Character = {
__typename?: 'Character';
/** The id of the character */
id: Scalars['Int'];
/** The names of the character */
name?: Maybe<CharacterName>;
/** Character images */
image?: Maybe<CharacterImage>;
/** A general description of the character */
description?: Maybe<Scalars['String']>;
/** The character's gender. Usually Male, Female, or Non-binary but can be any string. */
gender?: Maybe<Scalars['String']>;
/** The character's birth date */
dateOfBirth?: Maybe<FuzzyDate>;
/** The character's age. Note this is a string, not an int, it may contain further text and additional ages. */
age?: Maybe<Scalars['String']>;
/** If the character is marked as favourite by the currently authenticated user */
isFavourite: Scalars['Boolean'];
/** If the character is blocked from being added to favourites */
isFavouriteBlocked: Scalars['Boolean'];
/** The url for the character page on the AniList website */
siteUrl?: Maybe<Scalars['String']>;
/** Media that includes the character */
media?: Maybe<MediaConnection>;
/** @deprecated No data available */
updatedAt?: Maybe<Scalars['Int']>;
/** The amount of user's who have favourited the character */
favourites?: Maybe<Scalars['Int']>;
/** Notes for site moderators */
modNotes?: Maybe<Scalars['String']>;
};
/** A character that features in an anime or manga */
export type CharacterDescriptionArgs = {
asHtml?: Maybe<Scalars['Boolean']>;
};
/** A character that features in an anime or manga */
export type CharacterMediaArgs = {
sort?: Maybe<Array<Maybe<MediaSort>>>;
type?: Maybe<MediaType>;
onList?: Maybe<Scalars['Boolean']>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
export type CharacterConnection = {
__typename?: 'CharacterConnection';
edges?: Maybe<Array<Maybe<CharacterEdge>>>;
nodes?: Maybe<Array<Maybe<Character>>>;
/** The pagination information */
pageInfo?: Maybe<PageInfo>;
};
/** Character connection edge */
export type CharacterEdge = {
__typename?: 'CharacterEdge';
node?: Maybe<Character>;
/** The id of the connection */
id?: Maybe<Scalars['Int']>;
/** The characters role in the media */
role?: Maybe<CharacterRole>;
/** Media specific character name */
name?: Maybe<Scalars['String']>;
/** The voice actors of the character */
voiceActors?: Maybe<Array<Maybe<Staff>>>;
/** The voice actors of the character with role date */
voiceActorRoles?: Maybe<Array<Maybe<StaffRoleType>>>;
/** The media the character is in */
media?: Maybe<Array<Maybe<Media>>>;
/** The order the character should be displayed from the users favourites */
favouriteOrder?: Maybe<Scalars['Int']>;
};
/** Character connection edge */
export type CharacterEdgeVoiceActorsArgs = {
language?: Maybe<StaffLanguage>;
sort?: Maybe<Array<Maybe<StaffSort>>>;
};
/** Character connection edge */
export type CharacterEdgeVoiceActorRolesArgs = {
language?: Maybe<StaffLanguage>;
sort?: Maybe<Array<Maybe<StaffSort>>>;
};
export type CharacterImage = {
__typename?: 'CharacterImage';
/** The character's image of media at its largest size */
large?: Maybe<Scalars['String']>;
/** The character's image of media at medium size */
medium?: Maybe<Scalars['String']>;
};
/** The names of the character */
export type CharacterName = {
__typename?: 'CharacterName';
/** The character's given name */
first?: Maybe<Scalars['String']>;
/** The character's middle name */
middle?: Maybe<Scalars['String']>;
/** The character's surname */
last?: Maybe<Scalars['String']>;
/** The character's first and last name */
full?: Maybe<Scalars['String']>;
/** The character's full name in their native language */
native?: Maybe<Scalars['String']>;
/** Other names the character might be referred to as */
alternative?: Maybe<Array<Maybe<Scalars['String']>>>;
/** Other names the character might be referred to as but are spoilers */
alternativeSpoiler?: Maybe<Array<Maybe<Scalars['String']>>>;
/** The currently authenticated users preferred name language. Default romaji for non-authenticated */
userPreferred?: Maybe<Scalars['String']>;
};
/** The names of the character */
export type CharacterNameInput = {
/** The character's given name */
first?: Maybe<Scalars['String']>;
/** The character's middle name */
middle?: Maybe<Scalars['String']>;
/** The character's surname */
last?: Maybe<Scalars['String']>;
/** The character's full name in their native language */
native?: Maybe<Scalars['String']>;
/** Other names the character might be referred by */
alternative?: Maybe<Array<Maybe<Scalars['String']>>>;
/** Other names the character might be referred to as but are spoilers */
alternativeSpoiler?: Maybe<Array<Maybe<Scalars['String']>>>;
};
/** The role the character plays in the media */
export enum CharacterRole {
/** A primary character role in the media */
Main = 'MAIN',
/** A supporting character role in the media */
Supporting = 'SUPPORTING',
/** A background character in the media */
Background = 'BACKGROUND',
}
/** Character sort enums */
export enum CharacterSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Role = 'ROLE',
RoleDesc = 'ROLE_DESC',
SearchMatch = 'SEARCH_MATCH',
Favourites = 'FAVOURITES',
FavouritesDesc = 'FAVOURITES_DESC',
/** Order manually decided by moderators */
Relevance = 'RELEVANCE',
}
/** A submission for a character that features in an anime or manga */
export type CharacterSubmission = {
__typename?: 'CharacterSubmission';
/** The id of the submission */
id: Scalars['Int'];
/** Character that the submission is referencing */
character?: Maybe<Character>;
/** The character submission changes */
submission?: Maybe<Character>;
/** Submitter for the submission */
submitter?: Maybe<User>;
/** Status of the submission */
status?: Maybe<SubmissionStatus>;
/** Inner details of submission status */
notes?: Maybe<Scalars['String']>;
source?: Maybe<Scalars['String']>;
createdAt?: Maybe<Scalars['Int']>;
};
export type CharacterSubmissionConnection = {
__typename?: 'CharacterSubmissionConnection';
edges?: Maybe<Array<Maybe<CharacterSubmissionEdge>>>;
nodes?: Maybe<Array<Maybe<CharacterSubmission>>>;
/** The pagination information */
pageInfo?: Maybe<PageInfo>;
};
/** CharacterSubmission connection edge */
export type CharacterSubmissionEdge = {
__typename?: 'CharacterSubmissionEdge';
node?: Maybe<CharacterSubmission>;
/** The characters role in the media */
role?: Maybe<CharacterRole>;
/** The voice actors of the character */
voiceActors?: Maybe<Array<Maybe<Staff>>>;
/** The submitted voice actors of the character */
submittedVoiceActors?: Maybe<Array<Maybe<StaffSubmission>>>;
};
/** Deleted data type */
export type Deleted = {
__typename?: 'Deleted';
/** If an item has been successfully deleted */
deleted?: Maybe<Scalars['Boolean']>;
};
/** User's favourite anime, manga, characters, staff & studios */
export type Favourites = {
__typename?: 'Favourites';
/** Favourite anime */
anime?: Maybe<MediaConnection>;
/** Favourite manga */
manga?: Maybe<MediaConnection>;
/** Favourite characters */
characters?: Maybe<CharacterConnection>;
/** Favourite staff */
staff?: Maybe<StaffConnection>;
/** Favourite studios */
studios?: Maybe<StudioConnection>;
};
/** User's favourite anime, manga, characters, staff & studios */
export type FavouritesAnimeArgs = {
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** User's favourite anime, manga, characters, staff & studios */
export type FavouritesMangaArgs = {
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** User's favourite anime, manga, characters, staff & studios */
export type FavouritesCharactersArgs = {
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** User's favourite anime, manga, characters, staff & studios */
export type FavouritesStaffArgs = {
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** User's favourite anime, manga, characters, staff & studios */
export type FavouritesStudiosArgs = {
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** Notification for when the authenticated user is followed by another user */
export type FollowingNotification = {
__typename?: 'FollowingNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The id of the user who followed the authenticated user */
userId: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The notification context text */
context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The liked activity */
user?: Maybe<User>;
};
/** User's format statistics */
export type FormatStats = {
__typename?: 'FormatStats';
format?: Maybe<MediaFormat>;
amount?: Maybe<Scalars['Int']>;
};
/** Date object that allows for incomplete date values (fuzzy) */
export type FuzzyDate = {
__typename?: 'FuzzyDate';
/** Numeric Year (2017) */
year?: Maybe<Scalars['Int']>;
/** Numeric Month (3) */
month?: Maybe<Scalars['Int']>;
/** Numeric Day (24) */
day?: Maybe<Scalars['Int']>;
};
/** Date object that allows for incomplete date values (fuzzy) */
export type FuzzyDateInput = {
/** Numeric Year (2017) */
year?: Maybe<Scalars['Int']>;
/** Numeric Month (3) */
month?: Maybe<Scalars['Int']>;
/** Numeric Day (24) */
day?: Maybe<Scalars['Int']>;
};
/** User's genre statistics */
export type GenreStats = {
__typename?: 'GenreStats';
genre?: Maybe<Scalars['String']>;
amount?: Maybe<Scalars['Int']>;
meanScore?: Maybe<Scalars['Int']>;
/** The amount of time in minutes the genre has been watched by the user */
timeWatched?: Maybe<Scalars['Int']>;
};
/** Page of data (Used for internal use only) */
export type InternalPage = {
__typename?: 'InternalPage';
mediaSubmissions?: Maybe<Array<Maybe<MediaSubmission>>>;
characterSubmissions?: Maybe<Array<Maybe<CharacterSubmission>>>;
staffSubmissions?: Maybe<Array<Maybe<StaffSubmission>>>;
revisionHistory?: Maybe<Array<Maybe<RevisionHistory>>>;
reports?: Maybe<Array<Maybe<Report>>>;
modActions?: Maybe<Array<Maybe<ModAction>>>;
/** The pagination information */
pageInfo?: Maybe<PageInfo>;
users?: Maybe<Array<Maybe<User>>>;
media?: Maybe<Array<Maybe<Media>>>;
characters?: Maybe<Array<Maybe<Character>>>;
staff?: Maybe<Array<Maybe<Staff>>>;
studios?: Maybe<Array<Maybe<Studio>>>;
mediaList?: Maybe<Array<Maybe<MediaList>>>;
airingSchedules?: Maybe<Array<Maybe<AiringSchedule>>>;
mediaTrends?: Maybe<Array<Maybe<MediaTrend>>>;
notifications?: Maybe<Array<Maybe<NotificationUnion>>>;
followers?: Maybe<Array<Maybe<User>>>;
following?: Maybe<Array<Maybe<User>>>;
activities?: Maybe<Array<Maybe<ActivityUnion>>>;
activityReplies?: Maybe<Array<Maybe<ActivityReply>>>;
threads?: Maybe<Array<Maybe<Thread>>>;
threadComments?: Maybe<Array<Maybe<ThreadComment>>>;
reviews?: Maybe<Array<Maybe<Review>>>;
recommendations?: Maybe<Array<Maybe<Recommendation>>>;
likes?: Maybe<Array<Maybe<User>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageMediaSubmissionsArgs = {
mediaId?: Maybe<Scalars['Int']>;
submissionId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
status?: Maybe<SubmissionStatus>;
type?: Maybe<MediaType>;
sort?: Maybe<Array<Maybe<SubmissionSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageCharacterSubmissionsArgs = {
characterId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
status?: Maybe<SubmissionStatus>;
sort?: Maybe<Array<Maybe<SubmissionSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageStaffSubmissionsArgs = {
staffId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
status?: Maybe<SubmissionStatus>;
sort?: Maybe<Array<Maybe<SubmissionSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageRevisionHistoryArgs = {
userId?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
characterId?: Maybe<Scalars['Int']>;
staffId?: Maybe<Scalars['Int']>;
studioId?: Maybe<Scalars['Int']>;
};
/** Page of data (Used for internal use only) */
export type InternalPageReportsArgs = {
reporterId?: Maybe<Scalars['Int']>;
reportedId?: Maybe<Scalars['Int']>;
};
/** Page of data (Used for internal use only) */
export type InternalPageModActionsArgs = {
userId?: Maybe<Scalars['Int']>;
modId?: Maybe<Scalars['Int']>;
};
/** Page of data (Used for internal use only) */
export type InternalPageUsersArgs = {
id?: Maybe<Scalars['Int']>;
name?: Maybe<Scalars['String']>;
isModerator?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
sort?: Maybe<Array<Maybe<UserSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageMediaArgs = {
id?: Maybe<Scalars['Int']>;
idMal?: Maybe<Scalars['Int']>;
startDate?: Maybe<Scalars['FuzzyDateInt']>;
endDate?: Maybe<Scalars['FuzzyDateInt']>;
season?: Maybe<MediaSeason>;
seasonYear?: Maybe<Scalars['Int']>;
type?: Maybe<MediaType>;
format?: Maybe<MediaFormat>;
status?: Maybe<MediaStatus>;
episodes?: Maybe<Scalars['Int']>;
duration?: Maybe<Scalars['Int']>;
chapters?: Maybe<Scalars['Int']>;
volumes?: Maybe<Scalars['Int']>;
isAdult?: Maybe<Scalars['Boolean']>;
genre?: Maybe<Scalars['String']>;
tag?: Maybe<Scalars['String']>;
minimumTagRank?: Maybe<Scalars['Int']>;
tagCategory?: Maybe<Scalars['String']>;
onList?: Maybe<Scalars['Boolean']>;
licensedBy?: Maybe<Scalars['String']>;
averageScore?: Maybe<Scalars['Int']>;
popularity?: Maybe<Scalars['Int']>;
source?: Maybe<MediaSource>;
countryOfOrigin?: Maybe<Scalars['CountryCode']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
idMal_not?: Maybe<Scalars['Int']>;
idMal_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
idMal_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
startDate_greater?: Maybe<Scalars['FuzzyDateInt']>;
startDate_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startDate_like?: Maybe<Scalars['String']>;
endDate_greater?: Maybe<Scalars['FuzzyDateInt']>;
endDate_lesser?: Maybe<Scalars['FuzzyDateInt']>;
endDate_like?: Maybe<Scalars['String']>;
format_in?: Maybe<Array<Maybe<MediaFormat>>>;
format_not?: Maybe<MediaFormat>;
format_not_in?: Maybe<Array<Maybe<MediaFormat>>>;
status_in?: Maybe<Array<Maybe<MediaStatus>>>;
status_not?: Maybe<MediaStatus>;
status_not_in?: Maybe<Array<Maybe<MediaStatus>>>;
episodes_greater?: Maybe<Scalars['Int']>;
episodes_lesser?: Maybe<Scalars['Int']>;
duration_greater?: Maybe<Scalars['Int']>;
duration_lesser?: Maybe<Scalars['Int']>;
chapters_greater?: Maybe<Scalars['Int']>;
chapters_lesser?: Maybe<Scalars['Int']>;
volumes_greater?: Maybe<Scalars['Int']>;
volumes_lesser?: Maybe<Scalars['Int']>;
genre_in?: Maybe<Array<Maybe<Scalars['String']>>>;
genre_not_in?: Maybe<Array<Maybe<Scalars['String']>>>;
tag_in?: Maybe<Array<Maybe<Scalars['String']>>>;
tag_not_in?: Maybe<Array<Maybe<Scalars['String']>>>;
tagCategory_in?: Maybe<Array<Maybe<Scalars['String']>>>;
tagCategory_not_in?: Maybe<Array<Maybe<Scalars['String']>>>;
licensedBy_in?: Maybe<Array<Maybe<Scalars['String']>>>;
averageScore_not?: Maybe<Scalars['Int']>;
averageScore_greater?: Maybe<Scalars['Int']>;
averageScore_lesser?: Maybe<Scalars['Int']>;
popularity_not?: Maybe<Scalars['Int']>;
popularity_greater?: Maybe<Scalars['Int']>;
popularity_lesser?: Maybe<Scalars['Int']>;
source_in?: Maybe<Array<Maybe<MediaSource>>>;
sort?: Maybe<Array<Maybe<MediaSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageCharactersArgs = {
id?: Maybe<Scalars['Int']>;
isBirthday?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
sort?: Maybe<Array<Maybe<CharacterSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageStaffArgs = {
id?: Maybe<Scalars['Int']>;
isBirthday?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
sort?: Maybe<Array<Maybe<StaffSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageStudiosArgs = {
id?: Maybe<Scalars['Int']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
sort?: Maybe<Array<Maybe<StudioSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageMediaListArgs = {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
userName?: Maybe<Scalars['String']>;
type?: Maybe<MediaType>;
status?: Maybe<MediaListStatus>;
mediaId?: Maybe<Scalars['Int']>;
isFollowing?: Maybe<Scalars['Boolean']>;
notes?: Maybe<Scalars['String']>;
startedAt?: Maybe<Scalars['FuzzyDateInt']>;
completedAt?: Maybe<Scalars['FuzzyDateInt']>;
compareWithAuthList?: Maybe<Scalars['Boolean']>;
userId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
status_in?: Maybe<Array<Maybe<MediaListStatus>>>;
status_not_in?: Maybe<Array<Maybe<MediaListStatus>>>;
status_not?: Maybe<MediaListStatus>;
mediaId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
notes_like?: Maybe<Scalars['String']>;
startedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_like?: Maybe<Scalars['String']>;
completedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_like?: Maybe<Scalars['String']>;
sort?: Maybe<Array<Maybe<MediaListSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageAiringSchedulesArgs = {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
episode?: Maybe<Scalars['Int']>;
airingAt?: Maybe<Scalars['Int']>;
notYetAired?: Maybe<Scalars['Boolean']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
episode_not?: Maybe<Scalars['Int']>;
episode_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
episode_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
episode_greater?: Maybe<Scalars['Int']>;
episode_lesser?: Maybe<Scalars['Int']>;
airingAt_greater?: Maybe<Scalars['Int']>;
airingAt_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<AiringSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageMediaTrendsArgs = {
mediaId?: Maybe<Scalars['Int']>;
date?: Maybe<Scalars['Int']>;
trending?: Maybe<Scalars['Int']>;
averageScore?: Maybe<Scalars['Int']>;
popularity?: Maybe<Scalars['Int']>;
episode?: Maybe<Scalars['Int']>;
releasing?: Maybe<Scalars['Boolean']>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
date_greater?: Maybe<Scalars['Int']>;
date_lesser?: Maybe<Scalars['Int']>;
trending_greater?: Maybe<Scalars['Int']>;
trending_lesser?: Maybe<Scalars['Int']>;
trending_not?: Maybe<Scalars['Int']>;
averageScore_greater?: Maybe<Scalars['Int']>;
averageScore_lesser?: Maybe<Scalars['Int']>;
averageScore_not?: Maybe<Scalars['Int']>;
popularity_greater?: Maybe<Scalars['Int']>;
popularity_lesser?: Maybe<Scalars['Int']>;
popularity_not?: Maybe<Scalars['Int']>;
episode_greater?: Maybe<Scalars['Int']>;
episode_lesser?: Maybe<Scalars['Int']>;
episode_not?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<MediaTrendSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageNotificationsArgs = {
type?: Maybe<NotificationType>;
resetNotificationCount?: Maybe<Scalars['Boolean']>;
type_in?: Maybe<Array<Maybe<NotificationType>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageFollowersArgs = {
userId: Scalars['Int'];
sort?: Maybe<Array<Maybe<UserSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageFollowingArgs = {
userId: Scalars['Int'];
sort?: Maybe<Array<Maybe<UserSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageActivitiesArgs = {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
messengerId?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
type?: Maybe<ActivityType>;
isFollowing?: Maybe<Scalars['Boolean']>;
hasReplies?: Maybe<Scalars['Boolean']>;
hasRepliesOrTypeText?: Maybe<Scalars['Boolean']>;
createdAt?: Maybe<Scalars['Int']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
userId_not?: Maybe<Scalars['Int']>;
userId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
userId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
messengerId_not?: Maybe<Scalars['Int']>;
messengerId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
messengerId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
type_not?: Maybe<ActivityType>;
type_in?: Maybe<Array<Maybe<ActivityType>>>;
type_not_in?: Maybe<Array<Maybe<ActivityType>>>;
createdAt_greater?: Maybe<Scalars['Int']>;
createdAt_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<ActivitySort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageActivityRepliesArgs = {
id?: Maybe<Scalars['Int']>;
activityId?: Maybe<Scalars['Int']>;
};
/** Page of data (Used for internal use only) */
export type InternalPageThreadsArgs = {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
replyUserId?: Maybe<Scalars['Int']>;
subscribed?: Maybe<Scalars['Boolean']>;
categoryId?: Maybe<Scalars['Int']>;
mediaCategoryId?: Maybe<Scalars['Int']>;
search?: Maybe<Scalars['String']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
sort?: Maybe<Array<Maybe<ThreadSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageThreadCommentsArgs = {
id?: Maybe<Scalars['Int']>;
threadId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<ThreadCommentSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageReviewsArgs = {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
mediaType?: Maybe<MediaType>;
sort?: Maybe<Array<Maybe<ReviewSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageRecommendationsArgs = {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
mediaRecommendationId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
rating?: Maybe<Scalars['Int']>;
onList?: Maybe<Scalars['Boolean']>;
rating_greater?: Maybe<Scalars['Int']>;
rating_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<RecommendationSort>>>;
};
/** Page of data (Used for internal use only) */
export type InternalPageLikesArgs = {
likeableId?: Maybe<Scalars['Int']>;
type?: Maybe<LikeableType>;
};
/** Types that can be liked */
export enum LikeableType {
Thread = 'THREAD',
ThreadComment = 'THREAD_COMMENT',
Activity = 'ACTIVITY',
ActivityReply = 'ACTIVITY_REPLY',
}
/** Likeable union type */
export type LikeableUnion =
| ListActivity
| TextActivity
| MessageActivity
| ActivityReply
| Thread
| ThreadComment;
/** User list activity (anime & manga updates) */
export type ListActivity = {
__typename?: 'ListActivity';
/** The id of the activity */
id: Scalars['Int'];
/** The user id of the activity's creator */
userId?: Maybe<Scalars['Int']>;
/** The type of activity */
type?: Maybe<ActivityType>;
/** The number of activity replies */
replyCount: Scalars['Int'];
/** The list item's textual status */
status?: Maybe<Scalars['String']>;
/** The list progress made */
progress?: Maybe<Scalars['String']>;
/** If the activity is locked and can receive replies */
isLocked?: Maybe<Scalars['Boolean']>;
/** If the currently authenticated user is subscribed to the activity */
isSubscribed?: Maybe<Scalars['Boolean']>;
/** The amount of likes the activity has */
likeCount: Scalars['Int'];
/** If the currently authenticated user liked the activity */
isLiked?: Maybe<Scalars['Boolean']>;
/** The url for the activity page on the AniList website */
siteUrl?: Maybe<Scalars['String']>;
/** The time the activity was created at */
createdAt: Scalars['Int'];
/** The owner of the activity */
user?: Maybe<User>;
/** The associated media to the activity update */
media?: Maybe<Media>;
/** The written replies to the activity */
replies?: Maybe<Array<Maybe<ActivityReply>>>;
/** The users who liked the activity */
likes?: Maybe<Array<Maybe<User>>>;
};
/** User's list score statistics */
export type ListScoreStats = {
__typename?: 'ListScoreStats';
meanScore?: Maybe<Scalars['Int']>;
standardDeviation?: Maybe<Scalars['Int']>;
};
/** Anime or Manga */
export type Media = {
__typename?: 'Media';
/** The id of the media */
id: Scalars['Int'];
/** The mal id of the media */
idMal?: Maybe<Scalars['Int']>;
/** The official titles of the media in various languages */
title?: Maybe<MediaTitle>;
/** The type of the media; anime or manga */
type?: Maybe<MediaType>;
/** The format the media was released in */
format?: Maybe<MediaFormat>;
/** The current releasing status of the media */
status?: Maybe<MediaStatus>;
/** Short description of the media's story and characters */
description?: Maybe<Scalars['String']>;
/** The first official release date of the media */
startDate?: Maybe<FuzzyDate>;
/** The last official release date of the media */
endDate?: Maybe<FuzzyDate>;
/** The season the media was initially released in */
season?: Maybe<MediaSeason>;
/** The season year the media was initially released in */
seasonYear?: Maybe<Scalars['Int']>;
/**
* The year & season the media was initially released in
* @deprecated
*/
seasonInt?: Maybe<Scalars['Int']>;
/** The amount of episodes the anime has when complete */
episodes?: Maybe<Scalars['Int']>;
/** The general length of each anime episode in minutes */
duration?: Maybe<Scalars['Int']>;
/** The amount of chapters the manga has when complete */
chapters?: Maybe<Scalars['Int']>;
/** The amount of volumes the manga has when complete */
volumes?: Maybe<Scalars['Int']>;
/** Where the media was created. (ISO 3166-1 alpha-2) */
countryOfOrigin?: Maybe<Scalars['CountryCode']>;
/** If the media is officially licensed or a self-published doujin release */
isLicensed?: Maybe<Scalars['Boolean']>;
/** Source type the media was adapted from. */
source?: Maybe<MediaSource>;
/** Official Twitter hashtags for the media */
hashtag?: Maybe<Scalars['String']>;
/** Media trailer or advertisement */
trailer?: Maybe<MediaTrailer>;
/** When the media's data was last updated */
updatedAt?: Maybe<Scalars['Int']>;
/** The cover images of the media */
coverImage?: Maybe<MediaCoverImage>;
/** The banner image of the media */
bannerImage?: Maybe<Scalars['String']>;
/** The genres of the media */
genres?: Maybe<Array<Maybe<Scalars['String']>>>;
/** Alternative titles of the media */
synonyms?: Maybe<Array<Maybe<Scalars['String']>>>;
/** A weighted average score of all the user's scores of the media */
averageScore?: Maybe<Scalars['Int']>;
/** Mean score of all the user's scores of the media */
meanScore?: Maybe<Scalars['Int']>;
/** The number of users with the media on their list */
popularity?: Maybe<Scalars['Int']>;
/** Locked media may not be added to lists our favorited. This may be due to the entry pending for deletion or other reasons. */
isLocked?: Maybe<Scalars['Boolean']>;
/** The amount of related activity in the past hour */
trending?: Maybe<Scalars['Int']>;
/** The amount of user's who have favourited the media */
favourites?: Maybe<Scalars['Int']>;
/** List of tags that describes elements and themes of the media */
tags?: Maybe<Array<Maybe<MediaTag>>>;
/** Other media in the same or connecting franchise */
relations?: Maybe<MediaConnection>;
/** The characters in the media */
characters?: Maybe<CharacterConnection>;
/** The staff who produced the media */
staff?: Maybe<StaffConnection>;
/** The companies who produced the media */
studios?: Maybe<StudioConnection>;
/** If the media is marked as favourite by the current authenticated user */
isFavourite: Scalars['Boolean'];
/** If the media is intended only for 18+ adult audiences */
isAdult?: Maybe<Scalars['Boolean']>;
/** The media's next episode airing schedule */
nextAiringEpisode?: Maybe<AiringSchedule>;
/** The media's entire airing schedule */
airingSchedule?: Maybe<AiringScheduleConnection>;
/** The media's daily trend stats */
trends?: Maybe<MediaTrendConnection>;
/** External links to another site related to the media */
externalLinks?: Maybe<Array<Maybe<MediaExternalLink>>>;
/** Data and links to legal streaming episodes on external sites */
streamingEpisodes?: Maybe<Array<Maybe<MediaStreamingEpisode>>>;
/** The ranking of the media in a particular time span and format compared to other media */
rankings?: Maybe<Array<Maybe<MediaRank>>>;
/** The authenticated user's media list entry for the media */
mediaListEntry?: Maybe<MediaList>;
/** User reviews of the media */
reviews?: Maybe<ReviewConnection>;
/** User recommendations for similar media */
recommendations?: Maybe<RecommendationConnection>;
stats?: Maybe<MediaStats>;
/** The url for the media page on the AniList website */
siteUrl?: Maybe<Scalars['String']>;
/** If the media should have forum thread automatically created for it on airing episode release */
autoCreateForumThread?: Maybe<Scalars['Boolean']>;
/** If the media is blocked from being recommended to/from */
isRecommendationBlocked?: Maybe<Scalars['Boolean']>;
/** Notes for site moderators */
modNotes?: Maybe<Scalars['String']>;
};
/** Anime or Manga */
export type MediaStatusArgs = {
version?: Maybe<Scalars['Int']>;
};
/** Anime or Manga */
export type MediaDescriptionArgs = {
asHtml?: Maybe<Scalars['Boolean']>;
};
/** Anime or Manga */
export type MediaSourceArgs = {
version?: Maybe<Scalars['Int']>;
};
/** Anime or Manga */
export type MediaCharactersArgs = {
sort?: Maybe<Array<Maybe<CharacterSort>>>;
role?: Maybe<CharacterRole>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** Anime or Manga */
export type MediaStaffArgs = {
sort?: Maybe<Array<Maybe<StaffSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** Anime or Manga */
export type MediaStudiosArgs = {
sort?: Maybe<Array<Maybe<StudioSort>>>;
isMain?: Maybe<Scalars['Boolean']>;
};
/** Anime or Manga */
export type MediaAiringScheduleArgs = {
notYetAired?: Maybe<Scalars['Boolean']>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** Anime or Manga */
export type MediaTrendsArgs = {
sort?: Maybe<Array<Maybe<MediaTrendSort>>>;
releasing?: Maybe<Scalars['Boolean']>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** Anime or Manga */
export type MediaReviewsArgs = {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<ReviewSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** Anime or Manga */
export type MediaRecommendationsArgs = {
sort?: Maybe<Array<Maybe<RecommendationSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** Internal - Media characters separated */
export type MediaCharacter = {
__typename?: 'MediaCharacter';
/** The id of the connection */
id?: Maybe<Scalars['Int']>;
/** The characters role in the media */
role?: Maybe<CharacterRole>;
roleNotes?: Maybe<Scalars['String']>;
dubGroup?: Maybe<Scalars['String']>;
/** Media specific character name */
characterName?: Maybe<Scalars['String']>;
/** The characters in the media voiced by the parent actor */
character?: Maybe<Character>;
/** The voice actor of the character */
voiceActor?: Maybe<Staff>;
};
export type MediaConnection = {
__typename?: 'MediaConnection';
edges?: Maybe<Array<Maybe<MediaEdge>>>;
nodes?: Maybe<Array<Maybe<Media>>>;
/** The pagination information */
pageInfo?: Maybe<PageInfo>;
};
export type MediaCoverImage = {
__typename?: 'MediaCoverImage';
/** The cover image url of the media at its largest size. If this size isn't available, large will be provided instead. */
extraLarge?: Maybe<Scalars['String']>;
/** The cover image url of the media at a large size */
large?: Maybe<Scalars['String']>;
/** The cover image url of the media at medium size */
medium?: Maybe<Scalars['String']>;
/** Average #hex color of cover image */
color?: Maybe<Scalars['String']>;
};
/** Media connection edge */
export type MediaEdge = {
__typename?: 'MediaEdge';
node?: Maybe<Media>;
/** The id of the connection */
id?: Maybe<Scalars['Int']>;
/** The type of relation to the parent model */
relationType?: Maybe<MediaRelation>;
/** If the studio is the main animation studio of the media (For Studio->MediaConnection field only) */
isMainStudio: Scalars['Boolean'];
/** The characters in the media voiced by the parent actor */
characters?: Maybe<Array<Maybe<Character>>>;
/** The characters role in the media */
characterRole?: Maybe<CharacterRole>;
/** Media specific character name */
characterName?: Maybe<Scalars['String']>;
/** Notes regarding the VA's role for the character */
roleNotes?: Maybe<Scalars['String']>;
/** Used for grouping roles where multiple dubs exist for the same language. Either dubbing company name or language variant. */
dubGroup?: Maybe<Scalars['String']>;
/** The role of the staff member in the production of the media */
staffRole?: Maybe<Scalars['String']>;
/** The voice actors of the character */
voiceActors?: Maybe<Array<Maybe<Staff>>>;
/** The voice actors of the character with role date */
voiceActorRoles?: Maybe<Array<Maybe<StaffRoleType>>>;
/** The order the media should be displayed from the users favourites */
favouriteOrder?: Maybe<Scalars['Int']>;
};
/** Media connection edge */
export type MediaEdgeRelationTypeArgs = {
version?: Maybe<Scalars['Int']>;
};
/** Media connection edge */
export type MediaEdgeVoiceActorsArgs = {
language?: Maybe<StaffLanguage>;
sort?: Maybe<Array<Maybe<StaffSort>>>;
};
/** Media connection edge */
export type MediaEdgeVoiceActorRolesArgs = {
language?: Maybe<StaffLanguage>;
sort?: Maybe<Array<Maybe<StaffSort>>>;
};
/** An external link to another site related to the media */
export type MediaExternalLink = {
__typename?: 'MediaExternalLink';
/** The id of the external link */
id: Scalars['Int'];
/** The url of the external link */
url: Scalars['String'];
/** The site location of the external link */
site: Scalars['String'];
};
/** An external link to another site related to the media */
export type MediaExternalLinkInput = {
/** The id of the external link */
id: Scalars['Int'];
/** The url of the external link */
url: Scalars['String'];
/** The site location of the external link */
site: Scalars['String'];
};
/** The format the media was released in */
export enum MediaFormat {
/** Anime broadcast on television */
Tv = 'TV',
/** Anime which are under 15 minutes in length and broadcast on television */
TvShort = 'TV_SHORT',
/** Anime movies with a theatrical release */
Movie = 'MOVIE',
/** Special episodes that have been included in DVD/Blu-ray releases, picture dramas, pilots, etc */
Special = 'SPECIAL',
/** (Original Video Animation) Anime that have been released directly on DVD/Blu-ray without originally going through a theatrical release or television broadcast */
Ova = 'OVA',
/** (Original Net Animation) Anime that have been originally released online or are only available through streaming services. */
Ona = 'ONA',
/** Short anime released as a music video */
Music = 'MUSIC',
/** Professionally published manga with more than one chapter */
Manga = 'MANGA',
/** Written books released as a series of light novels */
Novel = 'NOVEL',
/** Manga with just one chapter */
OneShot = 'ONE_SHOT',
}
/** List of anime or manga */
export type MediaList = {
__typename?: 'MediaList';
/** The id of the list entry */
id: Scalars['Int'];
/** The id of the user owner of the list entry */
userId: Scalars['Int'];
/** The id of the media */
mediaId: Scalars['Int'];
/** The watching/reading status */
status?: Maybe<MediaListStatus>;
/** The score of the entry */
score?: Maybe<Scalars['Float']>;
/** The amount of episodes/chapters consumed by the user */
progress?: Maybe<Scalars['Int']>;
/** The amount of volumes read by the user */
progressVolumes?: Maybe<Scalars['Int']>;
/** The amount of times the user has rewatched/read the media */
repeat?: Maybe<Scalars['Int']>;
/** Priority of planning */
priority?: Maybe<Scalars['Int']>;
/** If the entry should only be visible to authenticated user */
private?: Maybe<Scalars['Boolean']>;
/** Text notes */
notes?: Maybe<Scalars['String']>;
/** If the entry shown be hidden from non-custom lists */
hiddenFromStatusLists?: Maybe<Scalars['Boolean']>;
/** Map of booleans for which custom lists the entry are in */
customLists?: Maybe<Scalars['Json']>;
/** Map of advanced scores with name keys */
advancedScores?: Maybe<Scalars['Json']>;
/** When the entry was started by the user */
startedAt?: Maybe<FuzzyDate>;
/** When the entry was completed by the user */
completedAt?: Maybe<FuzzyDate>;
/** When the entry data was last updated */
updatedAt?: Maybe<Scalars['Int']>;
/** When the entry data was created */
createdAt?: Maybe<Scalars['Int']>;
media?: Maybe<Media>;
user?: Maybe<User>;
};
/** List of anime or manga */
export type MediaListScoreArgs = {
format?: Maybe<ScoreFormat>;
};
/** List of anime or manga */
export type MediaListCustomListsArgs = {
asArray?: Maybe<Scalars['Boolean']>;
};
/** List of anime or manga */
export type MediaListCollection = {
__typename?: 'MediaListCollection';
/** Grouped media list entries */
lists?: Maybe<Array<Maybe<MediaListGroup>>>;
/** The owner of the list */
user?: Maybe<User>;
/** If there is another chunk */
hasNextChunk?: Maybe<Scalars['Boolean']>;
/**
* A map of media list entry arrays grouped by status
* @deprecated Not GraphQL spec compliant, use lists field instead.
*/
statusLists?: Maybe<Array<Maybe<Array<Maybe<MediaList>>>>>;
/**
* A map of media list entry arrays grouped by custom lists
* @deprecated Not GraphQL spec compliant, use lists field instead.
*/
customLists?: Maybe<Array<Maybe<Array<Maybe<MediaList>>>>>;
};
/** List of anime or manga */
export type MediaListCollectionStatusListsArgs = {
asArray?: Maybe<Scalars['Boolean']>;
};
/** List of anime or manga */
export type MediaListCollectionCustomListsArgs = {
asArray?: Maybe<Scalars['Boolean']>;
};
/** List group of anime or manga entries */
export type MediaListGroup = {
__typename?: 'MediaListGroup';
/** Media list entries */
entries?: Maybe<Array<Maybe<MediaList>>>;
name?: Maybe<Scalars['String']>;
isCustomList?: Maybe<Scalars['Boolean']>;
isSplitCompletedList?: Maybe<Scalars['Boolean']>;
status?: Maybe<MediaListStatus>;
};
/** A user's list options */
export type MediaListOptions = {
__typename?: 'MediaListOptions';
/** The score format the user is using for media lists */
scoreFormat?: Maybe<ScoreFormat>;
/** The default order list rows should be displayed in */
rowOrder?: Maybe<Scalars['String']>;
/** @deprecated No longer used */
useLegacyLists?: Maybe<Scalars['Boolean']>;
/** The user's anime list options */
animeList?: Maybe<MediaListTypeOptions>;
/** The user's manga list options */
mangaList?: Maybe<MediaListTypeOptions>;
/**
* The list theme options for both lists
* @deprecated No longer used
*/
sharedTheme?: Maybe<Scalars['Json']>;
/**
* If the shared theme should be used instead of the individual list themes
* @deprecated No longer used
*/
sharedThemeEnabled?: Maybe<Scalars['Boolean']>;
};
/** A user's list options for anime or manga lists */
export type MediaListOptionsInput = {
/** The order each list should be displayed in */
sectionOrder?: Maybe<Array<Maybe<Scalars['String']>>>;
/** If the completed sections of the list should be separated by format */
splitCompletedSectionByFormat?: Maybe<Scalars['Boolean']>;
/** The names of the user's custom lists */
customLists?: Maybe<Array<Maybe<Scalars['String']>>>;
/** The names of the user's advanced scoring sections */
advancedScoring?: Maybe<Array<Maybe<Scalars['String']>>>;
/** If advanced scoring is enabled */
advancedScoringEnabled?: Maybe<Scalars['Boolean']>;
/** list theme */
theme?: Maybe<Scalars['String']>;
};
/** Media list sort enums */
export enum MediaListSort {
MediaId = 'MEDIA_ID',
MediaIdDesc = 'MEDIA_ID_DESC',
Score = 'SCORE',
ScoreDesc = 'SCORE_DESC',
Status = 'STATUS',
StatusDesc = 'STATUS_DESC',
Progress = 'PROGRESS',
ProgressDesc = 'PROGRESS_DESC',
ProgressVolumes = 'PROGRESS_VOLUMES',
ProgressVolumesDesc = 'PROGRESS_VOLUMES_DESC',
Repeat = 'REPEAT',
RepeatDesc = 'REPEAT_DESC',
Priority = 'PRIORITY',
PriorityDesc = 'PRIORITY_DESC',
StartedOn = 'STARTED_ON',
StartedOnDesc = 'STARTED_ON_DESC',
FinishedOn = 'FINISHED_ON',
FinishedOnDesc = 'FINISHED_ON_DESC',
AddedTime = 'ADDED_TIME',
AddedTimeDesc = 'ADDED_TIME_DESC',
UpdatedTime = 'UPDATED_TIME',
UpdatedTimeDesc = 'UPDATED_TIME_DESC',
MediaTitleRomaji = 'MEDIA_TITLE_ROMAJI',
MediaTitleRomajiDesc = 'MEDIA_TITLE_ROMAJI_DESC',
MediaTitleEnglish = 'MEDIA_TITLE_ENGLISH',
MediaTitleEnglishDesc = 'MEDIA_TITLE_ENGLISH_DESC',
MediaTitleNative = 'MEDIA_TITLE_NATIVE',
MediaTitleNativeDesc = 'MEDIA_TITLE_NATIVE_DESC',
MediaPopularity = 'MEDIA_POPULARITY',
MediaPopularityDesc = 'MEDIA_POPULARITY_DESC',
}
/** Media list watching/reading status enum. */
export enum MediaListStatus {
/** Currently watching/reading */
Current = 'CURRENT',
/** Planning to watch/read */
Planning = 'PLANNING',
/** Finished watching/reading */
Completed = 'COMPLETED',
/** Stopped watching/reading before completing */
Dropped = 'DROPPED',
/** Paused watching/reading */
Paused = 'PAUSED',
/** Re-watching/reading */
Repeating = 'REPEATING',
}
/** A user's list options for anime or manga lists */
export type MediaListTypeOptions = {
__typename?: 'MediaListTypeOptions';
/** The order each list should be displayed in */
sectionOrder?: Maybe<Array<Maybe<Scalars['String']>>>;
/** If the completed sections of the list should be separated by format */
splitCompletedSectionByFormat?: Maybe<Scalars['Boolean']>;
/**
* The list theme options
* @deprecated This field has not yet been fully implemented and may change without warning
*/
theme?: Maybe<Scalars['Json']>;
/** The names of the user's custom lists */
customLists?: Maybe<Array<Maybe<Scalars['String']>>>;
/** The names of the user's advanced scoring sections */
advancedScoring?: Maybe<Array<Maybe<Scalars['String']>>>;
/** If advanced scoring is enabled */
advancedScoringEnabled?: Maybe<Scalars['Boolean']>;
};
/** The ranking of a media in a particular time span and format compared to other media */
export type MediaRank = {
__typename?: 'MediaRank';
/** The id of the rank */
id: Scalars['Int'];
/** The numerical rank of the media */
rank: Scalars['Int'];
/** The type of ranking */
type: MediaRankType;
/** The format the media is ranked within */
format: MediaFormat;
/** The year the media is ranked within */
year?: Maybe<Scalars['Int']>;
/** The season the media is ranked within */
season?: Maybe<MediaSeason>;
/** If the ranking is based on all time instead of a season/year */
allTime?: Maybe<Scalars['Boolean']>;
/** String that gives context to the ranking type and time span */
context: Scalars['String'];
};
/** The type of ranking */
export enum MediaRankType {
/** Ranking is based on the media's ratings/score */
Rated = 'RATED',
/** Ranking is based on the media's popularity */
Popular = 'POPULAR',
}
/** Type of relation media has to its parent. */
export enum MediaRelation {
/** An adaption of this media into a different format */
Adaptation = 'ADAPTATION',
/** Released before the relation */
Prequel = 'PREQUEL',
/** Released after the relation */
Sequel = 'SEQUEL',
/** The media a side story is from */
Parent = 'PARENT',
/** A side story of the parent media */
SideStory = 'SIDE_STORY',
/** Shares at least 1 character */
Character = 'CHARACTER',
/** A shortened and summarized version */
Summary = 'SUMMARY',
/** An alternative version of the same media */
Alternative = 'ALTERNATIVE',
/** An alternative version of the media with a different primary focus */
SpinOff = 'SPIN_OFF',
/** Other */
Other = 'OTHER',
/** Version 2 only. The source material the media was adapted from */
Source = 'SOURCE',
/** Version 2 only. */
Compilation = 'COMPILATION',
/** Version 2 only. */
Contains = 'CONTAINS',
}
export enum MediaSeason {
/** Months December to February */
Winter = 'WINTER',
/** Months March to May */
Spring = 'SPRING',
/** Months June to August */
Summer = 'SUMMER',
/** Months September to November */
Fall = 'FALL',
}
/** Media sort enums */
export enum MediaSort {
Id = 'ID',
IdDesc = 'ID_DESC',
TitleRomaji = 'TITLE_ROMAJI',
TitleRomajiDesc = 'TITLE_ROMAJI_DESC',
TitleEnglish = 'TITLE_ENGLISH',
TitleEnglishDesc = 'TITLE_ENGLISH_DESC',
TitleNative = 'TITLE_NATIVE',
TitleNativeDesc = 'TITLE_NATIVE_DESC',
Type = 'TYPE',
TypeDesc = 'TYPE_DESC',
Format = 'FORMAT',
FormatDesc = 'FORMAT_DESC',
StartDate = 'START_DATE',
StartDateDesc = 'START_DATE_DESC',
EndDate = 'END_DATE',
EndDateDesc = 'END_DATE_DESC',
Score = 'SCORE',
ScoreDesc = 'SCORE_DESC',
Popularity = 'POPULARITY',
PopularityDesc = 'POPULARITY_DESC',
Trending = 'TRENDING',
TrendingDesc = 'TRENDING_DESC',
Episodes = 'EPISODES',
EpisodesDesc = 'EPISODES_DESC',
Duration = 'DURATION',
DurationDesc = 'DURATION_DESC',
Status = 'STATUS',
StatusDesc = 'STATUS_DESC',
Chapters = 'CHAPTERS',
ChaptersDesc = 'CHAPTERS_DESC',
Volumes = 'VOLUMES',
VolumesDesc = 'VOLUMES_DESC',
UpdatedAt = 'UPDATED_AT',
UpdatedAtDesc = 'UPDATED_AT_DESC',
SearchMatch = 'SEARCH_MATCH',
Favourites = 'FAVOURITES',
FavouritesDesc = 'FAVOURITES_DESC',
}
/** Source type the media was adapted from */
export enum MediaSource {
/** An original production not based of another work */
Original = 'ORIGINAL',
/** Asian comic book */
Manga = 'MANGA',
/** Written work published in volumes */
LightNovel = 'LIGHT_NOVEL',
/** Video game driven primary by text and narrative */
VisualNovel = 'VISUAL_NOVEL',
/** Video game */
VideoGame = 'VIDEO_GAME',
/** Other */
Other = 'OTHER',
/** Version 2 only. Written works not published in volumes */
Novel = 'NOVEL',
/** Version 2 only. Self-published works */
Doujinshi = 'DOUJINSHI',
/** Version 2 only. Japanese Anime */
Anime = 'ANIME',
}
/** A media's statistics */
export type MediaStats = {
__typename?: 'MediaStats';
scoreDistribution?: Maybe<Array<Maybe<ScoreDistribution>>>;
statusDistribution?: Maybe<Array<Maybe<StatusDistribution>>>;
/** @deprecated Replaced by MediaTrends */
airingProgression?: Maybe<Array<Maybe<AiringProgression>>>;
};
/** The current releasing status of the media */
export enum MediaStatus {
/** Has completed and is no longer being released */
Finished = 'FINISHED',
/** Currently releasing */
Releasing = 'RELEASING',
/** To be released at a later date */
NotYetReleased = 'NOT_YET_RELEASED',
/** Ended before the work could be finished */
Cancelled = 'CANCELLED',
/** Version 2 only. Is currently paused from releasing and will resume at a later date */
Hiatus = 'HIATUS',
}
/** Data and links to legal streaming episodes on external sites */
export type MediaStreamingEpisode = {
__typename?: 'MediaStreamingEpisode';
/** Title of the episode */
title?: Maybe<Scalars['String']>;
/** Url of episode image thumbnail */
thumbnail?: Maybe<Scalars['String']>;
/** The url of the episode */
url?: Maybe<Scalars['String']>;
/** The site location of the streaming episodes */
site?: Maybe<Scalars['String']>;
};
/** Media submission */
export type MediaSubmission = {
__typename?: 'MediaSubmission';
/** The id of the submission */
id: Scalars['Int'];
/** User submitter of the submission */
submitter?: Maybe<User>;
/** Status of the submission */
status?: Maybe<SubmissionStatus>;
submitterStats?: Maybe<Scalars['Json']>;
notes?: Maybe<Scalars['String']>;
source?: Maybe<Scalars['String']>;
changes?: Maybe<Array<Maybe<Scalars['String']>>>;
media?: Maybe<Media>;
submission?: Maybe<Media>;
characters?: Maybe<Array<Maybe<MediaSubmissionComparison>>>;
staff?: Maybe<Array<Maybe<MediaSubmissionComparison>>>;
studios?: Maybe<Array<Maybe<MediaSubmissionComparison>>>;
relations?: Maybe<Array<Maybe<MediaEdge>>>;
externalLinks?: Maybe<Array<Maybe<MediaExternalLink>>>;
createdAt?: Maybe<Scalars['Int']>;
};
/** Media submission with comparison to current data */
export type MediaSubmissionComparison = {
__typename?: 'MediaSubmissionComparison';
submission?: Maybe<MediaSubmissionEdge>;
character?: Maybe<MediaCharacter>;
staff?: Maybe<StaffEdge>;
studio?: Maybe<StudioEdge>;
};
export type MediaSubmissionEdge = {
__typename?: 'MediaSubmissionEdge';
/** The id of the direct submission */
id?: Maybe<Scalars['Int']>;
characterRole?: Maybe<CharacterRole>;
staffRole?: Maybe<Scalars['String']>;
roleNotes?: Maybe<Scalars['String']>;
dubGroup?: Maybe<Scalars['String']>;
characterName?: Maybe<Scalars['String']>;
isMain?: Maybe<Scalars['Boolean']>;
character?: Maybe<Character>;
characterSubmission?: Maybe<Character>;
voiceActor?: Maybe<Staff>;
voiceActorSubmission?: Maybe<Staff>;
staff?: Maybe<Staff>;
staffSubmission?: Maybe<Staff>;
studio?: Maybe<Studio>;
media?: Maybe<Media>;
};
/** A tag that describes a theme or element of the media */
export type MediaTag = {
__typename?: 'MediaTag';
/** The id of the tag */
id: Scalars['Int'];
/** The name of the tag */
name: Scalars['String'];
/** A general description of the tag */
description?: Maybe<Scalars['String']>;
/** The categories of tags this tag belongs to */
category?: Maybe<Scalars['String']>;
/** The relevance ranking of the tag out of the 100 for this media */
rank?: Maybe<Scalars['Int']>;
/** If the tag could be a spoiler for any media */
isGeneralSpoiler?: Maybe<Scalars['Boolean']>;
/** If the tag is a spoiler for this media */
isMediaSpoiler?: Maybe<Scalars['Boolean']>;
/** If the tag is only for adult 18+ media */
isAdult?: Maybe<Scalars['Boolean']>;
};
/** The official titles of the media in various languages */
export type MediaTitle = {
__typename?: 'MediaTitle';
/** The romanization of the native language title */
romaji?: Maybe<Scalars['String']>;
/** The official english title */
english?: Maybe<Scalars['String']>;
/** Official title in it's native language */
native?: Maybe<Scalars['String']>;
/** The currently authenticated users preferred title language. Default romaji for non-authenticated */
userPreferred?: Maybe<Scalars['String']>;
};
/** The official titles of the media in various languages */
export type MediaTitleRomajiArgs = {
stylised?: Maybe<Scalars['Boolean']>;
};
/** The official titles of the media in various languages */
export type MediaTitleEnglishArgs = {
stylised?: Maybe<Scalars['Boolean']>;
};
/** The official titles of the media in various languages */
export type MediaTitleNativeArgs = {
stylised?: Maybe<Scalars['Boolean']>;
};
/** The official titles of the media in various languages */
export type MediaTitleInput = {
/** The romanization of the native language title */
romaji?: Maybe<Scalars['String']>;
/** The official english title */
english?: Maybe<Scalars['String']>;
/** Official title in it's native language */
native?: Maybe<Scalars['String']>;
};
/** Media trailer or advertisement */
export type MediaTrailer = {
__typename?: 'MediaTrailer';
/** The trailer video id */
id?: Maybe<Scalars['String']>;
/** The site the video is hosted by (Currently either youtube or dailymotion) */
site?: Maybe<Scalars['String']>;
/** The url for the thumbnail image of the video */
thumbnail?: Maybe<Scalars['String']>;
};
/** Daily media statistics */
export type MediaTrend = {
__typename?: 'MediaTrend';
/** The id of the tag */
mediaId: Scalars['Int'];
/** The day the data was recorded (timestamp) */
date: Scalars['Int'];
/** The amount of media activity on the day */
trending: Scalars['Int'];
/** A weighted average score of all the user's scores of the media */
averageScore?: Maybe<Scalars['Int']>;
/** The number of users with the media on their list */
popularity?: Maybe<Scalars['Int']>;
/** The number of users with watching/reading the media */
inProgress?: Maybe<Scalars['Int']>;
/** If the media was being released at this time */
releasing: Scalars['Boolean'];
/** The episode number of the anime released on this day */
episode?: Maybe<Scalars['Int']>;
/** The related media */
media?: Maybe<Media>;
};
export type MediaTrendConnection = {
__typename?: 'MediaTrendConnection';
edges?: Maybe<Array<Maybe<MediaTrendEdge>>>;
nodes?: Maybe<Array<Maybe<MediaTrend>>>;
/** The pagination information */
pageInfo?: Maybe<PageInfo>;
};
/** Media trend connection edge */
export type MediaTrendEdge = {
__typename?: 'MediaTrendEdge';
node?: Maybe<MediaTrend>;
};
/** Media trend sort enums */
export enum MediaTrendSort {
Id = 'ID',
IdDesc = 'ID_DESC',
MediaId = 'MEDIA_ID',
MediaIdDesc = 'MEDIA_ID_DESC',
Date = 'DATE',
DateDesc = 'DATE_DESC',
Score = 'SCORE',
ScoreDesc = 'SCORE_DESC',
Popularity = 'POPULARITY',
PopularityDesc = 'POPULARITY_DESC',
Trending = 'TRENDING',
TrendingDesc = 'TRENDING_DESC',
Episode = 'EPISODE',
EpisodeDesc = 'EPISODE_DESC',
}
/** Media type enum, anime or manga. */
export enum MediaType {
/** Japanese Anime */
Anime = 'ANIME',
/** Asian comic */
Manga = 'MANGA',
}
/** User message activity */
export type MessageActivity = {
__typename?: 'MessageActivity';
/** The id of the activity */
id: Scalars['Int'];
/** The user id of the activity's recipient */
recipientId?: Maybe<Scalars['Int']>;
/** The user id of the activity's sender */
messengerId?: Maybe<Scalars['Int']>;
/** The type of the activity */
type?: Maybe<ActivityType>;
/** The number of activity replies */
replyCount: Scalars['Int'];
/** The message text (Markdown) */
message?: Maybe<Scalars['String']>;
/** If the activity is locked and can receive replies */
isLocked?: Maybe<Scalars['Boolean']>;
/** If the currently authenticated user is subscribed to the activity */
isSubscribed?: Maybe<Scalars['Boolean']>;
/** The amount of likes the activity has */
likeCount: Scalars['Int'];
/** If the currently authenticated user liked the activity */
isLiked?: Maybe<Scalars['Boolean']>;
/** If the message is private and only viewable to the sender and recipients */
isPrivate?: Maybe<Scalars['Boolean']>;
/** The url for the activity page on the AniList website */
siteUrl?: Maybe<Scalars['String']>;
/** The time the activity was created at */
createdAt: Scalars['Int'];
/** The user who the activity message was sent to */
recipient?: Maybe<User>;
/** The user who sent the activity message */
messenger?: Maybe<User>;
/** The written replies to the activity */
replies?: Maybe<Array<Maybe<ActivityReply>>>;
/** The users who liked the activity */
likes?: Maybe<Array<Maybe<User>>>;
};
/** User message activity */
export type MessageActivityMessageArgs = {
asHtml?: Maybe<Scalars['Boolean']>;
};
export type ModAction = {
__typename?: 'ModAction';
/** The id of the action */
id: Scalars['Int'];
user?: Maybe<User>;
mod?: Maybe<User>;
type?: Maybe<ModActionType>;
objectId?: Maybe<Scalars['Int']>;
objectType?: Maybe<Scalars['String']>;
data?: Maybe<Scalars['String']>;
createdAt: Scalars['Int'];
};
export enum ModActionType {
Note = 'NOTE',
Ban = 'BAN',
Delete = 'DELETE',
Edit = 'EDIT',
Expire = 'EXPIRE',
Report = 'REPORT',
Reset = 'RESET',
Anon = 'ANON',
}
/** Mod role enums */
export enum ModRole {
/** An AniList administrator */
Admin = 'ADMIN',
/** A head developer of AniList */
LeadDeveloper = 'LEAD_DEVELOPER',
/** An AniList developer */
Developer = 'DEVELOPER',
/** A lead community moderator */
LeadCommunity = 'LEAD_COMMUNITY',
/** A community moderator */
Community = 'COMMUNITY',
/** A discord community moderator */
DiscordCommunity = 'DISCORD_COMMUNITY',
/** A lead anime data moderator */
LeadAnimeData = 'LEAD_ANIME_DATA',
/** An anime data moderator */
AnimeData = 'ANIME_DATA',
/** A lead manga data moderator */
LeadMangaData = 'LEAD_MANGA_DATA',
/** A manga data moderator */
MangaData = 'MANGA_DATA',
/** A lead social media moderator */
LeadSocialMedia = 'LEAD_SOCIAL_MEDIA',
/** A social media moderator */
SocialMedia = 'SOCIAL_MEDIA',
/** A retired moderator */
Retired = 'RETIRED',
}
export type Mutation = {
__typename?: 'Mutation';
UpdateUser?: Maybe<User>;
/** Create or update a media list entry */
SaveMediaListEntry?: Maybe<MediaList>;
/** Update multiple media list entries to the same values */
UpdateMediaListEntries?: Maybe<Array<Maybe<MediaList>>>;
/** Delete a media list entry */
DeleteMediaListEntry?: Maybe<Deleted>;
/** Delete a custom list and remove the list entries from it */
DeleteCustomList?: Maybe<Deleted>;
/** Create or update text activity for the currently authenticated user */
SaveTextActivity?: Maybe<TextActivity>;
/** Create or update message activity for the currently authenticated user */
SaveMessageActivity?: Maybe<MessageActivity>;
/** Update list activity (Mod Only) */
SaveListActivity?: Maybe<ListActivity>;
/** Delete an activity item of the authenticated users */
DeleteActivity?: Maybe<Deleted>;
/** Toggle the subscription of an activity item */
ToggleActivitySubscription?: Maybe<ActivityUnion>;
/** Create or update an activity reply */
SaveActivityReply?: Maybe<ActivityReply>;
/** Delete an activity reply of the authenticated users */
DeleteActivityReply?: Maybe<Deleted>;
/**
* Add or remove a like from a likeable type.
* Returns all the users who liked the same model
*/
ToggleLike?: Maybe<Array<Maybe<User>>>;
/** Add or remove a like from a likeable type. */
ToggleLikeV2?: Maybe<LikeableUnion>;
/** Toggle the un/following of a user */
ToggleFollow?: Maybe<User>;
/** Favourite or unfavourite an anime, manga, character, staff member, or studio */
ToggleFavourite?: Maybe<Favourites>;
/** Update the order favourites are displayed in */
UpdateFavouriteOrder?: Maybe<Favourites>;
/** Create or update a review */
SaveReview?: Maybe<Review>;
/** Delete a review */
DeleteReview?: Maybe<Deleted>;
/** Rate a review */
RateReview?: Maybe<Review>;
/** Recommendation a media */
SaveRecommendation?: Maybe<Recommendation>;
/** Create or update a forum thread */
SaveThread?: Maybe<Thread>;
/** Delete a thread */
DeleteThread?: Maybe<Deleted>;
/** Toggle the subscription of a forum thread */
ToggleThreadSubscription?: Maybe<Thread>;
/** Create or update a thread comment */
SaveThreadComment?: Maybe<ThreadComment>;
/** Delete a thread comment */
DeleteThreadComment?: Maybe<Deleted>;
UpdateAniChartSettings?: Maybe<Scalars['Json']>;
UpdateAniChartHighlights?: Maybe<Scalars['Json']>;
};
export type MutationUpdateUserArgs = {
about?: Maybe<Scalars['String']>;
titleLanguage?: Maybe<UserTitleLanguage>;
displayAdultContent?: Maybe<Scalars['Boolean']>;
airingNotifications?: Maybe<Scalars['Boolean']>;
scoreFormat?: Maybe<ScoreFormat>;
rowOrder?: Maybe<Scalars['String']>;
profileColor?: Maybe<Scalars['String']>;
donatorBadge?: Maybe<Scalars['String']>;
notificationOptions?: Maybe<Array<Maybe<NotificationOptionInput>>>;
timezone?: Maybe<Scalars['String']>;
activityMergeTime?: Maybe<Scalars['Int']>;
animeListOptions?: Maybe<MediaListOptionsInput>;
mangaListOptions?: Maybe<MediaListOptionsInput>;
staffNameLanguage?: Maybe<UserStaffNameLanguage>;
};
export type MutationSaveMediaListEntryArgs = {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
status?: Maybe<MediaListStatus>;
score?: Maybe<Scalars['Float']>;
scoreRaw?: Maybe<Scalars['Int']>;
progress?: Maybe<Scalars['Int']>;
progressVolumes?: Maybe<Scalars['Int']>;
repeat?: Maybe<Scalars['Int']>;
priority?: Maybe<Scalars['Int']>;
private?: Maybe<Scalars['Boolean']>;
notes?: Maybe<Scalars['String']>;
hiddenFromStatusLists?: Maybe<Scalars['Boolean']>;
customLists?: Maybe<Array<Maybe<Scalars['String']>>>;
advancedScores?: Maybe<Array<Maybe<Scalars['Float']>>>;
startedAt?: Maybe<FuzzyDateInput>;
completedAt?: Maybe<FuzzyDateInput>;
};
export type MutationUpdateMediaListEntriesArgs = {
status?: Maybe<MediaListStatus>;
score?: Maybe<Scalars['Float']>;
scoreRaw?: Maybe<Scalars['Int']>;
progress?: Maybe<Scalars['Int']>;
progressVolumes?: Maybe<Scalars['Int']>;
repeat?: Maybe<Scalars['Int']>;
priority?: Maybe<Scalars['Int']>;
private?: Maybe<Scalars['Boolean']>;
notes?: Maybe<Scalars['String']>;
hiddenFromStatusLists?: Maybe<Scalars['Boolean']>;
advancedScores?: Maybe<Array<Maybe<Scalars['Float']>>>;
startedAt?: Maybe<FuzzyDateInput>;
completedAt?: Maybe<FuzzyDateInput>;
ids?: Maybe<Array<Maybe<Scalars['Int']>>>;
};
export type MutationDeleteMediaListEntryArgs = {
id?: Maybe<Scalars['Int']>;
};
export type MutationDeleteCustomListArgs = {
customList?: Maybe<Scalars['String']>;
type?: Maybe<MediaType>;
};
export type MutationSaveTextActivityArgs = {
id?: Maybe<Scalars['Int']>;
text?: Maybe<Scalars['String']>;
locked?: Maybe<Scalars['Boolean']>;
};
export type MutationSaveMessageActivityArgs = {
id?: Maybe<Scalars['Int']>;
message?: Maybe<Scalars['String']>;
recipientId?: Maybe<Scalars['Int']>;
private?: Maybe<Scalars['Boolean']>;
locked?: Maybe<Scalars['Boolean']>;
asMod?: Maybe<Scalars['Boolean']>;
};
export type MutationSaveListActivityArgs = {
id?: Maybe<Scalars['Int']>;
locked?: Maybe<Scalars['Boolean']>;
};
export type MutationDeleteActivityArgs = {
id?: Maybe<Scalars['Int']>;
};
export type MutationToggleActivitySubscriptionArgs = {
activityId?: Maybe<Scalars['Int']>;
subscribe?: Maybe<Scalars['Boolean']>;
};
export type MutationSaveActivityReplyArgs = {
id?: Maybe<Scalars['Int']>;
activityId?: Maybe<Scalars['Int']>;
text?: Maybe<Scalars['String']>;
asMod?: Maybe<Scalars['Boolean']>;
};
export type MutationDeleteActivityReplyArgs = {
id?: Maybe<Scalars['Int']>;
};
export type MutationToggleLikeArgs = {
id?: Maybe<Scalars['Int']>;
type?: Maybe<LikeableType>;
};
export type MutationToggleLikeV2Args = {
id?: Maybe<Scalars['Int']>;
type?: Maybe<LikeableType>;
};
export type MutationToggleFollowArgs = {
userId?: Maybe<Scalars['Int']>;
};
export type MutationToggleFavouriteArgs = {
animeId?: Maybe<Scalars['Int']>;
mangaId?: Maybe<Scalars['Int']>;
characterId?: Maybe<Scalars['Int']>;
staffId?: Maybe<Scalars['Int']>;
studioId?: Maybe<Scalars['Int']>;
};
export type MutationUpdateFavouriteOrderArgs = {
animeIds?: Maybe<Array<Maybe<Scalars['Int']>>>;
mangaIds?: Maybe<Array<Maybe<Scalars['Int']>>>;
characterIds?: Maybe<Array<Maybe<Scalars['Int']>>>;
staffIds?: Maybe<Array<Maybe<Scalars['Int']>>>;
studioIds?: Maybe<Array<Maybe<Scalars['Int']>>>;
animeOrder?: Maybe<Array<Maybe<Scalars['Int']>>>;
mangaOrder?: Maybe<Array<Maybe<Scalars['Int']>>>;
characterOrder?: Maybe<Array<Maybe<Scalars['Int']>>>;
staffOrder?: Maybe<Array<Maybe<Scalars['Int']>>>;
studioOrder?: Maybe<Array<Maybe<Scalars['Int']>>>;
};
export type MutationSaveReviewArgs = {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
body?: Maybe<Scalars['String']>;
summary?: Maybe<Scalars['String']>;
score?: Maybe<Scalars['Int']>;
private?: Maybe<Scalars['Boolean']>;
};
export type MutationDeleteReviewArgs = {
id?: Maybe<Scalars['Int']>;
};
export type MutationRateReviewArgs = {
reviewId?: Maybe<Scalars['Int']>;
rating?: Maybe<ReviewRating>;
};
export type MutationSaveRecommendationArgs = {
mediaId?: Maybe<Scalars['Int']>;
mediaRecommendationId?: Maybe<Scalars['Int']>;
rating?: Maybe<RecommendationRating>;
};
export type MutationSaveThreadArgs = {
id?: Maybe<Scalars['Int']>;
title?: Maybe<Scalars['String']>;
body?: Maybe<Scalars['String']>;
categories?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaCategories?: Maybe<Array<Maybe<Scalars['Int']>>>;
sticky?: Maybe<Scalars['Boolean']>;
locked?: Maybe<Scalars['Boolean']>;
};
export type MutationDeleteThreadArgs = {
id?: Maybe<Scalars['Int']>;
};
export type MutationToggleThreadSubscriptionArgs = {
threadId?: Maybe<Scalars['Int']>;
subscribe?: Maybe<Scalars['Boolean']>;
};
export type MutationSaveThreadCommentArgs = {
id?: Maybe<Scalars['Int']>;
threadId?: Maybe<Scalars['Int']>;
parentCommentId?: Maybe<Scalars['Int']>;
comment?: Maybe<Scalars['String']>;
};
export type MutationDeleteThreadCommentArgs = {
id?: Maybe<Scalars['Int']>;
};
export type MutationUpdateAniChartSettingsArgs = {
titleLanguage?: Maybe<Scalars['String']>;
outgoingLinkProvider?: Maybe<Scalars['String']>;
theme?: Maybe<Scalars['String']>;
sort?: Maybe<Scalars['String']>;
};
export type MutationUpdateAniChartHighlightsArgs = {
highlights?: Maybe<Array<Maybe<AniChartHighlightInput>>>;
};
/** Notification option */
export type NotificationOption = {
__typename?: 'NotificationOption';
/** The type of notification */
type?: Maybe<NotificationType>;
/** Whether this type of notification is enabled */
enabled?: Maybe<Scalars['Boolean']>;
};
/** Notification option input */
export type NotificationOptionInput = {
/** The type of notification */
type?: Maybe<NotificationType>;
/** Whether this type of notification is enabled */
enabled?: Maybe<Scalars['Boolean']>;
};
/** Notification type enum */
export enum NotificationType {
/** A user has sent you message */
ActivityMessage = 'ACTIVITY_MESSAGE',
/** A user has replied to your activity */
ActivityReply = 'ACTIVITY_REPLY',
/** A user has followed you */
Following = 'FOLLOWING',
/** A user has mentioned you in their activity */
ActivityMention = 'ACTIVITY_MENTION',
/** A user has mentioned you in a forum comment */
ThreadCommentMention = 'THREAD_COMMENT_MENTION',
/** A user has commented in one of your subscribed forum threads */
ThreadSubscribed = 'THREAD_SUBSCRIBED',
/** A user has replied to your forum comment */
ThreadCommentReply = 'THREAD_COMMENT_REPLY',
/** An anime you are currently watching has aired */
Airing = 'AIRING',
/** A user has liked your activity */
ActivityLike = 'ACTIVITY_LIKE',
/** A user has liked your activity reply */
ActivityReplyLike = 'ACTIVITY_REPLY_LIKE',
/** A user has liked your forum thread */
ThreadLike = 'THREAD_LIKE',
/** A user has liked your forum comment */
ThreadCommentLike = 'THREAD_COMMENT_LIKE',
/** A user has replied to activity you have also replied to */
ActivityReplySubscribed = 'ACTIVITY_REPLY_SUBSCRIBED',
/** A new anime or manga has been added to the site where its related media is on the user's list */
RelatedMediaAddition = 'RELATED_MEDIA_ADDITION',
}
/** Notification union type */
export type NotificationUnion =
| AiringNotification
| FollowingNotification
| ActivityMessageNotification
| ActivityMentionNotification
| ActivityReplyNotification
| ActivityReplySubscribedNotification
| ActivityLikeNotification
| ActivityReplyLikeNotification
| ThreadCommentMentionNotification
| ThreadCommentReplyNotification
| ThreadCommentSubscribedNotification
| ThreadCommentLikeNotification
| ThreadLikeNotification
| RelatedMediaAdditionNotification;
/** Page of data */
export type Page = {
__typename?: 'Page';
/** The pagination information */
pageInfo?: Maybe<PageInfo>;
users?: Maybe<Array<Maybe<User>>>;
media?: Maybe<Array<Maybe<Media>>>;
characters?: Maybe<Array<Maybe<Character>>>;
staff?: Maybe<Array<Maybe<Staff>>>;
studios?: Maybe<Array<Maybe<Studio>>>;
mediaList?: Maybe<Array<Maybe<MediaList>>>;
airingSchedules?: Maybe<Array<Maybe<AiringSchedule>>>;
mediaTrends?: Maybe<Array<Maybe<MediaTrend>>>;
notifications?: Maybe<Array<Maybe<NotificationUnion>>>;
followers?: Maybe<Array<Maybe<User>>>;
following?: Maybe<Array<Maybe<User>>>;
activities?: Maybe<Array<Maybe<ActivityUnion>>>;
activityReplies?: Maybe<Array<Maybe<ActivityReply>>>;
threads?: Maybe<Array<Maybe<Thread>>>;
threadComments?: Maybe<Array<Maybe<ThreadComment>>>;
reviews?: Maybe<Array<Maybe<Review>>>;
recommendations?: Maybe<Array<Maybe<Recommendation>>>;
likes?: Maybe<Array<Maybe<User>>>;
};
/** Page of data */
export type PageUsersArgs = {
id?: Maybe<Scalars['Int']>;
name?: Maybe<Scalars['String']>;
isModerator?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
sort?: Maybe<Array<Maybe<UserSort>>>;
};
/** Page of data */
export type PageMediaArgs = {
id?: Maybe<Scalars['Int']>;
idMal?: Maybe<Scalars['Int']>;
startDate?: Maybe<Scalars['FuzzyDateInt']>;
endDate?: Maybe<Scalars['FuzzyDateInt']>;
season?: Maybe<MediaSeason>;
seasonYear?: Maybe<Scalars['Int']>;
type?: Maybe<MediaType>;
format?: Maybe<MediaFormat>;
status?: Maybe<MediaStatus>;
episodes?: Maybe<Scalars['Int']>;
duration?: Maybe<Scalars['Int']>;
chapters?: Maybe<Scalars['Int']>;
volumes?: Maybe<Scalars['Int']>;
isAdult?: Maybe<Scalars['Boolean']>;
genre?: Maybe<Scalars['String']>;
tag?: Maybe<Scalars['String']>;
minimumTagRank?: Maybe<Scalars['Int']>;
tagCategory?: Maybe<Scalars['String']>;
onList?: Maybe<Scalars['Boolean']>;
licensedBy?: Maybe<Scalars['String']>;
averageScore?: Maybe<Scalars['Int']>;
popularity?: Maybe<Scalars['Int']>;
source?: Maybe<MediaSource>;
countryOfOrigin?: Maybe<Scalars['CountryCode']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
idMal_not?: Maybe<Scalars['Int']>;
idMal_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
idMal_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
startDate_greater?: Maybe<Scalars['FuzzyDateInt']>;
startDate_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startDate_like?: Maybe<Scalars['String']>;
endDate_greater?: Maybe<Scalars['FuzzyDateInt']>;
endDate_lesser?: Maybe<Scalars['FuzzyDateInt']>;
endDate_like?: Maybe<Scalars['String']>;
format_in?: Maybe<Array<Maybe<MediaFormat>>>;
format_not?: Maybe<MediaFormat>;
format_not_in?: Maybe<Array<Maybe<MediaFormat>>>;
status_in?: Maybe<Array<Maybe<MediaStatus>>>;
status_not?: Maybe<MediaStatus>;
status_not_in?: Maybe<Array<Maybe<MediaStatus>>>;
episodes_greater?: Maybe<Scalars['Int']>;
episodes_lesser?: Maybe<Scalars['Int']>;
duration_greater?: Maybe<Scalars['Int']>;
duration_lesser?: Maybe<Scalars['Int']>;
chapters_greater?: Maybe<Scalars['Int']>;
chapters_lesser?: Maybe<Scalars['Int']>;
volumes_greater?: Maybe<Scalars['Int']>;
volumes_lesser?: Maybe<Scalars['Int']>;
genre_in?: Maybe<Array<Maybe<Scalars['String']>>>;
genre_not_in?: Maybe<Array<Maybe<Scalars['String']>>>;
tag_in?: Maybe<Array<Maybe<Scalars['String']>>>;
tag_not_in?: Maybe<Array<Maybe<Scalars['String']>>>;
tagCategory_in?: Maybe<Array<Maybe<Scalars['String']>>>;
tagCategory_not_in?: Maybe<Array<Maybe<Scalars['String']>>>;
licensedBy_in?: Maybe<Array<Maybe<Scalars['String']>>>;
averageScore_not?: Maybe<Scalars['Int']>;
averageScore_greater?: Maybe<Scalars['Int']>;
averageScore_lesser?: Maybe<Scalars['Int']>;
popularity_not?: Maybe<Scalars['Int']>;
popularity_greater?: Maybe<Scalars['Int']>;
popularity_lesser?: Maybe<Scalars['Int']>;
source_in?: Maybe<Array<Maybe<MediaSource>>>;
sort?: Maybe<Array<Maybe<MediaSort>>>;
};
/** Page of data */
export type PageCharactersArgs = {
id?: Maybe<Scalars['Int']>;
isBirthday?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
sort?: Maybe<Array<Maybe<CharacterSort>>>;
};
/** Page of data */
export type PageStaffArgs = {
id?: Maybe<Scalars['Int']>;
isBirthday?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
sort?: Maybe<Array<Maybe<StaffSort>>>;
};
/** Page of data */
export type PageStudiosArgs = {
id?: Maybe<Scalars['Int']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
sort?: Maybe<Array<Maybe<StudioSort>>>;
};
/** Page of data */
export type PageMediaListArgs = {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
userName?: Maybe<Scalars['String']>;
type?: Maybe<MediaType>;
status?: Maybe<MediaListStatus>;
mediaId?: Maybe<Scalars['Int']>;
isFollowing?: Maybe<Scalars['Boolean']>;
notes?: Maybe<Scalars['String']>;
startedAt?: Maybe<Scalars['FuzzyDateInt']>;
completedAt?: Maybe<Scalars['FuzzyDateInt']>;
compareWithAuthList?: Maybe<Scalars['Boolean']>;
userId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
status_in?: Maybe<Array<Maybe<MediaListStatus>>>;
status_not_in?: Maybe<Array<Maybe<MediaListStatus>>>;
status_not?: Maybe<MediaListStatus>;
mediaId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
notes_like?: Maybe<Scalars['String']>;
startedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_like?: Maybe<Scalars['String']>;
completedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_like?: Maybe<Scalars['String']>;
sort?: Maybe<Array<Maybe<MediaListSort>>>;
};
/** Page of data */
export type PageAiringSchedulesArgs = {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
episode?: Maybe<Scalars['Int']>;
airingAt?: Maybe<Scalars['Int']>;
notYetAired?: Maybe<Scalars['Boolean']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
episode_not?: Maybe<Scalars['Int']>;
episode_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
episode_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
episode_greater?: Maybe<Scalars['Int']>;
episode_lesser?: Maybe<Scalars['Int']>;
airingAt_greater?: Maybe<Scalars['Int']>;
airingAt_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<AiringSort>>>;
};
/** Page of data */
export type PageMediaTrendsArgs = {
mediaId?: Maybe<Scalars['Int']>;
date?: Maybe<Scalars['Int']>;
trending?: Maybe<Scalars['Int']>;
averageScore?: Maybe<Scalars['Int']>;
popularity?: Maybe<Scalars['Int']>;
episode?: Maybe<Scalars['Int']>;
releasing?: Maybe<Scalars['Boolean']>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
date_greater?: Maybe<Scalars['Int']>;
date_lesser?: Maybe<Scalars['Int']>;
trending_greater?: Maybe<Scalars['Int']>;
trending_lesser?: Maybe<Scalars['Int']>;
trending_not?: Maybe<Scalars['Int']>;
averageScore_greater?: Maybe<Scalars['Int']>;
averageScore_lesser?: Maybe<Scalars['Int']>;
averageScore_not?: Maybe<Scalars['Int']>;
popularity_greater?: Maybe<Scalars['Int']>;
popularity_lesser?: Maybe<Scalars['Int']>;
popularity_not?: Maybe<Scalars['Int']>;
episode_greater?: Maybe<Scalars['Int']>;
episode_lesser?: Maybe<Scalars['Int']>;
episode_not?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<MediaTrendSort>>>;
};
/** Page of data */
export type PageNotificationsArgs = {
type?: Maybe<NotificationType>;
resetNotificationCount?: Maybe<Scalars['Boolean']>;
type_in?: Maybe<Array<Maybe<NotificationType>>>;
};
/** Page of data */
export type PageFollowersArgs = {
userId: Scalars['Int'];
sort?: Maybe<Array<Maybe<UserSort>>>;
};
/** Page of data */
export type PageFollowingArgs = {
userId: Scalars['Int'];
sort?: Maybe<Array<Maybe<UserSort>>>;
};
/** Page of data */
export type PageActivitiesArgs = {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
messengerId?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
type?: Maybe<ActivityType>;
isFollowing?: Maybe<Scalars['Boolean']>;
hasReplies?: Maybe<Scalars['Boolean']>;
hasRepliesOrTypeText?: Maybe<Scalars['Boolean']>;
createdAt?: Maybe<Scalars['Int']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
userId_not?: Maybe<Scalars['Int']>;
userId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
userId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
messengerId_not?: Maybe<Scalars['Int']>;
messengerId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
messengerId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
type_not?: Maybe<ActivityType>;
type_in?: Maybe<Array<Maybe<ActivityType>>>;
type_not_in?: Maybe<Array<Maybe<ActivityType>>>;
createdAt_greater?: Maybe<Scalars['Int']>;
createdAt_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<ActivitySort>>>;
};
/** Page of data */
export type PageActivityRepliesArgs = {
id?: Maybe<Scalars['Int']>;
activityId?: Maybe<Scalars['Int']>;
};
/** Page of data */
export type PageThreadsArgs = {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
replyUserId?: Maybe<Scalars['Int']>;
subscribed?: Maybe<Scalars['Boolean']>;
categoryId?: Maybe<Scalars['Int']>;
mediaCategoryId?: Maybe<Scalars['Int']>;
search?: Maybe<Scalars['String']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
sort?: Maybe<Array<Maybe<ThreadSort>>>;
};
/** Page of data */
export type PageThreadCommentsArgs = {
id?: Maybe<Scalars['Int']>;
threadId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<ThreadCommentSort>>>;
};
/** Page of data */
export type PageReviewsArgs = {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
mediaType?: Maybe<MediaType>;
sort?: Maybe<Array<Maybe<ReviewSort>>>;
};
/** Page of data */
export type PageRecommendationsArgs = {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
mediaRecommendationId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
rating?: Maybe<Scalars['Int']>;
onList?: Maybe<Scalars['Boolean']>;
rating_greater?: Maybe<Scalars['Int']>;
rating_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<RecommendationSort>>>;
};
/** Page of data */
export type PageLikesArgs = {
likeableId?: Maybe<Scalars['Int']>;
type?: Maybe<LikeableType>;
};
export type PageInfo = {
__typename?: 'PageInfo';
/** The total number of items */
total?: Maybe<Scalars['Int']>;
/** The count on a page */
perPage?: Maybe<Scalars['Int']>;
/** The current page */
currentPage?: Maybe<Scalars['Int']>;
/** The last page */
lastPage?: Maybe<Scalars['Int']>;
/** If there is another page */
hasNextPage?: Maybe<Scalars['Boolean']>;
};
/** Provides the parsed markdown as html */
export type ParsedMarkdown = {
__typename?: 'ParsedMarkdown';
/** The parsed markdown as html */
html?: Maybe<Scalars['String']>;
};
export type Query = {
__typename?: 'Query';
Page?: Maybe<Page>;
/** Media query */
Media?: Maybe<Media>;
/** Media Trend query */
MediaTrend?: Maybe<MediaTrend>;
/** Airing schedule query */
AiringSchedule?: Maybe<AiringSchedule>;
/** Character query */
Character?: Maybe<Character>;
/** Staff query */
Staff?: Maybe<Staff>;
/** Media list query */
MediaList?: Maybe<MediaList>;
/** Media list collection query, provides list pre-grouped by status & custom lists. User ID and Media Type arguments required. */
MediaListCollection?: Maybe<MediaListCollection>;
/** Collection of all the possible media genres */
GenreCollection?: Maybe<Array<Maybe<Scalars['String']>>>;
/** Collection of all the possible media tags */
MediaTagCollection?: Maybe<Array<Maybe<MediaTag>>>;
/** User query */
User?: Maybe<User>;
/** Get the currently authenticated user */
Viewer?: Maybe<User>;
/** Notification query */
Notification?: Maybe<NotificationUnion>;
/** Studio query */
Studio?: Maybe<Studio>;
/** Review query */
Review?: Maybe<Review>;
/** Activity query */
Activity?: Maybe<ActivityUnion>;
/** Activity reply query */
ActivityReply?: Maybe<ActivityReply>;
/** Follow query */
Following?: Maybe<User>;
/** Follow query */
Follower?: Maybe<User>;
/** Thread query */
Thread?: Maybe<Thread>;
/** Comment query */
ThreadComment?: Maybe<Array<Maybe<ThreadComment>>>;
/** Recommendation query */
Recommendation?: Maybe<Recommendation>;
/** Like query */
Like?: Maybe<User>;
/** Provide AniList markdown to be converted to html (Requires auth) */
Markdown?: Maybe<ParsedMarkdown>;
AniChartUser?: Maybe<AniChartUser>;
/** Site statistics query */
SiteStatistics?: Maybe<SiteStatistics>;
};
export type QueryPageArgs = {
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
export type QueryMediaArgs = {
id?: Maybe<Scalars['Int']>;
idMal?: Maybe<Scalars['Int']>;
startDate?: Maybe<Scalars['FuzzyDateInt']>;
endDate?: Maybe<Scalars['FuzzyDateInt']>;
season?: Maybe<MediaSeason>;
seasonYear?: Maybe<Scalars['Int']>;
type?: Maybe<MediaType>;
format?: Maybe<MediaFormat>;
status?: Maybe<MediaStatus>;
episodes?: Maybe<Scalars['Int']>;
duration?: Maybe<Scalars['Int']>;
chapters?: Maybe<Scalars['Int']>;
volumes?: Maybe<Scalars['Int']>;
isAdult?: Maybe<Scalars['Boolean']>;
genre?: Maybe<Scalars['String']>;
tag?: Maybe<Scalars['String']>;
minimumTagRank?: Maybe<Scalars['Int']>;
tagCategory?: Maybe<Scalars['String']>;
onList?: Maybe<Scalars['Boolean']>;
licensedBy?: Maybe<Scalars['String']>;
averageScore?: Maybe<Scalars['Int']>;
popularity?: Maybe<Scalars['Int']>;
source?: Maybe<MediaSource>;
countryOfOrigin?: Maybe<Scalars['CountryCode']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
idMal_not?: Maybe<Scalars['Int']>;
idMal_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
idMal_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
startDate_greater?: Maybe<Scalars['FuzzyDateInt']>;
startDate_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startDate_like?: Maybe<Scalars['String']>;
endDate_greater?: Maybe<Scalars['FuzzyDateInt']>;
endDate_lesser?: Maybe<Scalars['FuzzyDateInt']>;
endDate_like?: Maybe<Scalars['String']>;
format_in?: Maybe<Array<Maybe<MediaFormat>>>;
format_not?: Maybe<MediaFormat>;
format_not_in?: Maybe<Array<Maybe<MediaFormat>>>;
status_in?: Maybe<Array<Maybe<MediaStatus>>>;
status_not?: Maybe<MediaStatus>;
status_not_in?: Maybe<Array<Maybe<MediaStatus>>>;
episodes_greater?: Maybe<Scalars['Int']>;
episodes_lesser?: Maybe<Scalars['Int']>;
duration_greater?: Maybe<Scalars['Int']>;
duration_lesser?: Maybe<Scalars['Int']>;
chapters_greater?: Maybe<Scalars['Int']>;
chapters_lesser?: Maybe<Scalars['Int']>;
volumes_greater?: Maybe<Scalars['Int']>;
volumes_lesser?: Maybe<Scalars['Int']>;
genre_in?: Maybe<Array<Maybe<Scalars['String']>>>;
genre_not_in?: Maybe<Array<Maybe<Scalars['String']>>>;
tag_in?: Maybe<Array<Maybe<Scalars['String']>>>;
tag_not_in?: Maybe<Array<Maybe<Scalars['String']>>>;
tagCategory_in?: Maybe<Array<Maybe<Scalars['String']>>>;
tagCategory_not_in?: Maybe<Array<Maybe<Scalars['String']>>>;
licensedBy_in?: Maybe<Array<Maybe<Scalars['String']>>>;
averageScore_not?: Maybe<Scalars['Int']>;
averageScore_greater?: Maybe<Scalars['Int']>;
averageScore_lesser?: Maybe<Scalars['Int']>;
popularity_not?: Maybe<Scalars['Int']>;
popularity_greater?: Maybe<Scalars['Int']>;
popularity_lesser?: Maybe<Scalars['Int']>;
source_in?: Maybe<Array<Maybe<MediaSource>>>;
sort?: Maybe<Array<Maybe<MediaSort>>>;
};
export type QueryMediaTrendArgs = {
mediaId?: Maybe<Scalars['Int']>;
date?: Maybe<Scalars['Int']>;
trending?: Maybe<Scalars['Int']>;
averageScore?: Maybe<Scalars['Int']>;
popularity?: Maybe<Scalars['Int']>;
episode?: Maybe<Scalars['Int']>;
releasing?: Maybe<Scalars['Boolean']>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
date_greater?: Maybe<Scalars['Int']>;
date_lesser?: Maybe<Scalars['Int']>;
trending_greater?: Maybe<Scalars['Int']>;
trending_lesser?: Maybe<Scalars['Int']>;
trending_not?: Maybe<Scalars['Int']>;
averageScore_greater?: Maybe<Scalars['Int']>;
averageScore_lesser?: Maybe<Scalars['Int']>;
averageScore_not?: Maybe<Scalars['Int']>;
popularity_greater?: Maybe<Scalars['Int']>;
popularity_lesser?: Maybe<Scalars['Int']>;
popularity_not?: Maybe<Scalars['Int']>;
episode_greater?: Maybe<Scalars['Int']>;
episode_lesser?: Maybe<Scalars['Int']>;
episode_not?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<MediaTrendSort>>>;
};
export type QueryAiringScheduleArgs = {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
episode?: Maybe<Scalars['Int']>;
airingAt?: Maybe<Scalars['Int']>;
notYetAired?: Maybe<Scalars['Boolean']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
episode_not?: Maybe<Scalars['Int']>;
episode_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
episode_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
episode_greater?: Maybe<Scalars['Int']>;
episode_lesser?: Maybe<Scalars['Int']>;
airingAt_greater?: Maybe<Scalars['Int']>;
airingAt_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<AiringSort>>>;
};
export type QueryCharacterArgs = {
id?: Maybe<Scalars['Int']>;
isBirthday?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
sort?: Maybe<Array<Maybe<CharacterSort>>>;
};
export type QueryStaffArgs = {
id?: Maybe<Scalars['Int']>;
isBirthday?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
sort?: Maybe<Array<Maybe<StaffSort>>>;
};
export type QueryMediaListArgs = {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
userName?: Maybe<Scalars['String']>;
type?: Maybe<MediaType>;
status?: Maybe<MediaListStatus>;
mediaId?: Maybe<Scalars['Int']>;
isFollowing?: Maybe<Scalars['Boolean']>;
notes?: Maybe<Scalars['String']>;
startedAt?: Maybe<Scalars['FuzzyDateInt']>;
completedAt?: Maybe<Scalars['FuzzyDateInt']>;
compareWithAuthList?: Maybe<Scalars['Boolean']>;
userId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
status_in?: Maybe<Array<Maybe<MediaListStatus>>>;
status_not_in?: Maybe<Array<Maybe<MediaListStatus>>>;
status_not?: Maybe<MediaListStatus>;
mediaId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
notes_like?: Maybe<Scalars['String']>;
startedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_like?: Maybe<Scalars['String']>;
completedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_like?: Maybe<Scalars['String']>;
sort?: Maybe<Array<Maybe<MediaListSort>>>;
};
export type QueryMediaListCollectionArgs = {
userId?: Maybe<Scalars['Int']>;
userName?: Maybe<Scalars['String']>;
type?: Maybe<MediaType>;
status?: Maybe<MediaListStatus>;
notes?: Maybe<Scalars['String']>;
startedAt?: Maybe<Scalars['FuzzyDateInt']>;
completedAt?: Maybe<Scalars['FuzzyDateInt']>;
forceSingleCompletedList?: Maybe<Scalars['Boolean']>;
chunk?: Maybe<Scalars['Int']>;
perChunk?: Maybe<Scalars['Int']>;
status_in?: Maybe<Array<Maybe<MediaListStatus>>>;
status_not_in?: Maybe<Array<Maybe<MediaListStatus>>>;
status_not?: Maybe<MediaListStatus>;
notes_like?: Maybe<Scalars['String']>;
startedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_like?: Maybe<Scalars['String']>;
completedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_like?: Maybe<Scalars['String']>;
sort?: Maybe<Array<Maybe<MediaListSort>>>;
};
export type QueryMediaTagCollectionArgs = {
status?: Maybe<Scalars['Int']>;
};
export type QueryUserArgs = {
id?: Maybe<Scalars['Int']>;
name?: Maybe<Scalars['String']>;
isModerator?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
sort?: Maybe<Array<Maybe<UserSort>>>;
};
export type QueryNotificationArgs = {
type?: Maybe<NotificationType>;
resetNotificationCount?: Maybe<Scalars['Boolean']>;
type_in?: Maybe<Array<Maybe<NotificationType>>>;
};
export type QueryStudioArgs = {
id?: Maybe<Scalars['Int']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
sort?: Maybe<Array<Maybe<StudioSort>>>;
};
export type QueryReviewArgs = {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
mediaType?: Maybe<MediaType>;
sort?: Maybe<Array<Maybe<ReviewSort>>>;
};
export type QueryActivityArgs = {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
messengerId?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
type?: Maybe<ActivityType>;
isFollowing?: Maybe<Scalars['Boolean']>;
hasReplies?: Maybe<Scalars['Boolean']>;
hasRepliesOrTypeText?: Maybe<Scalars['Boolean']>;
createdAt?: Maybe<Scalars['Int']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
userId_not?: Maybe<Scalars['Int']>;
userId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
userId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
messengerId_not?: Maybe<Scalars['Int']>;
messengerId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
messengerId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
type_not?: Maybe<ActivityType>;
type_in?: Maybe<Array<Maybe<ActivityType>>>;
type_not_in?: Maybe<Array<Maybe<ActivityType>>>;
createdAt_greater?: Maybe<Scalars['Int']>;
createdAt_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<ActivitySort>>>;
};
export type QueryActivityReplyArgs = {
id?: Maybe<Scalars['Int']>;
activityId?: Maybe<Scalars['Int']>;
};
export type QueryFollowingArgs = {
userId: Scalars['Int'];
sort?: Maybe<Array<Maybe<UserSort>>>;
};
export type QueryFollowerArgs = {
userId: Scalars['Int'];
sort?: Maybe<Array<Maybe<UserSort>>>;
};
export type QueryThreadArgs = {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
replyUserId?: Maybe<Scalars['Int']>;
subscribed?: Maybe<Scalars['Boolean']>;
categoryId?: Maybe<Scalars['Int']>;
mediaCategoryId?: Maybe<Scalars['Int']>;
search?: Maybe<Scalars['String']>;
id_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
sort?: Maybe<Array<Maybe<ThreadSort>>>;
};
export type QueryThreadCommentArgs = {
id?: Maybe<Scalars['Int']>;
threadId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<ThreadCommentSort>>>;
};
export type QueryRecommendationArgs = {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
mediaRecommendationId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
rating?: Maybe<Scalars['Int']>;
onList?: Maybe<Scalars['Boolean']>;
rating_greater?: Maybe<Scalars['Int']>;
rating_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<RecommendationSort>>>;
};
export type QueryLikeArgs = {
likeableId?: Maybe<Scalars['Int']>;
type?: Maybe<LikeableType>;
};
export type QueryMarkdownArgs = {
markdown: Scalars['String'];
};
/** Media recommendation */
export type Recommendation = {
__typename?: 'Recommendation';
/** The id of the recommendation */
id: Scalars['Int'];
/** Users rating of the recommendation */
rating?: Maybe<Scalars['Int']>;
/** The rating of the recommendation by currently authenticated user */
userRating?: Maybe<RecommendationRating>;
/** The media the recommendation is from */
media?: Maybe<Media>;
/** The recommended media */
mediaRecommendation?: Maybe<Media>;
/** The user that first created the recommendation */
user?: Maybe<User>;
};
export type RecommendationConnection = {
__typename?: 'RecommendationConnection';
edges?: Maybe<Array<Maybe<RecommendationEdge>>>;
nodes?: Maybe<Array<Maybe<Recommendation>>>;
/** The pagination information */
pageInfo?: Maybe<PageInfo>;
};
/** Recommendation connection edge */
export type RecommendationEdge = {
__typename?: 'RecommendationEdge';
node?: Maybe<Recommendation>;
};
/** Recommendation rating enums */
export enum RecommendationRating {
NoRating = 'NO_RATING',
RateUp = 'RATE_UP',
RateDown = 'RATE_DOWN',
}
/** Recommendation sort enums */
export enum RecommendationSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Rating = 'RATING',
RatingDesc = 'RATING_DESC',
}
/** Notification for when new media is added to the site */
export type RelatedMediaAdditionNotification = {
__typename?: 'RelatedMediaAdditionNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The id of the new media */
mediaId: Scalars['Int'];
/** The notification context text */
context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The associated media of the airing schedule */
media?: Maybe<Media>;
};
export type Report = {
__typename?: 'Report';
id: Scalars['Int'];
reporter?: Maybe<User>;
reported?: Maybe<User>;
reason?: Maybe<Scalars['String']>;
/** When the entry data was created */
createdAt?: Maybe<Scalars['Int']>;
cleared?: Maybe<Scalars['Boolean']>;
};
/** A Review that features in an anime or manga */
export type Review = {
__typename?: 'Review';
/** The id of the review */
id: Scalars['Int'];
/** The id of the review's creator */
userId: Scalars['Int'];
/** The id of the review's media */
mediaId: Scalars['Int'];
/** For which type of media the review is for */
mediaType?: Maybe<MediaType>;
/** A short summary of the review */
summary?: Maybe<Scalars['String']>;
/** The main review body text */
body?: Maybe<Scalars['String']>;
/** The total user rating of the review */
rating?: Maybe<Scalars['Int']>;
/** The amount of user ratings of the review */
ratingAmount?: Maybe<Scalars['Int']>;
/** The rating of the review by currently authenticated user */
userRating?: Maybe<ReviewRating>;
/** The review score of the media */
score?: Maybe<Scalars['Int']>;
/** If the review is not yet publicly published and is only viewable by creator */
private?: Maybe<Scalars['Boolean']>;
/** The url for the review page on the AniList website */
siteUrl?: Maybe<Scalars['String']>;
/** The time of the thread creation */
createdAt: Scalars['Int'];
/** The time of the thread last update */
updatedAt: Scalars['Int'];
/** The creator of the review */
user?: Maybe<User>;
/** The media the review is of */
media?: Maybe<Media>;
};
/** A Review that features in an anime or manga */
export type ReviewBodyArgs = {
asHtml?: Maybe<Scalars['Boolean']>;
};
export type ReviewConnection = {
__typename?: 'ReviewConnection';
edges?: Maybe<Array<Maybe<ReviewEdge>>>;
nodes?: Maybe<Array<Maybe<Review>>>;
/** The pagination information */
pageInfo?: Maybe<PageInfo>;
};
/** Review connection edge */
export type ReviewEdge = {
__typename?: 'ReviewEdge';
node?: Maybe<Review>;
};
/** Review rating enums */
export enum ReviewRating {
NoVote = 'NO_VOTE',
UpVote = 'UP_VOTE',
DownVote = 'DOWN_VOTE',
}
/** Review sort enums */
export enum ReviewSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Score = 'SCORE',
ScoreDesc = 'SCORE_DESC',
Rating = 'RATING',
RatingDesc = 'RATING_DESC',
CreatedAt = 'CREATED_AT',
CreatedAtDesc = 'CREATED_AT_DESC',
UpdatedAt = 'UPDATED_AT',
UpdatedAtDesc = 'UPDATED_AT_DESC',
}
/** Feed of mod edit activity */
export type RevisionHistory = {
__typename?: 'RevisionHistory';
/** The id of the media */
id: Scalars['Int'];
/** The action taken on the objects */
action?: Maybe<RevisionHistoryAction>;
/** A JSON object of the fields that changed */
changes?: Maybe<Scalars['Json']>;
/** The user who made the edit to the object */
user?: Maybe<User>;
/** The media the mod feed entry references */
media?: Maybe<Media>;
/** The character the mod feed entry references */
character?: Maybe<Character>;
/** The staff member the mod feed entry references */
staff?: Maybe<Staff>;
/** The studio the mod feed entry references */
studio?: Maybe<Studio>;
/** When the mod feed entry was created */
createdAt?: Maybe<Scalars['Int']>;
};
/** Revision history actions */
export enum RevisionHistoryAction {
Create = 'CREATE',
Edit = 'EDIT',
}
/** A user's list score distribution. */
export type ScoreDistribution = {
__typename?: 'ScoreDistribution';
score?: Maybe<Scalars['Int']>;
/** The amount of list entries with this score */
amount?: Maybe<Scalars['Int']>;
};
/** Media list scoring type */
export enum ScoreFormat {
/** An integer from 0-100 */
Point_100 = 'POINT_100',
/** A float from 0-10 with 1 decimal place */
Point_10Decimal = 'POINT_10_DECIMAL',
/** An integer from 0-10 */
Point_10 = 'POINT_10',
/** An integer from 0-5. Should be represented in Stars */
Point_5 = 'POINT_5',
/** An integer from 0-3. Should be represented in Smileys. 0 => No Score, 1 => :(, 2 => :|, 3 => :) */
Point_3 = 'POINT_3',
}
export type SiteStatistics = {
__typename?: 'SiteStatistics';
users?: Maybe<SiteTrendConnection>;
anime?: Maybe<SiteTrendConnection>;
manga?: Maybe<SiteTrendConnection>;
characters?: Maybe<SiteTrendConnection>;
staff?: Maybe<SiteTrendConnection>;
studios?: Maybe<SiteTrendConnection>;
reviews?: Maybe<SiteTrendConnection>;
};
export type SiteStatisticsUsersArgs = {
sort?: Maybe<Array<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
export type SiteStatisticsAnimeArgs = {
sort?: Maybe<Array<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
export type SiteStatisticsMangaArgs = {
sort?: Maybe<Array<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
export type SiteStatisticsCharactersArgs = {
sort?: Maybe<Array<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
export type SiteStatisticsStaffArgs = {
sort?: Maybe<Array<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
export type SiteStatisticsStudiosArgs = {
sort?: Maybe<Array<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
export type SiteStatisticsReviewsArgs = {
sort?: Maybe<Array<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** Daily site statistics */
export type SiteTrend = {
__typename?: 'SiteTrend';
/** The day the data was recorded (timestamp) */
date: Scalars['Int'];
count: Scalars['Int'];
/** The change from yesterday */
change: Scalars['Int'];
};
export type SiteTrendConnection = {
__typename?: 'SiteTrendConnection';
edges?: Maybe<Array<Maybe<SiteTrendEdge>>>;
nodes?: Maybe<Array<Maybe<SiteTrend>>>;
/** The pagination information */
pageInfo?: Maybe<PageInfo>;
};
/** Site trend connection edge */
export type SiteTrendEdge = {
__typename?: 'SiteTrendEdge';
node?: Maybe<SiteTrend>;
};
/** Site trend sort enums */
export enum SiteTrendSort {
Date = 'DATE',
DateDesc = 'DATE_DESC',
Count = 'COUNT',
CountDesc = 'COUNT_DESC',
Change = 'CHANGE',
ChangeDesc = 'CHANGE_DESC',
}
/** Voice actors or production staff */
export type Staff = {
__typename?: 'Staff';
/** The id of the staff member */
id: Scalars['Int'];
/** The names of the staff member */
name?: Maybe<StaffName>;
/**
* The primary language the staff member dub's in
* @deprecated Replaced with languageV2
*/
language?: Maybe<StaffLanguage>;
/** The primary language of the staff member. Current values: Japanese, English, Korean, Italian, Spanish, Portuguese, French, German, Hebrew, Hungarian, Chinese, Arabic, Filipino, Catalan */
languageV2?: Maybe<Scalars['String']>;
/** The staff images */
image?: Maybe<StaffImage>;
/** A general description of the staff member */
description?: Maybe<Scalars['String']>;
/** The person's primary occupations */
primaryOccupations?: Maybe<Array<Maybe<Scalars['String']>>>;
/** The staff's gender. Usually Male, Female, or Non-binary but can be any string. */
gender?: Maybe<Scalars['String']>;
dateOfBirth?: Maybe<FuzzyDate>;
dateOfDeath?: Maybe<FuzzyDate>;
/** The person's age in years */
age?: Maybe<Scalars['Int']>;
/** [startYear, endYear] (If the 2nd value is not present staff is still active) */
yearsActive?: Maybe<Array<Maybe<Scalars['Int']>>>;
/** The persons birthplace or hometown */
homeTown?: Maybe<Scalars['String']>;
/** If the staff member is marked as favourite by the currently authenticated user */
isFavourite: Scalars['Boolean'];
/** If the staff member is blocked from being added to favourites */
isFavouriteBlocked: Scalars['Boolean'];
/** The url for the staff page on the AniList website */
siteUrl?: Maybe<Scalars['String']>;
/** Media where the staff member has a production role */
staffMedia?: Maybe<MediaConnection>;
/** Characters voiced by the actor */
characters?: Maybe<CharacterConnection>;
/** Media the actor voiced characters in. (Same data as characters with media as node instead of characters) */
characterMedia?: Maybe<MediaConnection>;
/** @deprecated No data available */
updatedAt?: Maybe<Scalars['Int']>;
/** Staff member that the submission is referencing */
staff?: Maybe<Staff>;
/** Submitter for the submission */
submitter?: Maybe<User>;
/** Status of the submission */
submissionStatus?: Maybe<Scalars['Int']>;
/** Inner details of submission status */
submissionNotes?: Maybe<Scalars['String']>;
/** The amount of user's who have favourited the staff member */
favourites?: Maybe<Scalars['Int']>;
/** Notes for site moderators */
modNotes?: Maybe<Scalars['String']>;
};
/** Voice actors or production staff */
export type StaffDescriptionArgs = {
asHtml?: Maybe<Scalars['Boolean']>;
};
/** Voice actors or production staff */
export type StaffStaffMediaArgs = {
sort?: Maybe<Array<Maybe<MediaSort>>>;
type?: Maybe<MediaType>;
onList?: Maybe<Scalars['Boolean']>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** Voice actors or production staff */
export type StaffCharactersArgs = {
sort?: Maybe<Array<Maybe<CharacterSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
/** Voice actors or production staff */
export type StaffCharacterMediaArgs = {
sort?: Maybe<Array<Maybe<MediaSort>>>;
onList?: Maybe<Scalars['Boolean']>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
export type StaffConnection = {
__typename?: 'StaffConnection';
edges?: Maybe<Array<Maybe<StaffEdge>>>;
nodes?: Maybe<Array<Maybe<Staff>>>;
/** The pagination information */
pageInfo?: Maybe<PageInfo>;
};
/** Staff connection edge */
export type StaffEdge = {
__typename?: 'StaffEdge';
node?: Maybe<Staff>;
/** The id of the connection */
id?: Maybe<Scalars['Int']>;
/** The role of the staff member in the production of the media */
role?: Maybe<Scalars['String']>;
/** The order the staff should be displayed from the users favourites */
favouriteOrder?: Maybe<Scalars['Int']>;
};
export type StaffImage = {
__typename?: 'StaffImage';
/** The person's image of media at its largest size */
large?: Maybe<Scalars['String']>;
/** The person's image of media at medium size */
medium?: Maybe<Scalars['String']>;
};
/** The primary language of the voice actor */
export enum StaffLanguage {
/** Japanese */
Japanese = 'JAPANESE',
/** English */
English = 'ENGLISH',
/** Korean */
Korean = 'KOREAN',
/** Italian */
Italian = 'ITALIAN',
/** Spanish */
Spanish = 'SPANISH',
/** Portuguese */
Portuguese = 'PORTUGUESE',
/** French */
French = 'FRENCH',
/** German */
German = 'GERMAN',
/** Hebrew */
Hebrew = 'HEBREW',
/** Hungarian */
Hungarian = 'HUNGARIAN',
}
/** The names of the staff member */
export type StaffName = {
__typename?: 'StaffName';
/** The person's given name */
first?: Maybe<Scalars['String']>;
/** The person's middle name */
middle?: Maybe<Scalars['String']>;
/** The person's surname */
last?: Maybe<Scalars['String']>;
/** The person's first and last name */
full?: Maybe<Scalars['String']>;
/** The person's full name in their native language */
native?: Maybe<Scalars['String']>;
/** Other names the staff member might be referred to as (pen names) */
alternative?: Maybe<Array<Maybe<Scalars['String']>>>;
/** The currently authenticated users preferred name language. Default romaji for non-authenticated */
userPreferred?: Maybe<Scalars['String']>;
};
/** The names of the staff member */
export type StaffNameInput = {
/** The person's given name */
first?: Maybe<Scalars['String']>;
/** The person's middle name */
middle?: Maybe<Scalars['String']>;
/** The person's surname */
last?: Maybe<Scalars['String']>;
/** The person's full name in their native language */
native?: Maybe<Scalars['String']>;
/** Other names the character might be referred by */
alternative?: Maybe<Array<Maybe<Scalars['String']>>>;
};
/** Voice actor role for a character */
export type StaffRoleType = {
__typename?: 'StaffRoleType';
/** The voice actors of the character */
voiceActor?: Maybe<Staff>;
/** Notes regarding the VA's role for the character */
roleNotes?: Maybe<Scalars['String']>;
/** Used for grouping roles where multiple dubs exist for the same language. Either dubbing company name or language variant. */
dubGroup?: Maybe<Scalars['String']>;
};
/** Staff sort enums */
export enum StaffSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Role = 'ROLE',
RoleDesc = 'ROLE_DESC',
Language = 'LANGUAGE',
LanguageDesc = 'LANGUAGE_DESC',
SearchMatch = 'SEARCH_MATCH',
Favourites = 'FAVOURITES',
FavouritesDesc = 'FAVOURITES_DESC',
/** Order manually decided by moderators */
Relevance = 'RELEVANCE',
}
/** User's staff statistics */
export type StaffStats = {
__typename?: 'StaffStats';
staff?: Maybe<Staff>;
amount?: Maybe<Scalars['Int']>;
meanScore?: Maybe<Scalars['Int']>;
/** The amount of time in minutes the staff member has been watched by the user */
timeWatched?: Maybe<Scalars['Int']>;
};
/** A submission for a staff that features in an anime or manga */
export type StaffSubmission = {
__typename?: 'StaffSubmission';
/** The id of the submission */
id: Scalars['Int'];
/** Staff that the submission is referencing */
staff?: Maybe<Staff>;
/** The staff submission changes */
submission?: Maybe<Staff>;
/** Submitter for the submission */
submitter?: Maybe<User>;
/** Status of the submission */
status?: Maybe<SubmissionStatus>;
/** Inner details of submission status */
notes?: Maybe<Scalars['String']>;
source?: Maybe<Scalars['String']>;
createdAt?: Maybe<Scalars['Int']>;
};
/** The distribution of the watching/reading status of media or a user's list */
export type StatusDistribution = {
__typename?: 'StatusDistribution';
/** The day the activity took place (Unix timestamp) */
status?: Maybe<MediaListStatus>;
/** The amount of entries with this status */
amount?: Maybe<Scalars['Int']>;
};
/** Animation or production company */
export type Studio = {
__typename?: 'Studio';
/** The id of the studio */
id: Scalars['Int'];
/** The name of the studio */
name: Scalars['String'];
/** If the studio is an animation studio or a different kind of company */
isAnimationStudio: Scalars['Boolean'];
/** The media the studio has worked on */
media?: Maybe<MediaConnection>;
/** The url for the studio page on the AniList website */
siteUrl?: Maybe<Scalars['String']>;
/** If the studio is marked as favourite by the currently authenticated user */
isFavourite: Scalars['Boolean'];
/** The amount of user's who have favourited the studio */
favourites?: Maybe<Scalars['Int']>;
};
/** Animation or production company */
export type StudioMediaArgs = {
sort?: Maybe<Array<Maybe<MediaSort>>>;
isMain?: Maybe<Scalars['Boolean']>;
onList?: Maybe<Scalars['Boolean']>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
};
export type StudioConnection = {
__typename?: 'StudioConnection';
edges?: Maybe<Array<Maybe<StudioEdge>>>;
nodes?: Maybe<Array<Maybe<Studio>>>;
/** The pagination information */
pageInfo?: Maybe<PageInfo>;
};
/** Studio connection edge */
export type StudioEdge = {
__typename?: 'StudioEdge';
node?: Maybe<Studio>;
/** The id of the connection */
id?: Maybe<Scalars['Int']>;
/** If the studio is the main animation studio of the anime */
isMain: Scalars['Boolean'];
/** The order the character should be displayed from the users favourites */
favouriteOrder?: Maybe<Scalars['Int']>;
};
/** Studio sort enums */
export enum StudioSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Name = 'NAME',
NameDesc = 'NAME_DESC',
SearchMatch = 'SEARCH_MATCH',
Favourites = 'FAVOURITES',
FavouritesDesc = 'FAVOURITES_DESC',
}
/** User's studio statistics */
export type StudioStats = {
__typename?: 'StudioStats';
studio?: Maybe<Studio>;
amount?: Maybe<Scalars['Int']>;
meanScore?: Maybe<Scalars['Int']>;
/** The amount of time in minutes the studio's works have been watched by the user */
timeWatched?: Maybe<Scalars['Int']>;
};
/** Submission sort enums */
export enum SubmissionSort {
Id = 'ID',
IdDesc = 'ID_DESC',
}
/** Submission status */
export enum SubmissionStatus {
Pending = 'PENDING',
Rejected = 'REJECTED',
PartiallyAccepted = 'PARTIALLY_ACCEPTED',
Accepted = 'ACCEPTED',
}
/** User's tag statistics */
export type TagStats = {
__typename?: 'TagStats';
tag?: Maybe<MediaTag>;
amount?: Maybe<Scalars['Int']>;
meanScore?: Maybe<Scalars['Int']>;
/** The amount of time in minutes the tag has been watched by the user */
timeWatched?: Maybe<Scalars['Int']>;
};
/** User text activity */
export type TextActivity = {
__typename?: 'TextActivity';
/** The id of the activity */
id: Scalars['Int'];
/** The user id of the activity's creator */
userId?: Maybe<Scalars['Int']>;
/** The type of activity */
type?: Maybe<ActivityType>;
/** The number of activity replies */
replyCount: Scalars['Int'];
/** The status text (Markdown) */
text?: Maybe<Scalars['String']>;
/** The url for the activity page on the AniList website */
siteUrl?: Maybe<Scalars['String']>;
/** If the activity is locked and can receive replies */
isLocked?: Maybe<Scalars['Boolean']>;
/** If the currently authenticated user is subscribed to the activity */
isSubscribed?: Maybe<Scalars['Boolean']>;
/** The amount of likes the activity has */
likeCount: Scalars['Int'];
/** If the currently authenticated user liked the activity */
isLiked?: Maybe<Scalars['Boolean']>;
/** The time the activity was created at */
createdAt: Scalars['Int'];
/** The user who created the activity */
user?: Maybe<User>;
/** The written replies to the activity */
replies?: Maybe<Array<Maybe<ActivityReply>>>;
/** The users who liked the activity */
likes?: Maybe<Array<Maybe<User>>>;
};
/** User text activity */
export type TextActivityTextArgs = {
asHtml?: Maybe<Scalars['Boolean']>;
};
/** Forum Thread */
export type Thread = {
__typename?: 'Thread';
/** The id of the thread */
id: Scalars['Int'];
/** The title of the thread */
title?: Maybe<Scalars['String']>;
/** The text body of the thread (Markdown) */
body?: Maybe<Scalars['String']>;
/** The id of the thread owner user */
userId: Scalars['Int'];
/** The id of the user who most recently commented on the thread */
replyUserId?: Maybe<Scalars['Int']>;
/** The id of the most recent comment on the thread */
replyCommentId?: Maybe<Scalars['Int']>;
/** The number of comments on the thread */
replyCount?: Maybe<Scalars['Int']>;
/** The number of times users have viewed the thread */
viewCount?: Maybe<Scalars['Int']>;
/** If the thread is locked and can receive comments */
isLocked?: Maybe<Scalars['Boolean']>;
/** If the thread is stickied and should be displayed at the top of the page */
isSticky?: Maybe<Scalars['Boolean']>;
/** If the currently authenticated user is subscribed to the thread */
isSubscribed?: Maybe<Scalars['Boolean']>;
/** The amount of likes the thread has */
likeCount: Scalars['Int'];
/** If the currently authenticated user liked the thread */
isLiked?: Maybe<Scalars['Boolean']>;
/** The time of the last reply */
repliedAt?: Maybe<Scalars['Int']>;
/** The time of the thread creation */
createdAt: Scalars['Int'];
/** The time of the thread last update */
updatedAt: Scalars['Int'];
/** The owner of the thread */
user?: Maybe<User>;
/** The user to last reply to the thread */
replyUser?: Maybe<User>;
/** The users who liked the thread */
likes?: Maybe<Array<Maybe<User>>>;
/** The url for the thread page on the AniList website */
siteUrl?: Maybe<Scalars['String']>;
/** The categories of the thread */
categories?: Maybe<Array<Maybe<ThreadCategory>>>;
/** The media categories of the thread */
mediaCategories?: Maybe<Array<Maybe<Media>>>;
};
/** Forum Thread */
export type ThreadBodyArgs = {
asHtml?: Maybe<Scalars['Boolean']>;
};
/** A forum thread category */
export type ThreadCategory = {
__typename?: 'ThreadCategory';
/** The id of the category */
id: Scalars['Int'];
/** The name of the category */
name: Scalars['String'];
};
/** Forum Thread Comment */
export type ThreadComment = {
__typename?: 'ThreadComment';
/** The id of the comment */
id: Scalars['Int'];
/** The user id of the comment's owner */
userId?: Maybe<Scalars['Int']>;
/** The id of thread the comment belongs to */
threadId?: Maybe<Scalars['Int']>;
/** The text content of the comment (Markdown) */
comment?: Maybe<Scalars['String']>;
/** The amount of likes the comment has */
likeCount: Scalars['Int'];
/** If the currently authenticated user liked the comment */
isLiked?: Maybe<Scalars['Boolean']>;
/** The url for the comment page on the AniList website */
siteUrl?: Maybe<Scalars['String']>;
/** The time of the comments creation */
createdAt: Scalars['Int'];
/** The time of the comments last update */
updatedAt: Scalars['Int'];
/** The thread the comment belongs to */
thread?: Maybe<Thread>;
/** The user who created the comment */
user?: Maybe<User>;
/** The users who liked the comment */
likes?: Maybe<Array<Maybe<User>>>;
/** The comment's child reply comments */
childComments?: Maybe<Scalars['Json']>;
};
/** Forum Thread Comment */
export type ThreadCommentCommentArgs = {
asHtml?: Maybe<Scalars['Boolean']>;
};
/** Notification for when a thread comment is liked */
export type ThreadCommentLikeNotification = {
__typename?: 'ThreadCommentLikeNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The id of the user who liked to the activity */
userId: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The id of the activity which was liked */
commentId: Scalars['Int'];
/** The notification context text */
context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The thread that the relevant comment belongs to */
thread?: Maybe<Thread>;
/** The thread comment that was liked */
comment?: Maybe<ThreadComment>;
/** The user who liked the activity */
user?: Maybe<User>;
};
/** Notification for when authenticated user is @ mentioned in a forum thread comment */
export type ThreadCommentMentionNotification = {
__typename?: 'ThreadCommentMentionNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The id of the user who mentioned the authenticated user */
userId: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The id of the comment where mentioned */
commentId: Scalars['Int'];
/** The notification context text */
context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The thread that the relevant comment belongs to */
thread?: Maybe<Thread>;
/** The thread comment that included the @ mention */
comment?: Maybe<ThreadComment>;
/** The user who mentioned the authenticated user */
user?: Maybe<User>;
};
/** Notification for when a user replies to your forum thread comment */
export type ThreadCommentReplyNotification = {
__typename?: 'ThreadCommentReplyNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The id of the user who create the comment reply */
userId: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The id of the reply comment */
commentId: Scalars['Int'];
/** The notification context text */
context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The thread that the relevant comment belongs to */
thread?: Maybe<Thread>;
/** The reply thread comment */
comment?: Maybe<ThreadComment>;
/** The user who replied to the activity */
user?: Maybe<User>;
};
/** Thread comments sort enums */
export enum ThreadCommentSort {
Id = 'ID',
IdDesc = 'ID_DESC',
}
/** Notification for when a user replies to a subscribed forum thread */
export type ThreadCommentSubscribedNotification = {
__typename?: 'ThreadCommentSubscribedNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The id of the user who commented on the thread */
userId: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The id of the new comment in the subscribed thread */
commentId: Scalars['Int'];
/** The notification context text */
context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The thread that the relevant comment belongs to */
thread?: Maybe<Thread>;
/** The reply thread comment */
comment?: Maybe<ThreadComment>;
/** The user who replied to the subscribed thread */
user?: Maybe<User>;
};
/** Notification for when a thread is liked */
export type ThreadLikeNotification = {
__typename?: 'ThreadLikeNotification';
/** The id of the Notification */
id: Scalars['Int'];
/** The id of the user who liked to the activity */
userId: Scalars['Int'];
/** The type of notification */
type?: Maybe<NotificationType>;
/** The id of the thread which was liked */
threadId: Scalars['Int'];
/** The notification context text */
context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
createdAt?: Maybe<Scalars['Int']>;
/** The thread that the relevant comment belongs to */
thread?: Maybe<Thread>;
/** The liked thread comment */
comment?: Maybe<ThreadComment>;
/** The user who liked the activity */
user?: Maybe<User>;
};
/** Thread sort enums */
export enum ThreadSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Title = 'TITLE',
TitleDesc = 'TITLE_DESC',
CreatedAt = 'CREATED_AT',
CreatedAtDesc = 'CREATED_AT_DESC',
UpdatedAt = 'UPDATED_AT',
UpdatedAtDesc = 'UPDATED_AT_DESC',
RepliedAt = 'REPLIED_AT',
RepliedAtDesc = 'REPLIED_AT_DESC',
ReplyCount = 'REPLY_COUNT',
ReplyCountDesc = 'REPLY_COUNT_DESC',
ViewCount = 'VIEW_COUNT',
ViewCountDesc = 'VIEW_COUNT_DESC',
IsSticky = 'IS_STICKY',
SearchMatch = 'SEARCH_MATCH',
}
/** A user */
export type User = {
__typename?: 'User';
/** The id of the user */
id: Scalars['Int'];
/** The name of the user */
name: Scalars['String'];
/** The bio written by user (Markdown) */
about?: Maybe<Scalars['String']>;
/** The user's avatar images */
avatar?: Maybe<UserAvatar>;
/** The user's banner images */
bannerImage?: Maybe<Scalars['String']>;
/** If the authenticated user if following this user */
isFollowing?: Maybe<Scalars['Boolean']>;
/** If this user if following the authenticated user */
isFollower?: Maybe<Scalars['Boolean']>;
/** If the user is blocked by the authenticated user */
isBlocked?: Maybe<Scalars['Boolean']>;
bans?: Maybe<Scalars['Json']>;
/** The user's general options */
options?: Maybe<UserOptions>;
/** The user's media list options */
mediaListOptions?: Maybe<MediaListOptions>;
/** The users favourites */
favourites?: Maybe<Favourites>;
/** The users anime & manga list statistics */
statistics?: Maybe<UserStatisticTypes>;
/** The number of unread notifications the user has */
unreadNotificationCount?: Maybe<Scalars['Int']>;
/** The url for the user page on the AniList website */
siteUrl?: Maybe<Scalars['String']>;
/** The donation tier of the user */
donatorTier?: Maybe<Scalars['Int']>;
/** Custom donation badge text */
donatorBadge?: Maybe<Scalars['String']>;
/** The user's moderator roles if they are a site moderator */
moderatorRoles?: Maybe<Array<Maybe<ModRole>>>;
/** When the user's account was created. (Does not exist for accounts created before 2020) */
createdAt?: Maybe<Scalars['Int']>;
/** When the user's data was last updated */
updatedAt?: Maybe<Scalars['Int']>;
/**
* The user's statistics
* @deprecated Deprecated. Replaced with statistics field.
*/
stats?: Maybe<UserStats>;
/**
* If the user is a moderator or data moderator
* @deprecated Deprecated. Replaced with moderatorRoles field.
*/
moderatorStatus?: Maybe<Scalars['String']>;
};
/** A user */
export type UserAboutArgs = {
asHtml?: Maybe<Scalars['Boolean']>;
};
/** A user */
export type UserFavouritesArgs = {
page?: Maybe<Scalars['Int']>;
};
/** A user's activity history stats. */
export type UserActivityHistory = {
__typename?: 'UserActivityHistory';
/** The day the activity took place (Unix timestamp) */
date?: Maybe<Scalars['Int']>;
/** The amount of activity on the day */
amount?: Maybe<Scalars['Int']>;
/** The level of activity represented on a 1-10 scale */
level?: Maybe<Scalars['Int']>;
};
/** A user's avatars */
export type UserAvatar = {
__typename?: 'UserAvatar';
/** The avatar of user at its largest size */
large?: Maybe<Scalars['String']>;
/** The avatar of user at medium size */
medium?: Maybe<Scalars['String']>;
};
export type UserCountryStatistic = {
__typename?: 'UserCountryStatistic';
count: Scalars['Int'];
meanScore: Scalars['Float'];
minutesWatched: Scalars['Int'];
chaptersRead: Scalars['Int'];
mediaIds: Array<Maybe<Scalars['Int']>>;
country?: Maybe<Scalars['CountryCode']>;
};
export type UserFormatStatistic = {
__typename?: 'UserFormatStatistic';
count: Scalars['Int'];
meanScore: Scalars['Float'];
minutesWatched: Scalars['Int'];
chaptersRead: Scalars['Int'];
mediaIds: Array<Maybe<Scalars['Int']>>;
format?: Maybe<MediaFormat>;
};
export type UserGenreStatistic = {
__typename?: 'UserGenreStatistic';
count: Scalars['Int'];
meanScore: Scalars['Float'];
minutesWatched: Scalars['Int'];
chaptersRead: Scalars['Int'];
mediaIds: Array<Maybe<Scalars['Int']>>;
genre?: Maybe<Scalars['String']>;
};
export type UserLengthStatistic = {
__typename?: 'UserLengthStatistic';
count: Scalars['Int'];
meanScore: Scalars['Float'];
minutesWatched: Scalars['Int'];
chaptersRead: Scalars['Int'];
mediaIds: Array<Maybe<Scalars['Int']>>;
length?: Maybe<Scalars['String']>;
};
/** User data for moderators */
export type UserModData = {
__typename?: 'UserModData';
alts?: Maybe<Array<Maybe<User>>>;
bans?: Maybe<Scalars['Json']>;
ip?: Maybe<Scalars['Json']>;
counts?: Maybe<Scalars['Json']>;
privacy?: Maybe<Scalars['Int']>;
email?: Maybe<Scalars['String']>;
};
/** A user's general options */
export type UserOptions = {
__typename?: 'UserOptions';
/** The language the user wants to see media titles in */
titleLanguage?: Maybe<UserTitleLanguage>;
/** Whether the user has enabled viewing of 18+ content */
displayAdultContent?: Maybe<Scalars['Boolean']>;
/** Whether the user receives notifications when a show they are watching aires */
airingNotifications?: Maybe<Scalars['Boolean']>;
/** Profile highlight color (blue, purple, pink, orange, red, green, gray) */
profileColor?: Maybe<Scalars['String']>;
/** Notification options */
notificationOptions?: Maybe<Array<Maybe<NotificationOption>>>;
/** The user's timezone offset (Auth user only) */
timezone?: Maybe<Scalars['String']>;
/** Minutes between activity for them to be merged together. 0 is Never, Above 2 weeks (20160 mins) is Always. */
activityMergeTime?: Maybe<Scalars['Int']>;
/** The language the user wants to see staff and character names in */
staffNameLanguage?: Maybe<UserStaffNameLanguage>;
};
export type UserReleaseYearStatistic = {
__typename?: 'UserReleaseYearStatistic';
count: Scalars['Int'];
meanScore: Scalars['Float'];
minutesWatched: Scalars['Int'];
chaptersRead: Scalars['Int'];
mediaIds: Array<Maybe<Scalars['Int']>>;
releaseYear?: Maybe<Scalars['Int']>;
};
export type UserScoreStatistic = {
__typename?: 'UserScoreStatistic';
count: Scalars['Int'];
meanScore: Scalars['Float'];
minutesWatched: Scalars['Int'];
chaptersRead: Scalars['Int'];
mediaIds: Array<Maybe<Scalars['Int']>>;
score?: Maybe<Scalars['Int']>;
};
/** User sort enums */
export enum UserSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Username = 'USERNAME',
UsernameDesc = 'USERNAME_DESC',
WatchedTime = 'WATCHED_TIME',
WatchedTimeDesc = 'WATCHED_TIME_DESC',
ChaptersRead = 'CHAPTERS_READ',
ChaptersReadDesc = 'CHAPTERS_READ_DESC',
SearchMatch = 'SEARCH_MATCH',
}
/** The language the user wants to see staff and character names in */
export enum UserStaffNameLanguage {
/** The romanization of the staff or character's native name, with western name ordering */
RomajiWestern = 'ROMAJI_WESTERN',
/** The romanization of the staff or character's native name */
Romaji = 'ROMAJI',
/** The staff or character's name in their native language */
Native = 'NATIVE',
}
export type UserStaffStatistic = {
__typename?: 'UserStaffStatistic';
count: Scalars['Int'];
meanScore: Scalars['Float'];
minutesWatched: Scalars['Int'];
chaptersRead: Scalars['Int'];
mediaIds: Array<Maybe<Scalars['Int']>>;
staff?: Maybe<Staff>;
};
export type UserStartYearStatistic = {
__typename?: 'UserStartYearStatistic';
count: Scalars['Int'];
meanScore: Scalars['Float'];
minutesWatched: Scalars['Int'];
chaptersRead: Scalars['Int'];
mediaIds: Array<Maybe<Scalars['Int']>>;
startYear?: Maybe<Scalars['Int']>;
};
export type UserStatisticTypes = {
__typename?: 'UserStatisticTypes';
anime?: Maybe<UserStatistics>;
manga?: Maybe<UserStatistics>;
};
export type UserStatistics = {
__typename?: 'UserStatistics';
count: Scalars['Int'];
meanScore: Scalars['Float'];
standardDeviation: Scalars['Float'];
minutesWatched: Scalars['Int'];
episodesWatched: Scalars['Int'];
chaptersRead: Scalars['Int'];
volumesRead: Scalars['Int'];
formats?: Maybe<Array<Maybe<UserFormatStatistic>>>;
statuses?: Maybe<Array<Maybe<UserStatusStatistic>>>;
scores?: Maybe<Array<Maybe<UserScoreStatistic>>>;
lengths?: Maybe<Array<Maybe<UserLengthStatistic>>>;
releaseYears?: Maybe<Array<Maybe<UserReleaseYearStatistic>>>;
startYears?: Maybe<Array<Maybe<UserStartYearStatistic>>>;
genres?: Maybe<Array<Maybe<UserGenreStatistic>>>;
tags?: Maybe<Array<Maybe<UserTagStatistic>>>;
countries?: Maybe<Array<Maybe<UserCountryStatistic>>>;
voiceActors?: Maybe<Array<Maybe<UserVoiceActorStatistic>>>;
staff?: Maybe<Array<Maybe<UserStaffStatistic>>>;
studios?: Maybe<Array<Maybe<UserStudioStatistic>>>;
};
export type UserStatisticsFormatsArgs = {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<UserStatisticsSort>>>;
};
export type UserStatisticsStatusesArgs = {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<UserStatisticsSort>>>;
};
export type UserStatisticsScoresArgs = {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<UserStatisticsSort>>>;
};
export type UserStatisticsLengthsArgs = {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<UserStatisticsSort>>>;
};
export type UserStatisticsReleaseYearsArgs = {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<UserStatisticsSort>>>;
};
export type UserStatisticsStartYearsArgs = {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<UserStatisticsSort>>>;
};
export type UserStatisticsGenresArgs = {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<UserStatisticsSort>>>;
};
export type UserStatisticsTagsArgs = {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<UserStatisticsSort>>>;
};
export type UserStatisticsCountriesArgs = {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<UserStatisticsSort>>>;
};
export type UserStatisticsVoiceActorsArgs = {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<UserStatisticsSort>>>;
};
export type UserStatisticsStaffArgs = {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<UserStatisticsSort>>>;
};
export type UserStatisticsStudiosArgs = {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<Array<Maybe<UserStatisticsSort>>>;
};
/** User statistics sort enum */
export enum UserStatisticsSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Count = 'COUNT',
CountDesc = 'COUNT_DESC',
Progress = 'PROGRESS',
ProgressDesc = 'PROGRESS_DESC',
MeanScore = 'MEAN_SCORE',
MeanScoreDesc = 'MEAN_SCORE_DESC',
}
/** A user's statistics */
export type UserStats = {
__typename?: 'UserStats';
/** The amount of anime the user has watched in minutes */
watchedTime?: Maybe<Scalars['Int']>;
/** The amount of manga chapters the user has read */
chaptersRead?: Maybe<Scalars['Int']>;
activityHistory?: Maybe<Array<Maybe<UserActivityHistory>>>;
animeStatusDistribution?: Maybe<Array<Maybe<StatusDistribution>>>;
mangaStatusDistribution?: Maybe<Array<Maybe<StatusDistribution>>>;
animeScoreDistribution?: Maybe<Array<Maybe<ScoreDistribution>>>;
mangaScoreDistribution?: Maybe<Array<Maybe<ScoreDistribution>>>;
animeListScores?: Maybe<ListScoreStats>;
mangaListScores?: Maybe<ListScoreStats>;
favouredGenresOverview?: Maybe<Array<Maybe<GenreStats>>>;
favouredGenres?: Maybe<Array<Maybe<GenreStats>>>;
favouredTags?: Maybe<Array<Maybe<TagStats>>>;
favouredActors?: Maybe<Array<Maybe<StaffStats>>>;
favouredStaff?: Maybe<Array<Maybe<StaffStats>>>;
favouredStudios?: Maybe<Array<Maybe<StudioStats>>>;
favouredYears?: Maybe<Array<Maybe<YearStats>>>;
favouredFormats?: Maybe<Array<Maybe<FormatStats>>>;
};
export type UserStatusStatistic = {
__typename?: 'UserStatusStatistic';
count: Scalars['Int'];
meanScore: Scalars['Float'];
minutesWatched: Scalars['Int'];
chaptersRead: Scalars['Int'];
mediaIds: Array<Maybe<Scalars['Int']>>;
status?: Maybe<MediaListStatus>;
};
export type UserStudioStatistic = {
__typename?: 'UserStudioStatistic';
count: Scalars['Int'];
meanScore: Scalars['Float'];
minutesWatched: Scalars['Int'];
chaptersRead: Scalars['Int'];
mediaIds: Array<Maybe<Scalars['Int']>>;
studio?: Maybe<Studio>;
};
export type UserTagStatistic = {
__typename?: 'UserTagStatistic';
count: Scalars['Int'];
meanScore: Scalars['Float'];
minutesWatched: Scalars['Int'];
chaptersRead: Scalars['Int'];
mediaIds: Array<Maybe<Scalars['Int']>>;
tag?: Maybe<MediaTag>;
};
/** The language the user wants to see media titles in */
export enum UserTitleLanguage {
/** The romanization of the native language title */
Romaji = 'ROMAJI',
/** The official english title */
English = 'ENGLISH',
/** Official title in it's native language */
Native = 'NATIVE',
/** The romanization of the native language title, stylised by media creator */
RomajiStylised = 'ROMAJI_STYLISED',
/** The official english title, stylised by media creator */
EnglishStylised = 'ENGLISH_STYLISED',
/** Official title in it's native language, stylised by media creator */
NativeStylised = 'NATIVE_STYLISED',
}
export type UserVoiceActorStatistic = {
__typename?: 'UserVoiceActorStatistic';
count: Scalars['Int'];
meanScore: Scalars['Float'];
minutesWatched: Scalars['Int'];
chaptersRead: Scalars['Int'];
mediaIds: Array<Maybe<Scalars['Int']>>;
voiceActor?: Maybe<Staff>;
characterIds: Array<Maybe<Scalars['Int']>>;
};
/** User's year statistics */
export type YearStats = {
__typename?: 'YearStats';
year?: Maybe<Scalars['Int']>;
amount?: Maybe<Scalars['Int']>;
meanScore?: Maybe<Scalars['Int']>;
};
export type SearchAnimeQueryVariables = Exact<{
search?: Maybe<Scalars['String']>;
type?: Maybe<MediaType>;
}>;
export type SearchAnimeQuery = { __typename?: 'Query' } & {
Media?: Maybe<
{ __typename?: 'Media' } & Pick<
Media,
| 'description'
| 'season'
| 'seasonYear'
| 'status'
| 'averageScore'
| 'episodes'
| 'source'
| 'genres'
| 'isAdult'
> & {
title?: Maybe<
{ __typename?: 'MediaTitle' } & Pick<MediaTitle, 'userPreferred'>
>;
coverImage?: Maybe<
{ __typename?: 'MediaCoverImage' } & Pick<MediaCoverImage, 'medium'>
>;
}
>;
};
export type SearchCharQueryVariables = Exact<{
charName?: Maybe<Scalars['String']>;
}>;
export type SearchCharQuery = { __typename?: 'Query' } & {
Character?: Maybe<
{ __typename?: 'Character' } & Pick<
Character,
'description' | 'age' | 'gender' | 'siteUrl'
> & {
name?: Maybe<
{ __typename?: 'CharacterName' } & Pick<
CharacterName,
'full' | 'native'
>
>;
image?: Maybe<
{ __typename?: 'CharacterImage' } & Pick<CharacterImage, 'large'>
>;
dateOfBirth?: Maybe<
{ __typename?: 'FuzzyDate' } & Pick<
FuzzyDate,
'year' | 'month' | 'day'
>
>;
}
>;
};
export type SearchMangaQueryVariables = Exact<{
search?: Maybe<Scalars['String']>;
type?: Maybe<MediaType>;
}>;
export type SearchMangaQuery = { __typename?: 'Query' } & {
Media?: Maybe<
{ __typename?: 'Media' } & Pick<
Media,
| 'description'
| 'status'
| 'averageScore'
| 'genres'
| 'chapters'
| 'volumes'
| 'source'
| 'isAdult'
> & {
title?: Maybe<
{ __typename?: 'MediaTitle' } & Pick<MediaTitle, 'userPreferred'>
>;
startDate?: Maybe<
{ __typename?: 'FuzzyDate' } & Pick<
FuzzyDate,
'year' | 'month' | 'day'
>
>;
endDate?: Maybe<
{ __typename?: 'FuzzyDate' } & Pick<
FuzzyDate,
'year' | 'month' | 'day'
>
>;
coverImage?: Maybe<
{ __typename?: 'MediaCoverImage' } & Pick<MediaCoverImage, 'medium'>
>;
}
>;
};
export const SearchAnimeDocument = gql`
query searchAnime($search: String, $type: MediaType) {
Media(search: $search, type: $type) {
title {
userPreferred
}
description(asHtml: false)
season
seasonYear
status
averageScore
episodes
source
coverImage {
medium
}
genres
isAdult
}
}
`;
export const SearchCharDocument = gql`
query searchChar($charName: String) {
Character(search: $charName) {
name {
full
native
}
image {
large
}
description(asHtml: true)
age
gender
dateOfBirth {
year
month
day
}
siteUrl
}
}
`;
export const SearchMangaDocument = gql`
query searchManga($search: String, $type: MediaType) {
Media(search: $search, type: $type) {
title {
userPreferred
}
description(asHtml: true)
startDate {
year
month
day
}
endDate {
year
month
day
}
status
averageScore
coverImage {
medium
}
genres
chapters
volumes
source
isAdult
}
}
`;
export type SdkFunctionWrapper = <T>(
action: (requestHeaders?: Record<string, string>) => Promise<T>,
operationName: string,
) => Promise<T>;
const defaultWrapper: SdkFunctionWrapper = (action, _operationName) => action();
export function getSdk(
client: GraphQLClient,
withWrapper: SdkFunctionWrapper = defaultWrapper,
) {
return {
searchAnime(
variables?: SearchAnimeQueryVariables,
requestHeaders?: Dom.RequestInit['headers'],
): Promise<SearchAnimeQuery> {
return withWrapper(
(wrappedRequestHeaders) =>
client.request<SearchAnimeQuery>(SearchAnimeDocument, variables, {
...requestHeaders,
...wrappedRequestHeaders,
}),
'searchAnime',
);
},
searchChar(
variables?: SearchCharQueryVariables,
requestHeaders?: Dom.RequestInit['headers'],
): Promise<SearchCharQuery> {
return withWrapper(
(wrappedRequestHeaders) =>
client.request<SearchCharQuery>(SearchCharDocument, variables, {
...requestHeaders,
...wrappedRequestHeaders,
}),
'searchChar',
);
},
searchManga(
variables?: SearchMangaQueryVariables,
requestHeaders?: Dom.RequestInit['headers'],
): Promise<SearchMangaQuery> {
return withWrapper(
(wrappedRequestHeaders) =>
client.request<SearchMangaQuery>(SearchMangaDocument, variables, {
...requestHeaders,
...wrappedRequestHeaders,
}),
'searchManga',
);
},
};
}
export type Sdk = ReturnType<typeof getSdk>;
<file_sep>export const DEFAULT_SHIRITORI_MIN_LEN = 4;
export const DEFAULT_SHIRITORI_HAND = 5;
<file_sep>export enum BlockingLevel {
channel = 1,
guild,
selfChannel,
selfGuild,
none,
}
<file_sep>import { User } from 'discord.js';
import { mock } from 'jest-mock-extended';
import { mocked } from 'ts-jest/utils';
import { prisma } from '../prismaClient';
import { forRibbons, redis } from '../redisClient';
import { UserProvider } from './userProvider';
jest.mock('../redisClient');
const mockRedis = mocked(redis, true);
const userProvider = new UserProvider(prisma, mockRedis);
const mockUserProps = { id: '1', tag: '#1' };
const mockUser = { ...mock<User>(), ...mockUserProps };
afterAll(async () => {
await prisma.user.deleteMany();
await prisma.$disconnect();
});
describe('#getRibbons', () => {
const findUnique = jest.spyOn(prisma.user, 'findUnique');
afterEach(() => {
findUnique.mockReset();
mockRedis.get.mockReset();
});
afterAll(() => {
findUnique.mockRestore();
});
test('should search in redis', async () => {
await userProvider.getRibbons(mockUser as any);
expect(mockRedis.get).toBeCalledTimes(1);
});
describe('found in cache', () => {
beforeEach(() => {
mockRedis.get.mockResolvedValueOnce('420');
});
test('should not hit db', async () => {
await userProvider.getRibbons(mockUser as any);
expect(findUnique).not.toBeCalled();
});
test('should return value given by redis', async () => {
const res = await userProvider.getRibbons(mockUser as any);
expect(res).toBe(420);
});
test('should extend ttl by 60 seconds', async () => {
await userProvider.getRibbons(mockUser as any);
expect(mockRedis.expire).toBeCalledWith(forRibbons(mockUser.id), 60);
});
});
describe('not in cache', () => {
beforeEach(() => {
mockRedis.get.mockResolvedValueOnce(null);
});
test('should hit the db', async () => {
findUnique.mockResolvedValueOnce({} as any);
await userProvider.getRibbons(mockUser as any);
expect(findUnique).toBeCalledTimes(1);
});
describe('found in db', () => {
beforeEach(() => {
findUnique.mockResolvedValueOnce({ ribbons: 420 } as any);
});
test('should return the value from db', async () => {
const res = await userProvider.getRibbons(mockUser as any);
expect(res).toBe(420);
});
test('should cache the retrieved value', async () => {
await userProvider.getRibbons(mockUser as any);
expect(mockRedis.set).toBeCalledWith(
forRibbons(mockUser.id),
420,
'ex',
60,
);
});
});
describe('not found in db', () => {
beforeEach(() => {
findUnique.mockResolvedValueOnce({} as any);
});
test('returns 0', async () => {
const res = await userProvider.getRibbons(mockUser as any);
expect(res).toBe(0);
});
test('caches 0', async () => {
await userProvider.getRibbons(mockUser as any);
expect(mockRedis.set).toBeCalledWith(
forRibbons(mockUser.id),
0,
'ex',
60,
);
});
});
});
});
describe('#incrRibbons', () => {
afterEach(async () => {
await prisma.user.deleteMany();
});
test('should try an error if a negative incrby is given', () => {
return expect(
userProvider.incrRibbons(mockUser as any, -10),
).rejects.toThrow();
});
test('should cache the value from db', async () => {
const upsert = jest.spyOn(prisma.user, 'upsert');
upsert.mockResolvedValueOnce({ ribbons: 10 } as any);
await userProvider.incrRibbons(mockUser as any, 10);
expect(mockRedis.set).toBeCalledWith(forRibbons(mockUser.id), 10, 'ex', 60);
upsert.mockRestore();
});
describe('user does not exist', () => {
test('should create the user', async () => {
const _user = await prisma.user.findUnique({
where: { userId: mockUser.id },
});
expect(_user).toBeNull();
await userProvider.incrRibbons(mockUser as any, 10);
const created = await prisma.user.findUnique({
where: { userId: mockUser.id },
});
expect(created).toMatchObject({ userId: '1', ribbons: 10 });
});
});
describe('user exists', () => {
const data = { userId: '1', tag: '#1', ribbons: 10 };
beforeEach(async () => {
await prisma.user.create({ data });
});
test('increment the ribbon count', async () => {
await userProvider.incrRibbons(mockUser as any, 10);
const res = await prisma.user.findUnique({
where: { userId: mockUser.id },
});
expect(res).toMatchObject({ ...data, ribbons: 20 });
});
});
});
describe('#decrRibbons', () => {
afterEach(async () => {
await prisma.user.deleteMany();
});
test('caches to redis with 60 seconds ttl', async () => {
const $transaction = jest.spyOn(prisma, '$transaction');
$transaction.mockResolvedValueOnce([1, { ribbons: 10 }]);
await userProvider.decrRibbons(mockUser as any, 10);
expect(mockRedis.set).toBeCalledWith(forRibbons(mockUser.id), 10, 'ex', 60);
$transaction.mockRestore();
});
describe('a negative decrby is given', () => {
test('throws an error', () => {
expect(userProvider.decrRibbons(mockUser as any, -1)).rejects.toThrow();
});
});
describe('decrby more than current stock', () => {
beforeEach(async () => {
await prisma.user.create({
data: { userId: mockUser.id, tag: mockUser.tag, ribbons: 10 },
});
});
test('sets to zero', async () => {
await userProvider.decrRibbons(mockUser as any, 20);
const res = await prisma.user.findUnique({
where: { userId: mockUser.id },
select: { ribbons: true },
});
expect(res?.ribbons).toBe(0);
});
});
describe('decrby less than current stock', () => {
beforeEach(async () => {
await prisma.user.create({
data: { userId: mockUser.id, tag: mockUser.tag, ribbons: 10 },
});
});
test('decreases correctly', async () => {
await userProvider.decrRibbons(mockUser as any, 5);
const res = await prisma.user.findUnique({
where: { userId: mockUser.id },
select: { ribbons: true },
});
expect(res?.ribbons).toBe(5);
});
});
describe('user does not exist', () => {
test('should create the user with 0 ribbons', async () => {
const _user = await prisma.user.findUnique({
where: { userId: mockUser.id },
});
expect(_user).toBeNull(); // check that its not in the db
await userProvider.decrRibbons(mockUser as any, 10);
const res = await prisma.user.findUnique({
where: { userId: mockUser.id },
select: { ribbons: true },
});
expect(res?.ribbons).toBe(0);
});
});
});
describe('#getGlobalTopRibbons', () => {
beforeAll(async () => {
await prisma.user.createMany({
data: [
{ userId: '1', tag: '#1', ribbons: 1 },
{ userId: '2', tag: '#2', ribbons: 2 },
{ userId: '3', tag: '#3', ribbons: 3 },
],
});
});
afterAll(async () => {
await prisma.user.deleteMany();
});
test('returns in correct order', async () => {
const res = await userProvider.getGlobalTopRibbons();
expect(res).toEqual([
{ tag: '#3', ribbons: 3 },
{ tag: '#2', ribbons: 2 },
{ tag: '#1', ribbons: 1 },
]);
});
});
describe('#getTopRibbonsForUsers', () => {
const mockUser1 = { ...mock<User>(), id: '1', tag: '#1', ribbons: 1 };
const mockUser2 = { ...mock<User>(), id: '2', tag: '#2', ribbons: 2 };
const mockUser3 = { ...mock<User>(), id: '3', tag: '#3', ribbons: 3 };
beforeAll(async () => {
await prisma.user.createMany({
data: [
{ userId: '1', tag: '#1', ribbons: 1 },
{ userId: '2', tag: '#2', ribbons: 2 },
{ userId: '3', tag: '#3', ribbons: 3 },
],
});
});
afterAll(async () => {
await prisma.user.deleteMany();
});
test('returns in right order', async () => {
const res = await userProvider.getTopRibbonsForUsers([
mockUser1 as any,
mockUser2,
mockUser3,
]);
expect(res).toEqual([
{ tag: '#3', ribbons: 3 },
{ tag: '#2', ribbons: 2 },
{ tag: '#1', ribbons: 1 },
]);
});
});
<file_sep>interface GameState {
gameTitle: string;
channelId: string;
}
export type { GameState };
<file_sep>import { CmdCategory } from '.prisma/client';
import { Command } from '../../types/command';
import type { IBlogPost } from './utils/types';
import { blogKey, redis } from '../../data/redisClient';
import { baseEmbed } from '../../shared/embeds';
import { white_check_mark } from '../../shared/assets';
import { setCooldown } from '../../lib/cooldownManager';
// TODO: enable anonymous posts
const blogPost = new Command({
name: 'blog-post',
aliases: ['bp', 'post'],
description: 'Post a post on the Chika blog.',
args: [{ name: 'post', optional: false, multi: true }],
category: CmdCategory.FUN,
userCooldown: 10000,
async execute(context, args) {
const { channel, author } = context;
// get the post
const message = args.join(' ');
const toStore: IBlogPost = {
author: author.tag,
time: Date.now(),
message,
};
// store the post
redis
.pipeline()
.lpush(blogKey, JSON.stringify(toStore))
.ltrim(blogKey, 0, 50)
.exec();
setCooldown(author.id, this.name, this.userCooldown!);
// ack
channel.send(
baseEmbed().setDescription(
`${white_check_mark} **${author.username}** posted!`,
),
);
},
});
export default blogPost;
<file_sep>export const chika_detective_png = 'https://i.imgur.com/Ftwr8nw.png';
export const chika_crying_png = 'https://i.imgur.com/yFjZVZN.png';
export const chika_peeking_png = 'https://i.imgur.com/Clk50IV.png';
export const chika_rap_png = 'https://i.imgur.com/AaSi3so.png';
export const chika_pointing_png = 'https://i.imgur.com/OsVZH9j.png';
export const ishigami_cake_png = 'https://i.imgur.com/y7STJ8k.jpg';
export const kaguya_pfp_png = 'https://i.imgur.com/i9Z2E31.png';
export const chika_beating_yu_gif = 'https://i.imgur.com/kYTIHbE.gif';
export const kaguya_sleep_gif = 'https://i.imgur.com/4y1lORB.gif';
export const chika_spin_gif = 'https://i.imgur.com/xMDHNDz.gif';
export const shiritori_rules_jpg = 'https://i.imgur.com/rzgelx8.jpg';
export const balloon_rules_jpg = 'https://i.imgur.com/0aoRzOA.jpg';
export const unknown_png = 'https://i.imgur.com/odkVxpH.png';
export const white_check_mark = '✅';
export const red_cross = '❌';
export const right_arrow = '➡️';
export const left_arrow = '⬅️';
export const ribbon_react = '851852767239864320';
export const ribbon_emoji = '<:chikaribbon:851852767239864320>';
export const chika_pink = '#f2d5da';
export const kaguya_red = '#b32819';
<file_sep>import { CmdCategory } from '@prisma/client';
import type { TextChannel } from 'discord.js';
import { getSdk, MediaType } from '../../generated/anilist';
import { lightErrorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { sendNotFoundError } from './embeds/errors';
import { mangaInfoEmbed } from './embeds/mangaInfoEmbed';
import { client } from './graphql/aniListClient';
const manga = new Command({
name: 'manga',
description: 'Look up info for a manga.',
args: [{ name: 'title', multi: true }],
category: CmdCategory.UTILITY,
async execute(message, args) {
const { channel } = message;
const search = args.join(' ');
const sdk = getSdk(client);
sdk
.searchManga({ search, type: MediaType.Manga })
.then((result) => {
if (!result.Media) {
sendNotFoundError(search, channel);
return;
}
if (channel.isText()) {
const textChannel = channel as TextChannel;
if (!textChannel.nsfw && result.Media.isAdult) {
channel.send(
lightErrorEmbed(
`This manga is marked as 18+! I can only show this in a NSFW channel.`,
),
);
return;
}
}
const {
averageScore,
coverImage,
description,
genres,
status,
title,
source,
startDate,
endDate,
volumes,
chapters,
} = result.Media;
channel.send(
mangaInfoEmbed({
coverImage: coverImage?.medium,
title: title?.userPreferred,
description: description!,
status,
genres,
averageScore,
startDate,
endDate,
source,
volumes,
chapters,
}),
);
})
.catch((err) => {
console.error(err);
sendNotFoundError(search, channel);
});
},
});
export default manga;
<file_sep>import { PrismaPromise } from '@prisma/client';
import type { Collection } from 'discord.js';
import { prisma } from '../data/prismaClient';
import type { Command } from '../types/command';
export const seedCommands = async (commands: Collection<string, Command>) => {
const jobs: PrismaPromise<any>[] = [
// FIXME: this shit doesn't work
// it's gonna remove all the relations between Guild and Command
prisma.$executeRaw(
`TRUNCATE TABLE "Command", "Arg" RESTART IDENTITY CASCADE`,
),
];
commands.forEach(({ name, args, aliases, description, category }) =>
jobs.push(
prisma.command.create({
data: {
name,
description,
category,
aliases,
args: {
createMany: {
data: args.map(({ name: argName, optional, multi }) => ({
name: argName,
optional: !!optional,
multi: !!multi,
})),
skipDuplicates: true,
},
},
},
}),
),
);
try {
await prisma.$transaction(jobs);
console.log(`commands have been written to ${process.env.DATABASE_URL}`);
} catch (err) {
console.error(err);
}
};
<file_sep>import type { Client } from 'discord.js';
import { activityUpdaters } from '../lib/activityUpdaters';
export function setIntervals(client: Client) {
client.setInterval(() => {
const updater =
activityUpdaters[Math.floor(Math.random() * activityUpdaters.length)];
updater(client);
}, 1000 * 60 * 15);
}
<file_sep>import { CmdCategory } from '@prisma/client';
import { TextChannel } from 'discord.js';
import { getSdk, MediaType } from '../../generated/anilist';
import { lightErrorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { animeInfoEmbed } from './embeds/animeInfoEmbed';
import { sendNotFoundError } from './embeds/errors';
import { client } from './graphql/aniListClient';
const anime = new Command({
name: 'anime',
description: 'Look up info for an anime.',
args: [{ name: 'title', multi: true }],
category: CmdCategory.UTILITY,
async execute(message, args) {
const { channel } = message;
const search = args.join(' ');
const sdk = getSdk(client);
sdk
.searchAnime({ search, type: MediaType.Anime })
.then((result) => {
if (!result.Media) {
sendNotFoundError(search, channel);
return;
}
if (channel.isText()) {
const textChannel = channel as TextChannel;
if (!textChannel.nsfw && result.Media.isAdult) {
channel.send(
lightErrorEmbed(
`This anime is marked as 18+! I can only show this in a NSFW channel.`,
),
);
return;
}
}
const {
averageScore,
coverImage,
description,
source,
episodes,
genres,
status,
season,
seasonYear,
title,
} = result.Media;
channel.send(
animeInfoEmbed({
coverImage: coverImage?.medium,
title: title?.userPreferred,
description: description!,
episodes,
status,
genres,
source,
averageScore,
season,
seasonYear,
}),
);
})
.catch((err) => {
console.error(err);
sendNotFoundError(search, channel);
});
},
});
export default anime;
<file_sep>import { CmdCategory } from '@prisma/client';
import { redis } from '../../data/redisClient';
import { baseEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
const ping = new Command({
name: 'ping',
description: 'Say hello to Chika bot.',
category: CmdCategory.FUN,
args: [],
async execute(message) {
const { channel, author } = message;
// TODO actually use the redis ping
channel.send(
baseEmbed().setDescription(
`Yo ${author.username}, Love Detective Chika here!`,
),
);
redis.ping().catch((err) => console.error(err));
},
});
export default ping;
<file_sep>import _ from 'lodash';
import { mocked } from 'ts-jest/utils';
import {
DEFAULT_SHIRITORI_HAND,
DEFAULT_SHIRITORI_MIN_LEN,
} from '../../games/shiritori/utils/defaults';
import { prisma } from '../prismaClient';
import { forShiritoriHand, forShiritoriMinLen, redis } from '../redisClient';
import { ShiritoriProvider } from './shiritoriProvider';
jest.mock('../redisClient');
const mockRedis = mocked(redis, true);
const shiritoriProvider = new ShiritoriProvider(prisma, mockRedis);
afterEach(async () => {
await prisma.guild.deleteMany();
await mockRedis.set.mockReset();
await mockRedis.expire.mockReset();
});
afterAll(() => prisma.$disconnect());
describe('#setMinLen', () => {
test('throws if negative minLen provided', async () => {
return expect(shiritoriProvider.setMinLen('1', -1)).rejects.toThrow();
});
test('caches to redis', async () => {
await shiritoriProvider.setMinLen('1', 1);
expect(mockRedis.set).toBeCalledWith(forShiritoriMinLen('1'), 1, 'ex', 60);
mockRedis.set.mockClear();
});
describe('guild exists in db', () => {
beforeEach(async () => {
await prisma.guild.create({
data: { guildId: '1', shiritori: { create: { minLen: 1 } } },
});
});
test('update the shiritori minLen', async () => {
await shiritoriProvider.setMinLen('1', 2);
const res = await prisma.shiritori.findUnique({
where: { guildId: '1' },
select: { minLen: true },
});
expect(res?.minLen).toBe(2);
});
});
describe('guild does not exist in db', () => {
test('creates the guild with minLen', async () => {
const _guild = await prisma.guild.findUnique({ where: { guildId: '1' } });
expect(_guild).toBeNull(); // check null
await shiritoriProvider.setMinLen('1', 1);
const res = await prisma.shiritori.findUnique({
where: { guildId: '1' },
select: { minLen: true },
});
expect(res?.minLen).toBe(1);
});
});
});
describe('#getMinLen', () => {
test('returns default if no guild id is given', async () => {
const res = await shiritoriProvider.getMinLen();
expect(res).toBe(DEFAULT_SHIRITORI_MIN_LEN);
});
describe('found in redis', () => {
beforeEach(() => {
mockRedis.get.mockResolvedValueOnce('1');
});
afterEach(() => {
mockRedis.get.mockReset();
});
test('returns the value from redis as number', async () => {
const res = await shiritoriProvider.getMinLen('1');
expect(res).toBe(1);
});
test('extends ttl of key', async () => {
await shiritoriProvider.getMinLen('1');
expect(mockRedis.expire).toBeCalledWith(forShiritoriMinLen('1'), 60);
});
});
describe('not in redis', () => {
beforeEach(() => {
mockRedis.get.mockResolvedValueOnce(null);
});
describe('not in db either', () => {
test('returns the default value', async () => {
const _sh = await prisma.shiritori.findUnique({
where: { guildId: '1' },
});
expect(_sh).toBeNull(); // check null
const res = await shiritoriProvider.getMinLen('1');
expect(res).toBe(DEFAULT_SHIRITORI_MIN_LEN);
});
test('caches the default value', async () => {
await shiritoriProvider.getMinLen('1');
expect(mockRedis.set).toBeCalledWith(
forShiritoriMinLen('1'),
DEFAULT_SHIRITORI_MIN_LEN,
'ex',
60,
);
});
});
describe('found in db', () => {
beforeEach(async () => {
await prisma.guild.create({
data: { guildId: '1', shiritori: { create: { minLen: 2 } } },
});
});
test('returns the value from the db', async () => {
const res = await shiritoriProvider.getMinLen('1');
expect(res).toBe(2);
});
test('caches the value', async () => {
await shiritoriProvider.getMinLen('1');
expect(mockRedis.set).toBeCalledWith(
forShiritoriMinLen('1'),
2,
'ex',
60,
);
});
});
});
});
describe('#setHandSize', () => {
test('throws if hand size less than 1', () => {
return expect(shiritoriProvider.setHandSize('1', 0)).rejects.toThrow();
});
test('caches to redis', async () => {
const size = _.random(1, 10);
await shiritoriProvider.setHandSize('1', size);
expect(mockRedis.set).toBeCalledWith(forShiritoriHand('1'), size, 'ex', 60);
});
describe('guild exists with settings', () => {
const size = _.random(1, 10);
beforeEach(async () => {
await prisma.guild.create({
data: { guildId: '1', shiritori: { create: { handSize: 1 } } },
});
});
test('updates the settings', async () => {
await shiritoriProvider.setHandSize('1', size);
const res = await prisma.shiritori.findUnique({
where: { guildId: '1' },
select: { handSize: true },
});
expect(res?.handSize).toBe(size);
});
});
describe('guild does not exist in settings', () => {
const size = _.random(1, 10);
test('creates guild with handSize', async () => {
const _sh = await prisma.shiritori.findUnique({
where: { guildId: '1' },
});
expect(_sh).toBeNull();
await shiritoriProvider.setHandSize('1', size);
const res = await prisma.shiritori.findUnique({
where: { guildId: '1' },
select: { handSize: true },
});
expect(res?.handSize).toBe(size);
});
});
});
describe('#getHandSize', () => {
describe('found in redis', () => {
beforeEach(() => {
mockRedis.get.mockResolvedValueOnce('1');
});
test('returns the value from redis as number', async () => {
const res = await shiritoriProvider.getHandSize('1');
expect(res).toBe(1);
});
test('extends ttl of key', async () => {
await shiritoriProvider.getHandSize('1');
expect(mockRedis.expire).toBeCalledWith(forShiritoriHand('1'), 60);
});
});
describe('not in redis', () => {
beforeEach(() => {
mockRedis.get.mockResolvedValueOnce(null);
});
describe('not in db either', () => {
test('returns the default value', async () => {
const _sh = await prisma.shiritori.findUnique({
where: { guildId: '1' },
});
expect(_sh).toBeNull(); // check null
const res = await shiritoriProvider.getHandSize('1');
expect(res).toBe(DEFAULT_SHIRITORI_HAND);
});
test('caches the default value', async () => {
await shiritoriProvider.getHandSize('1');
expect(mockRedis.set).toBeCalledWith(
forShiritoriHand('1'),
DEFAULT_SHIRITORI_HAND,
'ex',
60,
);
});
});
describe('found in db', () => {
beforeEach(async () => {
await prisma.guild.create({
data: { guildId: '1', shiritori: { create: { handSize: 2 } } },
});
});
test('returns the value from the db', async () => {
const res = await shiritoriProvider.getHandSize('1');
expect(res).toBe(2);
});
test('caches the value', async () => {
await shiritoriProvider.getHandSize('1');
expect(mockRedis.set).toBeCalledWith(
forShiritoriHand('1'),
2,
'ex',
60,
);
});
});
});
});
<file_sep>import type { Message } from 'discord.js';
import { BlockingLevel } from '../../types/blockingLevel';
import type { Game } from '../../types/game';
export const checkAndBlock = (game: Game, message: Message): Promise<void> => {
const {
guild,
channel,
client: {
cache: { inGameStates },
},
} = message;
let inGame;
switch (game.blockingLevel) {
case BlockingLevel.channel:
inGame = inGameStates.get(channel.id);
if (inGame)
return Promise.reject(
`There is already a game of **${inGame}** being played in this channel.`,
);
inGameStates.set(channel.id, game.displayTitle);
break;
case BlockingLevel.guild:
if (!guild)
return Promise.reject(
`${game.displayTitle} can only be played in a guild.`,
);
inGame = inGameStates.get(guild.id);
if (inGame)
return Promise.reject(
`There is already a game of **${inGame}** being played in this server.`,
);
inGameStates.set(guild.id, game.displayTitle);
break;
case BlockingLevel.selfChannel:
inGame = inGameStates.get(`${game.title}:${channel.id}`);
if (inGame)
return Promise.reject(
`There is already a game of **${inGame}** being played in this channel.`,
);
inGameStates.set(`${game.title}:${channel.id}`, game.displayTitle);
break;
case BlockingLevel.selfGuild:
if (!guild)
return Promise.reject(
`${game.displayTitle} can only be played in a guild.`,
);
inGame = inGameStates.get(`${game.title}:${guild.id}`);
if (inGame)
return Promise.reject(
`There is already a game of **${inGame}** being played in this channel.`,
);
inGameStates.set(`${game.title}:${guild.id}`, game.displayTitle);
break;
default:
break;
}
return Promise.resolve();
};
export const isGameActive = (game: Game, message: Message): boolean => {
const {
client: {
cache: { inGameStates },
},
channel,
guild,
} = message;
let gameActive = false;
switch (game.blockingLevel) {
case BlockingLevel.channel:
gameActive = !!inGameStates.get(channel.id);
break;
case BlockingLevel.guild:
if (!guild)
throw new Error(`${game.displayTitle} is a guild-level game.`);
gameActive = !!inGameStates.get(guild.id);
break;
case BlockingLevel.selfChannel:
gameActive = !!inGameStates.get(`${game.title}:${channel.id}`);
break;
case BlockingLevel.selfGuild:
if (!guild)
throw new Error(`${game.displayTitle} is a guild-level game.`);
gameActive = !!inGameStates.get(`${game.title}:${guild.id}`);
break;
default:
break;
}
return gameActive;
};
export const unblock = (game: Game, message: Message): void => {
const {
client: {
cache: { inGameStates },
},
channel,
guild,
} = message;
switch (game.blockingLevel) {
case BlockingLevel.channel:
inGameStates.delete(channel.id);
break;
case BlockingLevel.guild:
if (!guild)
throw new Error(`${game.displayTitle} is a guild-level game.`);
inGameStates.delete(guild.id);
break;
case BlockingLevel.selfChannel:
inGameStates.delete(`${game.title}:${channel.id}`);
break;
case BlockingLevel.selfGuild:
if (!guild)
throw new Error(`${game.displayTitle} is a guild-level game.`);
inGameStates.delete(`${game.title}:${guild.id}`);
break;
default:
break;
}
};
export const blindUnblock = (message: Message): Promise<boolean> => {
const {
channel,
guild,
client: {
cache: { inGameStates },
},
} = message;
if (inGameStates.delete(channel.id)) return Promise.resolve(true);
if (guild && inGameStates.delete(guild.id)) return Promise.resolve(true);
return Promise.reject(`I couldn't find an active game.`);
};
<file_sep>import type { Message } from 'discord.js';
import { filterMessage } from '../../../lib/validateMessages';
import { unblock } from '../../utils/manageState';
import type { Balloon } from '../balloon';
import { postGameBalloon } from './postGame';
import type { BalloonState } from './types';
export const createBalloonListener = (state: BalloonState, game: Balloon) => {
const { players, channelId } = state;
const listener = (message: Message) => {
const { content, client } = message;
if (
!filterMessage(message, {
authors: players.map((user) => user),
channelId,
})
) {
client.once('message', listener);
return;
}
state.currentVolume += content.length;
if (state.currentVolume > state.tolerance) {
unblock(game, message);
postGameBalloon(message, players);
return;
}
client.once('message', listener);
};
return listener;
};
<file_sep>import { CmdCategory } from '@prisma/client';
import { redisQueue } from '../../data/redisClient';
import { lightErrorEmbed, withAuthorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { sendMusicOnlyInGuild } from './utils/embeds';
const clear = new Command({
name: 'clear',
description: 'Clears all tracks from the queue.',
aliases: ['c'],
category: CmdCategory.MUSIC,
args: [],
async execute(message) {
const { guild, channel, author } = message;
if (!guild) {
sendMusicOnlyInGuild(channel);
return;
}
redisQueue.del(guild.id).then((res) => {
if (!res) {
channel.send(lightErrorEmbed('Queue is already empty.'));
return;
}
channel.send(withAuthorEmbed(author).setTitle('Queue has been cleared.'));
});
},
});
export default clear;
<file_sep>export function shuffle<T>(arr: T[]): T[] {
const carr = [...arr];
let currentIndex = carr.length;
while (currentIndex) {
currentIndex -= 1;
const randomIndex = Math.floor(Math.random() * currentIndex);
[carr[currentIndex], carr[randomIndex]] = [
carr[randomIndex],
carr[currentIndex],
];
}
return carr;
}
<file_sep>import { CmdCategory } from '@prisma/client';
import { redisQueue as tracks } from '../../data/redisClient';
import { lightErrorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { sendMusicOnlyInGuild, sendQueue } from './utils/embeds';
// TODO use paginated embed for this
const queue = new Command({
name: 'queue',
description: 'Display tracks in the queue.',
aliases: ['q'],
args: [],
category: CmdCategory.MUSIC,
async execute(message) {
const { channel, client, guild } = message;
if (!guild) {
sendMusicOnlyInGuild(channel);
return;
}
tracks.lrange(guild.id, 0, -1).then((_tracks) => {
const audioUtils = client.cache.audioUtils.get(guild.id);
if (_tracks.length === 0 && !audioUtils) {
channel.send(
lightErrorEmbed(
'There are no tracks queued, and nothing is playing now.',
),
);
return;
}
sendQueue(channel, _tracks.map((track) => JSON.parse(track)) || [], {
nowPlaying: audioUtils?.nowPlaying,
isPaused: audioUtils?.dispatcher.paused,
current: audioUtils?.dispatcher.streamTime,
});
});
},
});
export default queue;
<file_sep>import { CmdCategory } from '.prisma/client';
import axios from 'axios';
import {
Collection,
DiscordAPIError,
TextChannel,
User,
Webhook,
} from 'discord.js';
import { userProvider } from '../../data/providers/userProvider';
import { forKaguyaInput, forKaguyaResponse } from '../../data/redisClient';
import { kaguya_pfp_png } from '../../shared/assets';
import { sendInsufficientRibbons } from '../../shared/embeds';
import { Command } from '../../types/command';
import {
cacheInput,
cacheResponse,
genChatData,
handleHuggingFaceError,
handleWebhookAPIError,
} from './utils/chatbot';
const kaguya = new Command({
name: 'kaguya',
aliases: ['ka'],
args: [{ name: 'your_message', optional: false, multi: true }],
category: CmdCategory.FUN,
description: 'Chat with Kaguya, who has an IQ above 3.',
async execute(message, args) {
const { channel, author } = message;
if (!(channel instanceof TextChannel)) return;
let hooks: Collection<string, Webhook>;
try {
hooks = await channel.fetchWebhooks();
} catch (err) {
// no webhook permissions, most likely
handleWebhookAPIError(channel, err);
return;
}
// try and find Kaguya in the collection of webhooks
let kaguya = hooks.find(
(wh) =>
wh.name === 'Kaguya' &&
wh.owner instanceof User &&
wh.owner.id === process.env.BOT_USER_ID,
);
if (!kaguya) {
// try to create a webhook for Kaguya
// TODO: add error handling if the channel has already maxed out
kaguya = await channel
.createWebhook('Kaguya', {
avatar: kaguya_pfp_png,
})
.catch((err: DiscordAPIError) => {
return handleWebhookAPIError(channel, err);
});
}
// we couldn't create a webhook
if (!kaguya) {
return;
}
const text = args.join(' ');
const ribbonCost = text.length;
const ribbonStock = await userProvider.getRibbons(author);
if (ribbonCost > ribbonStock) {
sendInsufficientRibbons(channel, ribbonCost, ribbonStock);
return;
}
const data = await genChatData(channel.id, {
input: forKaguyaInput,
response: forKaguyaResponse,
text,
});
axios
.post(process.env.HUGGING_FACE_KAGUYA, data, {
headers: {
Authorization: `Bearer ${process.env.HUGGING_FACE_KAGUYA_KEY}`,
},
})
.then((res) => {
const reply = res.data.generated_text;
kaguya!.send(`> ${text}\n${reply}`);
cacheInput(channel.id, text, forKaguyaInput);
cacheResponse(channel.id, reply, forKaguyaResponse);
userProvider.decrRibbons(author, ribbonCost);
})
.catch((err) => {
handleHuggingFaceError(kaguya!, err, 'ka', text);
});
},
});
export default kaguya;
<file_sep>import type { User } from 'discord.js';
import he from 'he';
import { chika_detective_png } from '../../../shared/assets';
import {
baseEmbed,
cryingEmbed,
lightErrorEmbed,
withAuthorEmbed,
} from '../../../shared/embeds';
import { GenericChannel } from '../../../types/command';
import { QueueItem } from '../../../types/queue';
import { secToString, stringToSec } from './helpers';
export const toUrlString = (
title: string,
link: string,
truncate?: number,
): string => {
const decodedTitle = he.decode(title);
if (!truncate) {
return `[${decodedTitle
.replace(/\[/g, '\uFF3B')
.replace(/\]/g, '\uFF3D')}](${link})`;
}
return `[${decodedTitle
.substring(0, truncate)
.replace(/\[/g, '\uFF3B')
.replace(/\]/g, '\uFF3D')} ${
title.length > truncate ? '...' : ''
}](${link})`;
};
export const trackLinkAndDuration = (
title: string,
url: string,
duration: string,
options?: { truncate?: number },
) => `${toUrlString(title, url, options?.truncate)} [${duration}]`;
export const genPlayBar = (current: number, total: string) => {
// current is in milliseconds
const totalMillis = stringToSec(total) * 1000;
const currentMin = secToString(Math.floor(current / 1000));
const cursor = Math.floor((current / totalMillis) * 29);
return `${currentMin} ${'-'.repeat(cursor)}o${'-'.repeat(
29 - cursor,
)} ${total}`;
};
interface sendNowPlayingOptions {
streamTime: number;
}
export const sendNowPlaying = async (
channel: GenericChannel,
videoData: QueueItem,
withBar?: sendNowPlayingOptions,
) => {
const { title, url, duration, thumbnailURL } = videoData;
channel.send(
baseEmbed()
.setTitle('Now playing...')
.setDescription(
`${toUrlString(title, url)}${
withBar ? `\n${genPlayBar(withBar.streamTime, duration)}` : ''
}`,
)
.setThumbnail(thumbnailURL),
);
};
export const sendNoVideo = async (channel: GenericChannel, searched: string) =>
channel.send(
cryingEmbed()
.setTitle('Sorry...')
.setDescription(
`I couldn't find anything at **${searched}**! It might be a restricted video.`,
),
);
export const sendCannotPlay = async (
channel: GenericChannel,
title: string,
url: string,
) =>
channel.send(
cryingEmbed()
.setTitle('Sorry...')
.setDescription(`I couldn't play [${title}](${url})!`)
.setFooter(
"It might be a restricted video, or Chika's music player might be down.",
),
);
export const sendNotInVoiceChannel = async (channel: GenericChannel) =>
channel.send(lightErrorEmbed('Join a voice channel first!'));
interface sendAddedToQueueOptions {
videoData: QueueItem;
author: User;
}
export const sendAddedToQueue = async (
channel: GenericChannel,
{
videoData: { title, url, duration, thumbnailURL },
author,
}: sendAddedToQueueOptions,
) =>
channel.send(
withAuthorEmbed(author)
.setTitle('Added to queue!')
.setDescription(trackLinkAndDuration(title, url, duration))
.setThumbnail(thumbnailURL),
);
export const sendMusicOnlyInGuild = async (channel: GenericChannel) =>
channel.send(lightErrorEmbed('I can only play music for you in a server!'));
export const toListString = (
arr: string[],
options?: { noNum?: boolean },
): string => {
const withCount = arr.map(
(item, i) => `${options?.noNum ? '' : `\`${i + 1}\``} ${item}`,
);
return withCount.join(`\n`);
};
interface sendQueueCurrentTrack {
nowPlaying?: QueueItem;
isPaused?: boolean;
current?: number;
}
export const sendQueue = async (
channel: GenericChannel,
tracks: QueueItem[],
info: sendQueueCurrentTrack,
) => {
const { current, isPaused, nowPlaying } = info;
const urlTracks = tracks
.slice(0, 10)
.map((track) => toUrlString(track.title, track.url, 40));
const now = nowPlaying
? `${isPaused ? ':pause_button:' : ':arrow_forward:'} ${toUrlString(
nowPlaying.title,
nowPlaying.url,
30,
)} [${secToString(Math.floor(current! / 1000))} / ${nowPlaying.duration}]`
: '';
const partialEmbed = baseEmbed()
.setTitle('Tracks Queued')
.setDescription(toListString(urlTracks))
.setThumbnail(tracks[0]?.thumbnailURL || nowPlaying!.thumbnailURL)
.setFooter(
`${tracks.length} ${tracks.length === 1 ? 'track' : 'tracks'} queued ${
tracks.length > 10 ? '(showing first 10)' : ''
} | ${
nowPlaying
? `One track ${isPaused ? 'paused' : 'playing'}`
: `Nothing playing now`
}`,
);
if (nowPlaying) {
channel.send(partialEmbed.addField(`Now playing`, now));
return;
}
channel.send(partialEmbed);
};
interface sendRepeatProps {
author: User;
videoData: QueueItem;
}
export const sendRepeat = async (
channel: GenericChannel,
{
author,
videoData: { title, url, thumbnailURL, duration },
}: sendRepeatProps,
) =>
channel.send(
withAuthorEmbed(author)
.setTitle('Track will repeat!')
.setDescription(trackLinkAndDuration(title, url, duration))
.setThumbnail(thumbnailURL),
);
export const sendSearchResults = (
channel: GenericChannel,
res: QueueItem[],
) => {
const urlTitles = res.map((videoData) =>
toUrlString(videoData.title, videoData.url, 36),
);
channel.send(
baseEmbed()
.setTitle('I found these tracks:')
.setDescription(toListString(urlTitles))
.setThumbnail(chika_detective_png)
.setFooter("Send me the track's number and I'll add it to the queue!"),
);
};
export const sendNoVoicePermissions = (channel: GenericChannel) =>
channel.send(
lightErrorEmbed(`Please give me permissions to join your voice chat.`),
);
export const sendFinishedAllTracks = (channel: GenericChannel) =>
channel.send(
baseEmbed().setDescription(`All requested tracks have finished playing.`),
);
<file_sep>import { CmdCategory } from '.prisma/client';
import { shiritoriProvider } from '../../data/providers/shiritoriProvider';
import {
baseEmbed,
lightErrorEmbed,
sendNotInGuild,
} from '../../shared/embeds';
import { Command } from '../../types/command';
const shiritoriHand = new Command({
name: 'shiritori-hand',
aliases: ['sh-hand'],
args: [{ name: 'size', optional: true, multi: false }],
category: CmdCategory.GAMES,
description: 'Check or set the initial hand size in Shiritori.',
async execute(ctx, args) {
const { channel, guild } = ctx;
if (!guild) {
sendNotInGuild(channel);
return;
}
const [_newSize] = args;
if (!_newSize) {
const currHand = await shiritoriProvider.getHandSize(guild.id);
channel.send(
baseEmbed().setDescription(
`Current starting hand size: **${currHand}**`,
),
);
return;
}
const newSize = parseInt(_newSize, 10);
if (Number.isNaN(newSize)) {
channel.send(lightErrorEmbed('Please give me a valid number!'));
return;
}
if (newSize < 0) {
channel.send(lightErrorEmbed('Haha how does that even work.'));
return;
}
if (newSize > 12) {
channel.send(lightErrorEmbed('I can only issue a maximum of 12 cards!'));
return;
}
await shiritoriProvider.setHandSize(guild.id, newSize);
channel.send(
baseEmbed().setDescription(
`The hand size for Shiritori has been set to **${newSize}**!
This will apply on the next game.`,
),
);
},
});
export default shiritoriHand;
<file_sep>import { CmdCategory } from '@prisma/client';
import { red_cross, white_check_mark } from '../../shared/assets';
import { baseEmbed, sendNotInGuild } from '../../shared/embeds';
import { Command } from '../../types/command';
const poll = new Command({
name: 'poll',
args: [{ name: 'question', multi: true }],
category: CmdCategory.UTILITY,
description: 'Show your enthusiasm for democracy.',
aliases: ['vote'],
async execute(message, args) {
const { guild, channel, author } = message;
if (!guild) {
sendNotInGuild(channel);
return;
}
const pollQn = args.join(' ');
channel
.send(
baseEmbed()
.setThumbnail(author.displayAvatarURL())
.setDescription(`**${author.username}** wants to know...`)
.addField(pollQn, `Please react to vote!`),
)
.then(async (_message) => {
await _message
.react(white_check_mark)
.then(() => _message.react(red_cross));
});
},
});
export default poll;
<file_sep>import { CmdCategory } from '@prisma/client';
import { Command } from '../../types/command';
import { avatarEmbed } from './utils/embeds';
const avatar = new Command({
name: 'avatar',
description: "Retrieves users' avatars.",
category: CmdCategory.FUN,
args: [{ name: 'user', optional: true, multi: true }],
async execute(message) {
const { mentions, author, channel } = message;
if (!mentions.users.size) {
channel.send(avatarEmbed(author));
return;
}
mentions.users.forEach((user) => {
channel.send(avatarEmbed(user));
});
},
});
export default avatar;
<file_sep>import type { Client } from 'discord.js';
import { Collection } from 'discord.js';
import fs from 'fs';
import path from 'path';
import { Command } from '../types/command';
export const loadCommands = (): Client['commands'] => {
const commands = new Collection<string, Command>();
const commandFolders = fs.readdirSync(path.join(__dirname, '..', 'commands'));
commandFolders.forEach((folder) => {
const commandFiles = fs
.readdirSync(path.join(__dirname, '..', 'commands', folder))
.filter((filename) => filename.endsWith('.js'));
commandFiles.forEach((filename) => {
const command: Command =
// eslint-disable-next-line @typescript-eslint/no-var-requires
require(`../commands/${folder}/${filename}`).default;
commands.set(command.name, command);
});
});
return commands;
};
<file_sep>import { Message, TextChannel } from 'discord.js';
import { mock } from 'jest-mock-extended';
import { redis } from '../data/redisClient';
import { Command } from '../types/command';
import * as cooldownManager from './cooldownManager';
import { isOnCooldown } from './validateCooldowns';
jest.mock('../data/redisClient');
afterAll(() => {
return redis.quit();
});
describe('#isOnCooldown', () => {
const mockMessage = mock<Message>();
mockMessage.channel = mock<TextChannel>();
const channelSendSpy = jest.spyOn(mockMessage.channel, 'send');
const getCooldownSpy = jest.spyOn(cooldownManager, 'getCooldown');
beforeEach(() => {
getCooldownSpy.mockClear();
channelSendSpy.mockClear();
});
describe('if command has no cooldown set', () => {
const mockCommand = mock<Command>();
mockCommand.channelCooldown = undefined;
mockCommand.userCooldown = undefined;
it('should return false', () => {
return isOnCooldown(mockMessage, mockCommand).then((res) => {
expect(res).toBe(false);
});
});
it('should not call #getCooldown', () => {
return isOnCooldown(mockMessage, mockCommand).then(() => {
expect(getCooldownSpy).toBeCalledTimes(0);
});
});
});
describe('if command has channel cooldown', () => {
const mockCommand = mock<Command>();
mockCommand.channelCooldown = 10000;
mockCommand.userCooldown = undefined;
it('should call #getCooldown once', () => {
return isOnCooldown(mockMessage, mockCommand).then(() => {
expect(getCooldownSpy).toBeCalledTimes(1);
});
});
describe('and got ttl > 0', () => {
it('should return true', () => {
getCooldownSpy.mockResolvedValueOnce(1000);
return isOnCooldown(mockMessage, mockCommand).then((res) => {
expect(res).toBe(true);
});
});
it('should call channel#send once', () => {
getCooldownSpy.mockResolvedValueOnce(1000);
return isOnCooldown(mockMessage, mockCommand).then(() => {
expect(channelSendSpy).toBeCalledTimes(1);
});
});
});
describe('got ttl 0', () => {
it('should return false', () => {
getCooldownSpy.mockResolvedValueOnce(0);
return isOnCooldown(mockMessage, mockCommand).then((res) => {
expect(res).toBe(false);
});
});
it('should not call channel#send', () => {
return isOnCooldown(mockMessage, mockCommand).then(() => {
expect(channelSendSpy).toBeCalledTimes(0);
});
});
});
});
describe('if command has user cooldown', () => {
const mockCommand = mock<Command>();
mockCommand.userCooldown = 10000;
mockCommand.channelCooldown = undefined;
it('should call getCooldown once', () => {
return isOnCooldown(mockMessage, mockCommand).then(() => {
expect(getCooldownSpy).toBeCalledTimes(1);
});
});
describe('and found ttl', () => {
it('should return true', () => {
getCooldownSpy.mockResolvedValueOnce(1000);
return isOnCooldown(mockMessage, mockCommand).then((res) => {
expect(res).toBe(true);
});
});
it('should call channel#send once', () => {
getCooldownSpy.mockResolvedValueOnce(1000);
return isOnCooldown(mockMessage, mockCommand).then(() => {
expect(channelSendSpy).toBeCalledTimes(1);
});
});
});
});
});
<file_sep>import _ from 'lodash';
import {
Maybe,
MediaSeason,
MediaSource,
MediaStatus,
} from '../../../generated/anilist';
import { unknown_png } from '../../../shared/assets';
import { baseEmbed } from '../../../shared/embeds';
import { parseHtml } from '../../../lib/typography';
interface animeEmbedParams {
title: string | null | undefined;
description: string | null | undefined;
status: MediaStatus | null | undefined;
averageScore: number | null | undefined;
episodes: number | null | undefined;
coverImage: string | null | undefined;
genres: Maybe<string>[] | null | undefined;
season: MediaSeason | null | undefined;
seasonYear: number | null | undefined;
source: MediaSource | null | undefined;
}
export const animeInfoEmbed = (info: animeEmbedParams) => {
const {
coverImage,
title,
description,
episodes,
status,
genres,
source,
averageScore,
season,
seasonYear,
} = info;
return baseEmbed()
.setThumbnail(coverImage || unknown_png)
.setTitle(title)
.setDescription(
description ? parseHtml(description) : `*No description for this anime.*`,
)
.addFields([
{
name: ':film_frames: Status',
value: status ? _.capitalize(status.replace(/_/g, ' ')) : '?',
inline: true,
},
{
name: ':cherry_blossom: Season',
value:
seasonYear && season
? `${_.startCase(season.toLowerCase())} ${seasonYear}`
: '?',
inline: true,
},
])
.addField(':shinto_shrine: Genres', genres?.join(', ') || ':question:')
.addFields([
{
name: ':tv: Episodes',
value: `${episodes || '?'}`,
inline: true,
},
{
name: ':star: Rating',
value: averageScore ? `${averageScore}/100` : '?',
inline: true,
},
{
name: ':ramen: Sauce',
value: source
? _.startCase(source.replace(/_/g, ' ').toLowerCase())
: '?',
inline: true,
},
]);
};
<file_sep>import axios from 'axios';
export const checkWord = (word: string): Promise<boolean> => {
const uri = `http://api.datamuse.com/words?sp=${word}&max=1`;
// TODO catch errors properly
return axios
.get(uri)
.then((response) => response.data.length === 1)
.catch(() => false);
};
<file_sep>import type {
Message,
MessageEmbed,
MessageReaction,
Snowflake,
User,
} from 'discord.js';
import { Collection } from 'discord.js';
import { toListString } from '../commands/music/utils/embeds';
import { unblock } from '../games/utils/manageState';
import { red_cross, white_check_mark } from '../shared/assets';
import {
baseEmbed,
detectiveEmbed,
genericErrorEmbed,
lightErrorEmbed,
} from '../shared/embeds';
import { BlockingLevel } from './blockingLevel';
import type { GenericChannel } from './command';
import { stripIndents } from 'common-tags';
interface collectPlayersOptions {
onTimeoutAccept: (players: Collection<Snowflake, User>) => void;
onTimeoutReject?: () => void;
}
interface getOpponentResponseOptions {
onAccept: () => void;
onReject?: () => void;
}
export abstract class Game {
abstract title: string;
abstract displayTitle: string;
abstract minPlayerCount: number;
abstract maxPlayerCount: number;
abstract rules: MessageEmbed;
abstract sessionDuration: number; // in milliseconds
abstract pregame(message: Message): void;
abstract blockingLevel: BlockingLevel;
collectPlayers(message: Message, options: collectPlayersOptions) {
const { author, channel } = message;
const { onTimeoutAccept, onTimeoutReject } = options;
const partialEmbed = baseEmbed()
.setDescription(
`**${author.username}** wants to play **${this.displayTitle}**!`,
)
.addField(`To join`, `React to this message with the green check-mark.`);
channel
.send(
this.minPlayerCount === 1
? partialEmbed
: partialEmbed.setFooter(
`We need ${this.minPlayerCount - 1} more ${
this.minPlayerCount - 1 > 1 ? 'players' : 'player'
} to start.`,
),
)
.then(async (_message) => {
await _message.react(white_check_mark);
return _message
.awaitReactions(
(reaction: MessageReaction, user: User) =>
user.id !== author.id && reaction.emoji.name === white_check_mark,
{ maxUsers: this.maxPlayerCount - 1, time: 10000 },
)
.then(async (collected) => {
const reactors =
(await collected.first()?.users.fetch()) ||
new Collection<Snowflake, User>();
const players = reactors
.filter((user) => !user.bot)
.set(author.id, author);
if (players.size < this.minPlayerCount) {
return Promise.reject(new Error(`Insufficient players.`));
}
return Promise.resolve(players);
});
})
.then(
(players) => onTimeoutAccept(players),
() => {
unblock(this, message);
if (onTimeoutReject) {
onTimeoutReject();
return;
}
channel.send(
lightErrorEmbed(
`We don't have enough players to start **${this.displayTitle}**.`,
),
);
},
)
.catch((err) => {
console.error(err);
channel.send(genericErrorEmbed());
});
}
getOpponentResponse(
message: Message,
opponent: User,
options: getOpponentResponseOptions,
) {
const { channel, author } = message;
const { onAccept, onReject } = options;
channel
.send(
`${opponent.toString()}! **${
author.username
}** has challenged you to a game of **${
this.displayTitle
}**!\nDo you accept this challenge?`,
)
.then(async (_message) => {
await _message
.react(white_check_mark)
.then(() => _message.react(red_cross));
_message
.awaitReactions(
(reaction: MessageReaction, user: User) =>
user.id === opponent.id &&
(reaction.emoji.name === white_check_mark ||
reaction.emoji.name === red_cross),
{ time: 10000, max: 1 },
)
.then((collected) => {
const reaction = collected.first();
switch (reaction?.emoji.name) {
case white_check_mark:
onAccept();
break;
case red_cross:
unblock(this, message);
if (onReject) {
onReject();
} else {
channel.send(
`**${opponent.username}** does not want to play ${this.displayTitle}`,
);
}
break;
default:
unblock(this, message);
channel.send(
lightErrorEmbed(`No response from **${opponent.username}**.`),
);
break;
}
});
})
.catch((err) => {
console.error(err);
channel.send(genericErrorEmbed());
});
}
async sendParticipants(
channel: GenericChannel,
participants: User[],
options?: { startsInMessage: string },
) {
const players = participants.map((user) => user.toString());
return channel.send(
detectiveEmbed()
.setTitle(this.displayTitle)
.addField(`Players:`, toListString(players))
.addField(
`More info`,
stripIndents`
To review the rules of **${
this.displayTitle
}**, use \`${`${this.title}-rules`}\`.
\`${'stop-game'}\` will stop the game at anytime.
${options?.startsInMessage || "I'll start the game in 5 seconds!"}
`,
),
);
}
}
<file_sep>import type { Client, Collection, Guild, Message, User } from 'discord.js';
import { balloonProvider } from '../../data/providers/balloonProvider';
import { balloon_rules_jpg, ribbon_emoji } from '../../shared/assets';
import { baseEmbed } from '../../shared/embeds';
import { BlockingLevel } from '../../types/blockingLevel';
import { GenericChannel } from '../../types/command';
import { Game } from '../../types/game';
import { createBalloonListener } from './utils/listener';
import { BalloonState } from './utils/types';
export class Balloon extends Game {
title = 'balloon';
displayTitle = 'Balloon';
minPlayerCount = 2;
maxPlayerCount = 6;
sessionDuration = 1000 * 60 * 10;
blockingLevel = BlockingLevel.guild;
pregame(message: Message) {
const { channel, client, guild } = message;
this.collectPlayers(message, {
onTimeoutAccept: (players) => {
this.sendParticipants(
channel,
players.map((user) => user),
{
startsInMessage: `Carry on with your lives. ʕ•ᴥ•ʔ
Each time you send something, the balloon gets pumped. You'll know when it pops.`,
},
);
this.startGame(players, { channel, client, guild: guild! });
},
});
}
async startGame(
players: Collection<string, User>,
meta: { channel: GenericChannel; guild: Guild; client: Client },
) {
const { channel, client, guild } = meta;
const max = await balloonProvider.getMax(guild.id);
const min = await balloonProvider.getMin(guild.id);
const tolerance = Math.floor(Math.random() * (max - min) + min);
const initState: BalloonState = {
gameTitle: this.title,
channelId: channel.id,
currentVolume: 0,
tolerance,
players,
};
client.once('message', createBalloonListener(initState, this));
}
rules = baseEmbed()
.setTitle('Balloon :balloon:')
.setImage(balloon_rules_jpg)
.setFooter(`chapter 91 page 3`)
.addFields([
{
name: 'How it works',
value: `
Chika hands you a pump and a
balloon. Each character you send
pumps the balloon by a certain
amount.
The balloon will pop! once it
reaches its limit, which is randomly
chosen each round. The player
who pops it loses!`,
},
{
name: 'Player count',
value: `${this.minPlayerCount} - ${this.maxPlayerCount} players`,
},
{
name: 'Losing',
value: `
The player who pops the balloon
will pay ${ribbon_emoji} to all other players.`,
},
{
name: 'Options',
value: `
You may override the default
balloon's volume range for
the server:
\`balloon-min\`
Set lower bound for volume.
\`balloon-max\`
Set upper bound for volume.`,
},
]);
}
<file_sep>import { CmdCategory } from '@prisma/client';
import { helpExtraInfo } from '../../init/fullHelpEmbed';
import { badCommandsEmbed, baseEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
const help = new Command({
name: 'help',
description: 'Get a list of all commands, or look up specific commands.',
args: [{ name: 'commands', optional: true, multi: true }],
category: CmdCategory.UTILITY,
aliases: ['h'],
async execute({ channel, client: { commands, commandsHelp } }, args) {
if (!args.length || /^all$/i.test(args[0])) {
// send a list of all commands
channel.send(commandsHelp).then(() => channel.send(helpExtraInfo));
return;
}
// return info for a specific command
const unknownCommands: string[] = [];
args.forEach((arg) => {
const match = commands.find(
(command) => command.name === arg || !!command.aliases?.includes(arg),
);
if (match) {
const embed = baseEmbed()
.addField(match.name, match.description)
.addField('Usage', `\`${match.usage}\``, true);
if (match.aliases) {
const preTag = match.aliases.map((alias) => `\`${alias}\``);
embed.addField('Aliases', preTag.join(', '), true);
}
channel.send(embed);
return;
}
unknownCommands.push(arg);
});
if (unknownCommands.length) {
channel.send(badCommandsEmbed(...unknownCommands));
}
},
});
export default help;
<file_sep>import type { Message, Snowflake, User } from 'discord.js';
import { Collection } from 'discord.js';
import { shiritoriProvider } from '../../data/providers/shiritoriProvider';
import { shiritori_rules_jpg } from '../../shared/assets';
import { baseEmbed, lightErrorEmbed } from '../../shared/embeds';
import { BlockingLevel } from '../../types/blockingLevel';
import { Game } from '../../types/game';
import { sendTaggedSelfError } from '../utils/embeds';
import { genInitialCards } from './utils/cards';
import { shiritoriPlayerCardsEmbed } from './utils/embeds';
import { createOnceShiritoriListener } from './utils/listener';
import type { ShiritoriState } from './utils/types';
interface startShiritoriParams {
p1: User;
p2: User;
}
export class Shiritori extends Game {
title = 'shiritori';
displayTitle = 'Shiritori';
minPlayerCount = 2;
maxPlayerCount = 2;
sessionDuration = 1000 * 60 * 10; // 10 min in ms
blockingLevel = BlockingLevel.channel;
pregame(message: Message) {
const { channel, mentions, author } = message;
const taggedOpponent = mentions.users.first();
if (
process.env.NODE_ENV !== 'development' &&
taggedOpponent?.id === author.id
) {
sendTaggedSelfError(channel);
return;
}
if (!taggedOpponent) {
this.collectPlayers(message, {
onTimeoutAccept: (players) => {
const [p1, p2] = players.map((player) => player);
this.startGame(message, { p1, p2 });
},
});
return;
}
this.getOpponentResponse(message, taggedOpponent, {
onAccept: () =>
this.startGame(message, { p1: author, p2: taggedOpponent }),
onReject: () =>
channel.send(
lightErrorEmbed(
`**${taggedOpponent.username}** does not want to play Shiritori.`,
),
),
});
}
async startGame(message: Message, { p1, p2 }: startShiritoriParams) {
const { channel, client, guild } = message;
const size = await shiritoriProvider.getHandSize(guild!.id);
const { p1Cards, p2Cards, startingChar } = genInitialCards(size);
const cards = new Collection<Snowflake, string[]>();
cards.set(p1.id, p1Cards);
cards.set(p2.id, p2Cards);
const minLen = await shiritoriProvider.getMinLen(message.guild?.id);
const initState: ShiritoriState = {
gameTitle: 'shiritori',
cards,
channelId: channel.id,
p1,
p2,
startingChar,
minLen,
};
this.sendParticipants(channel, [p1, p2], {
startsInMessage: `Your words must have at least **${minLen}** ${
minLen === 1 ? 'letter' : 'letters'
}.
I'll reveal the first card in 5 seconds!`,
}).then(() => channel.send(shiritoriPlayerCardsEmbed(initState)));
setTimeout(() => {
client.once('message', createOnceShiritoriListener(initState, this)); // register the new listener
channel.send(`:regional_indicator_${initState.startingChar}:`);
}, 5000);
}
rules = baseEmbed()
.setTitle('Shiritori :u55b6:')
.addFields([
{
name: 'How it works',
value: `
Each player is issued 5 cards.
You must form a word which a) starts
with the last played card, b) ends
on one of your cards, and c) be at
least 4 characters long.
The game will start with a random
card.
`,
},
{
name: 'Player count',
value: '2',
},
{
name: 'To win',
value: `Be the first to clear all 5 cards!`,
},
{
name: 'Options',
value: `
You can override the default
minimum word length, as well as the
number of cards issued to each
player.
\`sh-min\`
Set the minimum word length.
\`sh-hand\`
Set the initial card count.`,
},
])
.setImage(shiritori_rules_jpg)
.setFooter(`chapter 188 page 4`);
}
<file_sep>import { CmdCategory } from '@prisma/client';
import { shiritoriGame } from '../../games/shiritori';
import { checkAndBlock } from '../../games/utils/manageState';
import { lightErrorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
const shiritori = new Command({
name: 'shiritori',
category: CmdCategory.GAMES,
description: 'Play a round of Shiritori.',
aliases: ['sh'],
args: [{ name: 'an_opponent', optional: true }],
async execute(message) {
const taggedCount = message.mentions.users.size;
if (taggedCount && taggedCount > 1) {
message.channel.send(
lightErrorEmbed(
`**Shiritori** is a 2-player game!\nPlease tag only one other player.`,
),
);
return;
}
checkAndBlock(shiritoriGame, message).then(
() => shiritoriGame.pregame(message),
(err) => message.channel.send(lightErrorEmbed(err)),
);
},
});
export default shiritori;
<file_sep>import { baseEmbed } from '../../../shared/embeds';
import type { ShiritoriState } from './types';
import { genCardsString } from './cards';
export const shiritoriPlayerCardsEmbed = ({ p1, p2, cards }: ShiritoriState) =>
baseEmbed()
.setTitle('Your cards!')
.addFields([
{
name: `**${p1.username}**'s cards`,
value: genCardsString(cards.get(p1.id)!),
},
{
name: `**${p2.username}**'s cards`,
value: genCardsString(cards.get(p2.id)!),
},
]);
<file_sep>import { stripIndents } from 'common-tags';
import { DiscordAPIError, Webhook } from 'discord.js';
import { redis, redisPrefixer } from '../../../data/redisClient';
import { lightErrorEmbed } from '../../../shared/embeds';
import { GenericChannel } from '../../../types/command';
import {
chatbotLimitError,
chatbotLoadingError,
chatbotTimeoutError,
} from './embeds';
import type { ChatbotChar, ChatbotInput } from './types';
interface IChatDataOptions {
input: redisPrefixer;
response: redisPrefixer;
text: string;
}
export async function genChatData(
channelId: string,
options: IChatDataOptions,
): Promise<string> {
const { input, response, text } = options;
const generated_responses = (
await redis.lrange(response(channelId), 0, -1)
).reverse();
const past_user_inputs = (
await redis.lrange(input(channelId), 0, -1)
).reverse();
const data: ChatbotInput = {
inputs: { text, generated_responses, past_user_inputs },
};
return JSON.stringify(data);
}
export function cacheInput(
channelId: string,
text: string,
prefixFn: redisPrefixer,
) {
const key = prefixFn(channelId);
redis.pipeline().lpush(key, text).ltrim(key, 0, 2).expire(key, 120).exec();
}
export function cacheResponse(
channelId: string,
response: string,
prefixFn: redisPrefixer,
) {
const key = prefixFn(channelId);
redis
.pipeline()
.lpush(key, response.replace(/[^\w\s]/gi, ''))
.ltrim(key, 0, 2)
.expire(key, 120)
.exec();
}
export function handleHuggingFaceError(
channelOrWebhook: GenericChannel | Webhook,
err: any,
char: ChatbotChar,
text?: string,
) {
console.error(err);
if (err.response?.data?.error?.includes(`is currently loading`)) {
if (channelOrWebhook instanceof Webhook) {
channelOrWebhook.send(text && `> ${text}`, {
embeds: [chatbotLoadingError(char)],
});
} else {
channelOrWebhook.send(text && `> ${text}`, {
embed: chatbotLoadingError(char),
});
}
} else if (err.response?.data?.error?.includes(`API usage limit reached`)) {
if (channelOrWebhook instanceof Webhook) {
channelOrWebhook.send(text && `> ${text}`, {
embeds: [chatbotLimitError(char)],
});
} else {
channelOrWebhook.send(text && `> ${text}`, {
embed: chatbotLimitError(char),
});
}
} else {
if (channelOrWebhook instanceof Webhook) {
channelOrWebhook.send(text && `> ${text}`, {
embeds: [chatbotTimeoutError(char)],
});
} else {
channelOrWebhook.send(text && `> ${text}`, {
embed: chatbotTimeoutError(char),
});
}
}
}
export function handleWebhookAPIError(
channel: GenericChannel,
err: DiscordAPIError,
) {
if (err.code === 50013) {
// we don't have permissions to manage webhooks
channel.send(
lightErrorEmbed(
stripIndents`
I need permissions to manage webhooks in this channel!
Otherwise I can't invite Kaguya here...`,
),
);
return undefined;
}
if (err.code === 30007) {
// they maxed out the number of webhooks
channel.send(
lightErrorEmbed(stripIndents`
This channel has already hit the maximum number of webhooks.
I can't invite Kaguya to this channel...`),
);
return undefined;
}
console.error(err);
return undefined;
}
<file_sep>-- CreateTable
CREATE TABLE "_CommandToGuild" (
"A" INTEGER NOT NULL,
"B" INTEGER NOT NULL
);
-- CreateIndex
CREATE UNIQUE INDEX "_CommandToGuild_AB_unique" ON "_CommandToGuild"("A", "B");
-- CreateIndex
CREATE INDEX "_CommandToGuild_B_index" ON "_CommandToGuild"("B");
-- AddForeignKey
ALTER TABLE "_CommandToGuild" ADD FOREIGN KEY ("A") REFERENCES "Command"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "_CommandToGuild" ADD FOREIGN KEY ("B") REFERENCES "Guild"("id") ON DELETE CASCADE ON UPDATE CASCADE;
<file_sep>import { mocked } from 'ts-jest/utils';
import { DEFAULT_PREFIX } from '../../shared/constants';
import { prisma } from '../prismaClient';
import { forPrefix, redis } from '../redisClient';
import { GuildProvider } from './guildProvider';
jest.mock('../redisClient');
const mockRedis = mocked(redis, true);
const guildProvider = new GuildProvider(prisma, mockRedis);
afterAll(() => prisma.$disconnect());
describe('#getPrefix', () => {
const findUnique = jest.spyOn(prisma.guild, 'findUnique');
afterAll(() => {
findUnique.mockRestore();
});
describe('prefix is cached', () => {
beforeEach(() => {
mockRedis.get.mockResolvedValue('prefix');
});
afterEach(() => {
mockRedis.expire.mockClear();
findUnique.mockClear();
});
mockRedis.get.mockResolvedValue('prefix');
test('prisma should not be called', async () => {
await guildProvider.getPrefix('guild-id');
expect(findUnique).not.toBeCalled();
});
test('redis should extend ttl', async () => {
await guildProvider.getPrefix('guild-id');
expect(mockRedis.expire).toBeCalledWith(forPrefix('guild-id'), 60);
});
test('should return the cached prefix', async () => {
const prefix = await guildProvider.getPrefix('guild-id');
expect(prefix).toBe('prefix');
});
});
describe('prefix is not cached', () => {
beforeEach(() => {
mockRedis.get.mockResolvedValue(null);
});
afterEach(() => {
mockRedis.set.mockClear();
findUnique.mockClear();
});
test('prisma should be called', async () => {
findUnique.mockResolvedValueOnce({} as any);
await guildProvider.getPrefix('guild-id');
expect(findUnique).toBeCalledTimes(1);
});
describe('and got result from db', () => {
beforeEach(() => {
findUnique.mockResolvedValue({
prefix: 'prefix',
} as any);
});
test('should cache in redis', async () => {
await guildProvider.getPrefix('guild-id');
expect(mockRedis.set).toBeCalledWith(
forPrefix('guild-id'),
'prefix',
'ex',
60,
);
});
test('returns the prefix', async () => {
const prefix = await guildProvider.getPrefix('guild-id');
expect(prefix).toBe('prefix');
});
});
describe('and could not get results from db', () => {
beforeEach(() => {
findUnique.mockResolvedValue({} as any); // no prefix set
});
test('returns the default prefix', async () => {
const prefix = await guildProvider.getPrefix('guild-id');
expect(prefix).toBe(DEFAULT_PREFIX);
});
test('caches the default prefix in redis', async () => {
await guildProvider.getPrefix('guild-id');
expect(mockRedis.set).toBeCalledWith(
forPrefix('guild-id'),
DEFAULT_PREFIX,
'ex',
60,
);
});
});
});
});
describe('#setPrefix', () => {
const guildId = 'g';
const upsert = jest.spyOn(prisma.guild, 'upsert');
afterEach(async () => {
await prisma.guild.deleteMany();
upsert.mockClear();
});
afterAll(() => {
upsert.mockRestore();
});
test('caches in redis', async () => {
await guildProvider.setPrefix('guild-id', 'p');
expect(mockRedis.set).toBeCalledWith(forPrefix('guild-id'), 'p', 'ex', 60);
});
test('uses upsert', async () => {
await guildProvider.setPrefix('guild-id', 'p');
expect(upsert).toBeCalledTimes(1);
});
describe('guild does not exist', () => {
test('inserts the guild', async () => {
// ensure the guild does not exist
const _guild = await prisma.guild.findUnique({ where: { guildId } });
expect(_guild).toBeNull();
await guildProvider.setPrefix(guildId, 'p');
const guild = await prisma.guild.findUnique({
where: { guildId },
select: { prefix: true },
});
expect(guild?.prefix).toBe('p');
});
});
describe('guild exists', () => {
test('updates the guild', async () => {
await prisma.guild.create({ data: { guildId, prefix: 'a' } });
await guildProvider.setPrefix(guildId, 'b');
const res = await prisma.guild.findUnique({
where: { guildId },
select: { prefix: true },
});
expect(res?.prefix).toBe('b');
});
});
});
<file_sep>import { CmdCategory } from '@prisma/client';
import { userProvider } from '../../data/providers/userProvider';
import { genericErrorEmbed, lightErrorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { MAX_TAKE } from './utils/defaults';
import { sendExceededMaxTake, sendTop } from './utils/embeds';
const globalTop = new Command({
name: 'global-top',
description: `Track down the top 1%.`,
args: [{ name: 'take', optional: true, multi: false }],
category: CmdCategory.CURRENCY,
aliases: ['gt'],
async execute(message, args) {
const { channel } = message;
let take;
const [count] = args;
if (count) {
const _take = parseInt(count, 10);
if (Number.isNaN(_take)) {
channel.send(lightErrorEmbed('Gimme a number yo.'));
return;
}
if (_take > MAX_TAKE) {
sendExceededMaxTake(channel);
return;
}
take = _take;
}
const top = await userProvider.getGlobalTopRibbons(take);
if (!top) {
channel.send(genericErrorEmbed());
return;
}
sendTop(channel, top);
},
});
export default globalTop;
<file_sep>import { CmdCategory } from '@prisma/client';
import { lightErrorEmbed, withAuthorEmbed } from '../../shared/embeds';
import { Command } from '../../types/command';
import { sendMusicOnlyInGuild, trackLinkAndDuration } from './utils/embeds';
const pause = new Command({
name: 'pause',
aliases: ['stop'],
description: 'Pause the current playback.',
category: CmdCategory.MUSIC,
args: [],
async execute(message) {
const { client, channel, guild, author } = message;
if (!guild) {
sendMusicOnlyInGuild(channel);
return;
}
const audioUtils = client.cache.audioUtils.get(guild.id);
if (!audioUtils?.dispatcher) {
channel.send(
lightErrorEmbed("There isn't anything playing right now..."),
);
return;
}
if (audioUtils.dispatcher.paused) {
channel.send(lightErrorEmbed('Playback is already paused!'));
return;
}
audioUtils.dispatcher.pause();
const { title, url, duration } = audioUtils.nowPlaying!;
channel.send(
withAuthorEmbed(author)
.setTitle(`:pause_button: Paused`)
.setDescription(trackLinkAndDuration(title, url, duration)),
);
},
});
export default pause;
<file_sep>import { PrismaClient } from '.prisma/client';
import { Redis } from 'ioredis';
import {
DEFAULT_MAX_BALLOON,
DEFAULT_MIN_BALLOON,
} from '../../games/balloon/utils/defaults';
import { prisma as prismaClient } from '../prismaClient';
import {
forBalloonMax,
forBalloonMin,
redis as redisClient,
} from '../redisClient';
export class BalloonProvider {
constructor(
private readonly prisma: PrismaClient,
private readonly redis: Redis,
) {}
async setMin(minVol: number, guildId: string) {
// validation to be done in app code
if (minVol < 0) throw new Error('Received negative volume.');
await this.prisma.guild
.upsert({
where: { guildId },
update: {
balloon: {
upsert: { update: { minVol }, create: { minVol } },
},
},
create: {
guildId,
balloon: {
connectOrCreate: { create: { minVol }, where: { guildId } },
},
},
})
.then(() => {
this.redis.set(forBalloonMin(guildId), minVol, 'ex', 60);
});
}
async getMin(guildId: string) {
const ping = await this.redis.get(forBalloonMin(guildId));
if (ping) {
this.redis.expire(forBalloonMin(guildId), 60);
return parseInt(ping, 10);
}
return this.prisma.balloon
.findUnique({
where: { guildId },
select: { minVol: true },
})
.then((res) => {
const minVol = res?.minVol || DEFAULT_MIN_BALLOON;
this.redis.set(forBalloonMin(guildId), minVol, 'ex', 60);
return minVol;
});
}
async setMax(maxVol: number, guildId: string) {
// validation to be done in app code
if (maxVol < 0) throw new Error('Received negative volume.');
await this.prisma.guild
.upsert({
where: { guildId },
update: {
balloon: {
upsert: { update: { maxVol }, create: { maxVol } },
},
},
create: {
guildId,
balloon: {
create: { maxVol },
},
},
})
.then(() => {
this.redis.set(forBalloonMax(guildId), maxVol, 'ex', 60);
});
}
async getMax(guildId: string) {
const ping = await this.redis.get(forBalloonMax(guildId));
if (ping) {
this.redis.expire(forBalloonMax(guildId), 60);
return parseInt(ping, 10);
}
return this.prisma.balloon
.findUnique({
where: { guildId },
select: { maxVol: true },
})
.then((res) => {
const maxVol = res?.maxVol || DEFAULT_MAX_BALLOON;
this.redis.set(forBalloonMax(guildId), maxVol, 'ex', 60);
return maxVol;
});
}
}
export const balloonProvider = new BalloonProvider(prismaClient, redisClient);
<file_sep>import { unknown_png } from '../../../shared/assets';
import { FuzzyDate } from '../../../generated/anilist';
import { baseEmbed } from '../../../shared/embeds';
import { parseHtml, truncate, wrapText } from '../../../lib/typography';
import { parseFuzzyDate } from './mangaInfoEmbed';
interface charInfoEmbedParams {
englishName: string | null | undefined;
japName: string | null | undefined;
image: string | null | undefined;
age: string | null | undefined;
gender: string | null | undefined;
description: string | null | undefined;
dateOfBirth: FuzzyDate | null | undefined;
siteUrl: string | null | undefined;
}
export const charInfoEmbed = (info: charInfoEmbedParams) => {
const {
englishName,
japName,
image,
gender,
age,
dateOfBirth,
description,
siteUrl,
} = info;
let genderEmoji;
switch (gender?.toLowerCase()) {
case 'male':
genderEmoji = ':male_sign:';
break;
case 'female':
genderEmoji = ':female_sign:';
break;
default:
genderEmoji = '';
break;
}
return baseEmbed()
.setTitle(`${englishName || '?'} ${genderEmoji}\n${japName || '?'}`)
.setDescription(characterDescription(description, siteUrl))
.addFields([
{ name: ':calendar: Age', value: age || '?', inline: true },
{
name: ':cake: Birthday',
value: parseFuzzyDate(dateOfBirth),
inline: true,
},
])
.setImage(image || unknown_png);
};
function characterDescription(
desc: string | null | undefined,
siteUrl: string | null | undefined,
) {
if (!desc) return '*No description for this character.*';
let body = truncate(parseHtml(desc), 70, true);
if (!siteUrl || body.length === desc.length) return body;
body = `${wrapText(`${body} [read more]`)}(${siteUrl})`;
return body;
}
<file_sep>-- CreateEnum
CREATE TYPE "CmdCategory" AS ENUM ('CURRENCY', 'FUN', 'GAMES', 'MUSIC', 'UTILITY');
-- CreateTable
CREATE TABLE "Arg" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"optional" BOOLEAN NOT NULL,
"multi" BOOLEAN NOT NULL,
"commandId" INTEGER,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Command" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT NOT NULL,
"category" "CmdCategory" NOT NULL,
PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "Command.name_unique" ON "Command"("name");
-- AddForeignKey
ALTER TABLE "Arg" ADD FOREIGN KEY ("commandId") REFERENCES "Command"("id") ON DELETE SET NULL ON UPDATE CASCADE;
| 218fe4f563031f88dcac4223d4b8cfa0d65a3eed | [
"Markdown",
"SQL",
"TypeScript",
"Shell"
] | 132 | TypeScript | shinomiya-corp/chika | 5109383e535463837e013249402a87ba2e2d3295 | 98f6a8648dbb191eacc550c246d124940ac959e9 | |
refs/heads/master | <file_sep>/**
* file: js.js
* purpose: interactivity
**/
console.log('Stardate 235678.89: JavaScript from js/js.js is up and running.');
// paste your javascript here
// the image names should be real image names
var myGallery = [
"scenery.png",
"home.png",
"nightcity.png",
"hotbath.png",
"sea.png",
"villas.png",
"waterfall.png",
"mountains.png"
];
for (i = 0; i < myGallery.length; i++) {
// note the shorthand code below
exhibition.innerHTML += '<img src="images/' +
myGallery[i] +
'" alt="from my galleries">';
}
// let the loop create the HTML for your gallery
| 8130362ac31dee226c69a27af888bafda1e5c58e | [
"JavaScript"
] | 1 | JavaScript | mihaelauzunova/2semForaar2020 | f0bce9d7c82a509fbbc58daa00a0cf5953734583 | cbee228b9079871987a3bc6382b182dfa5d02da4 | |
refs/heads/master | <file_sep>import * as React from "react";
import { ProductsList } from "./Products/ProductsList";
import { AppHeader } from "./AppHeader";
import {Login} from "./Components/Login";
export class App extends React.Component {
state = {
products: null
};
componentDidMount() {
fetch("http://chamniam.pl/api/foodproduct")
.then(res => res.json())
.then(json => this.setState({ products: json})
);
}
render() {
const products = this.state.products;
return (
<div>
<Login/>
<AppHeader />
<main className="ui main text container">
{products ? <ProductsList products={products} /> : 'Ładowanie…'}
</main>
</div>
);
}
}<file_sep>import * as React from "react";
import "./Components.css"
export const Textbox = ({label
}) => {
return (
<div>
<label>{label}</label><input type="text" />
</div>
);
};<file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "d4a7a4c635d03daa5df25140f8d9150e",
"url": "/type-of-web-test/index.html"
},
{
"revision": "1485a38dbef828ac08b2",
"url": "/type-of-web-test/static/css/main.5f361e03.chunk.css"
},
{
"revision": "b077ffec2f0d97749d54",
"url": "/type-of-web-test/static/js/2.5b0a94fe.chunk.js"
},
{
"revision": "<PASSWORD>",
"url": "/type-of-web-test/static/js/2.5b0a94fe.chunk.js.LICENSE.txt"
},
{
"revision": "1485a38dbef828ac08b2",
"url": "/type-of-web-test/static/js/main.696c9894.chunk.js"
},
{
"revision": "0ae4dbeea75956a66165",
"url": "/type-of-web-test/static/js/runtime-main.309de35e.js"
},
{
"revision": "5d5d9eefa31e5e13a6610d9fa7a283bb",
"url": "/type-of-web-test/static/media/logo.5d5d9eef.svg"
}
]);<file_sep>import * as React from "react";
import "./Components.css"
import {Textbox} from "./Textbox";
export const Login = ({
}) => {
// <script src="https://www.google.com/recaptcha/api.js"></script>
// grecaptcha.ready(function() {
// grecaptcha.execute('<KEY>', {action: 'homepage'}).then(function(token) {
// alert(token);
// });
// });
// }
return (
<div className="login">
<div className="login-header">
<div>Logowanie</div>
<div className="login-close-btn">
<span className="x">+
</span>
</div>
</div>
<div className="login-screen">
<Textbox label="Login: "/>
<Textbox label="Email: "/>
<KEY>_9vr7F
6Ld3B8wZAAAAAEQipCMnKa0NQFwpLwgy3kvNDagA
</div>
</div>
)};<file_sep>import * as React from "react";
export const AppHeader = () => {
return (
<header className="ui fixed menu">
<nav className="ui container">
<span className="header item">
Lista produktów
</span>
<div className="header item">
<button className="ui button">Dodaj</button>
</div>
</nav>
</header>
);
};<file_sep>
import * as React from "react";
import { ProductItem } from "./ProductItem";
export class ProductsList extends React.Component {
productToproductItem = product => {
const productCategory = product.ProductCategory.PCategory;
const name = product.ProductName;
const foodProductId = product.FoodProductId;
const calories = product.Calories;
const carbohydrates = product.Carbohydrates;
const fat = product.Fat;
const fiber = product.Fiber;
const kiloJoules = product.KiloJoules;
const productCategoryId = product.ProductCategoryId;
const protein = product.Protein;
const salt = product.Salt;
return <ProductItem key={foodProductId}
calories = {calories}
productCategory={productCategory}
name={name}
carbohydrates={carbohydrates}
fat ={fat}
fiber = {fiber}
kiloJoules = {kiloJoules}
productCategoryId = {productCategoryId}
protein = {protein}
salt = {salt}
/>;
};
render() {
return (
<ul className="ui relaxed divided list selection">
{this.props.products.map(this.productToproductItem)}
</ul>
);
}
}
<file_sep>import * as React from "react";
export const ProductItem = ({
product:Product,
carbohydrates,
fat,
fiber,
kiloJoules,
productCategoryId,
protein,
salt,
name,
productCategory
}) => {
return (
<li className="item">
<img src={name} className="ui mini rounded image" alt={name} />
<div className="content">
<h4 className="header">{name}</h4>
<div className="description">Węglowodany: {carbohydrates}</div>
<div className="description">Tłuszcz: {fat}</div>
<div className="description">Błonnik: {fiber}</div>
<div className="description">KiloJoule: {kiloJoules}</div>
<div className="description">Białko: {protein}<div/>
<div className="description">Sól: {salt}</div>
<div className="description">Kategoria produktu: {productCategory}</div>
</div>
</div>
</li>
);
}; | 8ecdae4c272c000c4a6064b294042280d1116e5a | [
"JavaScript"
] | 7 | JavaScript | Limanov/React-Product | 2940b167ea4ad679692d1482b8768410714bea9e | 7f70fab08bdd8581cbaa52332e4a94283080b55d | |
refs/heads/master | <file_sep>from util import load_data
import matplotlib.pyplot as plt
from skimage import data
from skimage.viewer import ImageViewer
if __name__ == "__main__":
data_in, data_targ, data_ids, unlabeled_in, test_in = load_data()
image = data_in[0,:].reshape(32, 32)
viewer = ImageViewer(image)
viewer.show()<file_sep>from sklearn import svm
from sklearn.cross_validation import train_test_split, cross_val_score
from util import *
import numpy as np
NUM_TEST = 1253
def run_SVC(train_in, valid_in, train_targ, valid_targ):
H_c = 3e2
H_kernel = 'poly'
H_degree = 2
H_coef0 = 0.0
H_g = 0.001
classifier = svm.SVC(kernel=H_kernel, C=H_c, coef0=H_coef0, degree=H_degree, gamma=H_g)
classifier.fit(train_in, train_targ)
return classifier.score(valid_in, valid_targ), classifier
def run_nu_SVC(train_in, valid_in, train_targ, valid_targ):
H_kernel = 'poly'
H_degree = 2
H_coef0 = 0.0
H_nu = 0.27
classifier = svm.NuSVC(nu=H_nu, kernel=H_kernel, coef0=H_coef0, degree=H_degree)
classifier.fit(train_in, train_targ)
return classifier.score(valid_in, valid_targ), classifier
if __name__ == "__main__":
data_in, data_targ, data_ids, unlabeled_in, test_in = load_data()
N, M = data_in.shape
full_data = np.append(np.append(data_in, data_targ, axis=1), data_ids, axis=1)
pruned_in, pruned_targ, pruned_ids = prune_individuals(full_data)
num_iters = 35
rates_svc = np.array([])
svc_models = np.array([])
rates_nusvc = np.array([])
nusvc_models = np.array([])
for i in xrange(num_iters):
train_in, valid_in, train_targ, valid_targ = train_test_split(pruned_in,
pruned_targ, test_size=0.28, stratify=pruned_ids)
curr_svc_rate, svc = run_SVC(train_in, valid_in, train_targ, valid_targ)
curr_nu_svc_rate, nu_svc = run_nu_SVC(train_in, valid_in, train_targ, valid_targ)
rates_svc = np.append(rates_svc, curr_svc_rate)
rates_nusvc = np.append(rates_nusvc, curr_nu_svc_rate)
svc_models = np.append(svc_models, svc)
nusvc_models = np.append(nusvc_models, nu_svc)
print "SVC Success Rate = {} ; NuSVC Success Rate = {}".format(rates_svc[i], rates_nusvc[i])
best_svc = svc_models[np.argmax(rates_svc)]
best_nu_svc = nusvc_models[np.argmax(rates_nusvc)]
print "Best SVC's accuracy = {}".format(np.max(rates_svc))
print "Best NuSVC's accuracy = {}".format(np.max(rates_nusvc))
print "Average SVC Success Rate = {}".format(np.mean(rates_svc))
print "Average NuSVC Success Rate = {}".format(np.mean(rates_nusvc))
max_accuracies = [np.max(rates_svc), np.max(rates_nusvc)]
test_classifier = [best_svc, best_nu_svc][np.argmax(max_accuracies)]
test_targ = best_svc.predict(test_in).astype(int)
with open("submission.csv", "w+") as f:
f.write("Id,Prediction\n")
for i in xrange(NUM_TEST):
if i > test_targ.size - 1:
f.write("{},0\n".format(i+1))
else:
f.write("{},{}\n".format(i+1, test_targ[i]))
f.close()
<file_sep>from sklearn import svm
from sklearn.cross_validation import train_test_split, cross_val_score
from util import *
from scipy.stats.mstats import mode
import numpy as np
import cPickle as pickle
NUM_TEST = 1253
def run_SVC(train_in, valid_in, train_targ, valid_targ):
H_c = 3e2
H_kernel = 'linear'
H_degree = 2
H_coef0 = 3e2
H_g = 0.001
classifier = svm.SVC(kernel=H_kernel, C=H_c, coef0=H_coef0, degree=H_degree, gamma=H_g)
classifier.fit(train_in, train_targ)
return classifier.score(valid_in, valid_targ), classifier
def run_nu_SVC(train_in, valid_in, train_targ, valid_targ):
H_kernel = 'linear'
H_degree = 2
H_coef0 = 3e2
H_nu = 0.27
classifier = svm.NuSVC(nu=H_nu, kernel=H_kernel, coef0=H_coef0, degree=H_degree)
classifier.fit(train_in, train_targ)
return classifier.score(valid_in, valid_targ), classifier
if __name__ == "__main__":
print "Loading data."
data_in, data_targ, data_ids, unlabeled_in, test_in = load_data()
N, M = data_in.shape
gabor_data = pickle.load(open("gabor.p","rb"))
gabor_test = pickle.load(open("gabor_test.p", "rb"))
full_data = np.append(np.append(gabor_data, data_targ, axis=1), data_ids, axis=1)
pruned_in, pruned_targ, pruned_ids = prune_individuals(full_data)
num_experts = 10
i = 0
rates_svc = np.array([])
svc_models = np.array([])
rates_nusvc = np.array([])
nusvc_models = np.array([])
predictions = np.empty([NUM_TEST, 0])
print "Finding {} experts.".format(num_experts)
while i < num_experts:
print "Training."
train_in, valid_in, train_targ, valid_targ = train_test_split(pruned_in,
pruned_targ, test_size=0.28, stratify=pruned_ids)
curr_nu_svc_rate, nu_svc = run_nu_SVC(train_in, valid_in, train_targ, valid_targ)
print "Score = {}".format(curr_nu_svc_rate)
if curr_nu_svc_rate > 0.80:
rates_nusvc = np.append(rates_nusvc, curr_nu_svc_rate)
nusvc_models = np.append(nusvc_models, nu_svc)
#nu_svc_predictions = np.append(nu_svc_predictions, nu_svc_prediction)
i += 1
print"{}.".format(i)
print "Found a NuSVC Expert."
for expert in nusvc_models:
test_targ = expert.predict(gabor_test)
predictions = np.append(predictions, test_targ.reshape(NUM_TEST, 1), axis=1)
final_test_targ, _ = mode(predictions, axis=1)
with open("submission.csv", "w+") as f:
f.write("Id,Prediction\n")
for i in xrange(NUM_TEST):
f.write("{},{}\n".format(i+1, int(final_test_targ.flatten()[i])))
f.close()
<file_sep>from sklearn.neighbors import KNeighborsClassifier
from sklearn.cross_validation import train_test_split
from util import *
import numpy as np
if __name__ == "__main__":
k_vals = [3, 5, 7, 9, 11, 13, 14, 16, 21]
data_in, data_targ, data_ids, unlabeled_in, test_in = load_data()
N, M = data_in.shape
full_data = np.append(np.append(data_in, data_targ, axis=1), data_ids, axis=1)
pruned_in, pruned_targ, pruned_ids = prune_individuals(full_data)
for k in k_vals:
kNN = KNeighborsClassifier(n_neighbors=k)
train_in, valid_in, train_targ, valid_targ = train_test_split(pruned_in,
pruned_targ, test_size=0.33, stratify=pruned_ids)
kNN.fit(train_in, train_targ.flatten())
print "k = {} ; classification rate = {}".format(k, kNN.score(valid_in, valid_targ))
<file_sep>import scipy.io as io
import sklearn as sk
import numpy as np
from sklearn.cross_validation import train_test_split
LABELED = "../data/labeled_images.mat"
UNLABELED = "../data/unlabeled_images.mat"
PUBLIC_TEST = "../data/public_test_images.mat"
HIDDEN_TEST = "../data/hidden_test_images.mat"
CSV_FILE_NAME = "submission.csv"
# This global variable represents the number of classes
# in this classification task.
K = 7
def load_data():
'''
Load all data and return it as a tuple of arrays.
input:
labeled_path - the path (relative or absolute) to labeled data.
this data MUST be stored in a .mat file.
unlabeled_path - the path (relative or absolute) to unlabeled data.
this data MUST be stored in a .mat file.
test_path - the path (relative or absolute) to test data.
this data MUST be stored in a .mat file.
output:
train_in - an NxM matrix of all training data.
train_targ - an Nx1 matrix of labels corresponding to training data.
train_ids - an Nx1 matrix of ids corresponding to training data.
unlabeled_in - a KxM matrix of additional unlabeled training data.
test_in - a JxM matrix of test data.
'''
# First, load the raw data into dictionaries.
# These dictionaries all contain keys that allow us to index
# into the data and metadata.
loaded_labeled = io.loadmat(LABELED)
loaded_unlabeled = io.loadmat(UNLABELED)
loaded_pub_test = io.loadmat(PUBLIC_TEST)
loaded_hid_test = io.loadmat(HIDDEN_TEST)
train_in = reshape_data(loaded_labeled['tr_images'])
train_targ = loaded_labeled['tr_labels']
train_ids = loaded_labeled['tr_identity']
pub_test_in = reshape_data(loaded_pub_test['public_test_images'])
hid_test_in = reshape_data(loaded_hid_test['hidden_test_images'])
test_in = np.vstack((pub_test_in, hid_test_in))
unlabeled_in = reshape_data(loaded_unlabeled['unlabeled_images'])
return train_in, train_targ, train_ids, unlabeled_in, test_in
def reshape_data(data_in):
'''
Return a z by x*y matrix of data points, where x & y are
the dimensions of each ith datapoint, and z is the number of examples.
input:
data_in - an x by y by z matrix of datapoints.
output:
reshaped_data_in - a z by x*y matrix of datapoints.
'''
x, y, z = data_in.shape
N, M = z, x *y
return data_in.flatten().reshape(M, N).T
def concatenate_data_info(data_in, data_targ, data_ids):
'''
Concatenate two rows to data_in: the targets for each row,
stored in data_targ; the ids for each row, stored in data_ids.
Return the resulting matrix.
input:
data_in - an NxM matrix of data points per row.
data_targ - an Nx1 matrix of data point targets.
data_ids - an Nx1 matrix of data point identities.
output:
full_data - an NxM+2 matrix of data and its corresponding
target and identity.
'''
data_in_targ = np.append(data_in, data_targ, axis=1)
return np.append(data_in_targ, data_ids, axis=1)
def prune_individuals(full_data):
'''
Replace all unique identifiers with a single identifier value.
This is done to enable stratifying based on identifier.
input:
full_data - an NxM+2 matrix, where each row is a datapoint
of M features. the M+1th column is the label
for that datapoint and the M+2th column is the id.
output:
pruned_in - an NxM matrix of data points.
pruned_targ - an Nx1 matrix of labels corresponding to pruned_in.
pruned_ids - an Nx1 matrix of ids corresponding to pruned_in
'''
N, M = full_data.shape
all_ids = full_data[:, M-1]
new_ids = np.array([])
for i in xrange(all_ids.size):
if np.sum(all_ids == all_ids[i]) == 1:
new_ids = np.append(new_ids, 42069)
else:
new_ids = np.append(new_ids, all_ids[i])
pruned_full_data = np.append(full_data[:, :M-1], new_ids.reshape(-1, 1), axis=1)
pruned_in = pruned_full_data[:, :M-2]
pruned_targ = pruned_full_data[:, M-2]
pruned_ids = pruned_full_data[:, M-1]
return pruned_in, pruned_targ, pruned_ids
def write_prediction_to_csv(test_targ):
'''
Write a file to disk that formats the prediction stored in
test_targ.
input:
test_targ - a Nx1 array of predictions for test data.
'''
N, _ = test_targ.shape
with open(CSV_FILE_NAME, "w+") as f:
f.write("Id,Prediction\n")
for i in xrange(N):
if i > N - 1:
f.write("{},0\n".format(i+1))
else:
f.write("{},{}\n".format(i+1, int(test_targ.flatten()[i])))
f.close()
def encode_prediction(model, data_in):
'''
Return a NxK matrix, where N is the number of examples and K
is the number of classes. This matrix represents the predictions
yielded by the input model in a 1-of-K format: that is, each row
has a 1 in the kth position, representing the prediction for the
corresponding row in data_in.
input:
model - a model that has been fit to training data.
must be a scikit-learn model, i.e. have a "prediciton"
method.
data_in - an NxM matrix, where each row is a data point of M features.
output:
encoded - an NxK matrix, where each row has a 1 in the kth position.
this indications that example i is of class k.
'''
N, M = data_in.shape
prediction = model.predict(data_in)
encoded = np.zeros((N, K+1))
encoded[np.arange(N), prediction.astype(int)] = 1
return encoded
<file_sep>from sklearn.ensemble import AdaBoostClassifier
from sklearn.cross_validation import train_test_split
from util import *
import numpy as np
def run_AdaBoost(train_in, valid_in, train_targ, valid_targ):
classifier = AdaBoostClassifier(learning_rate=0.8)
classifier.fit(train_in, train_targ)
print classifier.score(valid_in, valid_targ)
if __name__ == "__main__":
data_in, data_targ, data_ids, unlabeled_in, test_in = load_data()
N, M = data_in.shape
full_data = np.append(np.append(data_in, data_targ, axis=1), data_ids, axis=1)
pruned_in, pruned_targ, pruned_ids = prune_individuals(full_data)
train_in, valid_in, train_targ, valid_targ = train_test_split(pruned_in,
pruned_targ, test_size=0.33, stratify=pruned_ids)
run_AdaBoost(train_in, valid_in, train_targ, valid_targ)
<file_sep>import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage as ndi
from skimage import data
from skimage.util import img_as_float
from skimage.filters import gabor_kernel
from skimage.viewer import ImageViewer
from util import load_data
import cPickle as pickle
def compute_gabor(image):
images = []
for theta in np.arange(0.1, np.pi, np.pi / 8):
for lmda in np.arange(0.1, np.pi, np.pi/4):
imaginary, real = gabor_filter(image, .5,theta=theta,bandwidth=lmda)
images.append(real)
return images
def compute_feats(image, kernels):
feats = []
for k, kernel in enumerate(kernels):
filtered = ndi.convolve(image, kernel, mode='wrap')
feats.append(filtered.flatten())
return np.vstack(feats).reshape(1,len(kernels)*image.size)
def gabor_features(data_in):
#create gabor kernels
kernels = []
for theta in range(8):
theta = theta / 8.0 * np.pi
for sigma in (1, 3, 5):
for frequency in (.10, 0.25, 1.0):
kernel = np.real(gabor_kernel(frequency, theta=theta, sigma_x=sigma, sigma_y=sigma))
kernels.append(kernel)
#iterate over data points, and compute the result of applying each gabor kernel
m,n = data_in.shape
gabor_features = []
for i in range(data_in.shape[0]):
gabor_features.append(compute_feats(data_in[i].reshape(32,32), kernels))
return np.vstack(gabor_features)
if __name__ == "__main__":
data_in, data_targ, data_ids, unlabeled_in, test_in = load_data()
print "Applying Gabor filters to input data."
gabor_feats = gabor_features(data_in)
print "Apply Gabor filters to test data."
gabor_test = gabor_features(test_in)
print "Dumping input data."
pickle.dump(gabor_feats, open("gabor.p", "wb"))
print "Dumping test data."
pickle.dump(gabor_test, open("gabor_test.p", "wb"))
<file_sep>from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
from util import *
import numpy as np
if __name__ == "__main__":
data_in, data_targ, data_ids, unlabeled_in, test_in = load_data()
N, M = data_in.shape
full_data = np.append(np.append(data_in, data_targ, axis=1), data_ids, axis=1)
pruned_in, pruned_targ, pruned_ids = prune_individuals(full_data)
logit = LogisticRegression()
train_in, valid_in, train_targ, valid_targ = train_test_split(pruned_in,
pruned_targ, test_size=0.33, stratify=pruned_ids)
logit.fit(train_in, train_targ.flatten())
print "Validation MCE = {}".format(logit.score(valid_in, valid_targ))
<file_sep>from sklearn import svm
from sklearn.decomposition import PCA
from sklearn.cross_validation import train_test_split
from util import *
import numpy as np
if __name__ == "__main__":
data_in, data_targ, data_ids, unlabeled_in, test_in = load_data()
N, M = data_in.shape
full_data = np.append(np.append(data_in, data_targ, axis=1), data_ids, axis=1)
pruned_in, pruned_targ, pruned_ids = prune_individuals(full_data)
pca = PCA(n_components=200)
print "Initializing PCA with {} components.".format(pca.n_components)
svc = svm.SVC(C=4.0, kernel='linear', degree=2)
print "Initializing SVM with a {} kernel of degree {}.".format(svc.kernel, svc.degree)
print "Transforming input data."
decomposed_in = pca.fit_transform(pruned_in)
num_iters = 10
rates = np.array([])
for i in xrange(num_iters):
print "ITERATION {}".format(i)
train_in, valid_in, train_targ, valid_targ = train_test_split(decomposed_in,
pruned_targ, test_size=0.33, stratify=pruned_ids)
print "Fitting SVM."
svc.fit(train_in, train_targ)
rates = np.append(rates, svc.score(valid_in, valid_targ))
print "Success rate = {}".format(rates[i])
print "Average Success Rate = {}".format(np.mean(rates))
| 964a13282b7979d81e6d8ad53aa61ef281f9d6ad | [
"Python"
] | 9 | Python | pkukulak/CSC411-A3 | 2c50acfc1511f1e02ab3611bd2d9000167da36ad | f720f3830c639f2023b2cf6fd022b75386b4f839 | |
refs/heads/master | <file_sep>import React from "react";
function SobreNos(){
return(
<h1>Pagina Sobre Nós</h1>
);
};
export default SobreNos;<file_sep>
import {BrowserRouter, Switch, Route, Link} from "react-router-dom";
export default function Navegacao(){
return(
<nav class="navbar navbar-dark bg-dark">
<nav class="nav nav-pills flex-column flex-sm-row justify-content-end">
<Link class="flex-sm-fill text-sm-center nav-link " to="/">Cadastrar</Link>
<Link class="flex-sm-fill text-sm-center nav-link" to="/editar">Editar</Link>
<Link class="flex-sm-fill text-sm-center nav-link" to="/buscar">Buscar</Link>
<a class="flex-sm-fill text-sm-center nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</nav>
</nav>
)
};<file_sep>import React from "react";
// import React, {useState, useEffect } from react;
import {BrowserRouter, Switch, Route, Link} from "react-router-dom";
import Cadastrar from "./pages/Cadastrar";
import Editar from "./pages/Editar";
import Buscar from "./pages/Buscar";
import SobreNos from "./pages/SobreNos";
import reactDom from "react-dom";
function Routes () {
// useEffect(() => {
// fetch("http://localhost:3001/dados-pessoais")
// .then(response => response.json())
// .then(dados-pessoais => console.log(dados-pessoais));
// }, [])
return(
<BrowserRouter>
<Switch>
<Route path= "/" exact component={Cadastrar} />
<Route path="/editar" component={Editar} />
<Route path="/buscar" component={Buscar} />
<Route path="/sobre-nos" component={SobreNos} />
</Switch>
</BrowserRouter>
);
};
export default Routes;
| d8aa6cb44ca95826d951e0ab021fca94abbab946 | [
"JavaScript"
] | 3 | JavaScript | BerdayesVanessa/Projeto_Final_React_Gestao_Escolar | d9737b5b66a84b4646dd19e24856873d1c3b9023 | e4c08ee033e424ac9c1f1a9a43202650f1d6ba54 | |
refs/heads/main | <repo_name>krystiano365/pong<file_sep>/pong.py
// prints text to console
print("<NAME>")
| de1c8ebab2c58edbe3d3d34287a3aaee9ad90299 | [
"Python"
] | 1 | Python | krystiano365/pong | 3bfcd2f5d8f0cb50322f86b28720be42d0beb0b0 | 66bc50f1dcd5fa489bfa725d1f295759b67b38f1 | |
refs/heads/master | <file_sep>import '../styles/style.css';
console.warn('Heello there!');
| 59feeb1eacaac44664bcd61ee2dd79a6fb8c2161 | [
"JavaScript"
] | 1 | JavaScript | wolftrax5/talkbox-client | 69b548fcdea6b01cd155d99824c4227c5f001423 | 4890dd7cbd36f0f7c24e3cc79c3f7daaf1c4cce3 | |
refs/heads/main | <repo_name>setuphub/webLEC<file_sep>/LEC/usuarios/migrations/0006_auto_20201019_1105.py
# Generated by Django 3.1.1 on 2020-10-19 11:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('usuarios', '0005_codigos_activacio_usuarios'),
]
operations = [
migrations.RemoveField(
model_name='usuario',
name='registrado',
),
migrations.AddField(
model_name='usuario',
name='confirmacion_activacion',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='usuario',
name='baja',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AlterField(
model_name='usuario',
name='equipo',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='usuarios.equipo'),
),
migrations.AlterField(
model_name='usuario',
name='imagen_perfil',
field=models.ImageField(blank=True, null=True, upload_to=None),
),
migrations.AlterField(
model_name='usuario',
name='rol',
field=models.CharField(choices=[('JE', 'Jefe de Equipo'), ('RP', 'Representante'), ('PV', 'Portavoz'), ('PI', 'Piloto')], default='JE', max_length=25),
),
migrations.DeleteModel(
name='codigos_activacio_usuarios',
),
]
<file_sep>/LEC/blog/migrations/0001_initial.py
# Generated by Django 3.1.1 on 2020-10-06 11:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('usuarios', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('titulo', models.CharField(max_length=50, unique_for_date='fecha_creacion')),
('subtitulo', models.CharField(max_length=75)),
('imagen', models.ImageField(upload_to=None)),
('cuerpo', models.TextField()),
('categoria', models.CharField(max_length=50)),
('etiquetas', models.CharField(max_length=50)),
('fecha_creacion', models.DateTimeField(auto_now_add=True)),
('fecha_modificado', models.DateTimeField(auto_now_add=True)),
('fecha_eliminado', models.DateTimeField()),
('creado_por', models.ForeignKey(on_delete=django.db.models.deletion.RESTRICT, to='usuarios.usuario', verbose_name='Creado por')),
],
options={
'verbose_name': 'Post',
'verbose_name_plural': 'Posts',
'db_table': 'post',
'ordering': ['-fecha_modificado'],
'get_latest_by': '-fecha_modificado',
},
),
migrations.AddIndex(
model_name='post',
index=models.Index(fields=['creado_por'], name='creador_por'),
),
]
<file_sep>/LEC/usuarios/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
ROL_CHOICES = [
('JE', 'Jefe de Equipo'),
('RP', 'Representante'),
('PV', 'Portavoz'),
('PI', 'Piloto')
]
class Equipo(models.Model):
"""Model definition for Equipo."""
# TODO: Define fields here
nombre_equipo = models.CharField( max_length=50)
abreviatura = models.CharField(max_length=50)
email_equipo = models.EmailField(max_length=254)
pilotos = models.ManyToManyField(User, through='Usuario') #foreign key con usuarios
activo = models.BooleanField(default = False)
fecha_creacion = models.DateTimeField( auto_now_add=True)
fecha_modificacion = models.DateTimeField(auto_now_add=True)
fecha_baja = models.DateTimeField(auto_now_add=False)
class Meta:
"""Meta definition for Equipo."""
db_table ='equipo'
managed = True
verbose_name = 'Equipo'
verbose_name_plural = 'Equipos'
def __str__(self):
"""Unicode representation of Equipo."""
return self.nombre_equipo
class Usuario(models.Model):
user = models.OneToOneField(User, verbose_name="usuario", on_delete=models.CASCADE)
equipo = models.ForeignKey(Equipo, on_delete=models.CASCADE, null = True)
rol = models.CharField( max_length=25, choices=ROL_CHOICES, default = 'JE') #si es piloto,jefe de equipo,representante,etc.
imagen_perfil = models.ImageField( upload_to=None, height_field=None, width_field=None, max_length=None, blank= True, null = True)
confirmacion_activacion = models.BooleanField(default = False)
baja = models.DateTimeField( auto_now=False, auto_now_add=False, null = True, blank = True)
def __str__(self):
return self.user.username
class Meta:
db_table ='usuario'
managed = True
verbose_name = 'Usuario'
verbose_name_plural = 'Usuarios'
<file_sep>/LEC/usuarios/migrations/0005_codigos_activacio_usuarios.py
# Generated by Django 3.1.1 on 2020-10-09 10:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('usuarios', '0004_auto_20201009_1020'),
]
operations = [
migrations.CreateModel(
name='codigos_activacio_usuarios',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('codigo', models.CharField(max_length=5)),
('usuario', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='usuarios.usuario')),
],
options={
'verbose_name': 'Codigo activacion',
'verbose_name_plural': 'Codigos de activacion',
},
),
]
<file_sep>/LEC/blog/migrations/0005_auto_20201027_1123.py
# Generated by Django 3.1.1 on 2020-10-27 11:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0004_auto_20201012_1625'),
]
operations = [
migrations.AlterField(
model_name='post',
name='categoria',
field=models.CharField(choices=[('GTS', 'Gran Turismo Sport'), ('GT7', 'Gran Turismo 7'), ('IR', 'iRacing'), ('PC2', 'Project Cars 2'), ('PC3', 'Project Cars 3'), ('RD4', 'Ride 4'), ('ATM', 'Automobilista 2'), ('RFC2', 'rFactor 2'), ('SR', 'SimRacing')], max_length=50),
),
]
<file_sep>/LEC/blog/urls.py
from django.urls import path
from . import views
from usuarios.views import registro, login, logout
urlpatterns = [
path('', views.index, name='index'),
path('login', login, name='login'),
path('logout',logout, name='logout'),
path('blog/articulo/<str:id>', views.entrada, name='post')
#path('registro', registro, name='registro')
]<file_sep>/LEC/foro/migrations/0001_initial.py
# Generated by Django 3.1.1 on 2020-11-02 18:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('usuarios', '0006_auto_20201019_1105'),
]
operations = [
migrations.CreateModel(
name='Comentario',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('comentario', models.TextField(blank=True, null=True, unique_for_date='fecha_creado')),
('fecha_creado', models.DateTimeField(auto_now_add=True)),
('fecha_modificado', models.DateTimeField(auto_now_add=True)),
('autor', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='usuarios.usuario', verbose_name='autor_comentario')),
],
options={
'verbose_name': 'Comentario',
'verbose_name_plural': 'Comentarios',
'ordering': ['-fecha_creado'],
'get_latest_by': '-fecha_creado',
},
),
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Titulo', models.CharField(max_length=50, unique_for_date='fecha_creado')),
('cuerpo', models.TextField()),
('fecha_creado', models.DateTimeField(auto_now_add=True)),
('fecha_modificado', models.DateTimeField(auto_now_add=True)),
('activo', models.BooleanField(default=True, null=True)),
('autor', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, to='usuarios.usuario', verbose_name='autor_post')),
('comentarios', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='foro.comentario')),
],
options={
'verbose_name': 'Post',
'verbose_name_plural': 'Posts',
'ordering': ['-fecha_creado'],
'get_latest_by': '-fecha_creado',
},
),
migrations.CreateModel(
name='Subcategoria',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Titulo', models.CharField(max_length=50)),
('creado', models.DateTimeField(auto_now_add=True)),
('modificado', models.DateTimeField(auto_now_add=True)),
('Posts', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='foro.post', verbose_name='Posts')),
],
options={
'verbose_name': 'Subcategoria',
'verbose_name_plural': 'Subcategoria',
},
),
migrations.CreateModel(
name='Categoria',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Titulo', models.CharField(max_length=50, unique=True)),
('creado', models.DateTimeField()),
('modificado', models.DateTimeField()),
('Subcategoria', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='foro.subcategoria', verbose_name='Subcategoria')),
],
options={
'verbose_name': 'Categoria',
'verbose_name_plural': 'Categorias',
},
),
]
<file_sep>/LEC/blog/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import permission_required, login_required
from django.db.models import Q
from .models import Entrada
# Create your views here.
def index(request):
try:
entradas = Entrada.objects.all()[:16]
except:
entradas = []
context = {
"entradas": entradas,
}
#return render(request,'GeneralTemplates/loginForm.html', {'form':form})
return render(request,'blog/blog.html', context)
def entrada(request,id): #No manda el objeto en el contexto
context={}
print(id)
try:
entrada = Entrada.objects.get(Q(id = id))
except:
error = True
context.update({'error': error})
return render(request, 'blog/entrada.html', context)
print(entrada.fecha_modificado)
context.update({'entrada': entrada})
return render(request, 'blog/entrada.html', context)
@permission_required('blog.can_publish', raise_exception=True)
def publish_post(request):
return redirect(index)<file_sep>/LEC/usuarios/migrations/0001_initial.py
# Generated by Django 3.1.1 on 2020-10-06 11:37
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
atomic = False
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Usuario',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('equipo', models.CharField(max_length=50)),
('status', models.CharField(max_length=50)),
('imagen_perfil', models.ImageField(upload_to=None)),
('activo', models.BooleanField()),
('registrado', models.DateTimeField()),
('baja', models.DateTimeField()),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user')),
],
options={
'verbose_name': 'Usuario',
'verbose_name_plural': 'Usuarios',
'db_table': 'usuario',
'managed': True,
},
),
]
<file_sep>/LEC/foro/tests.py
from django.test import TestCase
# Create your tests here.
class Hilo(models.Model):
"""Model definition for Hilo."""
# TODO: Define fields here
class Meta:
"""Meta definition for Hilo."""
verbose_name = 'Hilo'
verbose_name_plural = 'Hilos'
def __str__(self):
"""Unicode representation of Hilo."""
pass
class POST(models.Model):
"""Model definition for POST."""
# TODO: Define fields here
class Meta:
"""Meta definition for POST."""
verbose_name = 'POST'
verbose_name_plural = 'POSTs'
def __str__(self):
"""Unicode representation of POST."""
pass
<file_sep>/LEC/blog/models.py
from django.db import models
from usuarios.models import Usuario
# Create your models here.
CATEGORIAS = [
('GTS', 'Gran Turismo Sport'),
('GT7', 'Gran Turismo 7'),
('IR', 'iRacing'),
('PC2', 'Project Cars 2'),
('PC3', 'Project Cars 3'),
('RD4', 'Ride 4'),
('ATM', 'Automobilista 2'),
('RFC2', 'rFactor 2'),
('SR', 'SimRacing')
]
class Entrada(models.Model):
"""Model definition for Post."""
# Define fields here
titulo = models.CharField( blank=False, max_length=50, unique_for_date="fecha_creacion")
subtitulo = models.CharField( blank=False, max_length=75)
imagen = models.ImageField( blank=False, upload_to='%Y/%m/%d/', height_field=None, width_field=None, max_length=None)
cuerpo = models.TextField( blank=False, )
categoria = models.CharField( blank=False, max_length=50, choices=CATEGORIAS)
etiquetas = models.CharField( blank=False, max_length=50)
fecha_creacion = models.DateTimeField( auto_now_add=True)
fecha_modificado = models.DateTimeField( auto_now_add=True)
fecha_eliminado = models.DateTimeField( blank = True, null = True, auto_now_add=False)
creado_por = models.ForeignKey(Usuario, blank=False, verbose_name="Creado por", on_delete=models.CASCADE)
class Meta:
"""Meta definition for Post."""
verbose_name = 'Entrada'
verbose_name_plural = 'Entradas'
get_latest_by = "-fecha_modificado"
ordering = ['-fecha_modificado']
indexes = [models.Index(fields=['creado_por'], name="creador_por")]
def __str__(self):
"""Unicode representation of Post."""
return self.titulo
<file_sep>/LEC/foro/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.foro, name='categorias'),
path('foro/<str:Titulo>/', views.subcategoria, name='post')
#path('registro', registro, name='registro')
]<file_sep>/LEC/usuarios/migrations/0002_auto_20201006_1143.py
# Generated by Django 3.1.1 on 2020-10-06 11:43
from django.db import migrations
class Migration(migrations.Migration):
atomic = False
dependencies = [
('usuarios', '0001_initial'),
]
operations = [
migrations.AlterModelTable(
name='usuario',
table='Usuario',
),
]
<file_sep>/LEC/foro/views.py
from django.shortcuts import render
from .models import *
from django.db.models import Q
# Create your views here.
def foro(request):
context = {}
categorias = Categoria.objects.all()
context.update({'categorias': categorias})
return render(request,'foro/categorias_foro.html',context)
def subcategoria(request,tCategoria,):
context = {}
subcategorias = Subcategoria.objects.get(Q(categoria = tCategoria))
context.update({'subcategorias': subcategorias})
return render(request,'foro/categorias_foro', context)<file_sep>/LEC/blog/migrations/0004_auto_20201012_1625.py
# Generated by Django 3.1.1 on 2020-10-12 16:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('usuarios', '0005_codigos_activacio_usuarios'),
('blog', '0003_auto_20201006_1144'),
]
operations = [
migrations.AlterField(
model_name='post',
name='creado_por',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='usuarios.usuario', verbose_name='Creado por'),
),
]
<file_sep>/LEC/LEC/context_processors.py
from usuarios.forms import formulario_login
def add_my_login_form(request):
return {
'login_form': formulario_login(),
}<file_sep>/LEC/requirements.txt
asgiref==3.2.10
attrs==20.2.0
awsebcli==3.19.0
bcrypt==3.2.0
blessed==1.17.10
botocore==1.17.63
cached-property==1.5.2
cement==2.8.2
certifi==2020.6.20
cffi==1.14.3
chardet==3.0.4
colorama==0.4.3
cryptography==3.1.1
Django==3.1.1
docker==4.3.1
docker-compose==1.25.5
dockerpty==0.4.1
docopt==0.6.2
docutils==0.15.2
future==0.16.0
idna==2.7
importlib-metadata==2.0.0
jmespath==0.10.0
jsonschema==3.2.0
paramiko==2.7.2
pathspec==0.5.9
Pillow==7.2.0
pkg-resources==0.0.0
pycparser==2.20
PyNaCl==1.4.0
pyrsistent==0.17.3
python-dateutil==2.8.0
pytz==2020.1
PyYAML==5.3.1
requests==2.20.1
semantic-version==2.5.0
six==1.11.0
sqlparse==0.3.1
termcolor==1.1.0
texttable==1.6.3
urllib3==1.24.3
wcwidth==0.1.9
websocket-client==0.57.0
zipp==3.3.0
<file_sep>/LEC/foro/migrations/0005_auto_20201102_1827.py
# Generated by Django 3.1.1 on 2020-11-02 18:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('foro', '0004_auto_20201102_1808'),
]
operations = [
migrations.RemoveField(
model_name='post',
name='comentarios',
),
migrations.AddField(
model_name='comentario',
name='content_type',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.contenttype'),
),
migrations.AddField(
model_name='comentario',
name='object_id',
field=models.PositiveIntegerField(null=True),
),
migrations.AddField(
model_name='post',
name='permitir_comentarios',
field=models.BooleanField(default=True),
),
]
<file_sep>/LEC/blog/migrations/0009_auto_20201102_1700.py
# Generated by Django 3.1.1 on 2020-11-02 17:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('usuarios', '0006_auto_20201019_1105'),
('blog', '0008_auto_20201027_1148'),
]
operations = [
migrations.RenameModel(
old_name='Post',
new_name='Entrada',
),
migrations.AlterModelOptions(
name='entrada',
options={'get_latest_by': '-fecha_modificado', 'ordering': ['-fecha_modificado'], 'verbose_name': 'Entrada', 'verbose_name_plural': 'Entradas'},
),
]
<file_sep>/LEC/foro/models.py
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericRelation
from usuarios.models import Usuario
# Create your models here.
class Comentario(models.Model):
"""Model definition for Comentario."""
# TODO: Define fields here
comentario = models.TextField(blank = True, null = True, unique_for_date = "fecha_creado")
autor = models.OneToOneField(Usuario, verbose_name="autor_comentario", on_delete=models.CASCADE)
fecha_creado = models.DateTimeField(auto_now_add=True)
fecha_modificado = models.DateTimeField( auto_now_add=True)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null = True)
object_id = models.PositiveIntegerField(null = True)
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
"""Meta definition for Comentario."""
verbose_name = 'Comentario'
verbose_name_plural = 'Comentarios'
get_latest_by = "-fecha_creado"
ordering = ['-fecha_creado']
def __str__(self):
"""Unicode representation of Comentario."""
pass
class Post(models.Model):
"""Model definition for MODELNAME."""
# TODO: Define fields here
Titulo = models.CharField( max_length=50, unique_for_date = "fecha_creado", null = False, blank = False )
autor = models.OneToOneField(Usuario, verbose_name="autor_post", on_delete=models.PROTECT, null = False)
cuerpo = models.TextField(null = False, blank = False)
comentarios = GenericRelation(Comentario)
permitir_comentarios = models.BooleanField(default = True)
fecha_creado = models.DateTimeField(auto_now_add=True)
fecha_modificado = models.DateTimeField(auto_now_add=True)
activo = models.BooleanField(default = True, null = True)
class Meta:
"""Meta definition for MODELNAME."""
verbose_name = 'Post'
verbose_name_plural = 'Posts'
get_latest_by = "-fecha_creado"
ordering = ['-fecha_creado']
def __str__(self):
"""Unicode representation of MODELNAME."""
return self.Titulo
class Subcategoria(models.Model):
"""Model definition for Post."""
# TODO: Define fields here
Titulo = models.CharField(max_length=50)
Posts = models.ForeignKey(Post, verbose_name="Posts", on_delete=models.CASCADE, blank = True, null = True)
creado = models.DateTimeField(auto_now_add=True)
modificado = models.DateTimeField(auto_now_add=True)
class Meta:
"""Meta definition for Post."""
verbose_name = 'Subcategoria'
verbose_name_plural = 'Subcategoria'
def __str__(self):
"""Unicode representation of Post."""
return self.Titulo
class Categoria(models.Model):
"""Model definition for Hilo."""
# TODO: Define fields here
Titulo = models.CharField(max_length=50, unique = True)
Subcategoria = models.ForeignKey("Subcategoria", verbose_name="Subcategoria", on_delete=models.CASCADE, blank = True, null= True)
creado = models.DateTimeField(auto_now_add=True)
modificado = models.DateTimeField(auto_now_add=True)
class Meta:
"""Meta definition for Hilo."""
verbose_name = 'Categoria'
verbose_name_plural = 'Categorias'
def __str__(self):
"""Unicode representation of Hilo."""
return self.Titulo<file_sep>/LEC/foro/migrations/0002_auto_20201102_1806.py
# Generated by Django 3.1.1 on 2020-11-02 18:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('foro', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='categoria',
name='Subcategoria',
field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='foro.subcategoria', verbose_name='Subcategoria'),
),
]
<file_sep>/README.md
# webLEC
WEB PARA LEC (Liga Española de Competicion)
Pagina principa donde se pueden ver post creados por redactor(Tipo resultado de competiciones,anuncios,info sobre eventos,etc... como si fuera un blog)
Menu para realizar las inscripciones a campeonato:
[ ] Para realizar inscripcion primero debe estar registrado(como equipo, no vale nombre de usuario random)
[ ] Equipo registra a pilotos(Se le asigna ese equipo al piloto). Cuando piloto haga login se muestra pantalla para poner nombre y contraseña
[ ] Primera pantalla donde se elige el campeonato(se muestra si el periodo de inscripcion esta abierto.En caso de no estarlo, se muestra fecha de apertura si existe)
[ ] Dentro de campeonato elegido se muestra formulario(diferentes pasos) para inscribir equipo y pilotos.
Consulta de equipos y pilotos por equipos inscritos en campeonatos
Formulario de contacto con administracion
Formulario de peticion de traspaso(Si se realiza traspaso de pilotos entre equipos se queda registrado y se muestra en web)
Se pueda ver streaming oficial desde pagina web<file_sep>/LEC/usuarios/urls.py
from django.urls import path
from . import views
app_name= 'usuarios'
urlpatterns = [
path('registro', views.registro, name='registro'),
path('sent/', views.activation_sent_view, name="activation_sent"),
path('activate/<slug:uidb64>/<slug:token>/', views.activate, name="activate"),
]<file_sep>/LEC/foro/migrations/0003_auto_20201102_1807.py
# Generated by Django 3.1.1 on 2020-11-02 18:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('foro', '0002_auto_20201102_1806'),
]
operations = [
migrations.AlterField(
model_name='categoria',
name='creado',
field=models.DateTimeField(auto_now_add=True),
),
migrations.AlterField(
model_name='categoria',
name='modificado',
field=models.DateTimeField(auto_now_add=True),
),
]
<file_sep>/LEC/usuarios/migrations/0004_auto_20201009_1020.py
# Generated by Django 3.1.1 on 2020-10-09 10:20
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('usuarios', '0003_auto_20201006_1147'),
]
operations = [
migrations.RenameField(
model_name='usuario',
old_name='status',
new_name='rol',
),
migrations.RemoveField(
model_name='usuario',
name='activo',
),
migrations.AlterField(
model_name='usuario',
name='user',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='usuario'),
),
migrations.CreateModel(
name='Equipo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre_equipo', models.CharField(max_length=50)),
('abreviatura', models.CharField(max_length=50)),
('email_equipo', models.EmailField(max_length=254)),
('activo', models.BooleanField(default=False)),
('fecha_creacion', models.DateTimeField(auto_now_add=True)),
('fecha_modificacion', models.DateTimeField(auto_now_add=True)),
('fecha_baja', models.DateTimeField()),
('pilotos', models.ManyToManyField(through='usuarios.Usuario', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'Equipo',
'verbose_name_plural': 'Equipos',
'db_table': 'equipo',
'managed': True,
},
),
migrations.AlterField(
model_name='usuario',
name='equipo',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='usuarios.equipo'),
),
]
<file_sep>/LEC/usuarios/views.py
from django.shortcuts import render, redirect
from django.contrib.sites.shortcuts import get_current_site
from django.utils.http import urlsafe_base64_decode
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from .tokens import account_activation_token
from django.template.loader import render_to_string
from django.utils.encoding import force_text
from django.contrib.auth.models import User
from .models import Usuario
from django.contrib.auth import authenticate, login as do_login, logout as do_logout
from .forms import formulario_registro, formulario_registro_equipo
# Create your views here.
def activation_sent_view(request):
return render(request, 'usuarios/activacion_enviada.html')
def login(request):
do_logout(request)
username = request.POST['nombre_usuario']
password = request.POST['<PASSWORD>']
usuario = authenticate(request, username=username, password=password)
print(usuario)
if usuario is not None:
do_login(request, usuario)
return redirect('index')
else:
return redirect('index')
def logout(request):
do_logout(request)
return redirect('index')
def registro(request):
"""
Funcion para realizar el registro de un usuario de manera manual(solo lo pueden hacer los jefes de equipo)
"""
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = formulario_registro(request.POST)
print(form.errors)
# check whether it's valid:
if form.is_valid():
print
# process the data in form.cleaned_data as required
user = form.save()
user.refresh_from_db()
user.is_active = False
user.save()
usuario = Usuario()
usuario.user = user
usuario.save()
current_site = get_current_site(request)
subject = 'Activacion de cuenta'
message = render_to_string('usuarios/activacion_cuenta.html',{
'usuario' : user,
'dominio' : current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
user.email_user(subject,message)
return redirect('usuarios:activation_sent')
# username = form.cleaned_data.get("username")
# password = form.cleaned_data.get("<PASSWORD>")
# usuario = authenticate(username=username, password=<PASSWORD>)
# print(usuario)
# if usuario is not None:
# do_login(request, usuario)
# return redirect('index')
# else:
# return redirect('index')
# if a GET (or any other method) we'll create a blank form
else:
form = formulario_registro()
return render(request,'GeneralTemplates/registerForm.html', {'form':form})
def activate(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
# checking if the user exists, if the token is valid.
if user is not None and account_activation_token.check_token(user, token):
# if valid set active true
user.is_active = True
# set signup_confirmation true
user.usuario.signup_confirmation = True
user.save()
do_login(request, user)
return redirect('index')
else:
return render(request, 'activacion_error.html')
def registro_equipo(request):
"""
Funcion para registrar los datos del equipo
"""
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = formulario_registro_equipo(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return render(request,'blog/blog.html')
# if a GET (or any other method) we'll create a blank form
else:
form = formulario_registro_equipo()
return render(request,'GeneralTemplates/teamRegister.html', {'form':form})
| 80ed2a6a86ccd635d801d4fa26b0db8fbb85e7c9 | [
"Markdown",
"Python",
"Text"
] | 26 | Python | setuphub/webLEC | 9136357cdeef0aedc52d6d97df8466a4bfe80bd8 | 0ed8a431baca256da119bbafcc5b572b538429c2 | |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package service;
import entity.Company;
import vo.CompanyVO;
import dao.CompanyDAO;
import dao.DAOFactory;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
/**
*
* @author ESTUDIANTE
*/
public class CompanyService extends BaseService {
public CompanyVO newCompany(CompanyVO companyVO) {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
CompanyDAO companyDAO = DAOFactory.getCompanyDAO(em);
Company company = companyVO.toEntity();
try {
trans.begin();
companyDAO.save(company);
trans.commit();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
if(company == null){
return null;
}
return company.toVO();
}
public CompanyVO findCompany(Long id) {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
CompanyDAO companyDAO = DAOFactory.getCompanyDAO(em);
Company company = null;
try {
trans.begin();
company = companyDAO.find(id);
trans.commit();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
if(company == null){
return null;
}
return company.toVO();
}
public List<CompanyVO> allCompanies() {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
CompanyDAO companyDAO = DAOFactory.getCompanyDAO(em);
List<Company> companies = null;
List<CompanyVO> companysVO = new ArrayList<CompanyVO>();
try {
trans.begin();
companies = companyDAO.getAll();
trans.commit();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
if(companies == null){
return null;
}
for (Company company : companies) {
companysVO.add(company.toVO());
}
return companysVO;
}
public List<CompanyVO> findCompaniesByMarketId(int market_id) {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
CompanyDAO companyDAO = DAOFactory.getCompanyDAO(em);
List<Company> comanies = null;
List<CompanyVO> companysVO = new ArrayList<CompanyVO>();
try {
trans.begin();
comanies = companyDAO.findByMarketId(market_id);
trans.commit();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
for (Company company : comanies) {
companysVO.add(company.toVO());
}
return companysVO;
}
public boolean updateCompany(CompanyVO companyVO) {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
CompanyDAO companyDAO = DAOFactory.getCompanyDAO(em);
boolean flag = true;
try {
trans.begin();
companyDAO.save(companyVO.toEntity());
trans.commit();
} catch (Exception e) {
trans.rollback();
flag = false;
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
return flag;
}
public boolean deleteCompany(long id) {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
CompanyDAO companyDAO = DAOFactory.getCompanyDAO(em);
boolean flag = true;
try {
trans.begin();
companyDAO.delete(id);
trans.commit();
} catch (Exception e) {
trans.rollback();
flag = false;
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
return flag;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import vo.DateVO;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
/**
*
* @author LOPEZ
*/
@Entity
public class Date implements Serializable {
// private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long date_id;
private int date_day;
private int date_month;
private java.sql.Date date_string;
private int date_year;
@OneToMany(mappedBy = "date")
private Collection<Quote> quoteCollection;
public Long getId() {
return getDate_id();
}
public void setId(Long id) {
this.setDate_id(id);
}
@Override
public int hashCode() {
int hash = 0;
hash += (getDate_id() != null ? getDate_id().hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Date)) {
return false;
}
Date other = (Date) object;
if ((this.getDate_id() == null && other.getDate_id() != null) || (this.getDate_id() != null && !this.date_id.equals(other.date_id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Entity.Date[ id=" + getDate_id() + " ]";
}
/**
* @return the date_id
*/
public Long getDate_id() {
return date_id;
}
/**
* @param date_id the date_id to set
*/
public void setDate_id(Long date_id) {
this.date_id = date_id;
}
/**
* @return the daet_Day
*/
public int getDate_day() {
return date_day;
}
/**
* @param daet_Day the daet_Day to set
*/
public void setDate_day(int daet_Day) {
this.date_day = daet_Day;
}
/**
* @return the date_month
*/
public int getDate_month() {
return date_month;
}
/**
* @param date_month the date_month to set
*/
public void setDate_month(int date_month) {
this.date_month = date_month;
}
/**
* @return the date_string
*/
public java.sql.Date getDate_string() {
return date_string;
}
/**
* @param date_string the date_string to set
*/
public void setDate_string(java.sql.Date date_string) {
this.date_string = date_string;
}
/**
* @return the date_year
*/
public int getDate_year() {
return date_year;
}
/**
* @param date_year the date_year to set
*/
public void setDate_year(int date_year) {
this.date_year = date_year;
}
public DateVO toVO() {
DateVO dateVO = new DateVO();
dateVO.setDateDay(this.getDate_day());
dateVO.setDateId(this.getDate_id());
dateVO.setDateMonth(this.date_month);
dateVO.setDateString(this.getDate_string());
dateVO.setDate_year(this.getDate_year());
return dateVO;
}
public java.sql.Date StringtoDate(String strFecha) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date fecha = null;
try {
java.util.Date parsed = format.parse(strFecha);
fecha = new java.sql.Date(parsed.getTime());
} catch (ParseException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return fecha;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import vo.RoleVO;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* @author LOPEZ
*/
@Entity
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "rol_id")
private Long id;
private String rol_name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Role)) {
return false;
}
Role other = (Role) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Entity.Role[ id=" + id + " ]";
}
/**
* @return the rol_name
*/
public String getRol_name() {
return rol_name;
}
/**
* @param rol_name the rol_name to set
*/
public void setRol_name(String rol_name) {
this.rol_name = rol_name;
}
public RoleVO getVO() {
RoleVO rolVO = new RoleVO();
rolVO.setRolId(this.id.intValue());
rolVO.setRolName(this.rol_name);
return rolVO;
}
public Role setVO(RoleVO rolVO) {
this.id = new Long(rolVO.getRolId());
this.rol_name = rolVO.getRolName();
return this;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import vo.UserVO;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* @author LOPEZ
*/
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long user_id;
private String name;
private String pass;
private int role_id;
public Long getId() {
return user_id;
}
public void setId(Long id) {
this.user_id = id;
}
@Override
public int hashCode() {
int hash = 0;
hash += (user_id != null ? user_id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof User)) {
return false;
}
User other = (User) object;
if ((this.user_id == null && other.user_id != null) || (this.user_id != null && !this.user_id.equals(other.user_id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Entity.Usuario[ id=" + user_id + " ]";
}
public UserVO getVO() {
UserVO userVO = new UserVO();
userVO.setName(name);
userVO.setPass(pass);
userVO.setRole_id(role_id);
userVO.setUser_id(this.user_id.intValue());
return userVO;
}
public User setVO(UserVO userVO) {
this.name = userVO.getName();
this.pass = userVO.getPass();
this.role_id = userVO.getRole_id();
this.user_id = new Long(userVO.getUser_id());
return this;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entity.Company;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
/**
*
* @author LOPEZ
*/
public class CompanyDAO extends BaseDAO<Company> {
public CompanyDAO(EntityManager em) {
super(em);
}
public List<Company> findByMarketId(int marketId) {
Query query = this.em.createQuery("SELECT e FROM Company e WHERE e.market_id=:market_id");
query.setParameter("market_id", marketId);
List<Company> companies = query.getResultList();
return companies;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vo;
/**
*
* @author windows 7
*/
public class RoleVO {
private int rolId;
private String rolName;
public int getRolId() {
return rolId;
}
public void setRolId(int rolId) {
this.rolId = rolId;
}
public String getRolName() {
return rolName;
}
public void setRolName(String rolName) {
this.rolName = rolName;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import vo.CompanyVO;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* @author LOPEZ
*/
@Entity
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long company_id;
private String company_description;
private String company_name;
private int market_id;
private String company_symbol;
public Long getId() {
return company_id;
}
public void setId(Long id) {
this.company_id = id;
}
/**
* @return the company_id
*/
public Long getCompany_id() {
return company_id;
}
/**
* @param company_id the company_id to set
*/
public void setCompany_id(Long company_id) {
this.company_id = company_id;
}
/**
* @return the company_description
*/
public String getCompany_description() {
return company_description;
}
/**
* @param company_description the company_description to set
*/
public void setCompany_description(String company_description) {
this.company_description = company_description;
}
/**
* @return the market_name
*/
public String getCompany_name() {
return company_name;
}
/**
* @param market_name the market_name to set
*/
public void setCompany_name(String market_name) {
this.company_name = market_name;
}
/**
* @return the market_id
*/
public int getMarket_id() {
return market_id;
}
/**
* @param market_id the market_id to set
*/
public void setMarket_id(int market_id) {
this.market_id = market_id;
}
/**
* @return the company_symbol
*/
public String getCompany_symbol() {
return company_symbol;
}
/**
* @param company_symbol the company_symbol to set
*/
public void setCompany_symbol(String company_symbol) {
this.company_symbol = company_symbol;
}
@Override
public String toString() {
return "Entity.Company[ id=" + company_id + " ]";
}
public CompanyVO toVO(){
CompanyVO companyVO = new CompanyVO();
companyVO.setCompanyDescription(this.getCompany_description());
companyVO.setCompanyId(this.getCompany_id());
companyVO.setCompanyName(this.getCompany_name());
companyVO.setMarketId(this.getMarket_id());
companyVO.setCompanySymbol(this.getCompany_symbol());
return companyVO;
}
}
<file_sep>package vo;
import entity.Date;
import entity.Quote;
import entity.Stock;
/*
* 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.
*/
/**
*
* @author ESTUDIANTE
*/
public class QuoteVO {
private Long quoteId;
private double quote;
private double quoteHigh;
private double quoteLow;
private double quoteOpen;
private double quoteClose;
private Stock stock;
private Date date;
/**
* @return the quote
*/
public double getQuote() {
return quote;
}
/**
* @param quote the quote to set
*/
public void setQuote(double quote) {
this.quote = quote;
}
/**
* @return the quoteHigh
*/
public double getQuoteHigh() {
return quoteHigh;
}
/**
* @param quoteHigh the quoteHigh to set
*/
public void setQuoteHigh(double quoteHigh) {
this.quoteHigh = quoteHigh;
}
public Long getQuoteId() {
return quoteId;
}
public void setQuoteId(Long quoteId) {
this.quoteId = quoteId;
}
public Stock getStock() {
return stock;
}
public void setStock(Stock stock) {
this.stock = stock;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
/**
* @return the quoteLow
*/
public double getQuoteLow() {
return quoteLow;
}
/**
* @param quoteLow the quoteLow to set
*/
public void setQuoteLow(double quoteLow) {
this.quoteLow = quoteLow;
}
/**
* @return the quoteOpen
*/
public double getQuoteOpen() {
return quoteOpen;
}
/**
* @param quoteOpen the quoteOpen to set
*/
public void setQuoteOpen(double quoteOpen) {
this.quoteOpen = quoteOpen;
}
/**
* @return the quoteClose
*/
public double getQuoteClose() {
return quoteClose;
}
/**
* @param quoteClose the quoteClose to set
*/
public void setQuoteClose(double quoteClose) {
this.quoteClose = quoteClose;
}
public Quote toEntity(){
Quote entity = new Quote();
entity.setQuote_id(this.getQuoteId());
entity.setQuote_open(this.getQuoteOpen());
entity.setQuote_high(this.getQuoteHigh());
entity.setQuote_low(this.getQuoteLow());
entity.setQuote_close(this.getQuoteClose());
entity.setDate(this.getDate());
entity.setStock(this.getStock());
return entity;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package service;
import dao.DAOFactory;
import entity.Market;
import vo.MarketVO;
import dao.MarketDAO;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
/**
*
* @author ESTUDIANTE
*/
public class MarketService extends BaseService {
public MarketVO newMarket(MarketVO marketVO) {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
MarketDAO marketDAO = DAOFactory.getMarketDAO(em);
Market market = marketVO.toEntity();
try {
trans.begin();
marketDAO.save(market);
trans.commit();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
if(market == null){
return null;
}
return market.toVO();
}
public MarketVO findMarket(Long id) {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
MarketDAO companyDAO = DAOFactory.getMarketDAO(em);
Market market = null;
try {
trans.begin();
market = companyDAO.find(id);
trans.commit();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
if(market == null){
return null;
}
return market.toVO();
}
public List<MarketVO> allMarkets() {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
MarketDAO companyDAO = DAOFactory.getMarketDAO(em);
List<Market> markets = null;
List<MarketVO> marketsVO = new ArrayList<MarketVO>();
try {
trans.begin();
markets = companyDAO.getAll();
trans.commit();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
if(markets == null){
return null;
}
for (Market market : markets) {
marketsVO.add(market.toVO());
}
return marketsVO;
}
public boolean updateMarket(MarketVO marketVO) {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
MarketDAO marketDAO = DAOFactory.getMarketDAO(em);
boolean flag = true;
Market market = marketVO.toEntity();
try {
trans.begin();
marketDAO.update(market);
trans.commit();
} catch (Exception e) {
trans.rollback();
flag = false;
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
return flag;
}
public boolean deleteMarket(Long id) {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
MarketDAO marketDAO = DAOFactory.getMarketDAO(em);
boolean flag = true;
try {
trans.begin();
marketDAO.delete(id);
trans.commit();
} catch (Exception e) {
trans.rollback();
flag = false;
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
return flag;
}
}
<file_sep>package vo;
import entity.Date;
/*
* 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.
*/
/**
*
* @author ESTUDIANTE
*/
public class DateVO {
private int dateDay;
private Long dateId;
private int dateMonth;
private java.sql.Date dateString;
private int date_year;
/**
* @return the dareDay
*/
public int getDateDay() {
return dateDay;
}
/**
* @param dateDay the dareDay to set
*/
public void setDateDay(int dateDay) {
this.dateDay = dateDay;
}
public Long getDateId() {
return dateId;
}
public void setDateId(Long dateId) {
this.dateId = dateId;
}
/**
* @return the dateMonth
*/
public int getDateMonth() {
return dateMonth;
}
/**
* @param dateMonth the dateMonth to set
*/
public void setDateMonth(int dateMonth) {
this.dateMonth = dateMonth;
}
/**
* @return the dateString
*/
public java.sql.Date getDateString() {
return dateString;
}
/**
* @param dateString the dateString to set
*/
public void setDateString(java.sql.Date dateString) {
this.dateString = dateString;
}
/**
* @return the date_year
*/
public int getDate_year() {
return date_year;
}
/**
* @param date_year the date_year to set
*/
public void setDate_year(int date_year) {
this.date_year = date_year;
}
public Date toEntity(){
Date entity = new Date();
entity.setDate_id(this.getDateId());
entity.setDate_day(this.getDateDay());
entity.setDate_month(this.getDateMonth());
entity.setDate_year(this.getDate_year());
entity.setDate_string(this.getDateString());
return entity;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package service;
import dao.DAOFactory;
import entity.Date;
import vo.DateVO;
import dao.DateDAO;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
/**
*
* @author ESTUDIANTE
*/
public class DateService extends BaseService {
public DateVO findDate(Long id) {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
DateDAO dateDAO = DAOFactory.getDateDAO(em);
Date date = null;
try {
trans.begin();
date = dateDAO.find(id);
trans.commit();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
if(date == null){
return null;
}
return date.toVO();
}
public List<DateVO> allDates() {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
DateDAO dateDAO = DAOFactory.getDateDAO(em);
List<Date> dates = null;
List<DateVO> datesVO = new ArrayList<DateVO>();
try {
trans.begin();
dates = dateDAO.getAll();
trans.commit();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
for (Date date : dates) {
datesVO.add(date.toVO());
}
return datesVO;
}
public DateVO newDate(DateVO dateVO) {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
DateDAO dateDAO = DAOFactory.getDateDAO(em);
Date date = dateVO.toEntity();
try {
trans.begin();
dateDAO.save(date);
trans.commit();
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
if(date == null){
return null;
}
return date.toVO();
}
public boolean updateDate(DateVO dateVO) {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
DateDAO dateDAO = DAOFactory.getDateDAO(em);
boolean flag = true;
try {
trans.begin();
dateDAO.save(dateVO.toEntity());
trans.commit();
} catch (Exception e) {
trans.rollback();
flag = false;
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
return flag;
}
public boolean deleteDate(Long id) {
EntityManager em = this.getNewEntityManager();
EntityTransaction trans = em.getTransaction();
DateDAO dateDAO = DAOFactory.getDateDAO(em);
boolean flag = true;
try {
trans.begin();
dateDAO.delete(id);
trans.commit();
} catch (Exception e) {
trans.rollback();
flag = false;
System.err.println(e.getMessage());
} finally {
em.clear();
em.close();
}
return flag;
}
}
| 710a01d0f79d8f97b436fc82563868c40e15bdcf | [
"Java"
] | 11 | Java | FelipeIzquierdo/exam_final | b7ea3ae13cd4e0aa2dacd3edffc489f239307040 | 1e53d251a5c10bd60653424f47afadb28450a020 | |
refs/heads/master | <file_sep>package com.foamvalue.wechat.service;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.foamvalue.wechat.dao.DaoImpl;
import com.foamvalue.wechat.utils.WechatUtils;
import io.vertx.core.json.JsonArray;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
/**
* @ClassName: WechatService
* @Description: 业务逻辑类
* @author FoamValue <EMAIL>
* @date 2016年1月25日 下午3:06:10
*
*/
public class WechatService {
private static final Logger LOG_MSG = LoggerFactory.getLogger("ChatUtils"); // 日志文件
public static final String CHAT_FORMAT = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";
// 多客服 XML 模版
public static final String TRANSFER_CUSTOMER = "<xml><ToUserName><![CDATA[%1$s]]></ToUserName><FromUserName><![CDATA[%2$s]]></FromUserName><CreateTime>%3$s</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>";
// 文本 XML 模版
public static final String TEXT_FORMAT = "<xml><ToUserName><![CDATA[%1$s]]></ToUserName><FromUserName><![CDATA[%2$s]]></FromUserName><CreateTime>%3$s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%4$s]]></Content></xml>";
/**
* @param msg
* @return
*/
public static final String fvLogChatIns(Map<String, String> msg) {
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO `fv-vertx`.`fv_log_chat`(`msg_type`,`to_user_name`,`from_user_name`,`create_time`");
switch (msg.get("MsgType")) {
case "text":
sql.append(",`msg_id`,`content`) ");
break;
case "image":
sql.append(",`msg_id`,`pic_url`,`media_id`) ");
break;
case "voice":
if (msg.get("Recognition") != null) {
sql.append(",`msg_id`,`media_id`,`format`, `recognition`) ");
} else {
sql.append(",`msg_id`,`media_id`,`format`) ");
}
break;
case "video":
case "shortvideo":
sql.append(",`msg_id`,`media_id`,`thumb_media_id`) ");
break;
case "location":
sql.append(",`msg_id`,`location_x`,`location_y`,`scale`,`label`) ");
break;
case "link":
sql.append(",`msg_id`,`title`,`description`,`url`) ");
break;
case "event": // TODO 事件消息
switch(msg.get("Event")) {
case "unsubscribe":
case "subscribe":
if (StringUtils.isBlank(msg.get("EventKey"))) {
sql.append(",`event`) ");
break;
}
case "SCAN":
sql.append(",`event`, `event_key`, `ticket`) ");
break;
case "LOCATION":
sql.append(",`event`, `latitude`, `longitude`, `precision`) ");
break;
case "CLICK":
case "VIEW":
sql.append(",`event`, `event_key`) ");
break;
}
break;
};
sql.append("VALUES ('").append(msg.get("MsgType")).append("','").append(msg.get("ToUserName")).append("','").append(msg.get("FromUserName")).append("','").append(msg.get("CreateTime")).append("'");
switch (msg.get("MsgType")) {
case "text":
sql.append(",'").append(msg.get("MsgId")).append("','").append(msg.get("Content")).append("')");
break;
case "image":
sql.append(",'").append(msg.get("MsgId")).append("','").append(msg.get("PicUrl")).append("','").append(msg.get("MediaId")).append("')");
break;
case "voice":
if (msg.get("Recognition") != null) {
sql.append(",'").append(msg.get("MsgId")).append("','").append(msg.get("MediaId")).append("','").append(msg.get("Format")).append("','").append(WechatUtils.transcoding(msg.get("Recognition"))).append("')");
} else {
sql.append(",'").append(msg.get("MsgId")).append("','").append(msg.get("MediaId")).append("','").append(msg.get("Format")).append("')");
}
break;
case "video":
case "shortvideo":
sql.append(",'").append(msg.get("MsgId")).append("','").append(msg.get("MediaId")).append("','").append(msg.get("ThumbMediaId")).append("')");
break;
case "location":
sql.append(",'").append(msg.get("MsgId")).append("','").append(msg.get("Location_X")).append("','").append(msg.get("Location_Y")).append("','").append(msg.get("Scale")).append("','").append(msg.get("Label")).append("')");
break;
case "link":
sql.append(",'").append(msg.get("MsgId")).append("','").append(msg.get("Title")).append("','").append(msg.get("Description")).append("','").append(msg.get("Url")).append("')");
break;
case "event": // TODO 事件消息
switch(msg.get("Event")) {
case "unsubscribe":
case "subscribe":
if (StringUtils.isBlank(msg.get("EventKey"))) {
sql.append(",'").append(msg.get("Event")).append("')");
break;
}
case "SCAN":
sql.append(",'").append(msg.get("Event")).append("','").append(msg.get("EventKey")).append("','").append(msg.get("Ticket")).append("')");
break;
case "LOCATION":
sql.append(",'").append(msg.get("Event")).append("','").append(msg.get("Latitude")).append("','").append(msg.get("Longitude")).append("','").append(msg.get("Precision")).append("')");
break;
case "CLICK":
case "VIEW":
sql.append(",'").append(msg.get("Event")).append("','").append(msg.get("EventKey")).append("')");
break;
}
break;
};
LOG_MSG.debug(sql.toString());
return sql.toString();
}
/**
* 取消订阅
* @param connection
* @param openId
*/
public static final void unsubscribe(String openId) {
DaoImpl.update("update `fv-vertx`.`fv_chat_fans` set `subscribe` = 0, `fv_upd_time` = now() where `open_id` = ?", updRes -> {
if (updRes.failed()) {
LOG_MSG.error(updRes.cause());
return;
}
});
}
/**
* 订阅
* @param connection
* @param openId
* @param eventKey 事件KEY值,qrscene_为前缀,后面为二维码的参数值
* @param ticket 二维码的ticket,可用来换取二维码图片
*/
public static final void subscribe(String openId, String eventKey, String ticket) {
DaoImpl.queryWithParams("select count(1) from fv_chat_fans where open_id = ?", new JsonArray().add(openId), selRes -> {
if (selRes.failed()) {
LOG_MSG.error(selRes.cause());
return;
}
Long count = selRes.result().getResults().get(0).getLong(0); // 获取行数
Boolean isScan = StringUtils.isNotBlank(eventKey) && StringUtils.isNotBlank(ticket);
if (count == 0L) {
StringBuilder insSql = new StringBuilder();
insSql.append("INSERT INTO `fv-vertx`.`fv_chat_fans`(`open_id`,`subscribe`");
if (isScan) {
insSql.append(",`event_key`,`ticket`");
}
insSql.append(") VALUES('")
.append(openId)
.append("', 1");
if (isScan) {
insSql.append(", '")
.append(eventKey)
.append("', '")
.append(ticket)
.append("'");
}
insSql.append(")");
DaoImpl.update(insSql.toString(), insRes -> {
if (insRes.failed()) {
LOG_MSG.error(insRes.cause());
return;
}
});
} else {
StringBuilder updSql = new StringBuilder();
updSql.append("update `fv-vertx`.`fv_chat_fans` set `subscribe` = 0, `fv_upd_time` = now()");
if (isScan) {
updSql.append(", `event_key` = '")
.append(eventKey)
.append("', `ticket` = '")
.append(ticket)
.append("' ");
}
updSql.append("where `open_id` = '")
.append(openId)
.append("'");
DaoImpl.update(updSql.toString(), updRes -> {
if (updRes.failed()) {
LOG_MSG.error(updRes.cause());
return;
}
});
}
});
}
/**
* 扫码
* @param connection
* @param openId
* @param eventKey
* @param ticket
*/
public static final void scan(String openId, String eventKey, String ticket) {
DaoImpl.updateWithParams("INSERT INTO `fv-vertx`.`fv_chat_fans_scan`(`open_id`,`event_key`,`ticket`)VALUES(?,?,?)",
new JsonArray().add(openId).add(eventKey).add(ticket), insRes -> {
if (insRes.failed()) {
LOG_MSG.error(insRes.cause());
return;
}
});
}
/**
* 上报地理位置信息
* @param client
* @param openId
* @param latitude
* @param longitude
* @param precision
*/
public static final void location(String openId, String latitude, String longitude, String precision) {
DaoImpl.updateWithParams("INSERT INTO `fv-vertx`.`fv_chat_fans_location`(`open_id`,`latitude`,`longitude`,`precision`)VALUES(?, ?, ?, ?)",
new JsonArray().add(openId).add(latitude).add(longitude).add(precision), insRes -> {
if (insRes.failed()) {
LOG_MSG.error(insRes.cause());
return;
}
});
}
}
<file_sep>package com.foamvalue.wechat.dao;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.SQLConnection;
import io.vertx.ext.sql.UpdateResult;
/**
* @ClassName: DaoImpl
* @Description: TODO 数据库操作类
* @author FoamValue <EMAIL>
* @date 2016年1月26日 上午10:36:15
*
*/
public class DaoImpl {
private static final Logger LOG_MSG = LoggerFactory.getLogger("DaoImpl"); // 日志文件
private static JDBCClient client; // 异步 JDBC 客户端
/**
* @param vertx
* @param config
*/
public DaoImpl(Vertx vertx, JsonObject config) {
client = JDBCClient.createShared(vertx, config);
}
/**
* @param sql
* @param resultHandler
*/
public static void execute(String sql, Handler<AsyncResult<Void>> resultHandler) {
client.getConnection(conn -> {
if (conn.failed()) {
LOG_MSG.error(conn.cause().getMessage());
return;
}
final SQLConnection connection = conn.result();
try {
connection.execute(sql, resultHandler);
closeConn(connection);
} catch (Exception e) {
closeConn(connection);
LOG_MSG.error(e.toString());
}
});
}
/**
* @param sql
* @param resultHandler
*/
public static void query(String sql, Handler<AsyncResult<ResultSet>> resultHandler) {
client.getConnection(conn -> {
if (conn.failed()) {
LOG_MSG.error(conn.cause().getMessage());
return;
}
final SQLConnection connection = conn.result();
try {
connection.query(sql, resultHandler);
closeConn(connection);
} catch (Exception e) {
closeConn(connection);
LOG_MSG.error(e.toString());
}
});
}
/**
* @param sql
* @param params
* @param resultHandler
*/
public static void updateWithParams(String sql, JsonArray params, Handler<AsyncResult<UpdateResult>> resultHandler) {
client.getConnection(conn -> {
if (conn.failed()) {
LOG_MSG.error(conn.cause().getMessage());
return;
}
final SQLConnection connection = conn.result();
try {
connection.updateWithParams(sql, params, resultHandler);
closeConn(connection);
} catch (Exception e) {
closeConn(connection);
LOG_MSG.error(e.toString());
}
});
}
/**
* @param sql
* @param params
* @param resultHandler
*/
public static void queryWithParams(String sql, JsonArray params, Handler<AsyncResult<ResultSet>> resultHandler) {
client.getConnection(conn -> {
if (conn.failed()) {
LOG_MSG.error(conn.cause().getMessage());
return;
}
final SQLConnection connection = conn.result();
try {
connection.queryWithParams(sql, params, resultHandler);
closeConn(connection);
} catch (Exception e) {
closeConn(connection);
LOG_MSG.error(e.toString());
}
});
}
/**
* @param sql
* @param resultHandler
*/
public static void update(String sql, Handler<AsyncResult<UpdateResult>> resultHandler) {
client.getConnection(conn -> {
if (conn.failed()) {
LOG_MSG.error(conn.cause().getMessage());
return;
}
final SQLConnection connection = conn.result();
try {
connection.update(sql, resultHandler);
closeConn(connection);
} catch (Exception e) {
closeConn(connection);
LOG_MSG.error(e.toString());
}
});
}
/**
* 关闭数据库链接
*
* @param connection
*/
private static void closeConn(SQLConnection connection) {
connection.close(done -> {
if (done.failed()) {
LOG_MSG.error(done.cause().getMessage());
}
});
}
}
<file_sep>package com.foamvalue.wechat;
import com.foamvalue.wechat.controller.Wechat;
import com.foamvalue.wechat.dao.DaoImpl;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonObject;
/**
* @ClassName: FoamValue
* @Description: Vert.x Web Verticle 实现类
* @author FoamValue <EMAIL>
* @date 2016年1月14日 下午4:12:07
*
*/
public class FoamValue extends AbstractVerticle {
//地址命名约定 CN.LIVE + ":" + SERVICE NAME + ":" + EVENT NAME + ":" + GET/POST
private static final String CHAT_GET_ADDRESS = "CN.LIVE:WECHAT:CHAT:GET";
private static final String CHAT_POST_ADDRESS = "CN.LIVE:WECHAT:CHAT:POST";
/**
* TODO 部署时,替换成 config();
* java -jar target/fv-rertx-0.0.1-SNAPSHOT-fat.jar -conf src/main/resources/application.json
*/
private static final JsonObject CONFIG = new JsonObject()
.put("url", "jdbc:mysql://localhost:3306/fv-vertx?useUnicode=true&characterEncoding=UTF-8")
.put("driver_class", "com.mysql.jdbc.Driver")
.put("user", "root")
.put("password", "<PASSWORD>")
.put("max_pool_size", 10);
@Override
public void start() {
EventBus eb = vertx.eventBus();
try {
new DaoImpl(vertx, CONFIG);
eb.consumer(CHAT_GET_ADDRESS, message -> {Wechat.doGet(message);});
eb.consumer(CHAT_POST_ADDRESS, message -> {Wechat.doPost(message);});
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.foamvalue</groupId>
<artifactId>x-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>x-parent</name>
<packaging>pom</packaging>
<modules>
<module>x-common</module>
</modules>
<properties>
<!-- 项目版本 -->
<project.encoding>UTF-8</project.encoding>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<project.version>0.0.1-SNAPSHOT</project.version>
<vertx.version>3.2.0</vertx.version>
<junit.version>4.12</junit.version>
<slf4j.version>1.7.14</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<gson.version>2.5</gson.version>
<commons.lang3.version>3.4</commons.lang3.version>
<commons.codec.version>1.10</commons.codec.version>
<dom4j.version>1.6.1</dom4j.version>
<mysql.version>5.1.37</mysql.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- vertx -->
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-core</artifactId>
<version>${vertx.version}</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
<version>${vertx.version}</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-hazelcast</artifactId>
<version>${vertx.version}</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-jdbc-client</artifactId>
<version>${vertx.version}</version>
</dependency>
<!-- log -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- tool -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons.codec.version}</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>${dom4j.version}</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-unit</artifactId>
<version>${vertx.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project><file_sep># Vert.x
Micro Services
<file_sep>package com.foamvalue.common.utils;
import io.vertx.core.http.HttpServerResponse;
/**
* @ClassName: ResultMsgUtils
* @Description: TODO 返回信息工具
* @author FoamValue <EMAIL>
* @date 2016年3月7日 下午8:30:26
*
*/
public class ResultMsgUtils {
/**
* 返回错误码
*
* @param routingContext
* @param code
*/
public static void returnMSG(HttpServerResponse response) {
returnMSG(response, "");
}
public static void returnMSG(HttpServerResponse response, ResultCodeEnum code) {
returnMSG(response, "错误码:" + code.getResultCode());
}
public static void returnMSG(HttpServerResponse response, String msg) {
response.setChunked(true);
response.write(msg); // Write a String to the response body, encoded in UTF-8.
response.end(); // Once the response has ended, it cannot be used any more.
}
public static void returnMSG(HttpServerResponse response, int statusCode) {
response.setStatusCode(statusCode).end();
}
}<file_sep>package com.foamvalue.eventBus.router;
import com.foamvalue.common.utils.ResultMsgUtils;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
/**
* @ClassName: WebsiteRouter
* @Description: TODO fv-website
* @author FoamValue <EMAIL>
* @date 2016年2月25日 下午2:08:15
*
*/
public class WebsiteRouter {
// WebSite
// 地址命名约定 CN.LIVE + ":" + SERVICE NAME + ":" + EVENT NAME + ":" + GET/POST
private static final String WEBSITE_ADDRESS = "CN.LIVE:WEBSITE";
/**
* 设置 fv-website 路由
* @param router
* @param vertx
*/
public static void setRouter(Router router, Vertx vertx) {
router.route().handler(new Handler<RoutingContext>() {
@Override
public void handle(RoutingContext event) {
vertx.eventBus().send(WEBSITE_ADDRESS, null, reply -> {
if (reply.succeeded()) {
Object rep = reply.result().body();
if (rep != null) {
ResultMsgUtils.returnMSG(event.response(), rep.toString());
} else {
ResultMsgUtils.returnMSG(event.response(), "");
}
} else {
ResultMsgUtils.returnMSG(event.response(), "");
}
});
}
});
}
}
<file_sep>package com.foamvalue.eventBus;
import com.foamvalue.eventBus.router.WeChatRouter;
import com.foamvalue.eventBus.router.WebsiteRouter;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
/**
* @ClassName: FoamValue
* @Description: 主服务
* @author FoamValue <EMAIL>
* @date 2016年2月18日 下午5:03:44
*
*/
public class FoamValue extends AbstractVerticle {
private static Router router;
private static final Logger LOG_MSG = LoggerFactory.getLogger("VertxHttpServer"); // 系统日志
@Override
public void start(Future<Void> fut) throws Exception {
router = Router.router(vertx); // 接受 HTTP 请求并转发给**第一个**匹配的路径
/**
* 服务化
* **优势**
* 服务松耦合原则:
* 1. 时间松耦合,异步操作保持高吞吐量;
* 2. 位置松耦合,地址访问不需要知道实际位置;
* 3. 版本松耦合,不依赖固定版本提供服务;
*
* **不足**
* 1. 提供新服务时,必须更新主服务。
* 2. 版本松耦合,功能必须向下兼容。
*
*/
router.route().handler(BodyHandler.create());
WeChatRouter.setRouter(router, vertx); // fv-wechat 路由
WebsiteRouter.setRouter(router, vertx); // TODO fv-website
LOG_MSG.info("Creating HTTP server for vert.x web application");
vertx.createHttpServer(new HttpServerOptions().setMaxWebsocketFrameSize(1000000)).requestHandler(router::accept).listen(80, result -> {
if (result.succeeded()) {
fut.complete();
} else {
fut.fail(result.cause());
}
});
}
}
| abc62545bb4e5f8ea39988204c6a26c344fe0f39 | [
"Markdown",
"Java",
"Maven POM"
] | 8 | Java | FoamValue/Vert.x | 2441974fc83bb47df1ff1b7eac4ef8ccfc484688 | 9665a47da976ec515c79092caa20e603d38a4a7f | |
refs/heads/master | <repo_name>omimo/mviz0<file_sep>/README.md
# mviz
A Gallery of Movement Visualizations
<file_sep>/p/gist_cache/scroll1/viz.js
// Variables
var title = 'Scroll Demo';
var skeleton; // Storing the skeleton data
var positions; // Storing the joint positions
var positions_scaled; // Storing the scaled joint positions
var figureScale = 2; // The scaling factor for our visualizations
var h = 200; // The height of the visualization
var w = 400; // The width of the visualization
var gap = 40;
var skip = 4;
//******************************************************************//
function run() {
d3.json("http://omid.al/moveviz/data/Skeleton_BEA.json", function(error, json) {
if (error) return console.warn(error);
skeleton = json;
d3.json("http://omid.al/moveviz/data/BEA1.json", function(error, json) {
positions = json;
updatefig();
$(window).scroll(updatefig);
});
});
}
function draw(index) {
document.getElementById('container').innerHTML = "";
var parent = d3.select("body").select("#container");
var svg = parent.append("svg")
.attr("width", w)
.attr("height", h)
.attr("overflow","scroll")
.style("display","inline-block");
// Scale the data
positions_scaled = positions.map(function(f, j) {
return f.map(function(d, i) {
return {
x: (d.x + 50) * figureScale,
y: -1 * d.y * figureScale + h - 10,
z: d.z * figureScale
};
});
});
// Choose the frame to draw
// index = 60; // the index of the frame
currentFrame = positions_scaled[index];
headJoint = 7;
svg.selectAll("circle.joints" + index)
.data(currentFrame)
.enter()
.append("circle")
.attr("cx", function(d) {
return d.x;
}).attr("cy", function(d) {
return d.y;
}).attr("r", function(d, i) {
if (i == headJoint )
return 4;
else
return 2;
}).attr("fill", function(d, i) {
return '#555555';
});
// Bones
svg.selectAll("line.bones" + index)
.data(skeleton)
.enter()
.append("line")
.attr("stroke", "#555555")
.attr("stroke-width",1)
.attr("x1",0).attr("x2",0)
.attr("x1", function(d, j) {
return currentFrame[d[0]].x;
})
.attr("x2", function(d, j) {
return currentFrame[d[1]].x;
})
.attr("y1", function(d, j) {
return currentFrame[d[0]].y;
})
.attr("y2", function(d, j) {
return currentFrame[d[1]].y;
});
window.parent.loaded();
}
function updatefig() {
var totalScroll = document.body.scrollHeight - document.body.clientHeight;
var currentScroll = window.scrollY;
var per = currentScroll / totalScroll;
var frame = Math.floor(per * (positions.length-1));
draw(frame);
}
<file_sep>/_gp.sh
#!/bin/bash
echo "Checking out into gh-pages"
git checkout gh-pages
echo "Merging"
git merge master
echo "Pushing to the origin"
git push origin gh-pages
echo "Back to the master"
git checkout master | d4e7ddd2a532c97e65d8cb4d3892d776f6c7abed | [
"Markdown",
"JavaScript",
"Shell"
] | 3 | Markdown | omimo/mviz0 | cea73bf0af818bd687e912c1943df8f274cbe4a9 | cc58759e34d31ce43d5dd88d434ca71620f3841a | |
refs/heads/master | <file_sep>import * as React from 'react';
import {Component} from 'react';
import {render} from 'react-dom';
import MapGL, {Marker, Popup} from 'react-map-gl';
import * as medData from './data/med-info.json';
import 'mapbox-gl/dist/mapbox-gl.css';
import './index.css';
import MedInfo from './medinfo'
const MAPBOX_TOKEN = process.env.REACT_APP_MAPBOX_TOKEN;
class Root extends Component {
constructor(props) {
super(props);
this.state = {
viewport: {
latitude: 41.5951,
longitude: -72.6454,
zoom: 14,
bearing: 0,
pitch: 0
},
popupInfo: null
};
}
_renderCityMarker = (med, index) => {
return(
<Marker
key={`marker-${index}`}
latitude={med.coordinates[1]}
longitude={med.coordinates[0]}
>
<button
className="marker-btn"
onClick={() => this.setState({popupInfo: med})}
>
<img src="weed.svg" alt="x" height="30px" width="30px" />
</button>
</Marker>
)
}
_updateViewport = viewport => {
this.setState({viewport});
};
_onClickMarker = med => {
this.setState({popupInfo: med})
}
_renderPopup() {
const {popupInfo} = this.state;
return (
popupInfo && (
<Popup
tipSize={5}
anchor="top"
longitude={popupInfo.coordinates[0]}
latitude={popupInfo.coordinates[1]}
closeOnClick={false}
onClose={() => this.setState({popupInfo: null})}
>
<MedInfo info={popupInfo} />
</Popup>
)
);
}
render() {
return (
<MapGL
{...this.state.viewport}
width="100vw"
height="100vh"
mapStyle="mapbox://styles/paduac/cka3d505900wa1ipi0<PASSWORD>"
onViewportChange={viewport => this.setState({viewport})}
mapboxApiAccessToken={MAPBOX_TOKEN}
>
{medData.dispos.map(this._renderCityMarker)}
{this._renderPopup()}
</MapGL>
);
}
}
document.body.style.margin = 0;
render(<Root />, document.body.appendChild(document.createElement('div')));
export default Root;
<file_sep>This project is map created with React-Map-GL with the intent of displaying every medical marijuana dispensary in the state of Connecticut. It's essentially a stripped-down version of WeedMaps.
| 705a62d3ba3771889daa9a9cda339c386f2f48a7 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | PaduaC/react-map | 76c82f7ce90371918235b655069f9b6f096d0ea2 | 3e76363775daf9f98a596a6be657cb81e3cd82ff | |
refs/heads/master | <repo_name>xdianovx/guitar-school<file_sep>/app/js/main.js
$(function () {
$('#courses__slider').slick({
loop: true
})
});
const burger = document.querySelector('#burger');
burger.addEventListener('click', function () {
let dropdown = document.querySelector('.header__nav');
dropdown.classList.toggle('active')
burger.classList.toggle('active')
})
//Tabs
document.querySelector('.about__tabs_link').classList.add('active');
document.querySelector('.about__tab').classList.add('active');
function selectTabContent(e) {
let target = e.target.dataset.targetYear;
document.querySelectorAll('.about__tabs_link, .about__tab').forEach((el) => {
el.classList.remove('active')
});
e.target.classList.add('active');
document.querySelector('.' + target).classList.add('active');
}
document.querySelectorAll('.about__tabs_link').forEach(el => {
el.addEventListener('click', selectTabContent)
})
| a4b73540af9bf36ac799cd89f03f08ec41d44c49 | [
"JavaScript"
] | 1 | JavaScript | xdianovx/guitar-school | 27b8797e8d0f2c1d2942eb3297e47db349f80215 | a9b65c09c3a821f9839ab5a8769304b5cbdf924c | |
refs/heads/master | <file_sep>/*
NAME: <NAME>
CRN: 41600
ASSIGNMENT: Lab 7
SOURCES: stackoverflow.com
*/
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
double A, B, a0, a1, a2, a3, a4, a5;
string in;
/* Accept decimal input */
cout << "Enter value for A below."
<< endl;
cin >> in;
try { // Check if x is numeric
A = stoll(in);
} catch (exception &e) {
cout << "\n"
<< "Make sure you're entering a real number!"
<< endl;
cin >> A;
}
cout << "Enter value for B below."
<< endl;
cin >> in;
try { // Check if x is numeric
B = stoll(in);
} catch (exception &e) {
cout << "\n"
<< "Make sure you're entering a real number!"
<< endl;
cin >> B;
}
cout << "Enter value for a0 below."
<< endl;
cin >> in;
try { // Check if x is numeric
a0 = stoll(in);
} catch (exception &e) {
cout << "\n"
<< "Make sure you're entering a real number!"
<< endl;
cin >> a0;
}
cout << "Enter value for a1 below."
<< endl;
cin >> in;
try { // Check if x is numeric
a1 = stoll(in);
} catch (exception &e) {
cout << "\n"
<< "Make sure you're entering a real number!"
<< endl;
cin >> a1;
}
// Report info
cout << "\nRECURRENCE RELATION: "
<< "A(k) = "
<< A
<< "A(k-1) + "
<< B
<< "A(k-2)"
<< endl;
cout << "INITIAL CONDITIONS: "
<< "a0 = "
<< a0
<< ", a1 = "
<< a1
<< endl;
cout << "CHARACTERISTIC EQUATION: "
<< "t^2 — "
<< A
<< "t — "
<< B
<< " = 0"
<< endl;
// Solve characteristic equation
double r, s;
double discriminant = A*A + 4*B;
double sequence[6];
if (discriminant > 0) {
r = (A + sqrt(discriminant)) / 2;
s = (A - sqrt(discriminant)) / 2;
double c, d;
if (s < 0) {
c = (a0 * -s)/(r+s); // this is (r+s)c
}
if (r < 0) {
d = (a0 * -r)/(r+s);
}
// Determine formula
cout << "FORMULA: A(n) = "
<< c // a0 = c + d
<< "("
<< r
<< ")^n + "
<< d // a1 = rc + sd
<< "("
<< s
<< ")^n"
<< endl;
// Print sequence
for(int n = 0; n < 6; n++) {
sequence[n] = (c * pow(r, n)) + (d * pow(s, n));
cout << "a"
<< n
<< " = "
<< sequence[n]
<< endl;
}
} else if (discriminant == 0) {
r = (A + sqrt(discriminant)) / 2;
// Determine formula
cout << "FORMULA: A(n) = "
<< a0
<< "("
<< r
<< ")^n + "
<< (a1 - a0*r) / r
<< "n("
<< r
<< ")^n"
<< endl;
// Print sequence
for(int n = 0; n < 6; n++) {
sequence[n] = (a0 * pow(r, n)) + (((a1 - a0*r) / r) * n * pow(r, n));
cout << "a"
<< n
<< " = "
<< sequence[n]
<< endl;
}
} else {
cout << "The roots are complex! Moving on..."
<< endl;
}
} | a0ef4ce2a6b32553c3d95fed6bd622682e0c447b | [
"C++"
] | 1 | C++ | hpalani/lab-7 | cc8f7e25f61d65965f15771f426b42d64e7c1ac2 | 7fe142f28f7599a9d5316a954bf580e670b0c13c | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KenkenSolve
{
abstract class Span//Collection of cells, may be a row, column or a group
{
public List<Cell> Cells = new List<Cell>();
public int Goal;
public char Character;
public abstract bool isValid();
public abstract void GenerateValids(Puzzle p);
public HashSet<int> Valids;
public bool ChangedSinceGeneration = true;
public abstract char CharCode { get; }
}
class ConstantSpan : Span
{
public override bool isValid()
{
return true;//Constants are always valid
}
public override void GenerateValids(Puzzle p)//Not necessary for constants
{ }
public override char CharCode { get { return 'c'; } }
}
class AddSpan : Span
{
public override bool isValid()
{
return Cells.Sum(c => c.Value) == Goal;
}
public override void GenerateValids(Puzzle p)
{
Valids = new HashSet<int>();
var sequence = Enumerable.Range(1, p.Size);//Generate a sequence 1, 2, ... n
//Find any integers that add from our current sum to some integer less than our goal
int currentSum = Cells.Sum(c => c.Value);
foreach (var i in sequence)
{
if (currentSum + i <= Goal)
{
Valids.Add(i);
}
}
}
public override char CharCode { get { return '+'; } }
}
class SubtractSpan : Span
{
public override bool isValid()
{
return Cells[0].Value - Cells[1].Value == Goal || Cells[1].Value - Cells[0].Value == Goal;
}
public override void GenerateValids(Puzzle p)
{
Valids = new HashSet<int>();
var sequence = Enumerable.Range(1, p.Size);//Generate a sequence 1, 2, ... n
foreach (var i in sequence)
{
foreach (var j in sequence)
{
if (i - j == Goal || j - i == Goal)
{
Valids.Add(i);
}
}
}
}
public override char CharCode { get { return '-'; } }
}
class MultiplySpan : Span
{
public override bool isValid()
{
int product = 1;
Cells.ForEach(c => product *= c.Value);
return product == Goal;
}
public override void GenerateValids(Puzzle p)
{
Valids = new HashSet<int>();
var sequence = Enumerable.Range(1, p.Size);//Generate a sequence 1, 2, ... n
if (Cells.Count == 1)
{
Valids.Add(Goal / Cells[0].Value);
}
else
{
//Find any integers that will multiply to some integer less than our equal to our goal
int currentProduct = 1;
Cells.ForEach(c => currentProduct *= c.Value != 0 ? c.Value : 1);
foreach (var i in sequence)
{
if (currentProduct * i <= Goal)
Valids.Add(i);
}
}
}
public override char CharCode { get { return 'x'; } }
}
class DivideSpan : Span
{
public override bool isValid()
{
if (Cells[0].Value == 0 || Cells[1].Value == 0)
return false;
return Cells[0].Value / Cells[1].Value == Goal || Cells[1].Value / Cells[0].Value == Goal;
}
public override void GenerateValids(Puzzle p)
{
Valids = new HashSet<int>();
var sequence = Enumerable.Range(1, p.Size);//Generate a sequence 1, 2, ... n
foreach (var i in sequence)
{
foreach (var j in sequence)
{
if (i / j == Goal || j / i == Goal)
{
Valids.Add(i);
}
}
}
}
public override char CharCode { get { return '/'; } }
}
class UniqueSpan : Span
{
public override bool isValid()
{
//Find the set difference between the sequence 1, 2 ... n and the row/column we have
var difference = Cells.Select(c => c.Value).Except(Enumerable.Range(1, Goal));
//If this has any values in it, it's not a valid row/column
return !difference.Any();
}
public override void GenerateValids(Puzzle p)
{ }
public override char CharCode { get { return ' '; } }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KenkenSolve
{
class Program
{
static void Main(string[] args)
{
Puzzle p = new Puzzle("game5.txt");
p.Print(c => c.Group.Goal.ToString() + c.Group.CharCode);
Stopwatch s = new Stopwatch();
s.Start();
PuzzleSolve.Solve(p);
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds);
p.Print(c => c.Value.ToString());
Console.WriteLine();
Console.ReadKey();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KenkenSolve
{
class Puzzle
{
public Puzzle(string file)
{
string[] lines = File.ReadAllLines(file);
Size = int.Parse(lines[0]);
char[,] grid = new char[Size, Size];
for (int y = 0; y < Size; y++)
{
string row = lines[1 + y];//Take a row from the game file
for (int x = 0; x < Size; x++)
grid[x, y] = row[x];
}
for (int i = Size + 1; i < lines.Length; i++)
{
Span span;
var pieces = lines[i].Split(';');
switch (pieces[2][0])
{
case '+':
span = new AddSpan();
break;
case '-':
span = new SubtractSpan();
break;
case 'x':
span = new MultiplySpan();
break;
case '/':
span = new DivideSpan();
break;
case 'c':
span = new ConstantSpan();
break;
default:
span = new AddSpan();
break;
}
span.Character = pieces[0][0];
span.Goal = int.Parse(pieces[1]);
Groups.Add(span);
}
for (int y = 0; y < Size; y++)
{
for (int x = 0; x < Size; x++)
{
char c = grid[x, y];
Cell cell = new Cell();
cell.X = x;
cell.Y = y;
//build a bidirectional relationship between groups and cells
cell.Group = Groups.FirstOrDefault(g => g.Character == c);
cell.Group.Cells.Add(cell);
All.Add(cell);
}
}
for (int i = 0; i < Size; i++)
{
Span column = new UniqueSpan { Cells = All.Where(c => c.X == i).ToList(), Goal = Size };
Span row = new UniqueSpan { Cells = All.Where(c => c.Y == i).ToList(), Goal = Size };
Columns.Add(column);
Rows.Add(row);
//build a bidirectional relationship between cells and columns/rows
column.Cells.ForEach(c => c.Column = column);
row.Cells.ForEach(c => c.Row = row);
}
All.ForEach(c=>c.Neighbours = getCellNeighbours(c));
}
static List<Cell> getCellNeighbours(Cell cell)
{
var neighbours = cell.Group.Cells.ToList();
neighbours.AddRange(cell.Column.Cells);
neighbours.AddRange(cell.Row.Cells);
return neighbours.Where(c => !(c.Group is ConstantSpan) && c != cell).Distinct().ToList();
}
public List<Cell> All = new List<Cell>();
public List<Span> Groups = new List<Span>();
public List<Span> Columns = new List<Span>();
public List<Span> Rows = new List<Span>();
public int Size;
//Tries to print the puzzle in a way that the original grid is visible, not perfect but works
public void Print(Func<Cell, string> value)
{
foreach (var puzzleRow in Rows)
{
foreach (var cell in puzzleRow.Cells)
{
Console.Write(value(cell).PadLeft(4, ' '));
int colI = puzzleRow.Cells.IndexOf(cell);
if (colI + 1 < puzzleRow.Cells.Count)//Check if we're at the end of the row
{
//If we're next to a neighbour of the same group, connect them on the same row
if (cell.Group == puzzleRow.Cells[colI + 1].Group)
Console.Write(" ");
else
Console.Write("|");
}
}
Console.WriteLine();
int rowI = Rows.IndexOf(puzzleRow);
if (rowI + 1 < Rows.Count)
{
foreach (var cell in puzzleRow.Cells)
{
int colI = puzzleRow.Cells.IndexOf(cell);
//If we're next to a neighbour of the same group, connect them on the same column
if (cell.Group == Rows[rowI + 1].Cells[colI].Group)
Console.Write(" ");
else
Console.Write("-----");
}
}
Console.WriteLine();
}
}
}
class Cell
{
public Span Column;
public Span Row;
public Span Group;
public int X;
public int Y;
public bool Busy = false;
public int Value;
public HashSet<int> PossibleValues = new HashSet<int>();
public int PossibleValueCount = 0;
public List<Cell> Neighbours = new List<Cell>();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MoreLinq;
namespace KenkenSolve
{
class PuzzleSolve
{
public static void Solve(Puzzle puzzle)
{
initPuzzle(puzzle);
puzzle.All.ForEach(c => updateCellPossibles(puzzle, c));
solveCell(puzzle, puzzle.All.Where(p => p.PossibleValues.Any()).MinBy(p => p.PossibleValueCount));
}
private static int i = 0;
static bool solveCell(Puzzle puzzle, Cell cell)
{
cell.Busy = true;//Set ourselves to 'busy' so we don't loop around in our search tree
int initialValue = cell.Value;//Store our initial state so we can revert to it later if we need to
HashSet<int> initialPossibleValues = cell.PossibleValues;
foreach (var possibleValue in cell.PossibleValues)
{
cell.Value = possibleValue;
i++;
//Don't bother continuing if we just filled in a final cell of a group and it resulted in an invalid configuration
if (cell.Group.Cells.All(c => c.Value != 0) && !cell.Group.isValid())
continue;
if (isPuzzleValid(puzzle))
return true;//Did we just solve the puzzle? If so, return
//Whenever we change our own value, we limit the possible values of all neighbours
//Update these so we know where to go next
foreach (var neighbour in cell.Neighbours)
updateCellPossibles(puzzle, neighbour);
if (i % 50000 == 0)
showProgress(puzzle);
Cell minNeighbour = null;
int minNeighbourCount = int.MaxValue;
foreach (var n in cell.Neighbours)
{
if (!n.Busy && n.PossibleValueCount > 0)
{
if (n.PossibleValueCount < minNeighbourCount)
{
minNeighbourCount = n.PossibleValueCount;
minNeighbour = n;
}
}
}
//No valid neighbours? We've made a wrong choice earlier
if (minNeighbour == null)
continue;
//Continue expanding the recursive tree down into the valid neighbour with the least possible choices
if (solveCell(puzzle, minNeighbour))
return true;//If a solution is found down the recursive tree, we can finish
}
//No solution found: time to clean up
cell.Value = initialValue;
cell.PossibleValues = initialPossibleValues;
cell.Busy = false;
return false;
}
static void showProgress(Puzzle puzzle)
{
int col = puzzle.Columns.Sum(c => c.isValid() ? 1 : 0);
int row = puzzle.Rows.Sum(r => r.isValid() ? 1 : 0);
int group = puzzle.Groups.Sum(g => g.isValid() ? 1 : 0);
int correct = col + row + group;
int num = puzzle.Columns.Count + puzzle.Groups.Count + puzzle.Rows.Count;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write(new string('G', group));
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(new string('C', col));
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(new string('R', row));
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(new string('_', num - correct));
Console.WriteLine(" ({0}/{1})", correct, num);
}
static void initPuzzle(Puzzle puzzle)
{
foreach (var cell in puzzle.All)
{
//Fill in constant value cells with their constant value
if (cell.Group is ConstantSpan)
{
cell.Value = cell.Group.Goal;
}
}
}
public static void updateCellPossibles(Puzzle puzzle, Cell cell)
{
if (cell.Group is ConstantSpan)
return;
var invalids = new List<int>();
foreach (var c in cell.Row.Cells)
if (c.Value > 0)
invalids.Add(c.Value);
foreach (var c in cell.Column.Cells)
if (c.Value > 0)
invalids.Add(c.Value);
if (cell.Group.ChangedSinceGeneration)
cell.Group.GenerateValids(puzzle);
//find the set of valids not including any invalids
cell.PossibleValues = cell.Group.Valids;
cell.PossibleValues.ExceptWith(invalids);
cell.PossibleValueCount = cell.PossibleValues.Count();
}
public static bool isPuzzleValid(Puzzle p)
{
bool valid = p.Columns.All(c => c.isValid());
valid = valid && p.Rows.All(r => r.isValid());
valid = valid && p.Groups.All(g => g.isValid());
return valid;
}
}
}
| c82dd34cf2626fffa5fcc7869ff6749d747938ee | [
"C#"
] | 4 | C# | ruarai/kenken_solve | f3337d59e7cdf687973ed67ae37dd784c00bdaf2 | c3aafe10a8daa235f02868a943685eccc01c55e3 | |
refs/heads/main | <repo_name>edgarcza/qr-code-list<file_sep>/test/Redux.test.js
import { QRListReducer } from '../app/redux/reducers/QRListReducer';
import { ADD_QR, REMOVE_QR } from '../app/redux/actions/QRListActions';
// import * as types from '../../constants/ActionTypes'
describe('QRList reducer', () => {
it('should return the initial state', () => {
expect(QRListReducer(undefined, {})).toEqual({
qrList: [],
})
})
it('should handle ADD_QR', () => {
expect(
QRListReducer({ qrList: [] }, {
type: ADD_QR,
payload: 'foo'
})
).toEqual({
qrList: [{
data: "foo",
id: 0,
}]
})
})
it('should handle REMOVE_QR', () => {
expect(
QRListReducer({ qrList: [{ data: "foo", id: 0 }] }, {
type: REMOVE_QR,
payload: 0
})
).toEqual({
qrList: []
})
})
})<file_sep>/README.md
# assessment
## Run project
Install dependencies
`npm install`
Start the project
`yarn start`
## Testing
Run npm test command
`npm test`
| 91a738543ca5abedd8dfb962a692c42195a84bd0 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | edgarcza/qr-code-list | 8c31e829f7369077407571d146c74e2d11a0eb6e | 24b98dabbc9bb15f1a944796c4e589644e78ad10 | |
refs/heads/master | <repo_name>tsolucio/coreBOSReceiveProducts<file_sep>/modules/Receiptcards/language/ro_ro.lang.php
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
$mod_strings = array(
'Receiptcards' => 'Receipt Cards',
'SINGLE_Receiptcards' => 'Receipt Card',
'Receiptcards ID' => 'Receipt Cards ID',
'LBL_MODULE_NAME'=>'Receipt Cards',
'LBL_MODULE_TITLE'=>'Receipt Cards',
'LBL_NEW_RECEIPTCARDS'=>'New Receipt Card',
'LBL_RECEIPTCARDS'=>'Receipt Cards',
'LBL_RECEIPTCARD'=>'Receipt Card',
'LBL_RECEIPTCARDS_INFO'=>'Basic Information',
'LBL_DESCRIPTION_INFO'=>'Description',
'LBL_CUSTOM_INFORMATION' => 'Custom Information',
'LBL_RELATED_PRODUCTS' => 'Products',
'LBL_RECALCULATE_STOCK' => 'Recalculate Stock',
'Receiptcards No' => 'Receipt Card No',
'receiptcards' => 'Receipt Cards',
'receiptcard' => 'Receipt Card',
'Receiptcards' => 'Receipt Cards',
'Delivery No' => 'Delivery No',
'Adoption Date' => 'Date of receipt',
'LBL_RECALCULATE_QUESTION'=>'Are you sure you want to calculate the actual quantity of products in stock?',
'Related To'=>'Related To',
);
?>
<file_sep>/modules/Receiptcards/RecalculateStockAction.php
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><title>TSolucio::coreBOS Customizations</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">@import url("themes/softed/style.css");br { display: block; margin: 2px; }</style>
</head><body class=small style="font-size: 12px; margin: 2px; padding: 2px; background-color:#f7fff3; ">
<table width="100%" border=0><tr><td><span style='color:red;float:right;margin-right:30px;'><h2>Proud member of the <a href='http://corebos.org'>coreBOS</a> family!</h2></span></td></tr></table>
<hr style="height: 1px">
<?php
// Turn on debugging level
$Vtiger_Utils_Log = true;
include_once 'vtlib/Vtiger/Module.php';
global $current_user,$adb;
set_time_limit(0);
ini_set('memory_limit', '1024M');
$mod_acc = Vtiger_Module::getInstance('Receiptcards');
$mod_acc->addLink('LISTVIEWBASIC', 'LBL_RECALCULATE_STOCK', 'javascript:recalculateStock()');
?><file_sep>/modules/Receiptcards/language/sk_sk.lang.php
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
$mod_strings = array(
'LBL_MODULE_NAME'=>'Prijemky',
'LBL_MODULE_TITLE'=>'Príjemky',
'LBL_NEW_RECEIPTCARDS'=>'Nová príjemka',
'LBL_RECEIPTCARDS'=>'Príjemky',
'LBL_RECEIPTCARD'=>'Príjemka',
'LBL_RECEIPTCARDS_INFO'=>'Základné informácie',
'LBL_DESCRIPTION_INFO'=>'Popis',
"LBL_RELATED_PRODUCTS"=>"Produkty",
"LBL_RECALCULATE_STOCK"=>"Prepočítať sklad",
'Receiptcards No' => 'Číslo príjemky',
'receiptcards' => 'Príjemky',
'receiptcard' => 'Príjemka',
'Receiptcards'=>'Príjemky',
'Delivery No'=>'Dodací list č.',
'Adoption Date'=>'Dátum prijatia',
'LBL_RECALCULATE_QUESTION'=>'Naozaj chcete prepočítať aktuálne množstvo produktov na sklade?',
'Related To'=>'Vzťahujúce sa na',
);
?>
<file_sep>/modules/Receiptcards/Receiptcards.js
/*********************************************************************************
** The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
********************************************************************************/
var i18nReceiptcards = '';
ExecuteFunctions('getTranslatedStrings','i18nmodule=Receiptcards&tkeys=LBL_RECALCULATE_QUESTION').then(function (data) {
i18nReceiptcards = JSON.parse(data);
});
function set_return(receiptcards_id, receiptcards_name) {
window.opener.document.EditView.parent_name.value = receiptcards_name;
window.opener.document.EditView.parent_id.value = receiptcards_id;
}
function set_return_specific(receiptcards_id, receiptcards_name) {
var fldName = getOpenerObj('receiptcards_name');
var fldId = getOpenerObj('receiptcards_id');
fldName.value = receiptcards_name;
fldId.value = receiptcards_id;
}
function recalculateStock() {
recalculate = confirm(i18nReceiptcards.LBL_RECALCULATE_QUESTION);
if (recalculate) {
jQuery('#status').show();
jQuery.ajax({
method:'POST',
url: 'index.php?module=Receiptcards&action=ReceiptcardsAjax&file=RecalculateStock'
}).done(function (response) {
jQuery('#status').hide();
});
}
window.open(baseURL, "vtlibui10", WindowSettings);
}
<file_sep>/modules/Receiptcards/language/es_mx.lang.php
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
$mod_strings = array(
'Receiptcards' => 'Recepción Productos',
'SINGLE_Receiptcards' => 'Recepción Producto',
'Receiptcards ID' => 'ID Recepción Producto',
'LBL_MODULE_NAME'=>'Recepción Productos',
'LBL_MODULE_TITLE'=>'Recepción Productos',
'LBL_NEW_RECEIPTCARDS'=>'Nueva Recepción Producto',
'LBL_RECEIPTCARDS'=>'Recepción Productos',
'LBL_RECEIPTCARD'=>'Recepción Producto',
'LBL_RECEIPTCARDS_INFO'=>'Información Recepción Producto',
'LBL_DESCRIPTION_INFO'=>'Descripción',
'LBL_CUSTOM_INFORMATION' => 'Información Personalizada',
'LBL_RELATED_PRODUCTS' => 'Productos',
'LBL_RECALCULATE_STOCK' => 'Actualizar Stock',
'Receiptcards No' => 'Nº Recepción Producto',
'receiptcards' => 'Recepción Productos',
'receiptcard' => 'Recepción Producto',
'Receiptcards' => 'Recepción Productos',
'Delivery No'=>'Nº Entrega',
'Adoption Date'=>'Fecha Recepción',
'LBL_RECALCULATE_QUESTION'=>'¿Estás seguro que quieres recalcular y actualizar la cantidad de productos en stock?',
'Related To'=>'Relacionado con',
);
?>
| 0d2ea0b01484e0be931f8590187993670f668ecb | [
"JavaScript",
"PHP"
] | 5 | PHP | tsolucio/coreBOSReceiveProducts | 599aecabdf33e271ac4b5209422d77659268c331 | 3cbfafd0f340c9343546e8538163416808abe9ac | |
refs/heads/master | <file_sep>class BaseStateMachine(object):
def run_all(self, *args, **kwargs):
assert False, 'run_all not implemented'
class StateMachine(BaseStateMachine):
def __init__(self, current_state):
self.current_state = current_state
self.current_state.run()
def run_all(self, inputs, verbose=False):
for input_state in inputs:
if verbose:
print(input_state)
self.current_state = self.current_state.next(input_state)
self.current_state.run()
<file_sep>from state_machine.state import State
from state_machine.machine import StateMachine
class MouseAction:
"""Class representing an action performed by the mouse"""
def __init__(self, action):
self.action = action
def __hash__(self):
return hash(self.action)
def __eq__(self, other):
return self.action == other.action
def __str__(self):
return 'action: ' + self.action
class WaitingState(State):
def run(self):
print("Waiting: Broadcasting cheese smell")
class LuringState(State):
def run(self):
print("Luring: Presenting Cheese, door open")
class TrappingState(State):
def run(self):
print("Trapping: Closing door")
class HoldingState(State):
def run(self):
print("HoldingState: Mouse caught")
class ActionSet:
"""All the actions a mouse can perform"""
appears = MouseAction('appears')
runs_away = MouseAction("mouse runs away")
enters = MouseAction("mouse enters trap")
escapes = MouseAction("mouse escapes")
trapped = MouseAction("mouse trapped")
removed = MouseAction("mouse removed")
class StateSet:
waiting = WaitingState()
luring = LuringState()
trapping = TrappingState()
holding = HoldingState()
# Declare state transition rules
StateSet.waiting.transitions = {
ActionSet.appears: StateSet.luring
}
StateSet.luring.transitions = {
ActionSet.runs_away: StateSet.waiting,
ActionSet.enters: StateSet.trapping
}
StateSet.trapping.transitions = {
ActionSet.escapes: StateSet.waiting,
ActionSet.trapped: StateSet.holding
}
StateSet.holding.transitions = {
ActionSet.removed: StateSet.waiting
}
if __name__ == "__main__":
inputs = [
ActionSet.appears,
ActionSet.runs_away,
ActionSet.enters,
ActionSet.runs_away,
ActionSet.appears,
ActionSet.enters,
ActionSet.trapped,
ActionSet.removed,
ActionSet.appears,
ActionSet.runs_away,
ActionSet.escapes,
ActionSet.appears,
ActionSet.enters,
ActionSet.trapped,
ActionSet.removed,
]
mouse_trap = StateMachine(StateSet.waiting)
mouse_trap.run_all(inputs, verbose=True)
<file_sep>class BaseState(object):
def run(self, *args, **kwargs):
assert False, 'run not implemented'
def next(self, *args, **kwargs):
assert False, 'next not implemented'
class State(BaseState):
transitions = dict()
def next(self, input):
"""If input has a next state in transition rule then return that state else returns
current state
Returns:
state_machine.state.State
"""
return self.transitions.get(input, self)
def __str__(self):
if hasattr(self, 'name'):
return self.name
else:
return 'State {}'.format(id(self))
| 5664491d18435b7eeef69b549632a965d46dde8b | [
"Python"
] | 3 | Python | aloktripathy/state-machine | 06fc508c6fd1108d5a90118907490ffa9017a192 | d95c58fe1825f50cd91f51d5775823a8f9b630bb | |
refs/heads/master | <repo_name>vbeloti/tinder-web<file_sep>/src/configs/firebase.ts
import * as firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/database';
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "tinder-web.firebaseapp.com",
databaseURL: "https://tinder-web.firebaseio.com",
projectId: "tinder-web",
storageBucket: "tinder-web.appspot.com",
messagingSenderId: "146790004483",
appId: "1:146790004483:web:55fbce2632718b2bfc9b36",
measurementId: "G-0RTN80NDX6"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
export default db;
<file_sep>/README.md
## Tinder (React.js && Typescript && Firebase)
<img src="https://github.com/vbeloti/tinder-web/blob/master/.github/img/tinder-1.jpg?raw=true" alt="Tinder" />
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
| d2ad35b8256ecc3d3c17327cfa36fb6e72b55290 | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | vbeloti/tinder-web | 8718f24c1648e8727dd66a8cc44d1b2044878668 | 08d9de438a3cc5c8c7e74e7c3c32a8da5fce05fe | |
refs/heads/main | <repo_name>faalbuquerque/my-promotion-system<file_sep>/db/migrate/20210214045344_create_category_promotions.rb
class CreateCategoryPromotions < ActiveRecord::Migration[6.1]
def change
create_table :category_promotions do |t|
t.integer :promotion_id
t.integer :category_id
t.timestamps
end
end
end
<file_sep>/spec/requests/coupon_management_spec.rb
require 'rails_helper'
describe 'Coupon management' do
context 'GET coupon' do
it 'should render coupon information' do
creator = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 1,
expiration_date: '22/12/2033', admin: creator)
promotion.create_coupons!
coupon = promotion.coupons.last
get "/api/v1/coupons/#{ coupon.code }"
json_response = JSON.parse(response.body, symbolize_names: true)
expect(response).to have_http_status(200)
expect(json_response[:status]).to eq('active')
expect(json_response[:promotion][:discount_rate]).to eq('10.0')
end
it 'should return 404, coupon does not exist' do
get "/api/v1/coupons/naoexiste"
expect(response).to have_http_status :not_found
end
end
end
<file_sep>/README.md
## Projeto TreinaDev 05 - Primeira Etapa
Desenvolvimento de um sistema em Ruby on Rails como parte do treinamento da Campus Code.
### Tecnologias:
- Ruby
- Rails
- RSpec
- I18n
### [Link: Trello](https://trello.com/b/zehBJt2P/treinadev-atividades-6)
<file_sep>/spec/features/admin_view_categories_spec.rb
require 'rails_helper'
feature 'Admin view categories' do
scenario 'successfully' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Category.create!(name: 'Filmes de Suspense', code: 'FILMESS')
Category.create!(name: 'Filmes de Medo', code: 'FILMESM', )
visit root_path
click_on 'Categorias'
expect(page).to have_content('Filmes de Suspense')
expect(page).to have_content('FILMESS')
expect(page).to have_content('Filmes de Medo')
expect(page).to have_content('FILMESM')
end
scenario 'and return to home page' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Category.create!(name: 'Games', code: 'games100')
visit root_path
click_on 'Categorias'
click_on 'Voltar'
expect(current_path).to eq root_path
end
scenario 'and view details' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Category.create!(name: 'Gatos', code: 'gatospeludos')
Category.create!(name: 'Caes', code: 'Caesfofinhos')
visit root_path
click_on 'Categorias'
click_on 'Gatos'
expect(page).to have_content('Gatos')
expect(page).to have_content('gatospeludos')
end
scenario 'and return to categories page' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Category.create!(name: 'Game of Thrones', code: 'GOT')
visit root_path
click_on 'Categorias'
click_on 'Game of Thrones'
click_on 'Voltar'
expect(current_path).to eq categories_path
end
scenario 'failure, not signed in' do
Category.create!(name: 'Gatos', code: 'gatospeludos')
Category.create!(name: 'Caes', code: 'Caesfofinhos')
visit categories_path
expect(page).to_not have_content('Gatos')
expect(page).to_not have_content('gatospeludos')
end
end
<file_sep>/spec/features/admin_edit_categories_spec.rb
require 'rails_helper'
feature 'Admin edit categories' do
scenario 'successfully' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Category.create!(name: 'Comidinha', code: 'comi100')
Category.first.update!(name: 'Comida japonesa', code: 'comijapa')
visit root_path
click_on 'Categorias'
expect(page).to_not have_content('Comidinha')
expect(page).to_not have_content('comi100')
expect(page).to have_content('Comida japonesa')
expect(page).to have_content('comijapa')
end
scenario 'and attributes cannot be blank' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Category.create!(name: 'Bebida', code: 'bebi100')
visit root_path
click_on 'Categorias'
click_on 'Editar categoria'
fill_in 'Nome', with: ''
fill_in 'Código', with: ''
click_on 'Atualizar categoria'
p page.html
expect(page).to have_content('não pode ficar em branco', count: 2)
end
scenario 'and code must be unique' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Category.create!(name: 'Caes', code: 'caes10')
Category.create!(name: 'Gatos', code: 'gatos10')
visit edit_category_path(Category.last)
fill_in 'Código', with: 'caes10'
click_on 'Atualizar categoria'
expect(page).to have_content('já está em uso')
end
end
<file_sep>/spec/models/promotion_approval_spec.rb
require 'rails_helper'
RSpec.describe PromotionApproval, type: :model do
describe '#valid?' do
describe "different_admin" do
it 'is different' do
creator = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
approval_admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: creator)
approval = PromotionApproval.new(promotion: promotion, admin: approval_admin)
expect(approval.valid?).to eq true
end
it 'is the same' do
creator = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
approval_admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: creator)
approval = PromotionApproval.new(promotion: promotion, admin: creator)
expect(approval.valid?).to eq false
end
it 'has no promotion or admin' do
approval = PromotionApproval.new()
expect(approval.valid?).to eq false
end
end
end
end
<file_sep>/spec/features/admin_approves_a_promotion_spec.rb
require 'rails_helper'
feature 'Admin approves a promotion' do
scenario 'successfully' do
creator = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
approval_admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: creator)
sign_in approval_admin
visit promotion_path(promotion)
click_on 'Aprovar promoção'
promotion.reload
expect(current_path).to eq promotion_path(promotion)
expect(promotion.approved?).to be_truthy
expect(promotion.approver).to eq approval_admin
expect(page).to have_content 'Status: Aprovada!'
end
scenario 'must not be the promotion creator' do
creator = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: creator)
sign_in creator
visit promotion_path(promotion)
expect(page).to_not have_link 'Aprovar promoção'
end
scenario 'must be another user' do
creator = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
approval_user = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: creator)
sign_in approval_user
visit promotion_path(promotion)
expect(page).to have_link 'Aprovar promoção'
end
end<file_sep>/spec/features/admin_register_product_category_spec.rb
require 'rails_helper'
feature 'Admin registers a product category' do
scenario 'and attributes cannot be blank' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
visit root_path
click_on 'Categorias'
click_on 'Registrar uma categoria'
fill_in 'Nome', with: ''
fill_in 'Código', with: ''
click_on 'Criar categoria'
expect(Category.count).to eq 0
expect(page).to have_content('Nome não pode ficar em branco')
expect(page).to have_content('Código não pode ficar em branco')
end
scenario 'and code must be unique' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Category.create!(name: 'Filmes', code: 'FILMES10')
visit root_path
click_on 'Categorias'
click_on 'Registrar uma categoria'
fill_in 'Código', with: 'FILMES10'
click_on 'Criar categoria'
expect(page).to have_content('já está em uso')
end
end
<file_sep>/app/models/promotion_approval.rb
class PromotionApproval < ApplicationRecord
belongs_to :promotion
belongs_to :admin
validate :different_admin
private
def different_admin
if promotion && promotion.admin == admin
errors.add(:admin, 'nao pode ser o criador da promocao')
end
end
end
<file_sep>/app/models/promotion.rb
class Promotion < ApplicationRecord
has_many :coupons, dependent: :destroy
has_one :promotion_approval
belongs_to :admin
has_many :category_promotions
has_many :categories, through: :category_promotions
validates :name, :code, presence: true, uniqueness: true
validates :discount_rate, :coupon_quantity, :expiration_date, presence: true
def create_coupons!
Coupon.transaction do
1.upto(coupon_quantity) do |num|
#transformar num array de hashes e fazer um insert all
coupons.create!(code: "#{ code }-#{ num.to_s.rjust(4, '0') }")
end
end
end
def approve!(approval_admin)
PromotionApproval.create(promotion: self, admin: approval_admin)
end
def approved?
promotion_approval
end
def approver
promotion_approval.admin
end
end
<file_sep>/spec/models/category_spec.rb
require 'rails_helper'
RSpec.describe Category, type: :model do
context 'validation' do
it { should validate_presence_of(:name) }
it { should validate_presence_of(:code) }
it { should validate_uniqueness_of(:code) }
end
end
<file_sep>/spec/models/promotion_spec.rb
require 'rails_helper'
describe Promotion do
context 'validation' do
it 'attributes cannot be blank' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
promotion = Promotion.new(name: '', description: '', code: '',
discount_rate: '', coupon_quantity: '',
expiration_date: '', admin: admin)
expect(promotion.valid?).to eq false
expect(promotion.errors.count).to eq 5
end
it 'description is optional' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
promotion = Promotion.new(name: 'Natal', description: '', code: 'NAT',
coupon_quantity: 10, discount_rate: 10,
expiration_date: '2021-10-10', admin: admin)
expect(promotion.valid?).to eq true
end
it 'error messages are in portuguese' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
promotion = Promotion.new
promotion.valid?
expect(promotion.errors[:name]).to include('não pode ficar em branco')
expect(promotion.errors[:code]).to include('não pode ficar em branco')
expect(promotion.errors[:discount_rate]).to include('não pode ficar em '\
'branco')
expect(promotion.errors[:coupon_quantity]).to include('não pode ficar em'\
' branco')
expect(promotion.errors[:expiration_date]).to include('não pode ficar em'\
' branco')
end
it 'code must be uniq' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10,
coupon_quantity: 100, expiration_date: '22/12/2033', admin: admin)
promotion = Promotion.new(code: 'NATAL10')
promotion.valid?
expect(promotion.errors[:code]).to include('já está em uso')
end
end
context '#create_coupons!' do
it 'create coupons with a quantity' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
promotion.create_coupons!
expect(promotion.coupons.size).to eq 100
codes = promotion.coupons.pluck(:code)
expect(codes).to include('NATAL10-0001')
expect(codes).to include('NATAL10-0100')
expect(codes).to_not include('NATAL10-0101')
expect(codes).to_not include('NATAL10-0000')
end
it 'do not create repeated codes' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
promotion.coupons.create!(code: 'NATAL10-0030')
expect { promotion.create_coupons! }.to raise_error(ActiveRecord::RecordInvalid)
expect(promotion.coupons.reload.size).to eq(1)
end
end
context '#approve!' do
it 'should generate a PromotionApproval object' do
creator = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
approval_admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: creator)
promotion.approve!(approval_admin)
promotion.reload
expect(promotion.approved?).to be_truthy
expect(promotion.approver).to eq approval_admin
end
it 'it should not approve if same admin ' do
creator = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: creator)
promotion.approve!(creator)
promotion.reload
expect(promotion.approved?).to be_falsy
end
end
end
<file_sep>/app/models/category_promotion.rb
class CategoryPromotion < ApplicationRecord
belongs_to :promotion
belongs_to :category
end
<file_sep>/spec/features/admin_search_for_promotion_and_coupons.rb
require 'rails_helper'
feature 'Admin search for promotion and coupons' do
scenario 'successfully' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
promotion_natal = Promotion.create!(name: 'Natal 2020', description: 'Promoção de Natal',
code: 'NATAL20', discount_rate: 5, coupon_quantity: 10, expiration_date: '22/12/2031', admin: admin)
promotion_ano = Promotion.create!(name: 'Ano novo', description: 'Promoção de Ano novo',
code: 'ANONOVO', discount_rate: 15, coupon_quantity: 30,
expiration_date: '22/12/2033', admin: admin)
Coupon.create!(code: 'NATAL-20', promotion: promotion_natal)
Coupon.create!(code: 'NOVO-20', promotion: promotion_ano)
visit root_path
click_on 'Promoções'
fill_in 'Buscar', with: 'natal'
click_on 'Pesquisar'
expect(current_path).to eq search_path
expect(page).to have_content('Natal')
expect(page).to_not have_content('Ano novo')
end
scenario 'result not found' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
promotion_natal21 = Promotion.create!(name: 'Natal 2021', coupon_quantity: 20,
description: 'Promoção de Natal de novo',
code: 'NATAL21', discount_rate: 10,
expiration_date: '22/12/2032', admin: admin)
promotion_ano_novo = Promotion.create!(name: 'Ano novo', description:'Anonovo'
code:'ANONOVO', discount_rate: 15,
coupon_quantity: 30, expiration_date: '22/12/2033', admin: admin)
Coupon.create!(code: 'NATAL21', promotion: promotion_natal21)
Coupon.create!(code: 'ANONOVO', promotion: promotion_ano_novo)
visit root_path
click_on 'Promoções'
fill_in 'Buscar', with: 'Cachorro'
click_on 'Pesquisar'
expect(current_path).to eq search_path
expect(page).to have_content('Nenhum resultado encontrado!')
expect(page).to_not have_content('Natal')
expect(page).to_not have_content('Ano novo')
end
end
<file_sep>/spec/features/admin_delete_promotions_spec.rb
require 'rails_helper'
feature 'Admin delete promotions' do
scenario 'successfully' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL50', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
Promotion.create!(name: 'Natal1', description: 'Promoção de Natal1',
code: 'NATAL501', discount_rate: 101, coupon_quantity: 1001,
expiration_date: '22/12/2031', admin: admin)
visit promotion_path(Promotion.last)
click_on 'Apagar promoção'
expect(page).to have_content('Natal')
expect(page).to have_content('Promoção de Natal')
expect(page).to have_content('NATAL50')
expect(page).to have_content('10,00%')
expect(page).to have_content('100')
expect(page).to have_content('22/12/2033')
expect(page).to_not have_content('Natal1')
expect(page).to_not have_content('Promoção de Natal1')
expect(page).to_not have_content('NATAL501')
expect(page).to_not have_content('101,00%')
expect(page).to_not have_content('1001')
expect(page).to_not have_content('22/12/2031')
end
end
<file_sep>/spec/features/admin_registers_and_login_in_the_application_spec.rb
require 'rails_helper'
feature 'Admin in the application' do
scenario 'register' do
visit root_path
click_on 'Login'
click_on 'Sign up'
fill_in 'E-mail', with: '<EMAIL>'
fill_in 'Senha', with: '<PASSWORD>'
fill_in 'Password confirmation', with: '<PASSWORD>'
click_on 'Sign up'
expect(page).to have_content('<EMAIL>')
expect(page).to have_content('Promoções')
end
scenario 'login successfully' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
visit root_path
click_on 'Login'
fill_in 'E-mail', with: '<EMAIL>'
fill_in 'Senha', with: '<PASSWORD>'
click_on 'Log in'
expect(page).to have_content(admin.email)
expect(page).to have_content('Logout')
end
scenario 'logout successfully' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
visit root_path
click_on 'Login'
fill_in 'E-mail', with: '<EMAIL>'
fill_in 'Senha', with: '<PASSWORD>'
click_on 'Log in'
click_on 'Logout'
expect(page).to_not have_content(admin.email)
expect(page).to have_content('Login')
end
end
<file_sep>/spec/features/admin_activate_coupon_spec.rb
require 'rails_helper'
feature 'Admin activate coupons' do
scenario 'successfully' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
coupon = Coupon.create!(code: 'AAA-11', promotion: promotion)
visit root_path
click_on 'Promoções'
click_on promotion.name
click_on 'Inativar'
coupon.reload
expect(page).to have_content('AAA-11(Inativo)')
#expect(coupon).to be_inactive
expect(coupon.inactive?).to be(true)
end
scenario 'do not view the button to activate coupons' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 2,
expiration_date: '22/12/2033', admin: admin)
inactive_coupon = Coupon.create!(code: 'ABC0001', promotion: promotion, status: :inactive)
active_coupon = Coupon.create!(code: 'ABC0002', promotion: promotion, status: :active)
visit root_path
click_on 'Promoções'
click_on promotion.name
expect(page).to have_content('ABC0001(Inativo)')
expect(page).to have_content('ABC0002(Ativo)')
within("div#coupon-#{active_coupon.id}") do
expect(page).to have_link 'Inativar'
end
within("div#coupon-#{inactive_coupon.id}") do
expect(page).not_to have_link 'Inativar'
end
end
end
<file_sep>/app/controllers/categories_controller.rb
class CategoriesController < ApplicationController
before_action :authenticate_admin!
before_action :find_category, only: %i[show edit update destroy]
def index
@categories = Category.all
end
def new
@category = Category.new
end
def create
@category = Category.new(category_params)
return redirect_to @category if @category.save
respond_to do |format|
format.js { render partial: 'message' }
format.html { render partial: 'result_message'}
end
#render :new
end
def show
end
def edit
end
def update
return redirect_to @category if @category.update(category_params)
respond_to do |format|
format.js { render partial: 'message' }
format.html { render partial: 'result_message'}
end
#render :edit
end
def destroy
return redirect_to categories_path if @category.delete
render :index
end
private
def category_params
params.require(:category).permit(:name, :code)
end
def find_category
@category = Category.find(params[:id])
end
end
<file_sep>/spec/features/admin_edit_promotions_spec.rb
require 'rails_helper'
feature 'Admin edit promotions' do
scenario 'successfully' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
Promotion.first.update!(name: 'Natal 2034', description: 'Promoção de Natal 2034',
coupon_quantity: 34, code: 'NATAL34', discount_rate: 34,
expiration_date: '22/12/2034', admin: admin)
visit root_path
click_on 'Promoções'
expect(page).to have_content('Natal 2034')
expect(page).to have_content('Promoção de Natal 2034')
expect(page).to have_content(34)
expect(page).to have_content('NATAL34')
expect(page).to have_content('34,00%')
expect(page).to have_content('22/12/2034')
end
scenario 'and attributes cannot be blank' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
visit root_path
click_on 'Promoções'
click_on 'Editar promoção'
fill_in 'Nome', with: ''
fill_in 'Descrição', with: ''
fill_in 'Código', with: ''
fill_in 'Desconto', with: ''
fill_in 'Quantidade de cupons', with: ''
fill_in 'Data de término', with: ''
click_on 'Atualizar promoção'
expect(page).to have_content('não pode ficar em branco', count: 5)
end
scenario 'and code must be unique' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL50', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
Promotion.create!(name: 'Natal2', description: 'Promoção de Natal',
code: 'NATAL59', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033',admin: admin)
visit edit_promotion_path(Promotion.last)
fill_in 'Código', with: 'NATAL50'
click_on 'Atualizar promoção'
expect(page).to have_content('já está em uso')
end
end
<file_sep>/app/controllers/coupons_controller.rb
class CouponsController < ApplicationController
before_action :authenticate_admin!
def inactivate
@coupon = Coupon.find(params[:id])
@coupon.inactive!
redirect_to @coupon.promotion
end
def activate
@coupon = Coupon.find(params[:id])
@coupon.active!
redirect_to @coupon.promotion
end
end
<file_sep>/app/controllers/promotions_controller.rb
class PromotionsController < ApplicationController
before_action :authenticate_admin!
before_action :find_promotion, except: %i[index new create search]
def index
@promotions = Promotion.all
end
def new
@promotion = Promotion.new
@categories = Category.all.order(name: :asc)
end
def create
@promotion = Promotion.create(promotion_params)
@promotion.admin = current_admin
return redirect_to @promotion if @promotion.save
respond_to do |format|
format.js { render partial: 'message' }
format.html { render partial: 'result_message'}
end
# @categories = Category.all.order(name: :asc)
# render :new
end
def show
end
def edit
@categories = Category.all.order(name: :asc)
end
def update
return redirect_to @promotion if @promotion.update(promotion_params)
respond_to do |format|
format.js { render partial: 'message' }
format.html { render partial: 'result_message'}
end
#@categories = Category.all.order(name: :asc)
#render :edit
end
def destroy
return redirect_to promotions_path if @promotion.destroy!
render promotions_path
end
def creates_coupons
return redirect_to @promotion, notice: t('.burned') if @promotion.coupons.any?
@promotion.create_coupons!
redirect_to @promotion, notice: t('.success')
end
def approve
find_promotion.approve!(current_admin)
redirect_to find_promotion
end
def search
@result_set = Promotion.where('name like ? OR description like ?',
"%#{params[:q]}%",
"%#{params[:q]}%")
@result_set += (Coupon.where('code like ?', "%#{params[:q]}%"))
end
private
def promotion_params
params.require(:promotion).permit(:name, :description, :code, :discount_rate,
:coupon_quantity, :expiration_date, category_ids: [] )
end
def find_promotion
@promotion = Promotion.find(params[:id])
end
end
<file_sep>/spec/features/admin_delete_categories_spec.rb
require 'rails_helper'
feature 'Admin delete categories' do
scenario 'successfully' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Category.create!(name: 'Eletronicos', code: '555')
Category.create!(name: 'Portateis', code: '666')
visit category_path(Category.last)
click_on 'Apagar categoria'
expect(page).to have_content('Eletronicos')
expect(page).to have_content('555')
expect(page).to_not have_content('Portateis')
expect(page).to_not have_content('666')
end
end
<file_sep>/spec/features/user_visit_home_page_spec.rb
require 'rails_helper'
feature 'User visit home page' do
scenario 'successfully' do
visit root_path
expect(page).to have_content('Promotion System')
expect(page).to have_content('Boas vindas ao sistema de gestão de '\
'promoções')
end
end
<file_sep>/db/migrate/20210210045743_add_admin_ref_to_promotion.rb
class AddAdminRefToPromotion < ActiveRecord::Migration[6.1]
def change
add_reference :promotions, :admin, null: false, foreign_key: true
end
end
<file_sep>/app/controllers/api/v1/coupons_controller.rb
class Api::V1::CouponsController < ApplicationController
def show
@coupon = Coupon.find_by(code: params[:id])
return render status: 404, json: "{ message: 'Coupon not found' }" if @coupon.nil?
render json: @coupon.as_json(only: [:code, :status],
include: {
promotion: { only: :discount_rate }
}), status: 200
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
root 'home#index'
devise_for :admins
resources :categories
resources :promotions do
member do
post 'creates_coupons'
post 'approve'
end
end
get 'search', to: 'promotions#search'
resources :coupons, only: [] do
member do
post 'inactivate'
post 'activate'
end
end
namespace 'api', defaults: { format: :json } do
namespace 'v1' do
resources :coupons, only: [:show]
end
end
end
<file_sep>/spec/features/admin_creates_coupons_spec.rb
require 'rails_helper'
feature 'Admin creates coupons' do
scenario 'in a promotion' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin )
visit root_path
click_on 'Promoções'
click_on promotion.name
click_on 'Gerar cupons'
expect(page).to have_current_path(promotion_path(promotion))
expect(page).to have_content('Cupons gerados com sucesso!')
expect(page).to have_content('NATAL10-0001')
expect(page).to have_content('NATAL10-0002')
expect(page).to have_content('NATAL10-0100')
expect(page).to_not have_content('NATAL10-0101')
end
scenario 'do not view the button to generate coupons' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 2,
expiration_date: '22/12/2033', admin: admin)
#active_coupon = Coupon.create!(code: 'ABC', promotion: promotion, status: :active)
active_coupon = promotion.coupons.create!
visit promotion_path(promotion)
expect(page).to_not have_link 'Gerar cupons'
end
end
<file_sep>/app/models/coupon.rb
class Coupon < ApplicationRecord
belongs_to :promotion
validates :code, uniqueness: true
enum status: { active: 0, inactive: 10 }
end
<file_sep>/spec/features/admin_registers_a_promotion_spec.rb
require 'rails_helper'
feature 'Admin registers a promotion' do
scenario 'from index page' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
visit root_path
click_on 'Promoções'
expect(page).to have_link('Registrar uma promoção',
href: new_promotion_path)
end
scenario 'successfully' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
visit root_path
click_on 'Promoções'
click_on 'Registrar uma promoção'
fill_in 'Nome', with: 'Cyber Monday'
fill_in 'Descrição', with: 'Promoção de Cyber Monday'
fill_in 'Código', with: 'CYBER15'
fill_in 'Desconto', with: '15'
fill_in 'Quantidade de cupons', with: '90'
fill_in 'Data de término', with: '22/12/2033'
click_on 'Criar promoção'
expect(current_path).to eq(promotion_path(Promotion.last))
expect(page).to have_content('Cyber Monday')
expect(page).to have_content('Promoção de Cyber Monday')
expect(page).to have_content('15,00%')
expect(page).to have_content('CYBER15')
expect(page).to have_content('22/12/2033')
expect(page).to have_content('90')
expect(page).to have_content 'Criada por: <EMAIL>'
expect(page).to have_link('Voltar')
end
scenario 'and choose categories' do
Category.create!(name: 'Mouses', code: 'mouse')
Category.create!(name: 'Jogos', code: 'jogo')
Category.create!(name: 'Monitores', code: 'monitor')
Category.create!(name: 'Teclados', code: 'teclado')
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
visit root_path
click_on 'Promoções'
click_on 'Registrar uma promoção'
fill_in 'Nome', with: '<NAME>'
fill_in 'Descrição', with: 'Promoção de Cyber Monday'
fill_in 'Código', with: 'CYBER15'
fill_in 'Desconto', with: '15'
fill_in 'Quantidade de cupons', with: '90'
fill_in 'Data de término', with: '22/12/2033'
check 'Mouses'
check 'Jogos'
check 'Monitores'
click_on 'Criar promoção'
expect(current_path).to eq(promotion_path(Promotion.last))
expect(page).to have_content('Mouses')
expect(page).to have_content('Jogos')
expect(page).to have_content('Monitores')
expect(page).to_not have_content('Teclados')
end
end
<file_sep>/spec/features/admin_registers_a_valid_promotion_spec.rb
require 'rails_helper'
feature 'Admin registers a valid promotion' do
scenario 'and attributes cannot be blank' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
visit root_path
click_on 'Promoções'
click_on 'Registrar uma promoção'
fill_in 'Nome', with: ''
fill_in 'Descrição', with: ''
fill_in 'Código', with: ''
fill_in 'Desconto', with: ''
fill_in 'Quantidade de cupons', with: ''
fill_in 'Data de término', with: ''
click_on 'Criar promoção'
expect(Promotion.count).to eq 0
expect(page).to have_content('Não foi possível criar a promoção')
expect(page).to have_content('Nome não pode ficar em branco')
expect(page).to have_content('Código não pode ficar em branco')
expect(page).to have_content('Desconto não pode ficar em branco')
expect(page).to have_content('Quantidade de cupons não pode ficar em branco')
expect(page).to have_content('Data de término não pode ficar em branco')
end
scenario 'and code must be unique' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
visit root_path
click_on 'Promoções'
click_on 'Registrar uma promoção'
fill_in 'Código', with: 'NATAL10'
click_on 'Criar promoção'
expect(page).to have_content('já está em uso')
end
scenario 'and name must be unique' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Promotion.create!(name: 'Natal1', description: 'Promoção',
code: 'NATAL', discount_rate: 11, coupon_quantity: 101,
expiration_date: '22/12/2033', admin: admin)
visit root_path
click_on 'Promoções'
click_on 'Registrar uma promoção'
fill_in 'Nome', with: 'Natal1'
click_on 'Criar promoção'
expect(page).to have_content('já está em uso')
end
end
<file_sep>/spec/features/admin_view_promotions_spec.rb
require 'rails_helper'
feature 'Admin view promotions' do
scenario 'successfully' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
Promotion.create!(name: 'Cyber Monday', coupon_quantity: 100,
description: 'Promoção de Cyber Monday',
code: 'CYBER15', discount_rate: 15,
expiration_date: '22/12/2033', admin: admin)
visit root_path
click_on 'Promoções'
expect(page).to have_content('Natal')
expect(page).to have_content('Promoção de Natal')
expect(page).to have_content('10,00%')
expect(page).to have_content('Cyber Monday')
expect(page).to have_content('Promoção de Cyber Monday')
expect(page).to have_content('15,00%')
end
scenario 'and view details' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
Promotion.create!(name: 'Cyber Monday', coupon_quantity: 90,
description: 'Promoção de Cyber Monday',
code: 'CYBER15', discount_rate: 15,
expiration_date: '22/12/2033', admin: admin)
visit root_path
click_on 'Promoções'
click_on 'Cyber Monday'
expect(page).to have_content('Cyber Monday')
expect(page).to have_content('Promoção de Cyber Monday')
expect(page).to have_content('15,00%')
expect(page).to have_content('CYBER15')
expect(page).to have_content('22/12/2033')
expect(page).to have_content('90')
end
scenario 'and no promotion are created' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
visit root_path
click_on 'Promoções'
expect(page).to have_content('Nenhuma promoção cadastrada')
end
scenario 'and return to home page' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
visit root_path
click_on 'Promoções'
click_on 'Voltar'
expect(current_path).to eq root_path
end
scenario 'and return to promotions page' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
sign_in admin
Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
visit root_path
click_on 'Promoções'
click_on 'Natal'
click_on 'Voltar'
expect(current_path).to eq promotions_path
end
scenario 'and must be signed in' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
promotion = Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
visit promotion_path(promotion)
expect(current_path).to eq new_admin_session_path
end
scenario 'failure, not signed in' do
admin = Admin.create!(email: '<EMAIL>', password: "<PASSWORD>")
Promotion.create!(name: 'Natal', description: 'Promoção de Natal',
code: 'NATAL10', discount_rate: 10, coupon_quantity: 100,
expiration_date: '22/12/2033', admin: admin)
visit root_path
click_on 'Promoções'
expect(current_path).to_not eq promotions_path
expect(page).to_not have_content('Natal')
expect(page).to_not have_content('Promoção de Natal')
expect(page).to_not have_content('10,00%')
end
end
| e29d456dfd98f6a59d51e25d34b6c85c0efcebc9 | [
"Markdown",
"Ruby"
] | 31 | Ruby | faalbuquerque/my-promotion-system | 9482d6fc97406e6a9d0899ef6d546b437133632c | 3345052c517467478e524be07e1e5308f5061a8b | |
refs/heads/master | <repo_name>sunnei/OOP-Jquery<file_sep>/pop-jquery.js
/**
* Created by o on 2016/8/24.
*/
(function () {
//str
// 优化面向过程版
function extend(obj, target) {
for (var i in obj) {
target[i] = obj[i];
}
};
function $(selector) {
if (selector) {
var dom = document.querySelectorAll(selector);
dom.mylength = dom.length; //mylength 代替 length
dom.__proto__ = $.prototype;
return dom;
}
};
$.fn=function(name,fn){
$.prototype[name]= function () {
this.each(fn,arguments)
return this;
}
}
$.extend = function (obj) {
extend(obj, $.prototype)
};
$.extend({
css: function (name, value) {
this.each(function () {
this.style[name] = value;
})
return this;
},
each: function (fn,argument) {
if(fn)for(var t= 0,l=this.mylength;t<l;t++){
fn.apply(this[t],argument);
};
}
});
window.$ = $;
}())
<file_sep>/README.md
# POP-Jquery
用面向过程(pop)实现 简单版 jquery 的架构设计,不是原生面向对象工厂模式版的jquery,pop版的优点是轻量,节省了内存,同时又能实现功能和效率,这里只是探讨架构,没有具体实现jq的全部功能,有兴趣可自行研究
<pre>
// 面向过程版
//Created by o on 2016/8/24.
(function () {
function extend(obj, target) {
for (var i in obj) {
target[i] = obj[i];
}
};
function $(selector) {
if (selector) {
var dom = document.querySelectorAll(selector);
dom.mylength = dom.length; //mylength 代替 length
dom.\_\_proto\_\_ = $.prototype;
return dom;
}
};
$.fn=function(name,fn){
$.prototype[name]= function () {
this.each(fn,arguments)
return this;
}
}
$.extend = function (obj) {
extend(obj, $.prototype)
};
$.extend({
css: function (name, value) {
this.each(function () {
this.style[name] = value;
})
return this;
},
each: function (fn,argument) {
if(fn)for(var t= 0,l=this.mylength;t<l;t++){
fn.apply(this[t],argument);
};
}
});
window.$ = $;
}())
| f7e16b388b7b2f291e6ad574472910aba529c7ab | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | sunnei/OOP-Jquery | c5ec6e45c915b197ac266a3f641407162b2ba9a5 | c7ca5607ee429289708716f11b7cd51d3f6450b6 | |
refs/heads/master | <repo_name>goutamtk14/NumberGameUsingJS<file_sep>/FirstNumberGame/FirstNumberGame/callHTA.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace FirstNumberGame
{
class callHTA
{
static void Main(string[] args)
{
try
{
string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(tempDirectory);
File.WriteAllText(tempDirectory + "\\" + "g1.hta", Properties.Resources.g1);
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("FirstNumberGame.Resources.bg.jpg");
FileStream fileStream = new FileStream(tempDirectory + "\\" + "bg.jpg", FileMode.CreateNew);
for (int i = 0; i < stream.Length; i++)
fileStream.WriteByte((byte)stream.ReadByte());
fileStream.Close();
Process p = new Process();
p.StartInfo.FileName = "mshta.exe";
p.StartInfo.Arguments = tempDirectory + "\\" + "g1.hta";
p.StartInfo.UseShellExecute = true;
p.Start();
p.WaitForExit();
Directory.Delete(tempDirectory, true);
}
catch (Exception)
{
}
}
}
}
| fc23c6788c781251b34c2d2471cf28d2bf18ae22 | [
"C#"
] | 1 | C# | goutamtk14/NumberGameUsingJS | 2894889133f6774d1a510814a07ee7194aeffe45 | ce53b29ab76c4ae8adaa0e0f0af361fb8c0defa4 | |
refs/heads/master | <repo_name>J-Moore/cs290-assignment4-part2<file_sep>/src/assignment4-part2.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
// PASSWORD HERE
include 'local_settings.php';
$tabledata = array();
$resultline = array();
$hostname = "oniddb.cws.oregonstate.edu";
$dbname = "moorjona-db";
$username = "moorjona-db";
$mysqli = new mysqli($hostname, $dbname, $dbpw, $username);
// CHECK FOR DELETE ACTION
if (isset($_POST['delete'])) {
$delstmt = $mysqli->prepare("DELETE FROM cs290sp2015_rentals WHERE id=?");
$delstmt->bind_param("i", $_POST['delete']);
$delstmt->execute();
$delstmt->close();
}
if (isset($_POST['update-id'])) {
$updstmt = $mysqli->prepare("UPDATE cs290sp2015_rentals SET rented=? WHERE id=?");
$updstmt->bind_param("ii", $_POST['update-value'], $_POST['update-id']);
$updstmt->execute();
$updstmt->close();
}
if (isset($_POST['movie-name'])) {
$addstmt = $mysqli->prepare("INSERT INTO cs290sp2015_rentals (name, category, length, rented)
VALUES (?, ?, ?, ?)");
$addstmt->bind_param("ssii", $_POST['movie-name'], $_POST['movie-category'], $_POST['movie-length'], $_POST['movie-rented']);
$addstmt->execute();
$addstmt->close();
}
if (isset($_POST['killalldata']) && $_POST['killalldata'] == "42") {
$killstmt = $mysqli->query("TRUNCATE TABLE cs290sp2015_rentals");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Assignment4 PHP 2</title>
<script></script>
</head>
<body>
<!-- ADD NEW MOVIE FORM -->
<h1>Add a New Movie</h1>
<form action="#" method="post">
<table>
<tr>
<td>Movie Name:
<td><input type="text" name="movie-name" required />
</tr>
<tr>
<td>Category:
<td><input type="text" name="movie-category" />
</tr>
<tr>
<td>Length in minutes:
<td><input type="number" name="movie-length" />
</tr>
<tr>
<td>
<td><select name="movie-rented">
<option value=0>Available</option>
<option value=1>Checked Out</option>
</select>
</tr>
<tr>
<td>
<td><input type="submit" value="Add Movie" />
</tr>
</table>
</form>
<br>
<!--FILTER MOVIES-->
<h1>Filter Movies By Category</h1>
<form action="#" method="post">
<select name="movie-filter">
<option>All Movies</option>
<?php
$filtstmt = $mysqli->prepare("SELECT DISTINCT(category) FROM cs290sp2015_rentals");
$filtstmt->execute();
$filtstmt->bind_result($cat_name);
$filtstmt->store_result();
if ($filtstmt->num_rows > 0) {
// DISPLAY CATEGORIES AS SELECT OPTIONS
while ($filtstmt->fetch()) {
echo "<option>" . $cat_name . "</option>\n";
}
}
$filtstmt->close();
?>
</select>
<input type="submit" value="Filter Movies" />
</form>
<br>
<!-- TABLE THAT SHOWS MOVIES -->
<h1>List of Movies</h1>
<table>
<tbody>
<tr>
<th>Name</th>
<th>Category</th>
<th>Length (min)</th>
<th>Status</th>
</tr>
<?php
// GRAB TABLE DATA FOR DISPLAYING
if (!$mysqli || $mysqli->connect_errno) {
echo "Connection error " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}
// IF NO FILTER IS SET DISPLAY EVERYTHING
if (!isset($_POST['movie-filter']) || $_POST['movie-filter'] == "All Movies") {
$stmt = $mysqli->prepare("SELECT id, name, category, length, rented FROM cs290sp2015_rentals");
if (!$stmt) {
echo "Error Selecting Data from Rentals Table - Prepare Failed: " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}
} else {
// OTHERWISE BIND PREPARE STATEMENT BASED ON CATEGORY FILTER
$stmt = $mysqli->prepare("SELECT id, name, category, length, rented
FROM cs290sp2015_rentals
WHERE category=?");
if (!$stmt) {
echo "Error Selecting Data from Rentals Table - Prepare Failed: " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}
if (!$stmt->bind_param("s", $_POST['movie-filter'])) {
echo "Error binding category filter on select statement - Bind Failed: " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}
}
if (!$stmt->execute()) {
echo "Error executing Select on Rentals Table - Execute Failed: " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}
if (!$stmt->bind_result($mov_id, $mov_name, $mov_category, $mov_length, $mov_rented)) {
echo "Error executing Select on Rentals Table - Execute Failed: " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}
$stmt->store_result();
if ($stmt->num_rows > 0) {
// DISPLAY TABLE INFO
while ($stmt->fetch()) {
echo "<tr>\n<td>" . $mov_name
. "</td>\n<td>" . $mov_category
. "</td>\n<td>" . $mov_length
. "</td>\n";
if ($mov_rented == 0) {
echo "<td>Available</td>\n";
} else {
echo "<td>Checked Out</td>\n";
}
// delete button
echo '<td><form name="Delete This" action="#" method="post">';
echo '<input type="hidden" name="delete" value=' . $mov_id . '>';
echo '<input type="submit" value="Delete">';
echo '</form>';
// change status button
echo '<td><form name="Change Status" action="#" method="post">';
echo '<input type="hidden" name="update-id" value=' . $mov_id . '>';
echo '<input type="hidden" name="update-value" value=' . !$mov_rented . '>';
echo '<input type="submit" value="Check In/Out">';
echo '</form>';
}
}
$stmt->close();
?>
</tbody>
</table>
<br>
<!--ERASE ALL MOVIES IN DATABASE-->
<h1>ERASE TABLE DATA</h1>
<form name="Delete All" action="#" method="post">
<input type="hidden" name="killalldata" value="42" />
<input type="submit" value="DELETE ALL VIDEOS" />
</form>
</body>
</html> | ff0b0a57b5335c55ee5f2fb9c1a57183e0bde6f2 | [
"PHP"
] | 1 | PHP | J-Moore/cs290-assignment4-part2 | c3fca0833157dfb573e1edd6681cf3794bcbf5bb | 2c060f346d195f09fc7f17264581e5ef9be38d9b | |
refs/heads/master | <repo_name>pvhee/todo<file_sep>/todos.js
// An example Backbone application contributed by
// [<NAME>](http://jgn.me/). This demo uses a simple
// [LocalStorage adapter](backbone-localstorage.html)
// to persist Backbone models within your browser.
// Load the application once the DOM is ready, using `jQuery.ready`:
$(function(){
// Todo Model
// ----------
// Our basic **Todo** model has `title`, `order`, and `done` attributes.
var Todo = Backbone.Model.extend({
// Default attributes for the todo item.
defaults: function() {
return {
title: "empty todo...",
order: Todos.nextOrder(),
done: false
};
},
// Ensure that each todo created has `title`.
initialize: function() {
if (!this.get("title")) {
this.set({"title": this.defaults().title});
}
// add some listeners to test out stuff
this.bind("change:done", function() {
console.log("changed done to " + this.get("done") + " for model " + this.get("title"));
})
},
// Toggle the `done` state of this todo item.
toggle: function() {
this.save({done: !this.get("done")});
},
// Remove this Todo from *localStorage* and delete its view.
clear: function() {
this.destroy();
}
});
// Todo Collection
// ---------------
// The collection of todos is backed by *localStorage* instead of a remote
// server.
// @todo use node.js and socket.io to share todo lists via the server
// tutorial: http://developer.teradata.com/blog/jasonstrimpel/2011/11/backbone-js-and-socket-io
// To understand the functionality below, you need to know the functions provided by
// Underscore JS, http://underscorejs.org/, a utility-belt library for JS
var TodoList = Backbone.Collection.extend({
// Reference to this collection's model.
model: Todo,
// Save all of the todo items under the `"todos"` namespace.
// localStorage: new Store("todos-backbone"),
// Filter down the list of all todo items that are finished.
// this.filter is by backbone.js adapted to this collection. We pass in a function
// that gets the model in as argument and does a truth test for it to be included
// in the final array returned by 'done'.
done: function() {
return this.filter(function(todo){ return todo.get('done'); });
},
// Filter down the list to only todo items that are still not finished.
remaining: function() {
// We are using the "apply invocation pattern" (functions can have methods, since they are objects in JS)
// apply takes to arguments: the value of "this" and an array of arguments.
// See http://stackoverflow.com/questions/9137398/backbone-js-todo-collection-what-exactly-is-happening-in-this-return-stateme
return this.without.apply(this, this.done());
// No idea really why this cannot work, it will have the proper this scope this AFAIK.
// return this.without(this.done());
},
// We keep the Todos in sequential order, despite being saved by unordered
// GUID in the database. This generates the next order number for new items.
nextOrder: function() {
if (!this.length) return 1;
return this.last().get('order') + 1;
},
// Todos are sorted by their original insertion order.
// This will be called by the Collection everytime an item is added or removed.
comparator: function(todo) {
return todo.get('order');
}
});
// Create our global collection of **Todos**.
var Todos = new TodoList;
// Todo Item View
// --------------
// The DOM element for a todo item...
var TodoView = Backbone.View.extend({
//... is a list tag.
// so the View is working with the <li> HTML element
tagName: "li",
// Cache the template function for a single item.
// The #item-template refers to the template defined within the HTML
// as '<script type="text/template" id="item-template">'
template: _.template($('#item-template').html()),
// The DOM events specific to an item.
// Delegates this jQuery events to methods provided by this View
events: {
// when the event click is triggered on the element with class .toggle, launch toggleDone
"click .toggle" : "toggleDone",
"dblclick .view" : "edit",
"click a.destroy" : "clear",
"keypress .edit" : "updateOnEnter",
"blur .edit" : "close"
},
// The TodoView listens for changes to its model, re-rendering. Since there's
// a one-to-one correspondence between a **Todo** and a **TodoView** in this
// app, we set a direct reference on the model for convenience.
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.remove, this);
},
// Re-render the titles of the todo item.
render: function() {
// we turn the model into a JSON object and pass it on to the templating engine
this.$el.html(this.template(this.model.toJSON()));
// use jQuery's toggleClass to add/remove the 'done' class to this <li>
this.$el.toggleClass('done', this.model.get('done'));
this.input = this.$('.edit');
return this;
},
// Toggle the `"done"` state of the model.
toggleDone: function() {
this.model.toggle();
},
// Switch this view into `"editing"` mode, displaying the input field.
edit: function() {
this.$el.addClass("editing");
this.input.focus();
},
// Close the `"editing"` mode, saving changes to the todo.
close: function() {
var value = this.input.val();
if (!value) this.clear();
this.model.save({title: value});
this.$el.removeClass("editing");
},
// If you hit `enter`, we're through editing the item.
updateOnEnter: function(e) {
if (e.keyCode == 13) this.close();
// this is space, don't allow them
// if (e.keyCode == 32) this.close();
},
// Remove the item, destroy the model.
clear: function() {
this.model.clear();
}
});
// The Application
// ---------------
// Our overall **AppView** is the top-level piece of UI.
var AppView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: $("#todoapp"),
// Our template for the line of statistics at the bottom of the app.
statsTemplate: _.template($('#stats-template').html()),
// Delegated events for creating new items, and clearing completed ones.
events: {
"keypress #new-todo": "createOnEnter",
"click #clear-completed": "clearCompleted",
"click #toggle-all": "toggleAllComplete"
},
// At initialization we bind to the relevant events on the `Todos`
// collection, when items are added or changed. Kick things off by
// loading any preexisting todos that might be saved in *localStorage*.
initialize: function() {
this.input = this.$("#new-todo");
this.allCheckbox = this.$("#toggle-all")[0];
Todos.bind('add', this.addOne, this);
Todos.bind('reset', this.addAll, this);
Todos.bind('all', this.render, this);
this.footer = this.$('footer');
this.main = $('#main');
Todos.fetch();
},
// Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
render: function() {
var done = Todos.done().length;
var remaining = Todos.remaining().length;
if (Todos.length) {
this.main.show();
this.footer.show();
this.footer.html(this.statsTemplate({done: done, remaining: remaining}));
} else {
this.main.hide();
this.footer.hide();
}
this.allCheckbox.checked = !remaining;
},
// Add a single todo item to the list by creating a view for it, and
// appending its element to the `<ul>`.
addOne: function(todo) {
var view = new TodoView({model: todo});
this.$("#todo-list").append(view.render().el);
},
// Add all items in the **Todos** collection at once.
addAll: function() {
Todos.each(this.addOne);
},
// If you hit return in the main input field, create new **Todo** model,
// persisting it to *localStorage*.
createOnEnter: function(e) {
if (e.keyCode != 13) return;
if (!this.input.val()) return;
Todos.create({title: this.input.val()});
this.input.val('');
},
// Clear all done todo items, destroying their models.
clearCompleted: function() {
_.each(Todos.done(), function(todo){ todo.clear(); });
return false;
},
toggleAllComplete: function () {
var done = this.allCheckbox.checked;
Todos.each(function (todo) { todo.save({'done': done}); });
}
});
// Override backbone's syncing method to provide interaction with a back-end
// via http://developer.teradata.com/blog/jasonstrimpel/2011/11/backbone-js-and-socket-io
// -------------------------------------------------------------------------
Backbone.sync = function (method, model, options) {
// console.log('we are syncing!');
console.log(method);
// console.log(model);
// console.log(options);
var socket = window.socket; // grab active socket from global namespace; io.connect() was used to create socket
// console.log(window.socket);
/*
* Create signature object that will emitted to server with every request.
* This is used on the server to push an event back to the client listener.
*/
var signature = function () {
var sig = {};
sig.endPoint = model.url + (model.id ? ('/' + model.id) : '');
if (model.ctx) sig.ctx = model.ctx;
return sig;
};
/*
* Create an event listener for server push. The server notifies
* the client upon success of CRUD operation.
*/
var event = function (operation, sig) {
var e = operation + ':';
e += sig.endPoint;
if (sig.ctx) e += (':' + sig.ctx);
return e;
};
// Save a new model to the server.
var create = function () {
var sign = signature(model);
var e = event('create', sign);
console.log(model.attributes);
socket.emit('create', {'signature' : sign, item : model.attributes });
socket.once(e, function (data) {
model.id = data.id;
console.log(model);
});
};
// Get a collection or model from the server.
var read = function () {
var sign = signature(model);
// console.log(model);
var e = event('read', sign);
socket.emit('read', {'signature' : sign});
socket.once(e, function (data) {
options.success(data); // updates collection, model; fetch
});
};
// Save an existing model to the server.
var update = function () {
var sign = signature(model);
var e = event('update', sign);
socket.emit('update', {'signature' : sign, item : model.attributes }); // model.attribues is the model data
socket.once(e, function (data) {
console.log(data);
});
};
// Delete a model on the server.
var destroy = function () {
var sign = signature(model);
var e = event('delete', sign);
socket.emit('delete', {'signature' : sign, item : model.attributes }); // model.attribues is the model data
socket.once(e, function (data) {
console.log(data);
});
};
// entry point for method
switch (method) {
case 'create':
create();
break;
case 'read':
read();
break;
case 'update':
update();
break;
case 'delete':
destroy();
break;
}
};
// Finally, we kick things off by creating the **App**.
var App = new AppView;
});
<file_sep>/README.md
Based on the TODO backbone.js demo by [<NAME>](http://jgn.me).
## Extensions (in progress):
* Integration with node.js and socket.io to replace HTML localStorage
## Author
[@pvhee](http://twitter.com/pvhee) | 0a12a53b6864ee04d16637f6dad32020d7bad8b5 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | pvhee/todo | a4d9f3bd49f7f329402fb3a3aec167aa47ce295e | d00edb4261855c3dcf3b3989a89f287be72bbdd3 | |
refs/heads/master | <file_sep>//fetching data from form.
myData = () => {
let fname = document.getElementById("fname").value;
let lname = document.getElementById("lname").value;
let address = document.getElementById("address").value;
let pincode = document.getElementById("pincode").value;
let gender = document.getElementsByName("gender");
let food_check = document.getElementsByName("optradio");
let country = document.getElementById('country').value;
let state = document.getElementById('state').value;
var gen;
var food = ""
for(var i=0; i<gender.length; i++)
{
if(gender[i].checked){
gen = gender[i].value
}
}
for(var i=0; i<food_check.length; i++){
if(food_check[i].checked){
food = food + food_check[i].value + ","
}
}
var data = [fname, lname, address, pincode, gen, food, state, country]
tab_body = document.getElementById("table-body");
tr = document.createElement('tr');
data.forEach(element => {
td = document.createElement('td')
td.innerHTML = element
tr.append(td)
console.log(element)
})
tab_body.appendChild(tr)
document.getElementById('frm').reset()
} | 32490d73d0f081b697f31f853942545841f79c72 | [
"JavaScript"
] | 1 | JavaScript | kewalb/Forms_Tables | 4e30106863c7ed16d5fd34988152e588f606cbdc | 495a986828ac350d2f6b5650d559c3cfc0c1d767 | |
refs/heads/master | <repo_name>weixr18/LeetCode<file_sep>/src/22_brackets.cpp
/*
22. 括号生成
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例:
输入:n = 3
输出:[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
/*
思路:
等效成二维平面上等腰直角三角形内的曼哈顿寻路问题
用一个栈辅助,做深度优先搜索,遍历所有可能路径。
*/
#include <vector>
#include <iostream>
#include <stdexcept>
using namespace std;
struct State
{
int x;
int y;
char *path;
int p; //pointer
State(int _x, int _y)
{
x = _x;
y = _y;
path = nullptr;
p = 0;
}
bool operator==(State &s)
{
return (this->x == s.x) && (this->y == s.y);
}
};
template <typename T>
class Stack
{
public:
T *b; //base
T *t; //top
int count;
Stack(int capacity)
{
b = new T[capacity];
t = b;
count = 0;
}
~Stack()
{
delete[] b;
}
void push(T &a)
{
*t = a;
t++;
count++;
}
T pop()
{
if (count > 0)
{
t--;
count--;
return *t;
}
else
{
throw out_of_range("Stack reached bottom");
}
}
int size()
{
return count;
}
};
class Solution
{
public:
vector<string> generateParenthesis(int n)
{
vector<string> *results = new vector<string>();
Stack<State *> st(n);
State *cur_state = new State(0, 0);
cur_state->path = new char[2 * n];
State final_state = State(n, n);
int cur_x;
int cur_y;
while (true)
{
cur_x = cur_state->x;
cur_y = cur_state->y;
if (cur_x == n)
{
if (*cur_state == final_state)
{
if (cur_state->p != 2 * n)
{
throw logic_error("path should be n characters.");
}
string s = string(cur_state->path, 2 * n);
//cout << s << endl;
results->push_back(s);
delete[] cur_state->path;
cur_state->path = nullptr;
delete cur_state;
if (st.size() > 0)
{
cur_state = st.pop();
}
else
{
break;
}
}
else
{
for (int i = cur_state->p; i < 2 * n; i++)
{
cur_state->path[i] = ')';
}
cur_state->p = 2 * n;
cur_state->y = n;
}
}
else if (cur_x == cur_y)
{
cur_state->x += 1;
cur_state->path[cur_state->p] = '(';
cur_state->p++;
}
else
{
State *new_state = new State(cur_x, cur_y + 1);
new_state->path = new char[2 * n];
memcpy(new_state->path, cur_state->path, cur_state->p);
new_state->path[cur_state->p] = ')';
new_state->p = cur_state->p;
new_state->p += 1;
st.push(new_state);
cur_state->x += 1;
cur_state->path[cur_state->p] = '(';
cur_state->p++;
}
}
return *results;
}
};
int main()
{
try
{
Solution s;
s.generateParenthesis(10);
}
catch (exception e)
{
cout << e.what() << endl;
}
return 0;
}
<file_sep>/note.md
# Notes
## Trivial
### 1 两数之和
+ 题目
+ 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
+ 思路
+ 带index排序 O(nlogn)
+ 带指针扫描 O(n)
### 866 回文素数
+ 题目
+ 求出大于或等于 N 的最小回文素数。
+ 思路
1. 拿到最小回文基,依次递增找回文数
2. 模6+方根法判断是否素数
### O07 重构二叉树
+ 题目
+ 先序遍历和中序遍历重构二叉树
+ 思路
+ 先序遍历最左侧为当前子树根节点。在中序遍历中看到该节点时,说明此时应该生长其右子树。
+ 用栈依次保存根节点。
## Medium
### 22 括号生成
+ 题目
+ 数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
+ 思路
+ 等效成二维平面上等腰直角三角形内的曼哈顿寻路问题。
+ 用一个栈辅助,做深度优先搜索,遍历所有可能路径。
### 51 逆序对个数
+ 题目
+ 求给定数组逆序对个数
+ 思路
+ 归并排序 O(nlogn)
## Star
### O41 数据流中位数
+ 题目
+ 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
+ 思路
+ 双堆
+ 一个大顶堆保存较小的一半,一个小顶堆保存较大的一半
+ O(log n)
### O04 有序二维数组查找
+ 题目
+ 在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
+ 思路
+ 从右上角开始,大于往左,小于往下,等于返回true,走到左下角返回false。
### 53 最大子数组和
+ 题目
+ 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
+ 思路
+ **线段树**
+ 每个线段维护4个值:左起最大和,右起最大和,总最大和,总和,遍历更新即可。O(log n)
### 300 最长上升子序列
+ 题目
+ 给定一个无序的整数数组,找到其中最长上升子序列的长度。
+ 思路
+ O(n^2) DP
+ 每个位置存储一个数:以该位置数结尾的上升子序列的最大长度
+ 从前到后遍历[0,i]的位置,获取第i+1位置的最大长度
+ 所有最大长度之最大值即为解
+ **O(nlogn) 贪心二分**
+ 记录每个长度对应的上升子序列的最小终值
+ 对于第i个位置,要么增长最长可能长度(比所有最小终值都大),要么更新某个最小终值
### 523 连续的子数组和
+ 题目
+ 给定一个包含 非负数 的数组和一个目标 整数 k,编写一个函数来判断该数组**是否**含有连续的子数组,其大小至少为 2,且总和为 k 的倍数,即总和为 n*k,其中 n 也是一个整数。
+ 思路
+ 最暴力
+ 对所有可能求和,O(n^3)
+ less 暴力
+ 用O(n^2)空间保存之前的所有子组和,O(n^2)
+ **Hashmap**
+ 若有[a_i, a_j]连续和模k余0,则必有[0, a_i]和[0, a_j]模k相同。
+ 用Hashmap保存每一个从头开始的连续和模k余数,重复即确定含有。
### O39 超过一半的数字
+ 题目
+ 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
+ 思路
+ Hash
+ 时间复杂度O(n) 空间复杂度O(n)
+ **摩尔投票法**
+ 众数票数为1,非众数票数为-1.由题,总票数为正
+ 若把某非众数的数当做众数
+ 当正负相消时,要么消了偶数票负数,要么消了0,即总票数仍为正,真正的众数仍为众数
+ 根据题目条件,一定可以相消
+ 因此可以无脑选众数,相消就换。最终剩下的数一定是众数。
<file_sep>/src/866_round_prime.cpp
/*866. 回文素数
求出大于或等于 N 的最小回文素数。
回顾一下,如果一个数大于 1,且其因数只有 1 和它自身,那么这个数是素数。
例如,2,3,5,7,11 以及 13 是素数。
回顾一下,如果一个数从左往右读与从右往左读是一样的,那么这个数是回文数。
例如,12321 是回文数。
*/
#include <cmath>
#include <iostream>
bool isPrime(int num)
{
if (num == 2 || num == 3 || num == 5)
return true;
unsigned long c = 7;
if (num % 2 == 0 || num % 3 == 0 || num % 5 == 0 || num == 1)
return false;
int maxc = int(sqrt(num));
while (c <= maxc)
{
if (num % c == 0)
return false;
c += 4;
if (num % c == 0)
return false;
c += 2;
if (num % c == 0)
return false;
c += 4;
if (num % c == 0)
return false;
c += 2;
if (num % c == 0)
return false;
c += 4;
if (num % c == 0)
return false;
c += 6;
if (num % c == 0)
return false;
c += 2;
if (num % c == 0)
return false;
c += 6;
}
return true;
}
int my_pow10(int n)
{
if (n == 0)
{
return 1;
}
else if (n == 1)
{
return 10;
}
else if (n == 2)
{
return 100;
}
else if (n == 3)
{
return 1000;
}
else if (n == 4)
{
return 10000;
}
else if (n == 5)
{
return 100000;
}
else if (n == 6)
{
return 1000000;
}
else if (n == 7)
{
return 10000000;
}
else if (n == 8)
{
return 100000000;
}
else if (n == 9)
{
return 1000000000;
}
return -1;
}
class Solution
{
public:
int getRound(int base, int d)
{
int sum = 0;
int N = base * my_pow10(d / 2);
sum += N;
for (int i = 0; i < d / 2; i++)
{
sum += ((N / my_pow10(d - 1 - i)) % 10) * (my_pow10(i));
}
return sum;
}
int primePalindrome(int N)
{
int n_copy = N;
int d = 0;
//int num[10] = {0};
while (n_copy > 0)
{
//num[d] = n_copy % 10;
n_copy = n_copy / 10;
d++;
}
int base = (N / my_pow10(d / 2));
int current = getRound(base, d);
if (N > current)
{
if (base < (my_pow10((d + 1) / 2) - 1))
{
base++;
current = getRound(base, d);
}
else
{
if (d % 2 == 0)
{
base++;
d++;
current = getRound(base, d);
}
else
{
base = (base++) / 10;
d++;
current = getRound(base, d);
}
}
}
while (!isPrime(current))
{
if (base < (my_pow10((d + 1) / 2) - 1))
{
base++;
current = getRound(base, d);
}
else
{
if (d % 2 == 0)
{
base++;
d++;
current = getRound(base, d);
}
else
{
base = (base++) / 10;
d++;
current = getRound(base, d);
}
}
}
return current;
}
};
/*
int main()
{
Solution s;
int n;
//s.primePalindrome(456);
while (true)
{
std::cin >> n;
std::cout << s.primePalindrome(n) << std::endl;
}
return 0;
}
*/<file_sep>/src/983_min_cost_for_tickets.cpp
/*
在一个火车旅行很受欢迎的国度,你提前一年计划了一些火车旅行。
在接下来的一年里,你要旅行的日子将以一个名为 days 的数组给出。
每一项是一个从 1 到 365 的整数。
火车票有三种不同的销售方式:
一张为期一天的通行证售价为 costs[0] 美元;
一张为期七天的通行证售价为 costs[1] 美元;
一张为期三十天的通行证售价为 costs[2] 美元。
通行证允许数天无限制的旅行。
例如,如果我们在第 2 天获得一张为期 7 天的通行证,
那么我们可以连着旅行 7 天:第 2 天、第 3 天、第 4 天、第 5 天、第 6 天、第 7 天和第 8 天。
返回你想要完成在给定的列表 days 中列出的每一天的旅行所需要的最低消费。
示例 1:
输入:days = [1,4,6,7,8,20], costs = [2,7,15]
输出:11
解释:
例如,这里有一种购买通行证的方法,可以让你完成你的旅行计划:
在第 1 天,你花了 costs[0] = $2 买了一张为期 1 天的通行证,它将在第 1 天生效。
在第 3 天,你花了 costs[1] = $7 买了一张为期 7 天的通行证,它将在第 3, 4, ..., 9 天生效。
在第 20 天,你花了 costs[0] = $2 买了一张为期 1 天的通行证,它将在第 20 天生效。
你总共花了 $11,并完成了你计划的每一天旅行。
示例 2:
输入:days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
输出:17
解释:
例如,这里有一种购买通行证的方法,可以让你完成你的旅行计划:
在第 1 天,你花了 costs[2] = $15 买了一张为期 30 天的通行证,它将在第 1, 2, ..., 30 天生效。
在第 31 天,你花了 costs[0] = $2 买了一张为期 1 天的通行证,它将在第 31 天生效。
你总共花了 $17,并完成了你计划的每一天旅行。
提示:
1 <= days.length <= 365
1 <= days[i] <= 365
days 按顺序严格递增
costs.length == 3
1 <= costs[i] <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-cost-for-tickets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
#include <vector>
#include <iostream>
using namespace std;
class Solution
{
public:
int mincostTickets(vector<int> &days, vector<int> &costs)
{
return 0;
}
};<file_sep>/src/1_two_sum.cpp
/*
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
/*
思路:
1. 带index排序 O(nlogn)
2. 双指针扫描 O(n)
*/
#include <vector>
#include <iostream>
using namespace std;
template <class T>
class Stack
{
public:
Stack(int n);
~Stack();
void push(const T &t);
T top();
T pop();
int size();
int isEmpty();
private:
T *arr;
int count;
};
template <class T>
Stack<T>::Stack(int n)
{
arr = new T[n];
count = 0;
if (!arr)
{
cout << "arr malloc error!" << endl;
}
}
template <class T>
Stack<T>::~Stack()
{
if (arr)
{
delete[] arr;
arr = NULL;
}
}
template <class T>
void Stack<T>::push(const T &t)
{
arr[count] = t;
count++;
}
template <class T>
T Stack<T>::top()
{
return arr[count - 1];
}
template <class T>
T Stack<T>::pop()
{
int ret = arr[count - 1];
count--;
return ret;
}
template <class T>
int Stack<T>::size()
{
return count;
}
template <class T>
int Stack<T>::isEmpty()
{
return size() == 0;
}
class Solution
{
public:
struct pair
{
int num;
int index;
};
vector<int> twoSum(vector<int> &nums, int target)
{
pair *num_and_index = new pair[nums.size()];
for (int i = 0; i < nums.size(); i++)
{
num_and_index[i].num = nums[i];
num_and_index[i].index = i;
}
quickSortNonRecursive(num_and_index, 0, nums.size() - 1);
for (int i = 0; i < nums.size(); i++)
{
cout << num_and_index[i].num << ' ';
}
int lo = 0;
int hi = nums.size() - 1;
while (lo < hi)
{
while (num_and_index[hi].num > target - num_and_index[lo].num && lo < hi)
{
hi--;
}
if (num_and_index[hi].num == target - num_and_index[lo].num)
{
return vector<int>({num_and_index[lo].index, num_and_index[hi].index});
}
while (num_and_index[lo].num < target - num_and_index[hi].num && lo < hi)
{
lo++;
}
if (num_and_index[hi].num == target - num_and_index[lo].num)
{
return vector<int>({num_and_index[lo].index, num_and_index[hi].index});
}
}
return vector<int>({num_and_index[lo].index, num_and_index[hi].index});
}
int getPartition(pair *pairs, int lo, int hi)
{
pair keyVal = pairs[lo];
while (lo < hi)
{
while (lo < hi && pairs[hi].num >= keyVal.num)
hi--;
pairs[lo] = pairs[hi];
while (lo < hi && pairs[lo].num <= keyVal.num)
lo++;
pairs[hi] = pairs[lo];
}
pairs[lo] = keyVal;
return lo;
}
void quickSortNonRecursive(pair *pairs, int lo, int hi)
{
Stack<int> s(hi + 1); //hi+1 is length.
if (lo < hi)
{
int mid = getPartition(pairs, lo, hi);
if (mid - 1 > lo)
{
s.push(lo);
s.push(mid - 1);
}
if (mid + 1 < hi)
{
s.push(mid + 1);
s.push(hi);
}
while (!s.isEmpty())
{
int qhi = s.top();
s.pop();
int plo = s.top();
s.pop();
int pqMid = getPartition(pairs, plo, qhi);
if (pqMid - 1 > plo)
{
s.push(plo);
s.push(pqMid - 1);
}
if (pqMid + 1 < qhi)
{
s.push(pqMid + 1);
s.push(qhi);
}
}
}
}
};
int main()
{
vector<int> nums = vector<int>({3, 2, 4});
int target = 6;
Solution solution;
auto a = solution.twoSum(nums, target);
cout << endl;
cout << a[0] << a[1];
return 0;
}
| 8ae00fd7357714aa9839646ab0d10cc209fc5641 | [
"Markdown",
"C++"
] | 5 | C++ | weixr18/LeetCode | f7166c8a1837ed6ca9630c29d585cae4222a779a | 1ad534ed4fd0338a8129c97614abf7cfee3c3317 | |
refs/heads/main | <file_sep>import logging, threading, time, concurrent.futures, psutil, sys, numpy, win32api, os
import pygame as pg
sys.coinit_flags = 2 # COINIT_APARTMENTTHREADED
import pyautogui, pywinauto
import commandQueue as cq
from PIL import ImageGrab
from functools import partial
ImageGrab.grab = partial(ImageGrab.grab, all_screens=True)
'''
a threaded machinecontrol program
'''
APPDATA = os.getenv('LOCALAPPDATA')
APPPATH = APPDATA + r"\Apps\2.0\C75B96K0.H2D\HN3DO2PP.HKG\shoc..tion_92aab741509f25fe_0005.0000_2eefa70506f6a3c9\Shockspot-Control.exe"
PROCNAME = "Shockspot-Control.exe"
SCRWID = win32api.GetSystemMetrics(0)
def processCommands():
'''take in commands from the queue in dict form'''
while True:
command = cq.q.get()
logging.info(f"received command {command}")
time.sleep(3)
logging.info("done")
cq.q.task_done()
class mControl:
def __init__(self, toyDim = [7,4,5]):
# get app PID or False if unable to find
self.PID = self.getPID()
if self.PID:
logging.debug(f"existing PID found: {self.PID}")
self.app = pywinauto.Application().connect(process=self.PID,backend="uia")
else:
logging.debug("no PID found, starting app")
self.app = self.startApp()
self.dlg = self.app.top_window()
self.dlg.move_window(SCRWID + 50,50,1820,980)
self.dlg.set_focus()
self.maxDepth = self.slider(self,"maxDepth", [0,8], 5)
self.depth = self.slider(self,"depth", [0,8], 5)
self.stroke = self.slider(self,"stroke", [0,8], 5)
self.speed = self.slider(self,"speed", [0,1], 10)
self.roughness = self.slider(self,"roughness", [0,1], 10)
# self.toy = toy(*toyDim,self.depth.getValue(),self.stroke.getValue())
def startApp(self):
app = pywinauto.Application().start(APPPATH)
app.top_window()['I have read and agree with the terms above'].click()
return app
def restartMachine(self):
pass
# kill & relaunch if problem detected
def getPID(self):
PID = False
for proc in psutil.process_iter(['pid','name']):
if proc.info['name'] == PROCNAME:
PID = proc.info['pid']
return PID
class slider:
""" an individual slider with pixel & real values """
sliderDict = {
"maxDepth" : "Max_Pos_Slider"
,"depth" : "Pos_Slider1"
,"stroke" : "pullback_pos_slider"
,"speed" : "Vel_Slider2"
,"roughness" : "Accel_Slider3"
}
def __init__(self,parent,name,valMap,minMove):
self.name = name
self.valMap = valMap
self.minMove = minMove
self.parent = parent
self.r = self.parent.dlg.child_window(auto_id=self.sliderDict[name], control_type="System.Windows.Forms.TrackBar").rectangle()
self.bounds = (self.r.left,self.r.top,self.r.width(),self.r.height())
self.getValue()
def getLocation(self):
pywinauto.mouse.move((100,100))
return pyautogui.locateCenterOnScreen('needle.png',
confidence=0.6,
region=self.bounds,
grayscale=False
)
def getValue(self):
# return real value (not pixel value)
self.loc = self.getLocation()
logging.debug(f"slider getLocation {self.name} result: {self.loc}")
if self.loc:
self.lastValue = numpy.interp(self.loc[0], (self.r.left,self.r.right), self.valMap)
return self.lastValue
else:
return False
def setValue(self, val):
logging.debug(f"setValue for {self.name} to {val}")
if self.getValue() is not False:
desiredPos = int(numpy.interp(val, self.valMap, (self.r.left,self.r.right)))
dist = abs(desiredPos - self.loc[0])
attempts = 1
while dist >= self.minMove and attempts <= 5:
logging.debug("attempt",attempts,"dist:",dist)
pyautogui.moveTo(self.loc)
pywinauto.mouse.press(coords=(self.loc[0],self.loc[1]))
pywinauto.mouse.release(coords=(desiredPos,self.loc[1]))
self.getValue()
dist = abs(desiredPos - self.loc[0])
attempts += 1
if dist <= self.minMove:
logging.debug("already at desired position, skipped")
class toy:
def __init__(self, length, knotStart, knotMid, knotDepth, initialStroke):
# physical characteristics
self.length = length
self.knotStart = knotStart
self.knotMid = knotMid
# adjusted for machine reading
self.knotDepth = knotDepth # true knot start depth
self.strokeOffset = max(0,knotDepth - initialStroke) # stroke must always be this much less than depth (may be 0)
self.midDepth = knotDepth + knotMid - knotStart # true depth setting for knot midpoint
self.totalDepth = knotDepth + length - knotStart # true max depth / length
self.progressDepth = knotDepth # for incrementing til midDepth
def increment(self, percent):
# move this % towards knot, max out at knot mid
self.progressDepth = min(self.progressDepth + (self.midDepth - self.knotDepth) * percent/100, self.midDepth)
if __name__ == "__main__":
m = mControl()
<file_sep># ARSM
machinecontrol.py
this library is designed to control the shockspot application in a multi-monitor setup. The application is launched or detected then moved to the monitor to the right of the main one.
create a mControl object using m = mControl()
Then the sliders can be controlled with:
m.depth.setValue(5)
depth sliders have values 0-8
speed / smoothness values 0-1
<file_sep>import logging, numpy, win32api, os , psutil, sys, pyautogui
import threading, time, concurrent.futures
from screeninfo import get_monitors
from PIL import ImageGrab
from functools import partial
ImageGrab.grab = partial(ImageGrab.grab, all_screens=True)
sys.coinit_flags = 2 # COINIT_APARTMENTTHREADED
import pywinauto
'''
controls a shockspot machine with an optional process to tace a command queue
'''
APPDATA = os.getenv('LOCALAPPDATA')
PROCNAME = "Shockspot-Control.exe"
SCRWID = win32api.GetSystemMetrics(0) # current screen width
SCRH = win32api.GetSystemMetrics(1) # current screen height
MONITORS = win32api.GetSystemMetrics(80) # number of current monitors
LEFTEXTENT = win32api.GetSystemMetrics(76) # coordinate of leftmost extent. (negative if monitor to the left of main)
TOTALWIDTH = win32api.GetSystemMetrics(78) # total width, e.g. 7680 for 3x 1440p monitors
NEEDLE = os.path.join(os.path.dirname(__file__), 'needle.png') # picture of the slider thumb to find current location
# try to find the shockspot EXE in appdata
APPPATH = False
for dirpath, dirs, files in os.walk(os.path.join(APPDATA,"Apps","2.0")):
for filename in files:
if filename == PROCNAME:
APPPATH = os.path.join(dirpath,filename)
if not APPPATH:
logging.error("ERROR: Shockspot EXE not found in %APPDATA%")
# get monitor info
monitors = get_monitors()
# get total monitor coordinate system canvas
xmin, xmax, ymin, ymax = 0,0,0,0
for monitor in monitors:
xmin = min(xmin,monitor.x)
ymin = min(ymin,monitor.y)
xmax = max(xmax,monitor.x+monitor.width)
ymax = max(ymax,monitor.y+monitor.width)
# margin between edge of slider object and it's maximum/minimum value
SLIDERMARGIN = (14,-14)
# this should really exist in the main file, not implemented here
def processCommands():
'''take in commands from the queue in dict form'''
while True:
command = cq.q.get()
logging.info(f"received command {command}")
time.sleep(3)
logging.info("done")
cq.q.task_done()
class shockspot:
def __init__(self, monitor = MONITORS, length = 8, maxDepthValue = 6, toyDim = [7,4,5]):
# get app PID or False if unable to find
self.monitor = monitor # by default use rightmost monitor
self.maxDepthValue = maxDepthValue
self.PID = self.getPID()
if self.PID:
logging.debug(f"existing PID found: {self.PID}")
self.app = pywinauto.Application().connect(process=self.PID,backend="uia")
else:
logging.debug("no PID found, starting app")
self.app = self.startApp()
self.dlg = self.getDialog(self.app)
self.maxDepth = self.slider(self,"maxDepth", [0,length], 5)
self.depth = self.slider(self,"depth", [0,length], 5)
self.stroke = self.slider(self,"stroke", [0,length], 5)
self.speed = self.slider(self,"speed", [0,1], 10)
self.roughness = self.slider(self,"roughness", [0,1], 10)
self.maxDepth.setValue(self.maxDepthValue)
# self.toy = toy(*toyDim,self.depth.getValue(),self.stroke.getValue())
def getDialog(self,app):
dlg = app.top_window()
dlg.move_window(SCRWID + 50,50,1820,980)
dlg.set_focus()
return dlg
def startApp(self):
app = pywinauto.Application().start(APPPATH)
app.top_window()['I have read and agree with the terms above'].click()
return app
def restart(self):
# kill & relaunch if problem detected
self.dlg.close()
self.app = self.startApp()
self.dlg = self.getDialog(self.app)
self.maxDepth.setValue(self.maxDepthValue)
# todo: set all sliders to previous value... need to keep some sort of state
def getPID(self):
PID = False
for proc in psutil.process_iter(['pid','name']):
if proc.info['name'] == PROCNAME:
PID = proc.info['pid']
return PID
class slider:
""" an individual slider with pixel & real values """
sliderDict = {
"maxDepth" : "Max_Pos_Slider"
,"depth" : "Pos_Slider1"
,"stroke" : "pullback_pos_slider"
,"speed" : "Vel_Slider2"
,"roughness" : "Accel_Slider3"
}
def __init__(self,parent,name,valMap,minMove):
self.name = name
self.valMap = valMap
self.minMove = minMove
self.parent = parent
self.r = self.parent.dlg.child_window(auto_id=self.sliderDict[name], control_type="System.Windows.Forms.TrackBar").rectangle()
self.bounds = (self.r.left-xmin,self.r.top-ymin,self.r.width(),self.r.height())
self.getValue()
def getLocation(self):
pywinauto.mouse.move((100,100))
loc = pyautogui.locateCenterOnScreen(NEEDLE,
confidence=0.6,
region=self.bounds,
grayscale=True
)
if loc:
return xmin+loc[0],ymin+loc[1]
else:
return False
def getValue(self):
# return real value (not pixel value)
self.loc = self.getLocation()
logging.debug(f"slider getLocation {self.name} result: {self.loc}")
if self.loc:
self.lastValue = numpy.interp(self.loc[0], (self.r.left+SLIDERMARGIN[0],self.r.right-SLIDERMARGIN[1]), self.valMap)
return self.lastValue
else:
return False
def setValue(self, val):
logging.debug(f"setValue for {self.name} to {val}")
if self.getValue() is not False:
desiredPos = int(numpy.interp(val, self.valMap, (self.r.left+SLIDERMARGIN[0],self.r.right+SLIDERMARGIN[1])))
dist = abs(desiredPos - self.loc[0])
attempts = 1
while dist >= self.minMove and attempts <= 5:
logging.debug(f"attempt {attempts}, dist: {dist}")
pyautogui.moveTo(self.loc)
pywinauto.mouse.press(coords=(self.loc[0],self.loc[1]))
pywinauto.mouse.release(coords=(desiredPos,self.loc[1]))
self.getValue()
dist = abs(desiredPos - self.loc[0])
attempts += 1
if dist <= self.minMove:
logging.debug("already at desired position, skipped")
else:
logging.error("setValue abort due to getValue false")
class toy:
def __init__(self, length, knotStart, knotMid, knotDepth, initialStroke):
# physical characteristics
self.length = length
self.knotStart = knotStart
self.knotMid = knotMid
# adjusted for machine reading
self.knotDepth = knotDepth # true knot start depth
self.strokeOffset = max(0,knotDepth - initialStroke) # stroke must always be this much less than depth (may be 0)
self.midDepth = knotDepth + knotMid - knotStart # true depth setting for knot midpoint
self.totalDepth = knotDepth + length - knotStart # true max depth / length
self.progressDepth = knotDepth # for incrementing til midDepth
def increment(self, percent):
# move this % towards knot, max out at knot mid
self.progressDepth = min(self.progressDepth + (self.midDepth - self.knotDepth) * percent/100, self.midDepth)
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.DEBUG,
datefmt="%H:%M:%S")
m = shockspot()
<file_sep>import threading, queue
q = queue.Queue()
| 5c42e428ca56165348dc4e53d4cc4c7a7a50cd63 | [
"Markdown",
"Python"
] | 4 | Python | seasoncurrent/ARSM | fd7eea30627de1431cc9573de080031273513199 | 24c00aa52e25f7aa41e284802d76e4835e9b40fe |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.