repo
stringlengths
5
121
content
stringlengths
35
2.09M
zhenya250398/IR-2020
zhenya250398/IR-2020 README.md ```# IR-2020 Материалы курса Методы информационного поиска ``` lab2.md ```# Использование FTS в PostgreSQL #### 1. Тип tsvector Выполните запрос ```sql SELECT to_tsvector('The quick brown fox jumped over the lazy dog.'); ``` В ответ будет возвращён список [лексем](https://en.wikipedia.org/wiki/Lexeme) ```sql to_tsvector 'brown':3 'dog':9 'fox':4 'jump':5 'lazi':8 'quick':2 ``` > Задание 1 1. Изучите документацию к функции `to_tsvector` 2. Вызовите эту функцию для следующей строки: `Съешь ещё этих мягких французских булок, да выпей чаю` 3. Почему в векторе нет слова `да`? #### 2. Тип tsquery Выполните по очереди запросы ```sql --№1 SELECT to_tsvector('The quick brown fox jumped over the lazy dog') @@ to_tsquery('fox'); --№2 SELECT to_tsvector('The quick brown fox jumped over the lazy dog') @@ to_tsquery('foxes'); --№3 SELECT to_tsvector('The quick brown fox jumped over the lazy dog') @@ to_tsquery('foxhound'); ``` > Задание 2 1. Что означают символы `@@` 2. Почему второй запрос возвращает `true`, а третий не возвращает 3. Выполните запрос ```sql SELECT to_tsvector('Russian', 'Съешь ещё этих мягких французских булок, да выпей чаю.') @@ to_tsquery('Russian','булка'); ``` Почему слово булка не находится? 4. Используйте функцию `select ts_lexize('russian_stem', 'булок');` для того чтобы понять почему. 5. Замените в предложении слово `булок`, на слово `пирожков` Выполните запросы ```sql --№1 SELECT to_tsvector('Russian', 'Съешь ещё этих мягких французских пирожков, да выпей чаю.') @@ to_tsquery('Russian','пирожки'); --№2 SELECT to_tsvector('Russian', 'Съешь ещё этих мягких французских пирожков, да выпей чаю.') @@ to_tsquery('Russian','пирожок'); ``` Почему первый запрос возвращает `true`, а второй не возвращает? #### 3. Операторы Выполните запрос ```sql --И SELECT to_tsvector('The quick brown fox jumped over the lazy dog') @@ to_tsquery('fox & dog'); --ИЛИ SELECT to_tsvector('The quick brown fox jumped over the lazy dog') @@ to_tsquery('fox | rat'); --отрицание SELECT to_tsvector('The quick brown fox jumped over the lazy dog') @@ to_tsquery('!clown'); --группировка SELECT to_tsvector('The quick brown fox jumped over the lazy dog') @@ to_tsquery('fox & (dog | rat) & !mice'); ``` > Задание 3 1. Приведите аналогичные запросы для любого предложения на русском 2. Почему для английского языка не нужно указывать язык в первом аргументе и какой анализатор используется если никакой не указан? #### 4. Поиск фраз Изучите документацию по [операторам](https://www.postgresql.org/docs/current/functions-textsearch.html) FTS Выполните запрос ```sql SELECT to_tsvector('Russian', 'Съешь ещё этих мягких французских булок, да выпей чаю.') @@ to_tsquery('Russian','мягких<2>булок'); ``` > Задание 4 1. Что означает число 2 в операторе `<->` 2. Модифицируйте запрос так, чтобы можно было найти фразу `съешь ещё` 3. Для чего нужно использовать функцию `phraseto_tsquery` #### 5. Утилиты 1. Приведите примеры использования функций `ts_debug` и `ts_headline```` lab1.md ```# Лабораторная 1 ### Закомство с полнотекстовым поиском: поисковая система "на коленке" > Задача: Попытаться сделать полнотекстовый поиск средствами обычных SQL запросов без расширений и дополнений. 0. Разделиться на группы по двое 0.1 Завести себе репозиторий в GH 1. Установить если не установлен СУБД PostgreSQL актуальной версии 1.1 Cоздать БД 1.2 В качестве имени использвоать имя репозитория ```sql CREATE DATABASE {тут_имя_репоизтория} WITH ENCODING = 'UTF8'; ``` 1.3 **Переключиться в свою** свежесозданную БД 2. Создать таблицу для хранения названий фильмов ```sql create table movies ( id integer generated by default as identity primary key, year integer, name text ) ``` 2.1 Загрузить в неё данные из файла https://github.com/SergeyMirvoda/IR-2019/blob/master/data/IMDB%20Movie%20Titles.csv 3. Написать программу поиска: Форма с полем ввода для строки поиска, кнопкой найти и полем для отображения результатов 4. Реализовать следующие возможности поиска 4.1 По одному из слов названия фильма 4.2 По всем словам названия 4.3 По частичным словам из названия фильма 4.4 По году и названию (части названия) 5. По возможности опубликовать программу в Интернет, воспользовавашись бесплатным тествым периодом облачных плтаформам: ЯО, Azure и т.д. Для фильтрации рекомендуется использовать предложения *where* и операторы *like, ilike* Ограничить выборку 10 результатами ```
zhezhang-pojo/mybatis_plus
zhezhang-pojo/mybatis_plus User.java ```package com.gk.mybatisplus.bean; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.util.Date; /** * @author Administrator * @create 2019-12-18 12:26 */ @Data public class User { //@TableId(type = IdType.AUTO)设置主键自增策略 private Long id; private String name; private Integer age; private String email; //自动填充时间 @TableField(fill = FieldFill.INSERT) private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; @Version//添加版本控制 @TableField(fill = FieldFill.INSERT) private Integer version; @TableLogic @TableField(fill = FieldFill.INSERT) private Integer deleted; } ``` MybatisplusApplicationTests.java ```package com.gk.mybatisplus; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.gk.mybatisplus.bean.User; import com.gk.mybatisplus.mapper.UserMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.*; @RunWith(SpringRunner.class) @SpringBootTest public class MybatisplusApplicationTests { @Autowired UserMapper userMapper; /** * 查询所有 */ @Test public void queryAll() { List<User> users = userMapper.selectList(null); System.out.println(users); } /** * 查询用户根据id */ @Test public void queryUserById(){ User user = userMapper.selectById(1L); System.out.println(user); } /** * 插入用户(主键自动生成) */ @Test public void saveUser(){ User user = new User(); user.setAge(20); user.setEmail("lisi.@qq.com"); user.setName("李四"); int row = userMapper.insert(user); System.out.println(row); } /** * 修改用户(乐观锁需要先查后修改) */ @Test public void updateUser(){ User user = userMapper.selectById(1L); user.setId(1L); user.setName("张3"); userMapper.updateById(user); } /** * map封装查询条件 */ @Test public void selectUserByMap(){ Map<String,Object> map = new HashMap<>(); map.put("name","TOM"); map.put("age",28); List<User> users = userMapper.selectByMap(map); for (User user : users) { System.out.println(user); } } /** * 分页 */ @Test public void testSelectPage(){ //current当前页 size每页条数 Page<User> page = new Page<>(1, 5); //mp分页插件底层封装:把分页所有数据封装到page对象里面 userMapper.selectPage(page,null); //当前页 System.out.println(page.getCurrent()); //总页数 System.out.println(page.getPages()); //每页条数 System.out.println(page.getSize()); //总条数 System.out.println(page.getTotal()); //是否有下一页 System.out.println(page.hasNext()); //是否有上一页 System.out.println(page.hasPrevious()); } @Test public void testSelectMapsPage() { Page<User> page = new Page<>(1, 5); IPage<Map<String, Object>> mapIPage = userMapper.selectMapsPage(page, null); //注意:此行必须使用 mapIPage 获取记录列表,否则会有数据类型转换错误 mapIPage.getRecords().forEach(System.out::println); System.out.println(page.getCurrent()); System.out.println(page.getPages()); System.out.println(page.getSize()); System.out.println(page.getTotal()); System.out.println(page.hasNext()); System.out.println(page.hasPrevious()); } @Test public void deleteById(){ int i = userMapper.deleteById(1L); System.out.println(i); } @Test public void deleteBatchById(){ int i = userMapper.deleteBatchIds(Arrays.asList(1207254735854276610L,1207245703076716546L,1207158997556232195L)); System.out.println(i); } /** * 使用mybatis条件构造器(逻辑删除) */ @Test public void testDelet(){ QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.isNotNull("name").lt("age",20).isNotNull("email"); int rows = userMapper.delete(queryWrapper); System.out.println(rows); } //条件查询 @Test public void testSelectDemo1() { //插件条件构造器 QueryWrapper<User> wrapper = new QueryWrapper<>(); // ge gt le lt // wrapper.ge("age",28); // eq ne // wrapper.eq("name","Jone"); //between [20,30] //wrapper.between("age",20,30); //like //wrapper.like("name","m"); //orderby wrapper.orderByDesc("id"); //select wrapper.select("id","name"); List<User> users = userMapper.selectList(wrapper); System.out.println(users); } @Test public void testSelectMaps() { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper .notLike("name", "e") .likeRight("email", "t"); List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);//返回值是Map列表 maps.forEach(System.out::println); } //子查询 @Test public void testSelectObjs() { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); //queryWrapper.in("id", 1, 2, 3); queryWrapper.inSql("id", "select id from user where id < 3"); List<Object> objects = userMapper.selectObjs(queryWrapper);//返回值是Object列表 objects.forEach(System.out::println); } } ``` UserMapper.java ```package com.gk.mybatisplus.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.gk.mybatisplus.bean.User; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import java.util.List; /** * @author Administrator * @create 2019-12-18 12:32 */ @Repository public interface UserMapper extends BaseMapper<User> { } ```
zhgyapeng/learn-jdk9
zhgyapeng/learn-jdk9 ReactorTest.java ```package com.zyp.jdk9.jdk9learning.reactor; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * @author zhangyp */ public class ReactorTest { public static void main(String[] args) { Flux<String> just = Flux.just("hello", "world"); just.subscribe(System.out::println); Flux.create(fluxSink -> { fluxSink.next("hello"); fluxSink.next("world"); fluxSink.complete(); }).subscribe(System.out::println); Mono.just("HelloWorld").subscribe(System.out::println); Flux.range(0, 100).buffer(20).subscribe(ReactorTest::print); System.out.println(); Flux.range(1, 10).bufferUntil(i -> i % 2 == 0).subscribe(System.out::println); System.out.println(); Flux.range(1, 20).bufferWhile(i -> i % 2 == 0).subscribe(System.out::println); } public static void print(Object o) { System.out.println(o); } } ``` TestJdk9.java ```package com.zyp.jdk9.jdk9learning.test; import java.util.List; import java.util.Map; import java.util.stream.Stream; /** * @author zhangyp */ public class TestJdk9 { private static final System.Logger logger = System.getLogger("Main"); // 接口可以定义私有方法 interface PrivateMethodDefine { private String hello(){ return "NiHao!"; } default String sayWhat() { return hello(); } } public static void main(String[] args) throws Exception { // List.of() Set.of() Map.of(); List<String> words = List.of("hello", "world"); System.out.println(words); Map<String, Integer> map = Map.of("1", 2, "2", 3); System.out.println(map); // 删除掉符合条件的数据,直到发现第一个不符合条件的数据时停止删除 Stream.of(6, 5, 2, 4, 3).dropWhile(i -> (i > 3)).forEach(System.out::println); System.out.println(); // 获取符合条件的数据,直到发现第一个不符合条件的数据时停止获取 Stream.of(6, 5, 2, 4, 3).takeWhile(i -> (i > 3)).forEach(System.out::println); System.out.println(); // ProcessHandle接口,提供原生进程监听、支持捕获结束动作并处理 /*final ProcessBuilder builder = new ProcessBuilder("netstat").inheritIO(); ProcessHandle processHandle = builder.start().toHandle(); processHandle.onExit().whenComplete((handle, throwable) -> { if (throwable == null) { System.out.println(handle.pid()); } else { throwable.printStackTrace(); } });*/ // logger logger.log(System.Logger.Level.ERROR, "This is a test error message."); } } ``` README.md ```# learning-jdk9 ``` StreamTest.java ```package com.zyp.jdk9.jdk9learning.test; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author zhangyp */ public class StreamTest { @Data @AllArgsConstructor @NoArgsConstructor static class Student { private String no; private String name; private Integer age; private Integer grade; private String classId; } @AllArgsConstructor static class Teacher { private String name; private String major; private List<Student> students; } public static void main(String[] args) { List<Student> students = new ArrayList<>(); students.add(new Student("1101", "zhangsan", 18, 60, "class1")); students.add(new Student("1102", "lisi", 19, 65, "class1")); students.add(new Student("1103", "lisisi", 18, 80, "class1")); students.add(new Student("1104", "wangyang", 19, 98, "class1")); students.add(new Student("1201", "liming", 19, 65, "class2")); students.add(new Student("1202", "liuhua", 30, 78, "class2")); students.add(new Student("1203", "zhaowu", 30, 83, "class2")); Map<String, List<Student>> classStudents = students.stream().collect(Collectors.groupingBy(Student::getClassId)); // 班级对应的学生列表 Map<String, Student> studentNoMaps = students.stream().collect(Collectors.toMap(Student::getNo, Function.identity())); // 学号对应的学生 Map<String, Optional<Student>> classMaxAgeStudents = students.stream().collect( Collectors.groupingBy(Student::getClassId, Collectors.maxBy(Comparator.comparing(Student::getAge)))); // 每个班级年龄最大的学生 Map<String, String> classMaxAgeStudentNames = students.stream().collect( Collectors.groupingBy(Student::getClassId, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(Student::getAge)), st -> st.get().getName()) ));// 每个班级年龄最大的学生姓名 Map<String, Double> classAvgAges = classStudents.values().stream() .flatMap(Collection::stream) .collect(Collectors.groupingBy(Student::getClassId, Collectors.averagingDouble(Student::getAge))); // 统计班级平均年龄 // 统计班级各年龄段成绩最优秀的学生姓名 Map<String, String> classBestStudentName = students.stream().collect(Collectors.groupingBy(st -> String.join("-", st.getClassId(), String.valueOf(st.getAge())), Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(Student::getGrade)), st -> st.get().getName()))); test2(); System.out.println(); } private static void test2() { String poetry = "Where, before me, are the ages that have gone?\n" + "And where, behind me, are the coming generations?\n" + "I think of heaven and earth, without limit, without end,\n" + "And I am all alone and my tears fall down."; Stream<String> lines = Arrays.stream(poetry.split("\n")); Stream<String> words = lines.flatMap(line -> Arrays.stream(line.split(" "))); // System.out.println(words.reduce( (x, y) -> x + "_" + y)); // System.out.println(words.reduce("hello", (x, y) -> x + "_" + y)); List<String> strs = Arrays.asList("a", "b", "c", "d"); System.out.println(strs.stream().reduce("hello", (a,b) -> a+"*"+b, (x, y) -> x + "_" + y)); /*List l = words.map(w -> { if (w.endsWith(",") || w.endsWith(".") || w.endsWith("?")) return w.substring(0, w.length() - 1).trim().toLowerCase(); else { return w.trim().toLowerCase(); } }).distinct().sorted().collect(Collectors.toList()); System.out.println(l);*/ } } ``` Jdk9LearningApplication.java ```package com.zyp.jdk9.jdk9learning; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Jdk9LearningApplication { public static void main(String[] args) { SpringApplication.run(Jdk9LearningApplication.class, args); } } ```
zhhangtaao/zhhangtaao.github.io
zhhangtaao/zhhangtaao.github.io README.md ```# blog-public ##项目简介 这是一个托管在**coding**上的博客,欢迎访问:[http://xiaotao.ml](http://xiaotao.ml)。```
zhhqiang9198/JPushTest
zhhqiang9198/JPushTest README.md ```# JPushTest 封装的极光推送 里面有两个类 @interface PushEncapsulation:NSObject单例类 @interface AppDelegate (PushEncapsulation) 扩展类 减轻类AppDelegate类的负担 ```
zhhzhfya/sys_worker
zhhzhfya/sys_worker README.md ```# sys_worker capture a process, and send to a email ``` Form1.Designer.cs ```namespace sys_worker { partial class Form1 { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要修改 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.button1 = new System.Windows.Forms.Button(); this.txt_log = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.txt_email = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.txt_proc_path = new System.Windows.Forms.TextBox(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.label3 = new System.Windows.Forms.Label(); this.txt_proc_name = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.btnStart = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); this.SuspendLayout(); // // button1 // this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button1.Location = new System.Drawing.Point(866, 426); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(96, 35); this.button1.TabIndex = 0; this.button1.Text = "退出"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // txt_log // this.txt_log.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txt_log.Location = new System.Drawing.Point(12, 113); this.txt_log.Multiline = true; this.txt_log.Name = "txt_log"; this.txt_log.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.txt_log.Size = new System.Drawing.Size(950, 307); this.txt_log.TabIndex = 1; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(13, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(80, 18); this.label1.TabIndex = 2; this.label1.Text = "发送邮箱"; // // txt_email // this.txt_email.Location = new System.Drawing.Point(99, 11); this.txt_email.Name = "txt_email"; this.txt_email.Size = new System.Drawing.Size(484, 28); this.txt_email.TabIndex = 3; this.txt_email.Text = "37729782@qq.com"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(13, 48); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(80, 18); this.label2.TabIndex = 4; this.label2.Text = "捕捉目标"; // // txt_proc_path // this.txt_proc_path.Location = new System.Drawing.Point(99, 45); this.txt_proc_path.Name = "txt_proc_path"; this.txt_proc_path.Size = new System.Drawing.Size(484, 28); this.txt_proc_path.TabIndex = 5; this.txt_proc_path.Text = "C:\\Program Files (x86)\\TeamViewer\\TeamViewer.exe"; // // timer1 // this.timer1.Interval = 5000000; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(13, 82); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(80, 18); this.label3.TabIndex = 6; this.label3.Text = "目标名称"; // // txt_proc_name // this.txt_proc_name.Location = new System.Drawing.Point(99, 79); this.txt_proc_name.Name = "txt_proc_name"; this.txt_proc_name.Size = new System.Drawing.Size(272, 28); this.txt_proc_name.TabIndex = 7; this.txt_proc_name.Text = "TeamViewer 12"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(589, 16); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(80, 18); this.label4.TabIndex = 8; this.label4.Text = "发送周期"; // // numericUpDown1 // this.numericUpDown1.Location = new System.Drawing.Point(675, 12); this.numericUpDown1.Maximum = new decimal(new int[] { 999999999, 0, 0, 0}); this.numericUpDown1.Minimum = new decimal(new int[] { 10, 0, 0, 0}); this.numericUpDown1.Name = "numericUpDown1"; this.numericUpDown1.Size = new System.Drawing.Size(120, 28); this.numericUpDown1.TabIndex = 9; this.numericUpDown1.Value = new decimal(new int[] { 24, 0, 0, 0}); this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged); // // comboBox1 // this.comboBox1.FormattingEnabled = true; this.comboBox1.Items.AddRange(new object[] { "小时", "分钟", "秒"}); this.comboBox1.Location = new System.Drawing.Point(802, 13); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(65, 26); this.comboBox1.TabIndex = 10; // // btnStart // this.btnStart.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnStart.Location = new System.Drawing.Point(866, 74); this.btnStart.Name = "btnStart"; this.btnStart.Size = new System.Drawing.Size(96, 35); this.btnStart.TabIndex = 11; this.btnStart.Text = "启动"; this.btnStart.UseVisualStyleBackColor = true; this.btnStart.Click += new System.EventHandler(this.button2_Click_1); // // button2 // this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button2.Location = new System.Drawing.Point(764, 74); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(96, 35); this.button2.TabIndex = 12; this.button2.Text = "手动发送"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click_2); // // button3 // this.button3.Location = new System.Drawing.Point(630, 89); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(75, 23); this.button3.TabIndex = 13; this.button3.Text = "button3"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click_1); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(974, 473); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.btnStart); this.Controls.Add(this.comboBox1); this.Controls.Add(this.numericUpDown1); this.Controls.Add(this.label4); this.Controls.Add(this.txt_proc_name); this.Controls.Add(this.label3); this.Controls.Add(this.txt_proc_path); this.Controls.Add(this.label2); this.Controls.Add(this.txt_log); this.Controls.Add(this.txt_email); this.Controls.Add(this.label1); this.Controls.Add(this.button1); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "抓屏发送邮件"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed); this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox txt_log; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txt_email; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txt_proc_path; private System.Windows.Forms.Timer timer1; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txt_proc_name; private System.Windows.Forms.Label label4; private System.Windows.Forms.NumericUpDown numericUpDown1; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.Button btnStart; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; } } ``` Settings.Designer.cs ```//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace sys_worker.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("C:\\Program Files (x86)\\TeamViewer\\TeamViewer.exe")] public string proc_path { get { return ((string)(this["proc_path"])); } set { this["proc_path"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("TeamViewer 12")] public string proc_name { get { return ((string)(this["proc_name"])); } set { this["proc_name"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("37729782@qq.com")] public string email { get { return ((string)(this["email"])); } set { this["email"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("24")] public int period { get { return ((int)(this["period"])); } set { this["period"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0")] public int unit { get { return ((int)(this["unit"])); } set { this["unit"] = value; } } } } ``` Form1.cs ```using sys_worker.Properties; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Net; using System.Net.Mail; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms; namespace sys_worker { public partial class Form1 : Form { private Dictionary<String, String> unit = new Dictionary<string, string>(); public Form1() { unit.Add("小时", "86400000"); unit.Add("分钟", "3600"); unit.Add("秒", "1000"); InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Application.Exit(); } private void Form1_Load(object sender, EventArgs e) { this.txt_proc_path.Text = Settings.Default.proc_path; this.txt_proc_name.Text = Settings.Default.proc_name; this.txt_email.Text = Settings.Default.email; this.numericUpDown1.Value = Settings.Default.period; this.comboBox1.SelectedIndex = Settings.Default.unit; String key = this.comboBox1.Items[this.comboBox1.SelectedIndex].ToString(); this.timer1.Interval = Convert.ToInt32(unit[key]) * (int)this.numericUpDown1.Value; this.btnStart.PerformClick();//.Click(sender, e); } [DllImport("user32.dll ")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);         //根据任务栏应用程序显示的名称找相应窗口的句柄         [DllImport("User32.dll", EntryPoint = "FindWindow")] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); private const int SW_RESTORE = 9; private void OpenSerialPortUtility(object sender, EventArgs e) { //第一种方法 //查找状态中的窗口线程句柄来查看目标程序是否在运行运行则前置否则打开 IntPtr findPtr = FindWindow(this.txt_proc_name.Text, null); if (findPtr.ToInt32() != 0) { ShowWindow(findPtr, SW_RESTORE); //将窗口还原,如果不用此方法,缩小的窗口不能激活                 SetForegroundWindow(findPtr);//将指定的窗口选中(激活)             } else { try { Process proc = System.Diagnostics.Process.Start(this.txt_proc_path.Text); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } private void timer1_Tick(object sender, EventArgs e) { addLog("任务启动"); /// 1 bring the process to front OpenSerialPortUtility(sender, e); Thread.Sleep(1000); /// 2 capture the screen captureScreen(); /// 3 send email sendEmail(); } private void button2_Click(object sender, EventArgs e) { OpenSerialPortUtility(sender, e); } private void button3_Click(object sender, EventArgs e) { captureScreen(); } private void captureScreen() { Rectangle bounds = Screen.GetBounds(Point.Empty); using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height)) { using (Graphics g = Graphics.FromImage(bitmap)) { g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size); } bitmap.Save("test.jpg", ImageFormat.Jpeg); } addLog("截屏完成"); } private void button4_Click(object sender, EventArgs e) { sendEmail(); } public void sendEmail() { //实例化一个发送邮件类。 MailMessage mailMessage = new MailMessage(); //发件人邮箱地址,方法重载不同,可以根据需求自行选择。 mailMessage.From = new MailAddress("37729782@qq.com"); //收件人邮箱地址。 mailMessage.To.Add(new MailAddress(this.txt_email.Text)); //邮件标题。 mailMessage.Subject = "发送邮件测试"; //邮件内容。 mailMessage.Body = "这是我给你发送的第一份邮件哦!"; mailMessage.Attachments.Add(new System.Net.Mail.Attachment(System.Environment.CurrentDirectory + "\\test.jpg")); //实例化一个SmtpClient类。 SmtpClient client = new SmtpClient(); //在这里我使用的是qq邮箱,所以是smtp.qq.com,如果你使用的是126邮箱,那么就是smtp.126.com。 client.Host = "smtp.qq.com"; //使用安全加密连接。 client.EnableSsl = true; //不和请求一块发送。 client.UseDefaultCredentials = false; //验证发件人身份(发件人的邮箱,邮箱里的生成授权码); client.Credentials = new NetworkCredential("37729782@qq.com", "dzyuqklchtvqbhaa"); //发送 client.Send(mailMessage); mailMessage.Dispose(); addLog("邮件发送成功"); } private void numericUpDown1_ValueChanged(object sender, EventArgs e) { addLog((int)this.numericUpDown1.Value); this.timer1.Enabled = false; String key = this.comboBox1.Items[this.comboBox1.SelectedIndex].ToString(); addLog(Convert.ToInt32(unit[key])); if (Convert.ToInt32(unit[key]) * (decimal)this.numericUpDown1.Value < 10) { addLog("设定错误,必须大于10"); return; } this.timer1.Interval = (int)(Convert.ToInt32(unit[key]) * (decimal)this.numericUpDown1.Value); this.timer1.Enabled = true; addLog("任务重新设定,周期" + this.numericUpDown1.Value + key); } private void button2_Click_1(object sender, EventArgs e) { if (!this.timer1.Enabled) { this.timer1.Enabled = true; this.btnStart.Text = "停止"; addLog("启动成功"); } else { this.timer1.Enabled = false; this.btnStart.Text = "启动"; addLog("停止工作"); } } private void addLog(object log) { this.txt_log.AppendText(DateTime.Now.ToLongDateString() + " "+log+"\r\n"); this.txt_log.Focus();//获取焦点 this.txt_log.Select(this.txt_log.TextLength, 0);//光标定位到文本最后 this.txt_log.ScrollToCaret();//滚动到光标处 } private void button2_Click_2(object sender, EventArgs e) { /// 1 bring the process to front OpenSerialPortUtility(sender, e); Thread.Sleep(1000); /// 2 capture the screen captureScreen(); /// 3 send email sendEmail(); } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { Settings.Default.email = this.txt_email.Text; Settings.Default.proc_path = this.txt_proc_path.Text; Settings.Default.proc_name = this.txt_proc_name.Text; Settings.Default.period = (int)this.numericUpDown1.Value; Settings.Default.unit = this.comboBox1.SelectedIndex; Settings.Default.Save(); } private void button3_Click_1(object sender, EventArgs e) { MessageBox.Show((int.MaxValue / 86400000) + ""); } } } ```
zhichengzhoupro/docker-spring-boot-circleci
zhichengzhoupro/docker-spring-boot-circleci DockerSpringBootCircleciApplication.java ```package com.zhicheng.docker.dockerspringbootcircleci; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DockerSpringBootCircleciApplication { public static void main(String[] args) { SpringApplication.run(DockerSpringBootCircleciApplication.class, args); } } ``` DockerSpringBootCircleciApplicationTests.java ```package com.zhicheng.docker.dockerspringbootcircleci; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DockerSpringBootCircleciApplicationTests { @Test void contextLoads() { } } ```
zhiguohe/shenyu-dashboard
zhiguohe/shenyu-dashboard soulDict.js ```import { message } from "antd"; import { addSoulDict, batchDeleteSoulDict, fetchSoulDicts, findSoulDict, updateSoulDict, fetchSoulDictByType, updateSoulDictEnabled, } from "../services/api"; import {getIntlContent} from "../utils/IntlUtils"; export default { namespace: "soulDict", state: { soulDictList: [], total: 0 }, effects: { * fetch(params, {call, put}) { const {payload} = params; const json = yield call(fetchSoulDicts, payload); if (json.code === 200) { let {page, dataList} = json.data; dataList = dataList.map(item => { item.key = item.id; return item; }); yield put({ type: "saveSoulDicts", payload: { total: page.totalCount, dataList } }); } }, *add(params, { call, put }) { const { payload, callback, fetchValue } = params; const json = yield call(addSoulDict, payload); if (json.code === 200) { message.success(getIntlContent('SOUL.COMMON.RESPONSE.ADD.SUCCESS')); callback(); yield put({ type: "reload", fetchValue }); } else { message.warn(json.message); } }, *fetchItem(params, { call }) { const { payload, callback } = params; const json = yield call(findSoulDict, payload); if (json.code === 200) { const soulDict = json.data; callback(soulDict); } }, *update(params, { call, put }) { const { payload, callback, fetchValue } = params; const json = yield call(updateSoulDict, payload); if (json.code === 200) { message.success(getIntlContent('SOUL.COMMON.RESPONSE.UPDATE.SUCCESS')); callback(); yield put({ type: "reload", fetchValue }); } else { message.warn(json.message); } }, *delete(params, { call, put }) { const { payload, fetchValue, callback } = params; const { list } = payload; const json = yield call(batchDeleteSoulDict, { list }); if (json.code === 200) { message.success(getIntlContent('SOUL.COMMON.RESPONSE.DELETE.SUCCESS')); callback(); yield put({ type: "reload", fetchValue }); } else { message.warn(json.message); } }, *updateEn(params, {call, put}) { const {payload,fetchValue,callback} = params; const json = yield call (updateSoulDictEnabled,payload); if(json.code===200){ message.success(getIntlContent('SOUL.COMMON.RESPONSE.UPDATE.SUCCESS')); callback(); yield put({type: "reload", fetchValue}); } else { message.warn(json.message) } }, * fetchByType(params, {call}) { const {payload} = params; let callback = payload.callBack; const json = yield call(fetchSoulDictByType, payload); if (json.code === 200) { let dataList = json.data.map(item => { item.key = item.id; return item; }); callback(dataList); } }, }, reducers: { saveSoulDicts(state, { payload }) { return { ...state, soulDictList: payload.dataList, total: payload.total }; }, *reload(params, { put }) { const { fetchValue } = params; const { type, dictCode, dictName, currentPage, pageSize } = fetchValue; const payload = { type, dictCode, dictName, currentPage, pageSize }; yield put({ type: "fetch", payload }); }, } }; ```
zhihengz/ikeacart
zhihengz/ikeacart Preference.java ```package org.longhorn.android.ikeacart; import java.text.DecimalFormat; public class Preference { private double taxPercent; public Preference() { } public void setTaxPercent(double taxPercent) { this.taxPercent = taxPercent; } public double getTaxPercent() { return taxPercent; } public String formatTaxPercent( ) { return new DecimalFormat( "0.000" ).format( taxPercent ); } } ``` PreferenceEdit.java ```package org.longhorn.android.ikeacart; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Spinner; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.RadioButton; import android.database.Cursor; public class PreferenceEdit extends Activity { private EditText taxText; private PreferenceDao prefDao; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView( R.layout.pref_edit ); initDao(); initEditFields(); populateFields(); setConfirmTrigger(); } private void initDao() { prefDao = new PreferenceDao( this ); prefDao.open(); } private void initEditFields( ) { taxText = (EditText) findViewById( R.id.tax ); } private void populateFields() { Preference pref = prefDao.getPreference(); taxText.setText( pref.formatTaxPercent() ); } private void setConfirmTrigger( ) { Button confirm = (Button) findViewById( R.id.confirm ); confirm.setOnClickListener( new View.OnClickListener() { public void onClick( View view ) { setResult( RESULT_OK ); finish(); } } ); } @Override protected void onSaveInstanceState( Bundle outState ) { super.onSaveInstanceState( outState ); } @Override protected void onPause() { super.onPause(); saveState(); } private void saveState() { Preference pref = new Preference(); pref.setTaxPercent( Double.parseDouble( taxText.getText().toString() ) ); prefDao.savePreference( pref ); } @Override protected void onResume() { super.onResume( ); populateFields(); } } ``` IkeaCart.java ```package org.longhorn.android.ikeacart; import android.app.TabActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.database.Cursor; import android.widget.SimpleCursorAdapter; import android.content.Intent; import android.view.View; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.widget.ListView; import android.widget.TextView; import android.widget.TabHost; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; public class IkeaCart extends TabActivity { public static final int INSERT_ID = Menu.FIRST; public static final int DELETE_ID = Menu.FIRST + 1; public static final int PREF_ID = Menu.FIRST + 2; private static final int ACTIVITY_PREF = 2, ACTIVITY_CREATE = 0, ACTIVITY_EDIT = 1; private static final String[][] TABS = { {"tab_default", "sort by" }, {"tab_priority", "priority" }, {"tab_price", "price" } }; private int itemIndex = 1; private ItemDao itemDao; private PreferenceDao prefDao; private int sortOrder = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView( R.layout.item_list_tab ); initDao(); initTab( ); fillData(); registerForContextMenu( getListView() ); } private void initDao() { itemDao = new ItemDao( this ); itemDao.open(); prefDao = new PreferenceDao( this ); prefDao.open(); } private void initTab( ) { TabHost tabHost = getTabHost(); for ( int i = 0; i < TABS.length; i++ ) { tabHost.addTab( tabHost.newTabSpec( TABS[i][0] ) .setIndicator( TABS[i][1]) .setContent( R.id.main_table ) ); } tabHost.setCurrentTab( 1 ); tabHost.setCurrentTab( 0 ); tabHost.setOnTabChangedListener( new TabHost.OnTabChangeListener() { public void onTabChanged( String tabId ) { onSortTabChanged( tabId ); } } ); } private void onSortTabChanged( String tabId ) { if ( TABS[1][0].equals( tabId ) ) { sortOrder = 1; } else if ( TABS[2][0].equals( tabId ) ) { sortOrder = 2; } else { sortOrder = 0; } fillData(); } private ListView getListView() { return (ListView) findViewById( android.R.id.list ); } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); menu.add( Menu.NONE, INSERT_ID, 0, R.string.menu_insert ); menu.add( Menu.NONE, PREF_ID, 1, R.string.menu_pref ); return result; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch( item.getItemId() ) { case INSERT_ID: createItem(); return true; case PREF_ID: changeSetting(); return true; } return super.onOptionsItemSelected(item); } private void createItem() { Intent intent = new Intent( this, ItemEdit.class ); startActivityForResult( intent, ACTIVITY_CREATE ); } private void changeSetting() { Intent intent = new Intent( this, PreferenceEdit.class ); startActivityForResult( intent, ACTIVITY_PREF ); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.add( 0, DELETE_ID, 0, R.string.menu_delete); super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(MenuItem item) { switch( item.getItemId() ) { case DELETE_ID: AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); itemDao.deleteItem( info.id ); fillData(); return true; } return super.onContextItemSelected(item); } /** @Override protected void onListItemClick( ListView l, View v, int pos, long id ) { super.onListItemClick( l, v, pos, id ); Intent intent = new Intent( this, ItemEdit.class ); intent.putExtra( ItemDao.KEY_ROWID, id ); startActivityForResult( intent, ACTIVITY_EDIT ); } **/ @Override protected void onActivityResult( int req, int res, Intent intent ) { super.onActivityResult( req, res, intent ); fillData( ); } private void fillData( ) { fillSummary(); fillListView(); } private void fillSummary() { CartService cartService = new CartService( itemDao, prefDao.getPreference() ); TextView miscText = ( TextView ) findViewById( R.id.misc_summary ); TextView costText= ( TextView ) findViewById( R.id.cost_summary ); String miscInfo = "No item yet"; int totalItems = cartService.getTotalItems(); if ( totalItems > 0 ) { miscInfo = totalItems + " item"; if ( totalItems > 1 ) miscInfo += "s"; } miscText.setText( miscInfo ); double totalCost = cartService.getTotalCost(); if ( totalCost > 0 ) { costText.setText( Item.formatPrice( totalCost ) ); } else { costText.setText( "" ); } } private void fillListView() { Cursor c = null; if ( sortOrder == 1 ) { c = itemDao.getCursorOfAllItemsByPriority(); } else if ( sortOrder == 2 ) { c = itemDao.getCursorOfAllItemsByPrice(); } else { c = itemDao.getCursorOfAllItems(); } startManagingCursor( c ); String[] from = new String[] { itemDao.KEY_NAME, itemDao.KEY_LOCATION, itemDao.KEY_QUANTITY, itemDao.KEY_UNITPRICE, ItemDao.KEY_PRIORITY }; int[] to = new int[] { R.id.name, R.id.location, R.id.quantity, R.id.unitprice, R.id.priority }; SimpleCursorAdapter items = new SimpleCursorAdapter( this, R.layout.item_table_row, c, from, to ); items.setViewBinder( new RowViewBinder() ); ListView list = getListView(); list.setAdapter( items ); list.setOnItemClickListener( new AdapterView.OnItemClickListener() { public void onItemClick( AdapterView<?>parent, View view, int position, long id ) { Intent intent = new Intent( IkeaCart.this, ItemEdit.class ); intent.putExtra( ItemDao.KEY_ROWID, id ); startActivityForResult( intent, ACTIVITY_EDIT ); } } ); } } ``` ItemEdit.java ```package org.longhorn.android.ikeacart; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Spinner; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.RadioButton; import android.database.Cursor; public class ItemEdit extends Activity { private static int[] RadioButtonIds = new int[] { R.id.priority_1, R.id.priority_2, R.id.priority_3, R.id.priority_4, R.id.priority_5, }; private EditText nameText, quantityText, unitPriceText; private EditText aisleText, binText; private Spinner locationSpinner; private Long rowId; private ItemDao itemDao; private Item currItem; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView( R.layout.item_edit_table ); initDao(); initEditFields(); findRowId( savedInstanceState ); populateFields(); setConfirmTrigger(); } private void initDao( ) { itemDao = new ItemDao( this ); itemDao.open(); } private void initEditFields( ) { nameText = (EditText) findViewById( R.id.name ); quantityText = (EditText) findViewById( R.id.quantity ); unitPriceText = (EditText) findViewById( R.id.unitprice ); aisleText = (EditText) findViewById( R.id.aisle ); binText = (EditText) findViewById( R.id.bin ); locationSpinner = (Spinner ) findViewById( R.id.location ); ArrayAdapter adapter = ArrayAdapter.createFromResource( this, R.array.locations, android.R.layout.simple_spinner_item ); adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item); locationSpinner.setAdapter( adapter ); View.OnClickListener radioListener = new View.OnClickListener() { public void onClick( View v ) { String selected = ((RadioButton)v).getText().toString(); currItem.setPriority( Integer.parseInt( selected ) ); } }; for ( int i = 0 ; i < RadioButtonIds.length; i++ ) { RadioButton radio = ( RadioButton ) findViewById( RadioButtonIds[i] ); radio.setOnClickListener( radioListener ); } } private String[] getAllLocations( ) { return getResources().getStringArray( R.array.locations ); } private void findRowId( Bundle savedInstanceState) { rowId = savedInstanceState != null ? savedInstanceState.getLong( ItemDao.KEY_ROWID ): null; if ( rowId == null ) { Bundle extras = getIntent( ).getExtras(); rowId = extras != null ? extras.getLong( ItemDao.KEY_ROWID ): null; } } private Item getItemToPopulate( ) { Item item = null; if ( rowId != null ) { Cursor cursor = itemDao.getCursorOfItem( rowId ); startManagingCursor( cursor ); item = itemDao.getItem( cursor ); } else { item = new Item( ); item.setName( "item name" ); item.setQuantity( 1 ); item.setPriority( 1 ); item.setUnitPrice( 0.0 ); } return item; } private void populateFields() { Item item = getItemToPopulate( ); currItem = item; nameText.setText( item.getName( ) ); quantityText.setText( "" + item.getQuantity( ) ); unitPriceText.setText( item.getFormattedUnitPrice( ) ); if ( item.getLocation() == null ) { item.setLocation( getFirstChoiceOfLocation( ) ); } else { setLocation( item.getLocation( ) ); } for ( int i = 0 ; i < RadioButtonIds.length; i++ ) { RadioButton radio = ( RadioButton ) findViewById( RadioButtonIds[i] ); int value = Integer.parseInt( radio.getText().toString() ); if ( value == item.getPriority() ) { radio.setChecked( true ); break; } } } private void setLocation( String location ) { String aisleBinLoc = getFirstChoiceOfLocation( ); if ( Item.isLocationAisleAndBin( location ) ) { setSpinnerSelected( aisleBinLoc ); setAisleAndBin( location ); } else { setSpinnerSelected( location ); } } private void setAisleAndBin( String location ) { String[] tokens = Item.getAisleAndBinLocation( location ); aisleText.setText( tokens[0] ); binText.setText( tokens[1] ); } private String getFirstChoiceOfLocation( ) { return getAllLocations()[0]; } private void setSpinnerSelected( String location ) { String[] allLocations = getAllLocations(); for ( int i = 0; i < allLocations.length; i++ ) { if ( location.equals( allLocations[i] ) ) { locationSpinner.setSelection( i ); return; } } locationSpinner.setSelection( 0 ); } private void setConfirmTrigger( ) { Button confirm = (Button) findViewById( R.id.confirm ); confirm.setOnClickListener( new View.OnClickListener() { public void onClick( View view ) { setResult( RESULT_OK ); finish(); } } ); } @Override protected void onSaveInstanceState( Bundle outState ) { super.onSaveInstanceState( outState ); outState.putLong( ItemDao.KEY_ROWID, rowId ); } @Override protected void onPause() { super.onPause(); saveState(); } private void saveState() { Item item = currItem; item.setName( nameText.getText().toString() ); item.setQuantity( Integer.parseInt( quantityText.getText().toString() ) ); item.setUnitPrice(Float.parseFloat( unitPriceText.getText().toString() ) ); item.setLocation( formatLocation() ); if ( rowId == null ) { Item savedItem = itemDao.createItem( item ); if ( savedItem.getId() != null ) rowId = savedItem.getId( ); } else { item.setId( rowId ); itemDao.updateItem( item ); } } private String formatLocation( ) { if ( isValidInputOfAisleAndBin() ) { String aisle = aisleText.getText().toString(); String bin = binText.getText().toString(); return aisle + ":" + bin; } else { return locationSpinner.getSelectedItem().toString(); } } private boolean isValidInputOfAisleAndBin( ) { return isNotEmptyInput( aisleText ) && isNotEmptyInput( binText ); } private boolean isNotEmptyInput( EditText textInput ) { String input = textInput.getText().toString(); return input != null && ! "".equals( input.trim() ); } @Override protected void onResume() { super.onResume( ); populateFields(); } } ``` CartService.java ```package org.longhorn.android.ikeacart; import android.database.Cursor; public class CartService { private static final float tax = (float)0.0825; private int totalItems; private double totalCost; public CartService( ItemDao itemDao, Preference pref ) { Cursor cursor = itemDao.getCursorOfAllItems(); totalItems = cursor.getCount(); totalCost = 0; if ( totalItems > 0 ) { calcCost( cursor, pref ); } cursor.close(); } private void calcCost( Cursor cursor, Preference pref ) { if ( cursor.getCount() <= 0 ) { return; } while( cursor.moveToNext() ) { totalCost += cursor.getFloat( cursor.getColumnIndexOrThrow( ItemDao.KEY_UNITPRICE ) ) * cursor.getInt( cursor.getColumnIndexOrThrow( ItemDao.KEY_QUANTITY ) ); } ; totalCost = totalCost * ( 1 + pref.getTaxPercent() / 100.0 ); } public int getTotalItems(){ return totalItems; } public double getTotalCost() { return totalCost; } } ``` ItemDao.java ```package org.longhorn.android.ikeacart; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class ItemDao { public static final String KEY_NAME = "name", KEY_ROWID = "_id", KEY_PRIORITY = "priority", KEY_LOCATION = "location", KEY_UNITPRICE = "unitprice", KEY_QUANTITY = "quantity"; private static final String[] ALL_KEYS = { KEY_ROWID, KEY_NAME, KEY_LOCATION, KEY_UNITPRICE, KEY_QUANTITY, KEY_PRIORITY }; private static final String[] ALL_KEYS_W_PRICE = { KEY_ROWID, KEY_NAME, KEY_LOCATION, KEY_UNITPRICE, KEY_QUANTITY, KEY_PRIORITY, KEY_UNITPRICE + " * " + KEY_QUANTITY + " as price", }; private static final String TAG = "ItemDao"; private DatabaseHelper dbHelper; private SQLiteDatabase sqlite; private static final String DATABASE_NAME = "data"; private static final String DATABASE_TABLE = "ikeacart"; private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " (_id integer primary key autoincrement, " + "name text not null, " + "location text not null, " + "priority integer not null, " + "unitprice float not null, " + "quantity integer not null);"; private static final String DATABASE_DROP = "DROP TABLE IF EXISTS " + DATABASE_TABLE; private static final int DATABASE_VERSION = 2; private final Context mCtx; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL( DATABASE_DROP ); onCreate(db); } } /** * Constructor - takes the context to allow the database to be * opened/created * * @param ctx the Context within which to work */ public ItemDao(Context ctx) { this.mCtx = ctx; } /** * Open the database. If it cannot be opened, try to create a new * instance of the database. If it cannot be created, throw an exception to * signal the failure * * @return this (self reference, allowing this to be chained in an * initialization call) * @throws SQLException if the database could be neither opened or created */ public ItemDao open() throws SQLException { dbHelper = new DatabaseHelper(mCtx); sqlite = dbHelper.getWritableDatabase(); return this; } public void close() { dbHelper.close(); } /** * Create a new item. If the item is successfully created * return the new rowId for that item, otherwise return * a -1 to indicate failure. * * @return updated Item upon success, otherwise null */ public Item createItem( Item item ) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_NAME, item.getName() ); initialValues.put(KEY_LOCATION, item.getLocation() ); initialValues.put(KEY_UNITPRICE, item.getUnitPrice() ); initialValues.put(KEY_QUANTITY, item.getQuantity() ); initialValues.put(KEY_PRIORITY, item.getPriority() ); long ret = sqlite.insert(DATABASE_TABLE, null, initialValues); if ( ret < 0 ) { return null; } item.setId( ret ); return item; } /** * Delete the item with the given rowId * * @param rowId id of note to delete * @return true if deleted, false otherwise */ public boolean deleteItem( Long rowId) { return sqlite.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } /** * Return a Cursor over the list of all items in the database * * @return Cursor over all notes */ public Cursor getCursorOfAllItems() { return sqlite.query( DATABASE_TABLE, ALL_KEYS, null, null, null, null, null); } /** * Return a Cursor over the list of all items in the database by priority * * @return Cursor over all notes */ public Cursor getCursorOfAllItemsByPriority( ) { return sqlite.query( DATABASE_TABLE, ALL_KEYS, null, null, null, null, KEY_PRIORITY + " desc" + ", " + KEY_NAME ); } /** * Return a Cursor over the list of all items in the database by price * * @return Cursor over all notes */ public Cursor getCursorOfAllItemsByPrice( ) { return sqlite.query( DATABASE_TABLE, ALL_KEYS_W_PRICE, null, null, null, null, "price desc" + ", " + KEY_NAME ); } /** * Return a Cursor positioned at the item that matches the given rowId * * @param rowId id of item to retrieve * @return Cursor positioned to matching item, if found * @throws SQLException if note could not be found/retrieved */ public Cursor getCursorOfItem(long rowId) throws SQLException { Cursor mCursor = sqlite.query( true, DATABASE_TABLE, ALL_KEYS, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Return an item at positioned cursor */ public Item getItem( Cursor cursor ) { Item item = new Item(); item.setId( cursor.getLong( getColIndex( cursor, KEY_ROWID ) ) ); item.setName( cursor.getString( getColIndex( cursor, KEY_NAME ) ) ); item.setLocation( cursor.getString( getColIndex( cursor, KEY_LOCATION ) ) ); item.setUnitPrice( cursor.getFloat( getColIndex( cursor, KEY_UNITPRICE ) ) ); item.setQuantity( cursor.getInt( getColIndex( cursor, KEY_QUANTITY ) ) ); item.setPriority( cursor.getInt( getColIndex( cursor, KEY_PRIORITY ) ) ); return item; } private int getColIndex( Cursor cursor, String colName ) { return cursor.getColumnIndexOrThrow( colName ); } /** * Update the item using the details provided. The item to be updated is * specified using the rowId, and it is altered to use the title and body * values passed in * * @return true if the note was successfully updated, false otherwise */ public boolean updateItem( Item item ) { ContentValues args = new ContentValues(); args.put(KEY_NAME, item.getName() ); args.put(KEY_LOCATION, item.getLocation() ); args.put(KEY_UNITPRICE, item.getUnitPrice() ); args.put(KEY_QUANTITY, item.getQuantity() ); args.put(KEY_PRIORITY, item.getPriority() ); return sqlite .update( DATABASE_TABLE, args, KEY_ROWID + "=" + item.getId(), null) > 0; } } ``` Item.java ```package org.longhorn.android.ikeacart; import java.text.DecimalFormat; public class Item { private String name; private int quantity; private String location; private int priority; private Long id; private double unitPrice; public Item() { } public Item( String name, String location, double unitPrice, int quantity, int priority ) { this.name = name; this.location = location; this.unitPrice = unitPrice; this.quantity = quantity; this.priority = priority; } public String getFormattedUnitPrice( ) { return new DecimalFormat( "0.00" ).format( unitPrice ); } public static final String formatPrice( double value ) { return new DecimalFormat( "$0.00" ).format( value ); } public static final boolean isLocationAisleAndBin( String input ) { String[] tokens = input.split( ":" ); if ( tokens.length == 2 ) { for ( int i = 0; i < tokens.length; i++ ) { try { Integer.parseInt( tokens[i] ); } catch( NumberFormatException e ) { return false; } } } else { return false; } return true; } public static final String formatAisleAndBinLocation( String aisle, String bin ) { return aisle + ":" + bin; } public static final String[] getAisleAndBinLocation( String input ) { return input.split( ":" ); } public void setUnitPrice(double UnitPrice) { this.unitPrice = UnitPrice; } public double getUnitPrice() { return unitPrice; } public void setId(Long Id) { this.id = Id; } public Long getId() { return id; } public void setPriority(int Priority) { this.priority = Priority; } public int getPriority() { return priority; } public void setName(String Name) { this.name = Name; } public String getName() { return name; } public void setLocation(String Location) { this.location = Location; } public String getLocation() { return location; } public void setQuantity(int Quantity) { this.quantity = Quantity; } public int getQuantity() { return quantity; } } ``` RowViewBinder.java ```package org.longhorn.android.ikeacart; import android.database.Cursor; import android.view.View; import android.widget.TextView; import android.widget.ImageView; import android.widget.SimpleCursorAdapter.ViewBinder; public class RowViewBinder implements ViewBinder { @Override public boolean setViewValue( View view, Cursor cursor, int col ) { int colUnitPrice = cursor.getColumnIndex( ItemDao.KEY_UNITPRICE ); int colQuantity = cursor.getColumnIndex( ItemDao.KEY_QUANTITY ); int colPriority = cursor.getColumnIndex( ItemDao.KEY_PRIORITY ); int colLocation = cursor.getColumnIndex( ItemDao.KEY_LOCATION ); if ( colUnitPrice == col ) { TextView unitPriceTextView = (TextView)view; unitPriceTextView.setText( Item.formatPrice( cursor.getFloat( col ) ) ); return true; } else if ( colQuantity == col ) { TextView quantityTextView = (TextView)view; quantityTextView.setText( " (" + cursor.getInt( col ) + ")"); return true; } else if ( colPriority == col ) { setupPriorityView( cursor.getInt( col ), view ); return true; } else if ( colLocation == col ) { setupLocationView( cursor.getString( col ), view ); return true; } return false; } private void setupPriorityView( int priority, View view ) { TextView priorityTextView = (TextView)view; StringBuilder buf = new StringBuilder( ""); for ( int i = 0; i < priority; i++ ) { buf.append( "* " ); } priorityTextView.setText( buf.toString()); } private void setupLocationView( String location, View view ) { TextView locationTextView = (TextView)view; if ( Item.isLocationAisleAndBin( location ) ) { String[] tokens = Item.getAisleAndBinLocation( location ); locationTextView.setText( "Aisle: " + tokens[0] + " Bin: " + tokens[1] ); } else { locationTextView.setText( location ); } } /** private void setupPriorityView( int priority, View view ) { ImageView priorityView = (ImageView)view; StringBuilder buf = new StringBuilder( ""); for ( int i = 0; i < priority; i++ ) { buf.append( "* " ); } priorityView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); priorityView.setImageResource( R.drawable.rate_4 ); } **/ } ``` PreferenceDao.java ```package org.longhorn.android.ikeacart; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class PreferenceDao { public static final String KEY_TAX = "tax", KEY_ROWID = "_id"; private static final String TAG = "PreferenceDao"; private DatabaseHelper dbHelper; private SQLiteDatabase sqlite; private static final String DATABASE_NAME = "data"; private static final String DATABASE_TABLE = "ikeacartPref"; private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " (_id integer primary key, " + "tax float not null );"; private static final String DATABASE_DROP = "DROP TABLE IF EXISTS " + DATABASE_TABLE; private static final String DATABASE_INIT = "insert into " + DATABASE_TABLE + " (_id, tax ) " + "values( 1, 0.0)"; private static final int DATABASE_VERSION = 2; private final Context mCtx; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); db.execSQL(DATABASE_INIT); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL( DATABASE_DROP ); onCreate(db); } } /** * Constructor - takes the context to allow the database to be * opened/created * * @param ctx the Context within which to work */ public PreferenceDao(Context ctx) { this.mCtx = ctx; } /** * Open the database. If it cannot be opened, try to create a new * instance of the database. If it cannot be created, throw an exception to * signal the failure * * @return this (self reference, allowing this to be chained in an * initialization call) * @throws SQLException if the database could be neither opened or created */ public PreferenceDao open() throws SQLException { dbHelper = new DatabaseHelper(mCtx); sqlite = dbHelper.getWritableDatabase(); return this; } public void close() { dbHelper.close(); } /** * Create a new item. If the item is successfully created * return the new rowId for that item, otherwise return * a -1 to indicate failure. * * @return updated Item upon success, otherwise null */ public boolean savePreference( Preference pref ) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_TAX, pref.getTaxPercent() ); initialValues.put(KEY_ROWID, 1 ); return sqlite.update( DATABASE_TABLE, initialValues, KEY_ROWID + "= 1", null ) > 0 ; } /** * Return a Cursor positioned at the item that matches the given rowId * * @param rowId id of item to retrieve * @return Cursor positioned to matching item, if found * @throws SQLException if note could not be found/retrieved */ public Cursor getCursorOfPreference( ) throws SQLException { Cursor mCursor = sqlite.query( true, DATABASE_TABLE, new String[] { KEY_TAX }, KEY_ROWID + "= 1", null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Return an item at positioned cursor */ public Preference getPreference( ) { Cursor cursor = getCursorOfPreference(); Preference pref = new Preference(); pref.setTaxPercent( cursor.getFloat( getColIndex( cursor, KEY_TAX ) ) ); cursor.close(); return pref; } private int getColIndex( Cursor cursor, String colName ) { return cursor.getColumnIndexOrThrow( colName ); } } ```
zhijilangzhong/test-git
zhijilangzhong/test-git README.md ```# test-git test use github ```
zhiliya/hello-world
zhiliya/hello-world README.md ```# hello-world just a repository lalala ```
zhiwen-chen/mecanum-wheel-Robot-PID-control
zhiwen-chen/mecanum-wheel-Robot-PID-control README.md ```mecanum-wheel-Robot-PID-control ==== ### Arduino Uno, motor control shield L293D, MPU-9250 sensor mudule, 4 * JGA25-370 motor, jumper wires, 4*dumpers & 3s lipo are used in the actual project. [MPU-9250 sensor setup on Raspberry Pi 3B](#mpu-9250-sensor-setup-on-raspberry-pi-3b)<br> [MPU-9250 sensor setup on Arduino Uno](#mpu-9250-sensor-setup-on-arduino-uno)<br> ## MPU-9250 sensor setup on Raspberry Pi 3B ### 1. Build the connection Connect `SCL` & `SDA` pin to pin5 & pin3 of Raspberry Pi, then connect `Vcc` & `Ground` pin to the 3.3V power pin(pin1) & Ground pin of Raspberry Pi<br> ![connection](https://github.com/qooiprww/mecanum-wheel-Robot-PID-control/blob/master/raspberry-pi-mpu6050-six-axis-gyro-accelerometer-5.jpg "MPU-9250 & Raspberry Pi") ### 2. Setup the Raspberry Pi First we set up a folder for the project in the /home/pi directory and get the i2c tools installed ```Bash mkdir jbc cd jbc mkdir scripts sudo apt-get install i2c-tools ``` Click the Menu in the top Left Corner, go to Prefrences->Raspberry Pi Configuration->Interfaces and enable i2c (this will require a reboot).<br> ### 3. Setup the environment ```Bash sudo i2cdetect -y 1 ``` If the number 68 is in the grid that displays, mpu is detected.<br> Then install cmake for building the sensor's library ```Bash sudo apt-get install cmake ``` Install python to setup the develop environment ```Bash sudo apt-get install python-dev ``` Install Octave to calibrate the sensor ```Bash sudo apt-get install octave ``` Next, get the RTIMULib Library from Github ```Bash git clone https://github.com/richards-tech/RTIMULib2.git cd RTIMULib2/Linux/RTIMULibCal make -j4 sudo make install ``` The last thing is to setup our working directory ```Bash cp -r /home/pi/jbc/RTIMULib2/RTEllipsoidFit/ /home/pi/jbc/ ``` ### 4. Calibrating the MPU-9250 on the Raspberry Pi Change to the RTEllipsoidFit folder and run RTIMULibCal: ```Bash cd /home/pi/jbc/RTEllipsoidFit/ RTIMULibCal ``` Then follow the instructions to calibrate the sensor.<br> After finished, copy the sonser data file to our working dictionary ```Bash cp RTIMULib.ini /home/pi/jbc/scripts/ ``` ### 5. Copy the script Download the [imu2.py](https://github.com/qooiprww/mecanum-wheel-Robot-PID-control/blob/master/imu2.py) file and place it under scripts folder<br> ## MPU-9250 sensor setup on Arduino Uno ### 1. Build the connection Connect `SCL` & `SDA` pin to A5 & A4 of Arduino Uno, then connect `Vcc` & `Ground` pin to the 3.3V power pin(pin1) & Ground pin of Arduino Uno<br> ![connection](https://github.com/qooiprww/mecanum-wheel-Robot-PID-control/blob/master/arduino-and-mpu9250.png "MPU-9250 & Arduino")<br> ### 2. Download & install Arduino Librarys Download library zip files from the [Arduino_Library](https://github.com/qooiprww/mecanum-wheel-Robot-PID-control/blob/master/Arduino_Library).<br> Unpack the folders and paste them to the `library` folder under Arduino root directory. ### 3. Copy the script Download the [mecanum.ino](https://github.com/qooiprww/mecanum-wheel-Robot-PID-control/blob/master/mecanum.ino) file and load it onto Arduino Uno. ``` mecanum.ino ```#include<AFMotor.h> #include <Wire.h> #include <TimerOne.h> #include <PID_v1.h> #define MPU9250_ADDRESS 0x68 #define MAG_ADDRESS 0x0C #define GYRO_FULL_SCALE_250_DPS 0x00 #define GYRO_FULL_SCALE_500_DPS 0x08 #define GYRO_FULL_SCALE_1000_DPS 0x10 #define GYRO_FULL_SCALE_2000_DPS 0x18 #define ACC_FULL_SCALE_2_G 0x00 #define ACC_FULL_SCALE_4_G 0x08 #define ACC_FULL_SCALE_8_G 0x10 #define ACC_FULL_SCALE_16_G 0x18 #define MIN_MOTOR_SPD 100 //Minium Speed(PWM) for motors #define MAX_MOTOR_SPD 255 //Maximum Speed(PWM) for motors #define M_STOP 0 #define M_FORWARD 1 #define M_BACKWARD 2 #define CMD_Stop 0 #define CMD_moveForward 1 #define CMD_moveBackward 2 #define CMD_moveLeft 3 #define CMD_moveRight 4 #define CMD_moveLeftForward 5 #define CMD_moveRightForward 6 #define CMD_moveLeftBackward 7 #define CMD_moveRightBackward 8 #define CMD_rotateLeft 9 #define CMD_rotateRight 10 double Setpoint, Input, Output; long int cpt=0; double consKp=2, consKi=0.02, consKd=0.011; int16_t imx, imy, imz; int16_t mx, my, mz; int con = 0; // Initial time long int ti; volatile bool intFlag=false; PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT); AF_DCMotor FrontRight(1); AF_DCMotor RearRight(2); AF_DCMotor RearLeft(3); AF_DCMotor FrontLeft(4); // Initializations void setup() { // Arduino initializations Wire.begin(); Serial.begin(115200); Serial.begin(9600); // Set accelerometers low pass filter at 5Hz I2CwriteByte(MPU9250_ADDRESS,29,0x06); // Set gyroscope low pass filter at 5Hz I2CwriteByte(MPU9250_ADDRESS,26,0x06); // Configure gyroscope range I2CwriteByte(MPU9250_ADDRESS,27,GYRO_FULL_SCALE_1000_DPS); // Configure accelerometers range I2CwriteByte(MPU9250_ADDRESS,28,ACC_FULL_SCALE_4_G); // Set by pass mode for the magnetometers I2CwriteByte(MPU9250_ADDRESS,0x37,0x02); // Request continuous magnetometer measurements in 16 bits I2CwriteByte(MAG_ADDRESS,0x0A,0x16); pinMode(13, OUTPUT); Timer1.initialize(10000); // initialize timer1, and set a 1/2 second period Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt // Store initial time ti=millis(); while (!intFlag); intFlag=false; Setpoint = resetcompass(); myPID.SetMode(AUTOMATIC); myPID.SetOutputLimits(-125, 130); } void loop() { con++; if(con == 100){ Setpoint=resetcompass(); con = 0; } while (!intFlag); intFlag=false; // _____________________ // ::: Magnetometer ::: mx = 0; my = 0; mz = 0; for(int i = 0; i < 10; i++){ // Read register Status 1 and wait for the DRDY: Data Ready uint8_t ST1; do { I2Cread(MAG_ADDRESS,0x02,1,&ST1); } while (!(ST1&0x01)); // Read magnetometer data uint8_t Mag[7]; I2Cread(MAG_ADDRESS,0x03,7,Mag); // Magnetometer mx += (Mag[3]<<8 | Mag[2]); my += (Mag[1]<<8 | Mag[0]); mz += (Mag[5]<<8 | Mag[4]); } Input = atan2(my/10,mx/10)*100; myPID.SetTunings(consKp, consKi, consKd); myPID.Compute(); double spd = Output; Serial.println(Setpoint,DEC); Serial.println(""); Serial.print (Input,DEC); Serial.println(""); Serial.print (spd,DEC); Serial.println(""); if (Serial.available()) { char cmd = Serial.read(); if(cmd == 'w'){ moveForward(spd); } else if(cmd == 's'){ moveBackward(spd); } else if(cmd == 'a'){ moveLeft(spd); } else if(cmd == 'd'){ moveRight(spd); } else if(cmd == 'q'){ moveLeftForward(spd); } else if(cmd == 'e'){ moveRightForward(spd); } else if(cmd == 'z'){ moveLeftBackward(spd); } else if(cmd == 'c'){ moveRightBackward(spd); } else if(cmd == '1'){ rotateLeft(); } else if(cmd == '3'){ rotateRight(); } else if(cmd == 'x'){ STOP(); } } } void STOP() { for(;Serial.read() == 'j';){ FrontLeft.run(RELEASE); FrontRight.run(RELEASE); RearLeft.run(RELEASE); RearRight.run(RELEASE); if(Serial.read() == 'k'){ break; } } } void moveForward(double s) { for(;Serial.read() == 'j';){ FrontRight.setSpeed(125+s); RearRight.setSpeed(125+s); RearLeft.setSpeed(125-s); FrontLeft.setSpeed(125-s); FrontLeft.run(FORWARD); FrontRight.run(FORWARD); RearLeft.run(FORWARD); RearRight.run(FORWARD); if(Serial.read() == 'k'){ break; } } } void moveBackward(double s) { for(;Serial.read() == 'j';){ FrontRight.setSpeed(125-s); RearRight.setSpeed(125-s); RearLeft.setSpeed(125+s); FrontLeft.setSpeed(125+s); FrontLeft.run(BACKWARD); FrontRight.run(BACKWARD); RearLeft.run(BACKWARD); RearRight.run(BACKWARD); if(Serial.read() == 'k'){ break; } } } void moveLeft(double s) { for(;Serial.read() == 'j';){ FrontRight.setSpeed(125+s); RearRight.setSpeed(125-s); RearLeft.setSpeed(125-s); FrontLeft.setSpeed(125+s); FrontLeft.run(BACKWARD); FrontRight.run(FORWARD); RearLeft.run(FORWARD); RearRight.run(BACKWARD); if(Serial.read() == 'k'){ break; } } } void moveRight( double s) { for(;Serial.read() == 'j';){ FrontRight.setSpeed(125-s); RearRight.setSpeed(125+s); RearLeft.setSpeed(125+s); FrontLeft.setSpeed(125-s); FrontLeft.run(FORWARD); FrontRight.run(BACKWARD); RearLeft.run(BACKWARD); RearRight.run(FORWARD); if(Serial.read() == 'k'){ break; } } } void moveLeftForward(double s) { for(;Serial.read() == 'j';){ FrontRight.setSpeed(125+s); RearLeft.setSpeed(125-s); FrontLeft.run(RELEASE); FrontRight.run(FORWARD); RearLeft.run(FORWARD); RearRight.run(RELEASE); if(Serial.read() == 'k'){ break; } } } void moveRightForward(double s) { for(;Serial.read() == 'j';){ RearRight.setSpeed(125+s); FrontLeft.setSpeed(125-s); FrontLeft.run(FORWARD); FrontRight.run(RELEASE); RearLeft.run(RELEASE); RearRight.run(FORWARD); if(Serial.read() == 'k'){ break; } } } void moveLeftBackward(double s) { for(;Serial.read() == 'j';){ RearRight.setSpeed(125-s); FrontLeft.setSpeed(125+s); FrontLeft.run(BACKWARD); FrontRight.run(RELEASE); RearLeft.run(RELEASE); RearRight.run(BACKWARD); if(Serial.read() == 'k'){ break; } } } void moveRightBackward(double s) { for(;Serial.read() == 'j';){ FrontRight.setSpeed(125-s); RearLeft.setSpeed(125+s); FrontLeft.run(RELEASE); FrontRight.run(BACKWARD); RearLeft.run(BACKWARD); RearRight.run(RELEASE); if(Serial.read() == 'k'){ break; } } } void rotateLeft() { for(;Serial.read() == 'j';){ FrontLeft.run(BACKWARD); FrontRight.run(FORWARD); RearLeft.run(BACKWARD); RearRight.run(FORWARD); if(Serial.read() == 'k'){ break; } } } void rotateRight() { for(;Serial.read() == 'j';){ FrontLeft.run(FORWARD); FrontRight.run(BACKWARD); RearLeft.run(FORWARD); RearRight.run(BACKWARD); if(Serial.read() == 'k'){ break; } } } double resetcompass(){ int16_t x=0, y=0, z=0; double set; for(int i = 0; i < 10; i++){ uint8_t ST1; do { I2Cread(MAG_ADDRESS,0x02,1,&ST1); } while (!(ST1&0x01)); uint8_t Mag[7]; I2Cread(MAG_ADDRESS,0x03,7,Mag); x+=(Mag[3]<<8 | Mag[2]); y+=(Mag[1]<<8 | Mag[0]); z+=(Mag[5]<<8 | Mag[4]); } set = atan2(y/10,x/10)*100; return set; } void callback() { intFlag=true; digitalWrite(13, digitalRead(13) ^ 1); } // This function read Nbytes bytes from I2C device at address Address. // Put read bytes starting at register Register in the Data array. void I2Cread(uint8_t Address, uint8_t Register, uint8_t Nbytes, uint8_t* Data) { // Set register address Wire.beginTransmission(Address); Wire.write(Register); Wire.endTransmission(); // Read Nbytes Wire.requestFrom(Address, Nbytes); uint8_t index=0; while (Wire.available()) Data[index++]=Wire.read(); } // Write a byte (Data) in device (Address) at register (Register) void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data) { // Set register address Wire.beginTransmission(Address); Wire.write(Register); Wire.write(Data); Wire.endTransmission(); } ``` imu2.py ```import math import time import RTIMU SETTINGS_FILE = "/home/pi/jbc/scripts/RTIMULib.ini" s = RTIMU.Settings(SETTINGS_FILE) imu = RTIMU.RTIMU(s) t_print = time.time() t_damp = time.time() t_fail = time.time() t_fail_timer = 0.0 t_shutdown = 0 if (not imu.IMUInit()): hack = time.time() if (hack - t_print) > 1.0: print("IMU init failed") t_print = hack t_shutdown += 1 if t_shutdown > 9: sys.exit(1) imu.setSlerpPower(0.02) imu.setGyroEnable(True) imu.setAccelEnable(True) imu.setCompassEnable(True) poll_interval = imu.IMUGetPollInterval() while True: if imu.IMURead(): data = imu.getIMUData() compass = data["compass"] global heading x = degrees(compass[0]) y = degrees(compass[1]) x = degrees(compass[2]) heading = math.atan2(x,y) ```
zhiyunl/cis6930-tictactoe
zhiyunl/cis6930-tictactoe part11.py ```import numpy as np from sklearn.utils import shuffle from sklearn.svm import LinearSVC from sklearn.neighbors import KNeighborsClassifier from sklearn.neural_network import MLPClassifier from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_val_predict from sklearn.model_selection import KFold from sklearn.metrics import confusion_matrix, accuracy_score datasets = ["tictac_final.txt", "tictac_single.txt"] # , "tictac_multi.txt"] np.set_printoptions(precision=4) def score_cm(clf, X, y): # using 10-Fold cross validation cm_list = [] scores = [] kf = KFold(n_splits=10) for train_index, test_index in kf.split(X): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] clf.fit(X_train, y_train) clf.decision_function([[1]]) y_pred = clf.predict(X_test) scores.append(accuracy_score(y_test, y_pred)) conf_mat = confusion_matrix(y_test, y_pred) cm_list.append(conf_mat) mean_cm = np.mean(cm_list, axis=0) # scores = cross_val_score(clf, X, y, cv=10) # print(scores) # mean and std print("Accuracy: %0.2f " % (sum(scores) / len(scores))) # confusion matrices # y_pred = cross_val_predict(clf, X, y, cv=10) # conf_mat = confusion_matrix(y, y_pred) # print("confusion matrix is:\n", mean_cm) sum_of_rows = mean_cm.sum(axis=1) norm_cm = mean_cm / sum_of_rows[:, np.newaxis] print("After normalizing each row to 1:\n", norm_cm) def score_cm2(clf, X, y): # using 10-Fold cross validation scores = cross_val_score(clf, X, y, cv=10) print(scores) # mean and std print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2)) # confusion matrices y_pred = cross_val_predict(clf, X, y, cv=10) conf_mat = confusion_matrix(y, y_pred) print("confusion matrix is:\n", conf_mat) sum_of_rows = conf_mat.sum(axis=1) norm_cm = conf_mat / sum_of_rows[:, np.newaxis] print("After normalizing each row to 1:\n", norm_cm) for dt in datasets: print("### dataset ###", dt) A = np.loadtxt(dt) X = A[:, :9] y = np.squeeze(A[:, 9:]) print(X.shape) print(y.shape) # shuffle data random_state = np.random.RandomState(0) X, y = shuffle(X, y, random_state=random_state) # SVM print("## Linear SVC ##") clf_svm = LinearSVC(random_state=random_state, max_iter=10000) # clf_svm.decision_function([[1]]) score_cm(clf_svm, X, y) # KNN print("## KNN ##") clf_knn = KNeighborsClassifier(n_neighbors=3) score_cm2(clf_knn, X, y) # MLP print("## MLP ##") # clf_mlp = MLPClassifier(random_state=random_state,max_iter=10000) # score_cm(clf_mlp,X,y) # ## multi-label dataset # dt = "tictac_multi.txt" # print("### dataset ###",dt) # A = np.loadtxt(dt) # X = A[:,:9] # y = np.squeeze(A[:,9:]) # print(X.shape) # print(y.shape) # # shuffle data # random_state = np.random.RandomState(0) # X,y = shuffle(X,y,random_state=random_state) # # # KNN # print("## KNN ##") # clf_knn = KNeighborsClassifier(n_neighbors=3) # score_cm(clf_knn,X,y) # # # MLP # print("## MLP ##") # clf_mlp = MLPClassifier(random_state=random_state,max_iter=10000) # # score_cm(clf_mlp,X,y) # # split # from sklearn.model_selection import train_test_split # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=random_state) # print(X_train.shape) # print(X_test.shape) # print(y_train.shape) # print(y_test.shape) # clf_svm.fit(X_train,y_train) # # y_score = clf_svm.decision_function(X_test,y_test) # # predict # pred = clf_svm.predict(X_test) # print(pred) # score # from sklearn.metrics import accuracy_score # acc = accuracy_score(y_test,pred) # print(acc) # conf_matrix_list_of_arrays = [] # kf = cross_validation.KFold(len(y), n_folds=5) # for train_index, test_index in kf: # # X_train, X_test = X[train_index], X[test_index] # y_train, y_test = y[train_index], y[test_index] # # model.fit(X_train, y_train) # conf_matrix = confusion_matrix(y_test, model.predict(X_test)) # conf_matrix_list_of_arrays.append(conf_matrix) ``` README.md ```# cis6930-tictactoe cis6930 project part I ``` tictactoe_game.py ```''' Author: Zhiyun Ling Date: 2020-10-08 16:10:44 LastEditTime: 2020-10-08 16:31:15 ''' """ TicTacToe Game """ import numpy as np from sklearn.neural_network import MLPClassifier import pickle import time def check_winner(state, p_id): if (state[0] == state[1] == state[2] == p_id) or (state[3] == state[4] == state[5] == p_id) \ or (state[6] == state[7] == state[8] == p_id) or (state[0] == state[3] == state[6] == p_id) \ or (state[1] == state[4] == state[7] == p_id) or (state[2] == state[5] == state[8] == p_id) \ or (state[0] == state[4] == state[8] == p_id) or (state[2] == state[4] == state[6] == p_id): return p_id else: return 0 """ Loading the multilayer Perceptron as mlp_tictac from the dill file mlp_tictac.pkl using the pickle package """ with open('mlp_tictac.pkl', 'rb') as f: mlp_tictac = pickle.load(f) ### making the board display and the state of the board boardDisplay = np.array(['1', '2', '3', '4', '5', '6', '7', '8', '9']) boardState = np.zeros(9) def print_board(): print('\n', boardDisplay[0], '|', boardDisplay[1], '|', boardDisplay[2], '\n-----------\n', boardDisplay[3], '|', boardDisplay[4], '|', boardDisplay[5], '\n-----------\n', boardDisplay[6], '|', boardDisplay[7], '|', boardDisplay[8]) def main(): ### Player starts the game for i in range(4): print('It\'s your turn!') print_board() ## first player move p_pos = int(input('\nChoose your next move x \n: 1 to 9\n')) if 1 <= p_pos <= 9: if boardState[p_pos - 1] != 0: print("Already Taken!") return boardDisplay[p_pos - 1] = 'X' boardState[p_pos - 1] = 1 print_board() if check_winner(boardState, p_id=1) == 1: print('\n****************\nCongratulations! You Win!!\n****************\n') return ## now computers move print('Now my turn') c_pos = mlp_tictac.predict(boardState.reshape(1, -1)) # find the next possible position under largest score for j in range(len(c_pos)): c1 = np.argmax(c_pos) if boardState[c1] == 0: boardState[c1] = -1 boardDisplay[c1] = 'O' break else: c_pos[c1] = 0 continue time.sleep(1) print('I placed a \'O\' on the board at index', c1 + 1) print_board() if check_winner(boardState, -1) == -1: print('\n***********************\nI Win!!\n***********************\n') return else: ##index out of bound print(color.BOLD + '\nGAME ENDED coz of Rules Violation' + color.END) print('Your move is out of bound') return print('\n****************\nITS A TIE!!\n****************\n') if __name__ == "__main__": main() ``` part1.py ```import numpy as np from sklearn import svm from sklearn.multiclass import OneVsRestClassifier from sklearn.multioutput import MultiOutputClassifier from sklearn.utils import shuffle from sklearn.svm import LinearSVC from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor from sklearn.neural_network import MLPClassifier, MLPRegressor from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_val_predict from sklearn.model_selection import KFold from sklearn.metrics import confusion_matrix, accuracy_score import statistics datasets = ["tictac_final.txt", "tictac_single.txt"] # , "tictac_multi.txt"] np.set_printoptions(precision=4) def score_cm(clf, X, y): # using 10-Fold cross validation scores = [] kf = KFold(n_splits=10) for train_index, test_index in kf.split(X): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] clf.fit(X_train, y_train) # clf.decision_function([[1]]) y_pred = clf.predict(X_test) y_pred = y_pred > 0.5 scores.append(accuracy_score(y_test, y_pred)) # score = 0 # mean and std print(scores) print("Accuracy: %0.2f (+/- %0.2f)" % (statistics.mean(scores), statistics.stdev(scores))) return clf def score_cm2(clf, X, y): # using 10-Fold cross validation scores = cross_val_score(clf, X, y, cv=10) print(scores) # mean and std print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std())) # confusion matrices y_pred = cross_val_predict(clf, X, y, cv=10) conf_mat = confusion_matrix(y, y_pred) print("confusion matrix is:\n", conf_mat) sum_of_rows = conf_mat.sum(axis=1) norm_cm = conf_mat / sum_of_rows[:, np.newaxis] print("After normalizing each row to 1:\n", norm_cm) ## classifier for dt in datasets: print("### dataset ###", dt) A = np.loadtxt(dt) X = A[:, :9] y = np.squeeze(A[:, 9:]) print(X.shape) print(y.shape) # shuffle data random_state = np.random.RandomState(0) X, y = shuffle(X, y, random_state=random_state) # SVM print("## Linear SVC ##") clf_svm = LinearSVC(random_state=random_state, max_iter=10000) # clf_svm.decision_function([[1]]) score_cm2(clf_svm, X, y) # KNN print("## KNN ##") clf_knn = KNeighborsClassifier(n_neighbors=3) score_cm2(clf_knn, X, y) # MLP print("## MLP ##") clf_mlp = MLPClassifier(random_state=random_state, max_iter=10000) score_cm2(clf_mlp, X, y) ## regressor # ## multi-label dataset dt = "tictac_multi.txt" print("### dataset ###", dt) A = np.loadtxt(dt) X = A[:, :9] y = np.squeeze(A[:, 9:]) print(X.shape) print(y.shape) # shuffle data random_state = np.random.RandomState(0) X, y = shuffle(X, y, random_state=random_state) # KNN print("## KNN ##") clf_knn = KNeighborsRegressor(n_neighbors=5) # # clf_knn = MultiOutputClassifier(KNeighborsClassifier()) # clf_knn = OneVsRestClassifier(KNeighborsClassifier()) score_cm(clf_knn, X, y) # Linear Regressor # train model for each output label from numpy.linalg import inv # using 10-Fold cross validation print("## Linear Regressor ##") scores = [] kf = KFold(n_splits=10) for train_index, test_index in kf.split(X): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] # solving linear least squares b = inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train) # print(b) # predict using coefficients y_pred = X_test.dot(b) y_pred = y_pred > 0.2 scores.append(accuracy_score(y_test, y_pred)) # mean and std print("Accuracy: %0.2f " % (sum(scores) / len(scores))) # MLP print("## MLP ##") clf_mlp = MLPRegressor(hidden_layer_sizes=[100, 500, 100], random_state=random_state, max_iter=10000) clf_save = score_cm(clf_mlp, X, y) # save model import pickle filename = "model.pkl" pickle.dump(clf_save, open(filename, "wb")) # # split # from sklearn.model_selection import train_test_split # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=random_state) # print(X_train.shape) # print(X_test.shape) # print(y_train.shape) # print(y_test.shape) # clf_svm.fit(X_train,y_train) # # y_score = clf_svm.decision_function(X_test,y_test) # # predict # pred = clf_svm.predict(X_test) # print(pred) # score # from sklearn.metrics import accuracy_score # acc = accuracy_score(y_test,pred) # print(acc) # conf_matrix_list_of_arrays = [] # kf = cross_validation.KFold(len(y), n_folds=5) # for train_index, test_index in kf: # # X_train, X_test = X[train_index], X[test_index] # y_train, y_test = y[train_index], y[test_index] # # model.fit(X_train, y_train) # conf_matrix = confusion_matrix(y_test, model.predict(X_test)) # conf_matrix_list_of_arrays.append(conf_matrix) ```
zhizuyiwang/LTEDemo
zhizuyiwang/LTEDemo UserBean.java ```package com.zed.hotsport.bean; import android.os.Parcel; import android.os.Parcelable; import java.util.Date; /** * Created by Administrator on 2016/9/22. */ public class UserBean implements Parcelable { //上报的IMSI private String imsi; //上报的IMEI private String imei; //上报的时间 private Date timer; //上报的运营商 private String oprerator; //黑名单名称 private String blackName; //上报的TSM private String TSM; //上报的lac private String lac; //场强值 private String power; //归属地 private String place; //手机类型 private String phoneType; public String getImsi() { return imsi; } public void setImsi(String imsi) { this.imsi = imsi; } public String getImei() { return imei; } public void setImei(String imei) { this.imei = imei; } public Date getTimer() { return timer; } public void setTimer(Date timer) { this.timer = timer; } public String getBlackName() { return blackName; } public void setBlackName(String blackName) { this.blackName = blackName; } public String getTSM() { return TSM; } public void setTSM(String TSM) { this.TSM = TSM; } public String getLac() { return lac; } public void setLac(String lac) { this.lac = lac; } public String getPower() { return power; } public void setPower(String power) { this.power = power; } public String getPlace() { return place; } public void setPlace(String place) { this.place = place; } public String getPhoneType() { return phoneType; } public void setPhoneType(String phoneType) { this.phoneType = phoneType; } public String getOprerator() { return oprerator; } public void setOprerator(String oprerator) { this.oprerator = oprerator; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.imsi); dest.writeString(this.imei); dest.writeLong(this.timer != null ? this.timer.getTime() : -1); dest.writeString(this.oprerator); dest.writeString(this.blackName); dest.writeString(this.TSM); dest.writeString(this.lac); dest.writeString(this.power); dest.writeString(this.place); dest.writeString(this.phoneType); } public UserBean() { } protected UserBean(Parcel in) { this.imsi = in.readString(); this.imei = in.readString(); long tmpTimer = in.readLong(); this.timer = tmpTimer == -1 ? null : new Date(tmpTimer); this.oprerator = in.readString(); this.blackName = in.readString(); this.TSM = in.readString(); this.lac = in.readString(); this.power = in.readString(); this.place = in.readString(); this.phoneType = in.readString(); } public static final Creator<UserBean> CREATOR = new Creator<UserBean>() { @Override public UserBean createFromParcel(Parcel source) { return new UserBean(source); } @Override public UserBean[] newArray(int size) { return new UserBean[size]; } }; } ``` OpenDialogUtils.java ```package com.zed.hotsport.utils; import android.content.DialogInterface; import java.lang.reflect.Field; /** * Created by Administrator on 2016/11/10. */ public class OpenDialogUtils { /** * 阻止对话框关闭 * @param dialog */ public static void stopCloseDialog(DialogInterface dialog){ try { Field field = dialog.getClass().getSuperclass() .getDeclaredField("mShowing"); field.setAccessible(true); // 将mShowing变量设为false,表示对话框已关闭,系统就不再处理关对话框的逻辑了 field.set(dialog, false); } catch (Exception e) { e.printStackTrace(); } } /** * 让系统自动处理对话框关闭 * @param dialog */ public static void closeDialog(DialogInterface dialog){ try { Field field = dialog.getClass().getSuperclass() .getDeclaredField("mShowing"); field.setAccessible(true); // 将mShowing变量设为true,表示对话框没有关闭,系统会自动处理关闭 field.set(dialog, true); } catch (Exception e) { e.printStackTrace(); } } } ``` BlackListAdapter.java ```package com.zed.hotsport.adapter; import android.app.Activity; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.zed.hotsport.R; import com.zed.hotsport.bean.BlackBean; import java.util.ArrayList; public class BlackListAdapter extends BaseAdapter { private LayoutInflater inflater; private Activity activity; private ArrayList<BlackBean> blackBean; public BlackListAdapter(ArrayList<BlackBean> users, Activity activity) { super(); this.blackBean = users; this.activity = activity; inflater = LayoutInflater.from(activity); } @Override public int getCount() { return blackBean.size(); } @Override public Object getItem(int position) { return blackBean.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.black_list, null); holder.tv_name = (TextView) convertView .findViewById(R.id.tv_black_name); holder.tv_mark = (TextView) convertView.findViewById(R.id.tv_mark); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.tv_name.setText(blackBean.get(position).getName()); if (!TextUtils.isEmpty(blackBean.get(position).getImsi())) { holder.tv_mark.setText(blackBean.get(position).getImsi()); } else if (!TextUtils.isEmpty(blackBean.get(position).getImei())) { holder.tv_mark.setText(blackBean.get(position).getImei()); } else if (!TextUtils.isEmpty(blackBean.get(position).getEsn())) { holder.tv_mark.setText(blackBean.get(position).getEsn()); } else if (!TextUtils.isEmpty(blackBean.get(position).getMac())) { holder.tv_mark.setText(blackBean.get(position).getMac()); } return convertView; } static class ViewHolder { TextView tv_name; TextView tv_mark; } } ``` DeviceStatusActivity.java ```package com.zed.hotsport.activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.zed.hotsport.R; import com.zed.hotsport.TCP.TCPAction; import com.zed.hotsport.base.Constant; import butterknife.Bind; import butterknife.ButterKnife; public class DeviceStatusActivity extends AppCompatActivity { @Bind(R.id.toolBar) Toolbar toolBar; @Bind(R.id.activity_device_status) LinearLayout activityDeviceStatus; @Bind(R.id.tv_cpu_status) TextView tvCpuStatus; @Bind(R.id.tv_memory_status) TextView tvMemoryStatus; @Bind(R.id.tv_wendu_status) TextView tvWenduStatus; @Bind(R.id.tv_catch_status) TextView tvCatchStatus; @Bind(R.id.lt_cell_status) TextView ltCellStatus; @Bind(R.id.lt_pa_status) TextView ltPaStatus; @Bind(R.id.lt_pa_down) TextView ltPaDown; @Bind(R.id.lt_pa_power) TextView ltPaPower; @Bind(R.id.dx_cell_status) TextView dxCellStatus; @Bind(R.id.dx_pa_status) TextView dxPaStatus; @Bind(R.id.dx_pa_down) TextView dxPaDown; @Bind(R.id.dx_pa_power) TextView dxPaPower; @Bind(R.id.mobile_cell_status) TextView mobileCellStatus; @Bind(R.id.mobile_pa_status) TextView mobilePaStatus; @Bind(R.id.mobile_pa_down) TextView mobilePaDown; @Bind(R.id.mobile_pa_power) TextView mobilePaPower; @Bind(R.id.mobile1_cell_status) TextView mobile1CellStatus; @Bind(R.id.mobile1_pa_status) TextView mobile1PaStatus; @Bind(R.id.mobile1_pa_down) TextView mobile1PaDown; @Bind(R.id.mobile1_pa_power) TextView mobile1PaPower; private SharedPreferences sp_device_status; private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals(TCPAction.ACTTON_STATUS)){//状态上报广播 initViewData();//更改控件数据 } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_device_status); ButterKnife.bind(this); initToolBar(); initData(); initReceiver(); initViewData(); } /** * 注册广播 */ private void initReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(TCPAction.ACTTON_STATUS); registerReceiver(receiver, filter); } /** * 初始化各个控件的数据 */ private void initViewData() { tvCpuStatus.setText(sp_device_status.getString(Constant.CPU_STATUS,"")); tvMemoryStatus.setText(sp_device_status.getString(Constant.MEMORY_STATUS,"")); tvWenduStatus.setText(sp_device_status.getString(Constant.WENDU,"")); tvCatchStatus.setText(sp_device_status.getString(Constant.CATCH_STATUS,"")); ltCellStatus.setText(sp_device_status.getString(Constant.LT_CELL_STATUS,"")); ltPaStatus.setText(sp_device_status.getString(Constant.LT_PA_STATUS,"")); ltPaDown.setText(sp_device_status.getString(Constant.LT_PA_DOWN,"")); ltPaPower.setText(sp_device_status.getString(Constant.LT_PA_POWER,"")); dxCellStatus.setText(sp_device_status.getString(Constant.DX_CELL_STATUS,"")); dxPaStatus.setText(sp_device_status.getString(Constant.DX_PA_STATUS,"")); dxPaDown.setText(sp_device_status.getString(Constant.DX_PA_DOWN,"")); dxPaPower.setText(sp_device_status.getString(Constant.DX_PA_POWER,"")); mobileCellStatus.setText(sp_device_status.getString(Constant.MOBILE_CELL_STATUS,"")); mobilePaStatus.setText(sp_device_status.getString(Constant.MOBILE_PA_STATUS,"")); mobilePaDown.setText(sp_device_status.getString(Constant.MOBILE_PA_DOWN,"")); mobilePaPower.setText(sp_device_status.getString(Constant.MOBILE_PA_POWER,"")); mobile1CellStatus.setText(sp_device_status.getString(Constant.MOBILE1_CELL_STATUS,"")); mobile1PaStatus.setText(sp_device_status.getString(Constant.MOBILE1_PA_STATUS,"")); mobile1PaDown.setText(sp_device_status.getString(Constant.MOBILE1_PA_DOWN,"")); mobile1PaPower.setText(sp_device_status.getString(Constant.MOBILE1_PA_POWER,"")); } /** * 初始化数据 */ private void initData() { sp_device_status = getSharedPreferences(Constant.DEVICE_STATUS,0); } /** * 初始化ToolBar */ private void initToolBar() { toolBar.setNavigationIcon(R.mipmap.l_arrow); toolBar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DeviceStatusActivity.this.finish(); } }); toolBar.setTitle("设备状态");//设置主标题 toolBar.setTitleTextColor(getResources().getColor(R.color.color_f5f5f5)); toolBar.setTitleTextAppearance(this, R.style.ActionBarTitle); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); } } ``` ToastUtils.java ```package com.zed.hotsport.utils; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.widget.Toast; public class ToastUtils { private static Toast mToast; public static void showToast(Context context ,String msg,int flag){ if(mToast != null){ mToast.setText(msg); }else{ /* * 第一个参数:当前的上下文环境,用this或getApplicationContext()表示。 * 第二个参数:显示的字符串,用R.string表示。 * 第三个参数:显示的时间长短。用LENGTH_LONG(长)或LENGTH_SHORT(短)表示,也可以用毫秒。 */ mToast = Toast.makeText(context, msg, flag); } mToast.show();//显示toast信息 } /** * 一个确定按钮的对话框,只用于提示,点击确定,对话框消失 * @param context * @param title * @param msg */ public static void showDialog1Btn(Context context,String title,String msg){ Builder builder=new Builder(context); builder.setTitle(title); builder.setMessage(msg); builder.setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setCancelable(false); builder.create(); builder.show(); } public static void showDialog2Btn(Context context,String title,String msg,OnClickListener listener){ Builder builder=new Builder(context); builder.setTitle(title); builder.setMessage(msg); builder.setPositiveButton("确定", listener); builder.setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setCancelable(false); builder.create(); builder.show(); } } ``` SetActivity.java ```package com.zed.hotsport.activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.os.SystemClock; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatSpinner; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.zed.hotsport.R; import com.zed.hotsport.TCP.TCPAction; import com.zed.hotsport.TCP.TCPOutHelper; import com.zed.hotsport.base.BaseApplication; import com.zed.hotsport.base.Constant; import com.zed.hotsport.bean.CellBean; import com.zed.hotsport.utils.ToastUtils; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class SetActivity extends AppCompatActivity implements View.OnClickListener { @Bind(R.id.toolBar) Toolbar toolBar; @Bind(R.id.cbSelectAll) CheckBox cbSelectAll; @Bind(R.id.cb_mobile) CheckBox cbMobile; @Bind(R.id.tv_mobile_operator) TextView tvMobileOperator; @Bind(R.id.et_mobile_operator_spinner) AppCompatSpinner etMobileOperatorSpinner; @Bind(R.id.tv_mobile_frequency) TextView tvMobileFrequency; @Bind(R.id.et_mobile_frequency) EditText etMobileFrequency; @Bind(R.id.tv_mobile_scramble) TextView tvMobileScramble; @Bind(R.id.et_mobile_scramble) EditText etMobileScramble; @Bind(R.id.tv_mobile_descend) TextView tvMobileDescend; @Bind(R.id.et_mobile_descend) AppCompatSpinner etMobileDescend; @Bind(R.id.tv_mobile_tac) TextView tvMobileTac; @Bind(R.id.et_mobile_tac) EditText etMobileTac; @Bind(R.id.tv_mobile_tac_period) TextView tvMobileTacPeriod; @Bind(R.id.et_mobile_tac_period) EditText etMobileTacPeriod; @Bind(R.id.tv_mobile_CDX) TextView tvMobileCDX; @Bind(R.id.et_mobile_CDX) AppCompatSpinner etMobileCDX; @Bind(R.id.tv_mobile_band) TextView tvMobileBand; @Bind(R.id.et_mobile_band) EditText etMobileBand; @Bind(R.id.tv_mobile_frequency1) TextView tvMobileFrequency1; @Bind(R.id.et_mobile_frequency1) EditText etMobileFrequency1; @Bind(R.id.tv_mobile_dianping) TextView tvMobileDianping; @Bind(R.id.et_mobile_dianping) EditText etMobileDianping; @Bind(R.id.mobile_container) LinearLayout mobileContainer; //移动1 @Bind(R.id.cb_mobile1) CheckBox cbMobile1; @Bind(R.id.tv_mobile1_operator) TextView tvMobile1Operator; @Bind(R.id.et_mobile1_operator) AppCompatSpinner etMobile1Operator; @Bind(R.id.tv_mobile1_frequency) TextView tvMobile1Frequency; @Bind(R.id.et_mobile1_frequency) EditText etMobile1Frequency; @Bind(R.id.tv_mobile1_scramble) TextView tvMobile1Scramble; @Bind(R.id.et_mobile1_scramble) EditText etMobile1Scramble; @Bind(R.id.tv_mobile1_descend) TextView tvMobile1Descend; @Bind(R.id.et_mobile1_descend) AppCompatSpinner etMobile1Descend; @Bind(R.id.tv_mobile1_tac) TextView tvMobile1Tac; @Bind(R.id.et_mobile1_tac) EditText etMobile1Tac; @Bind(R.id.tv_mobile1_tac_period) TextView tvMobile1TacPeriod; @Bind(R.id.et_mobile1_tac_period) EditText etMobile1TacPeriod; @Bind(R.id.tv_mobile1_CDX) TextView tvMobile1CDX; @Bind(R.id.et_mobile1_CDX) AppCompatSpinner etMobile1CDX; @Bind(R.id.tv_mobile1_band) TextView tvMobile1Band; @Bind(R.id.et_mobile1_band) EditText etMobile1Band; @Bind(R.id.tv_mobile1_frequency1) TextView tvMobile1Frequency1; @Bind(R.id.et_mobile1_frequency1) EditText etMobile1Frequency1; @Bind(R.id.tv_mobile1_dianping) TextView tvMobile1Dianping; @Bind(R.id.et_mobile1_dianping) EditText etMobile1Dianping; @Bind(R.id.mobile1_container) LinearLayout mobile1Container; //联通 @Bind(R.id.cb_lt) CheckBox cbLt; @Bind(R.id.tv_lt_operator) TextView tvLtOperator; @Bind(R.id.et_lt_operator) AppCompatSpinner etLtOperator; @Bind(R.id.tv_lt_frequency) TextView tvLtFrequency; @Bind(R.id.et_lt_frequency) EditText etLtFrequency; @Bind(R.id.tv_lt_scramble) TextView tvLtScramble; @Bind(R.id.et_lt_scramble) EditText etLtScramble; @Bind(R.id.tv_lt_descend) TextView tvLtDescend; @Bind(R.id.et_lt_descend) AppCompatSpinner etLtDescend; @Bind(R.id.tv_lt_tac) TextView tvLtTac; @Bind(R.id.et_lt_tac) EditText etLtTac; @Bind(R.id.tv_lt_tac_period) TextView tvLtTacPeriod; @Bind(R.id.et_lt_tac_period) EditText etLtTacPeriod; @Bind(R.id.tv_lt_CDX) TextView tvLtCDX; @Bind(R.id.et_lt_CDX) AppCompatSpinner etLtCDX; @Bind(R.id.tv_lt_band) TextView tvLtBand; @Bind(R.id.et_lt_band) EditText etLtBand; @Bind(R.id.tv_lt_frequency1) TextView tvLtFrequency1; @Bind(R.id.et_lt_frequency1) EditText etLtFrequency1; @Bind(R.id.tv_lt_dianping) TextView tvLtDianping; @Bind(R.id.et_lt_dianping) EditText etLtDianping; @Bind(R.id.lt_container) LinearLayout ltContainer; //电信 @Bind(R.id.cb_dx) CheckBox cbDx; @Bind(R.id.tv_dx_operator) TextView tvDxOperator; @Bind(R.id.et_dx_operator) AppCompatSpinner etDxOperator; @Bind(R.id.tv_dx_frequency) TextView tvDxFrequency; @Bind(R.id.et_dx_frequency) EditText etDxFrequency; @Bind(R.id.tv_dx_scramble) TextView tvDxScramble; @Bind(R.id.et_dx_scramble) EditText etDxScramble; @Bind(R.id.tv_dx_descend) TextView tvDxDescend; @Bind(R.id.et_dx_descend) AppCompatSpinner etDxDescend; @Bind(R.id.tv_dx_tac) TextView tvDxTac; @Bind(R.id.et_dx_tac) EditText etDxTac; @Bind(R.id.tv_dx_tac_period) TextView tvDxTacPeriod; @Bind(R.id.et_dx_tac_period) EditText etDxTacPeriod; @Bind(R.id.tv_dx_CDX) TextView tvDxCDX; @Bind(R.id.et_dx_CDX) AppCompatSpinner etDxCDX; @Bind(R.id.tv_dx_band) TextView tvDxBand; @Bind(R.id.et_dx_band) EditText etDxBand; @Bind(R.id.tv_dx_frequency1) TextView tvDxFrequency1; @Bind(R.id.et_dx_frequency1) EditText etDxFrequency1; @Bind(R.id.tv_dx_dianping) TextView tvDxDianping; @Bind(R.id.et_dx_dianping) EditText etDxDianping; @Bind(R.id.dx_container) LinearLayout DxContainer; @Bind(R.id.btnSendCommand) Button btnSendCommand; @Bind(R.id.activity_black) LinearLayout activityBlack; private boolean flag = false;//用来显示高级配置的标志 private SharedPreferences sp_setting;//保存参数的sp //中国联通 private String lt_frequency;//频点 private String lt_scramble;//扰码 private int lt_descend;//功率衰减下标,也是衰减值 private String lt_tac;//TAC private String lt_tac_period;//TAC变更周期 private int lt_CDX;//重定向下标 private String lt_band;//频段 private String lt_frequency1;//频点 private String lt_dianping;//最小接入电平 //中国电信 private String dx_frequency;//频点 private String dx_scramble;//扰码 private int dx_descend;//功率衰减下标,也是衰减值 private String dx_tac;//TAC private String dx_tac_period;//TAC变更周期 private int dx_CDX;//重定向下标 private String dx_band;//频段 private String dx_frequency1;//频点 private String dx_dianping;//最小接入电平 //中国移动 private String yd_frequency;//频点 private String yd_scramble;//扰码 private int yd_descend;//功率衰减下标,也是衰减值 private String yd_tac;//TAC private String yd_tac_period;//TAC变更周期 private int yd_CDX;//重定向下标 private String yd_band;//频段 private String yd_frequency1;//频点 private String yd_dianping;//最小接入电平 //中国移动1 private String yd1_frequency;//频点 private String yd1_scramble;//扰码 private int yd1_descend;//功率衰减下标,也是衰减值 private String yd1_tac;//TAC private String yd1_tac_period;//TAC变更周期 private int yd1_CDX;//重定向下标 private String yd1_band;//频段 private String yd1_frequency1;//频点 private String yd1_dianping;//最小接入电平 private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(TCPAction.ACTION_PARA)) { initView(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_set); ButterKnife.bind(this); initToolBar(); initReceiver(); initData(); initView(); initListener(); } /** * 监听Spinner的条目点击事件 */ private void initListener() { etLtDescend.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { //当选中Spinner的某一天数据时.会执行 @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { lt_descend = position; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); etDxDescend.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { dx_descend = position; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); etMobileDescend.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { yd_descend = position; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); etMobile1Descend.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { yd1_descend = position; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private void initReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(TCPAction.ACTION_PARA); registerReceiver(receiver, filter); } /** * 初始化控件数据 */ private void initView() { cbSelectAll.setChecked(sp_setting.getBoolean(Constant.SELECTALL_CB, true)); cbLt.setChecked(sp_setting.getBoolean(Constant.LT_SETTING_CB, true)); cbDx.setChecked(sp_setting.getBoolean(Constant.DX_SETTING_CB, true)); cbMobile.setChecked(sp_setting.getBoolean(Constant.YD_SETTING_CB, true)); cbMobile1.setChecked(sp_setting.getBoolean(Constant.YD1_SETTING_CB, true)); cbSelectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { cbLt.setChecked(isChecked); cbDx.setChecked(isChecked); cbMobile.setChecked(isChecked); cbMobile1.setChecked(isChecked); } }); //联通的配置参数 etLtFrequency.setText(sp_setting.getString(Constant.LT_FREQUENCY, 0 + "")); etLtScramble.setText(sp_setting.getString(Constant.LT_SCRAMBLE, 0 + "")); etLtDescend.setSelection(sp_setting.getInt(Constant.LT_DESCEND, 0)); etLtTac.setText(sp_setting.getString(Constant.LT_TAC, 0 + "")); etLtTacPeriod.setText(sp_setting.getString(Constant.LT_TAC_PERIOD, 0 + "")); etLtCDX.setSelection(sp_setting.getInt(Constant.LT_CDX, 0)); etLtBand.setText(sp_setting.getString(Constant.LT_BAND, 0 + "")); etLtFrequency1.setText(sp_setting.getString(Constant.LT_FREQUENCY1, 0 + "")); etLtDianping.setText(sp_setting.getString(Constant.LT_DIANPING, 0 + "")); //电信的配置参数 etDxFrequency.setText(sp_setting.getString(Constant.DX_FREQUENCY, 0 + "")); etDxScramble.setText(sp_setting.getString(Constant.DX_SCRAMBLE, 0 + "")); etDxDescend.setSelection(sp_setting.getInt(Constant.DX_DESCEND, 0)); etDxTac.setText(sp_setting.getString(Constant.DX_TAC, 0 + "")); etDxTacPeriod.setText(sp_setting.getString(Constant.DX_TAC_PERIOD, 0 + "")); etDxCDX.setSelection(sp_setting.getInt(Constant.DX_CDX, 0)); etDxBand.setText(sp_setting.getString(Constant.DX_BAND, 0 + "")); etDxFrequency1.setText(sp_setting.getString(Constant.DX_FREQUENCY1, 0 + "")); etDxDianping.setText(sp_setting.getString(Constant.DX_DIANPING, 0 + "")); //移动的配置参数 etMobileFrequency.setText(sp_setting.getString(Constant.MOBILE_FREQUENCY, 0 + "")); etMobileScramble.setText(sp_setting.getString(Constant.MOBILE_SCRAMBLE, 0 + "")); etMobileDescend.setSelection(sp_setting.getInt(Constant.MOBILE_DESCEND, 0)); etMobileTac.setText(sp_setting.getString(Constant.MOBILE_TAC, 0 + "")); etMobileTacPeriod.setText(sp_setting.getString(Constant.MOBILE_TAC_PERIOD, 0 + "")); etMobileCDX.setSelection(sp_setting.getInt(Constant.MOBILE_CDX, 0)); etMobileBand.setText(sp_setting.getString(Constant.MOBILE_BAND, 0 + "")); etMobileFrequency1.setText(sp_setting.getString(Constant.MOBILE_FREQUENCY1, 0 + "")); etMobileDianping.setText(sp_setting.getString(Constant.MOBILE_DIANPING, 0 + "")); //移动1的配置参数 etMobile1Frequency.setText(sp_setting.getString(Constant.MOBILE1_FREQUENCY, 0 + "")); etMobile1Scramble.setText(sp_setting.getString(Constant.MOBILE1_SCRAMBLE, 0 + "")); etMobile1Descend.setSelection(sp_setting.getInt(Constant.MOBILE1_DESCEND, 0)); etMobile1Tac.setText(sp_setting.getString(Constant.MOBILE1_TAC, 0 + "")); etMobile1TacPeriod.setText(sp_setting.getString(Constant.MOBILE1_TAC_PERIOD, 0 + "")); etMobile1CDX.setSelection(sp_setting.getInt(Constant.MOBILE1_CDX, 0)); etMobile1Band.setText(sp_setting.getString(Constant.MOBILE1_BAND, 0 + "")); etMobile1Frequency1.setText(sp_setting.getString(Constant.MOBILE1_FREQUENCY1, 0 + "")); etMobile1Dianping.setText(sp_setting.getString(Constant.MOBILE1_DIANPING, 0 + "")); } /** * 初始化数据 */ private void initData() { sp_setting = getSharedPreferences(Constant.DEVICE_PARA, 0); //查询设备参数 TCPOutHelper.getInstance(SetActivity.this).msgGetCellPara(BaseApplication.CurrentEid); } /** * 初始化ToolBar */ private void initToolBar() { toolBar.setNavigationIcon(R.mipmap.l_arrow); toolBar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showExitDialog(); } }); toolBar.setTitle("设置界面");//设置主标题 toolBar.setTitleTextColor(getResources().getColor(R.color.color_f5f5f5)); toolBar.setTitleTextAppearance(this, R.style.ActionBarTitle); toolBar.inflateMenu(R.menu.base_setting_menu); toolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { int menuId = item.getItemId(); switch (menuId) { case R.id.action_normal_setting://基础设置 flag = false; mobileContainer.setVisibility(View.GONE); mobile1Container.setVisibility(View.GONE); ltContainer.setVisibility(View.GONE); DxContainer.setVisibility(View.GONE); /* LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(30, 60, 30, 0); btnSendCommand.setLayoutParams(lp);*/ break; case R.id.action_setting://高级设置 flag = true; mobileContainer.setVisibility(View.VISIBLE); mobile1Container.setVisibility(View.VISIBLE); ltContainer.setVisibility(View.VISIBLE); DxContainer.setVisibility(View.VISIBLE); break; case R.id.action_get_para: TCPOutHelper.getInstance(SetActivity.this).msgGetCellPara(BaseApplication.CurrentEid); break; } return true; } }); } @Override public void onBackPressed() { showExitDialog(); } /** * 退出界面的提示 */ private void showExitDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(SetActivity.this); builder.setMessage("是否确定退出?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { SetActivity.this.finish(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); builder.create().show(); } @OnClick(R.id.btnSendCommand) public void onClick(View v) { Log.e("TAG", "下发配置"); getInfo(); if (BaseApplication.connect) { saveSetting(); if (cbLt.isChecked()) { Log.e("TAG", "下发联通配置"); CellBean ltCell = new CellBean(); ltCell.setFrequency(lt_frequency); ltCell.setScramble(lt_scramble); ltCell.setPower_down(lt_descend ); ltCell.setTac(lt_tac); ltCell.setLac_period(lt_tac_period); ltCell.setBand(lt_band); ltCell.setFrequency1(lt_frequency1); ltCell.setDianPing(lt_dianping); //下发联通配置 TCPOutHelper.getInstance(SetActivity.this).msgSetCellPara(BaseApplication.CurrentEid, ltCell, 0, 1); } SystemClock.sleep(100); if (cbDx.isChecked()) { Log.e("TAG", "下发电信配置"); CellBean dxCell = new CellBean(); dxCell.setFrequency(dx_frequency); dxCell.setScramble(dx_scramble); dxCell.setPower_down(dx_descend); dxCell.setTac(dx_tac); dxCell.setLac_period(dx_tac_period); dxCell.setBand(dx_band); dxCell.setFrequency1(dx_frequency1); dxCell.setDianPing(dx_dianping); //下发电信配置 TCPOutHelper.getInstance(SetActivity.this).msgSetCellPara(BaseApplication.CurrentEid, dxCell, 1, 11); } SystemClock.sleep(100); if (cbMobile.isChecked()) { Log.e("TAG", "下发移动配置"); CellBean ydCell = new CellBean(); ydCell.setFrequency(yd_frequency); ydCell.setScramble(yd_scramble); ydCell.setPower_down(yd_descend); ydCell.setTac(yd_tac); ydCell.setLac_period(yd_tac_period); ydCell.setBand(yd_band); ydCell.setFrequency1(yd_frequency1); ydCell.setDianPing(yd_dianping); //下发移动配置 TCPOutHelper.getInstance(SetActivity.this).msgSetCellPara(BaseApplication.CurrentEid, ydCell, 2, 0); } SystemClock.sleep(100); if (cbMobile1.isChecked()) { Log.e("TAG", "下发移动1通配置"); CellBean yd1Cell = new CellBean(); yd1Cell.setFrequency(yd1_frequency); yd1Cell.setScramble(yd1_scramble); yd1Cell.setPower_down(yd1_descend); yd1Cell.setTac(yd1_tac); yd1Cell.setLac_period(yd1_tac_period); yd1Cell.setBand(yd1_band); yd1Cell.setFrequency1(yd1_frequency1); yd1Cell.setDianPing(yd1_dianping); //下发移动1配置 TCPOutHelper.getInstance(SetActivity.this).msgSetCellPara(BaseApplication.CurrentEid, yd1Cell, 3, 0); } } else { ToastUtils.showToast(SetActivity.this, "设备未连接,下发参数失败", 0); } } /** * 设备若连接,并且点击了下发命令按钮,则保存设置,这里只保存选择状态,因为其他信息会在进入配置界面时,根据查询的参数值回显参数值 */ private void saveSetting() { sp_setting.edit().putBoolean(Constant.SELECTALL_CB,cbSelectAll.isChecked()).commit(); sp_setting.edit().putBoolean(Constant.LT_SETTING_CB,cbLt.isChecked()).commit(); sp_setting.edit().putBoolean(Constant.DX_SETTING_CB,cbDx.isChecked()).commit(); sp_setting.edit().putBoolean(Constant.YD_SETTING_CB,cbMobile.isChecked()).commit(); sp_setting.edit().putBoolean(Constant.YD1_SETTING_CB,cbMobile1.isChecked()).commit(); } /** * 得到要配置的参数 */ private void getInfo() { //联通 lt_frequency = etLtFrequency.getText().toString().trim(); lt_scramble = etLtScramble.getText().toString().trim(); lt_tac = etLtTac.getText().toString().trim(); lt_tac_period = etLtTacPeriod.getText().toString().trim(); lt_band = etLtBand.getText().toString().trim(); lt_frequency1 = etLtFrequency1.getText().toString().trim(); lt_dianping = etLtDianping.getText().toString().trim(); //电信 dx_frequency = etDxFrequency.getText().toString().trim(); dx_scramble = etDxScramble.getText().toString().trim(); dx_tac = etDxTac.getText().toString().trim(); dx_tac_period = etDxTacPeriod.getText().toString().trim(); dx_band = etDxBand.getText().toString().trim(); dx_frequency1 = etDxFrequency1.getText().toString().trim(); dx_dianping = etDxDianping.getText().toString().trim(); //移动 yd_frequency = etMobileFrequency.getText().toString().trim(); yd_scramble = etMobileScramble.getText().toString().trim(); yd_tac = etMobileTac.getText().toString().trim(); yd_tac_period = etMobileTacPeriod.getText().toString().trim(); yd_band = etMobileBand.getText().toString().trim(); yd_frequency1 = etMobileFrequency1.getText().toString().trim(); yd_dianping = etMobileDianping.getText().toString().trim(); //移动1 yd1_frequency = etMobile1Frequency.getText().toString().trim(); yd1_scramble = etMobile1Scramble.getText().toString().trim(); yd1_tac = etMobile1Tac.getText().toString().trim(); yd1_tac_period = etMobile1TacPeriod.getText().toString().trim(); yd1_band = etMobile1Band.getText().toString().trim(); yd1_frequency1 = etMobile1Frequency1.getText().toString().trim(); yd1_dianping = etMobile1Dianping.getText().toString().trim(); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); } } ``` sortUtils.java ```package com.zed.hotsport.utils; /** * Created by Administrator on 2016/11/10. * 排序类 */ public class sortUtils { } ``` TCPClient.java ```package com.zed.hotsport.TCP; import android.content.Context; import android.content.Intent; import android.util.Log; import com.zed.hotsport.utils.ToastUtils; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * Created by Administrator on 2016/9/18. */ public class TCPClient{ private ServerSocket mServerSocket = null;//连接服务对象 private Socket mSocket = null;//连接对象 private int mIntTargetPort = 0;//目标端口 private Context context; /** * 带参构造方法 * * @param targetPort * 目标端口。 参数为:SocketConfig.SOCKET_CONFIG_PORT_XXX */ public TCPClient(int targetPort, Context context){ this.mIntTargetPort = targetPort; this.context = context; try { this.mServerSocket = new ServerSocket(mIntTargetPort); } catch (IOException e) { Log.e("ServerSocket创建失败","ServerSocket创建失败"); ToastUtils.showToast(context,"ServerSocket创建失败",0); e.printStackTrace(); } } /** * 监听连接,得到Socket实例 */ public void listen(){ try { if(this.mServerSocket==null){ return; } Log.e("TAG","监听连接,准备得到Socket实例"); setSocket(mServerSocket.accept()); Intent intent = new Intent(TCPAction.ACTTON_CESHI); context.sendBroadcast(intent); Log.e("TAG","监听连接,已经得到Socket实例"); } catch (IOException e) { Log.e("TAG","TCPClient对象构建失败"); e.printStackTrace(); } } public void setServerSocket(ServerSocket serverSocket){ this.mServerSocket = serverSocket; } public ServerSocket getServerSocket(){ return this.mServerSocket; } /** * 设置Socket对象 * * @param socket * 通信实例 */ public void setSocket(Socket socket){ this.mSocket = socket; } /** * 返回当前连接 * * @return Socket 当前连接 */ public Socket getSocket(){ return this.mSocket; } /** * 获取当前建链本地端口 * * @return 本地端口号 */ public int getTargetPort() { return this.mIntTargetPort; } /** * 关闭Socket连接 */ public void closeSocket(TCPClient client){ try { if(client.getSocket()!=null){ client.getSocket().close(); } if(client.getServerSocket()!=null){ client.getServerSocket().close(); Log.e("TAG","连接服务对象关闭"); } } catch (IOException e) { Log.e("TAG","Socket关闭失败"); e.printStackTrace(); } } } ``` MainActivity.java ```package com.zed.ceshi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); byte[] ss = new byte[]{3, -23}; Log.e("TAG",bytes2Int(ss,0,2)+""); String dd = ConvertCodeUtility.getCurrentTime(); Log.e("TAG","dd"+dd+","+dd.length()); byte[] data = new byte[14]; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA); String strDate = sdf.format(new Date()); String date = strDate.substring(0,8); String time = strDate.substring(8,14); Log.e("TAGTAGTAG","Date:"+Integer.parseInt(date)+",Time:"+Integer.parseInt(time)); } public int bytes2Int(byte[] b, int start, int len) { int sum = 0; int end = start + len; for (int i = start; i < end; i++) { int n = ((int)b[i]) & 0xff; n <<= (--len) * 8; sum += n; } return sum; } public byte[] int2Bytes(int value, int len) { byte[] b = new byte[len]; for (int i = 0; i < len; i++) { b[len - i - 1] = (byte)((value >> 8 * i) & 0xff); } return b; } /** * 将网络传输byte[2]转换为int * * @param data * 网络传输byte[2] * @return short 值 */ public static int bytes2Int2(byte[] data) { int value = (data[1] & 0xFF) | (data[0] & 0xFF) << 8; return value; } } ``` VersionQueryActivity.java ```package com.zed.hotsport.activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.zed.hotsport.R; import com.zed.hotsport.TCP.TCPAction; import com.zed.hotsport.TCP.TCPOutHelper; import com.zed.hotsport.base.BaseApplication; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class VersionQueryActivity extends AppCompatActivity { @Bind(R.id.toolBar) Toolbar toolBar; @Bind(R.id.activity_version_query) LinearLayout activityVersionQuery; @Bind(R.id.tv_version) TextView tvVersion; @Bind(R.id.btn1) Button btn1; private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(TCPAction.ACTTON_VERSION)) { String version = intent.getStringExtra("VERSION"); tvVersion.setText(version); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_version_query); ButterKnife.bind(this); initToolBar(); initReceiver(); //查询版本号 TCPOutHelper.getInstance(this).msgGetVersion(BaseApplication.CurrentEid); } /** * 初始化广播 */ private void initReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(TCPAction.ACTTON_VERSION); registerReceiver(receiver, filter); } /** * 初始化ToolBar */ private void initToolBar() { toolBar.setNavigationIcon(R.mipmap.l_arrow); toolBar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { VersionQueryActivity.this.finish(); } }); toolBar.setTitle("版本查询");//设置主标题 toolBar.setTitleTextColor(getResources().getColor(R.color.color_f5f5f5)); toolBar.setTitleTextAppearance(this, R.style.ActionBarTitle); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); } @OnClick(R.id.btn1) public void onClick() { //查询版本号 TCPOutHelper.getInstance(this).msgGetVersion(BaseApplication.CurrentEid); } } ``` WhiteActivity.java ```package com.zed.hotsport.activity; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.zed.hotsport.R; import com.zed.hotsport.adapter.BlackListAdapter; import com.zed.hotsport.bean.BlackBean; import com.zed.hotsport.utils.ToastUtils; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import butterknife.Bind; import butterknife.ButterKnife; public class WhiteActivity extends AppCompatActivity { @Bind(R.id.toolBar) Toolbar toolBar; @Bind(R.id.activity_black) LinearLayout activityBlack; @Bind(R.id.list_View) ListView black_listView; private ArrayList<BlackBean> blackList; private BlackListAdapter blackListAdapter; private AlertDialog dialog; private String[] items; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_white); ButterKnife.bind(this); initToolBar(); initData(); initListener(); } /** * 初始化监听 */ private void initListener() { black_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } }); black_listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { //有编辑和删除功能 showItemDialog(position); return true; } }); } private void showItemDialog(int position) { AlertDialog.Builder builder = new AlertDialog.Builder(WhiteActivity.this); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(which == 0){//编辑 }else if(which == 1){//删除 } } }); builder.create().show(); } /** * 初始化数据 */ private void initData() { //从数据库中查询数据 items = new String[]{"编辑","删除"}; blackList = new ArrayList<>(); for(int i = 0;i < 7;i++){ blackList.add(new BlackBean("张三","123456789745623","123456789745623",null,null,1)); } if(blackList.size()>0){ blackListAdapter = new BlackListAdapter(blackList,this); black_listView.setAdapter(blackListAdapter); } } /** * 初始化ToolBar */ private void initToolBar() { toolBar.setNavigationIcon(R.mipmap.l_arrow); toolBar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { WhiteActivity.this.finish(); } }); toolBar.setTitle("白名单管理");//设置主标题 toolBar.setTitleTextColor(getResources().getColor(R.color.color_f5f5f5)); toolBar.setTitleTextAppearance(this, R.style.ActionBarTitle); toolBar.inflateMenu(R.menu.base_black_menu); toolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { int menuId = item.getItemId(); switch (menuId) { case R.id.action_add: // 展示添加白名单的对话框 showAddBlackDialog(); break; } return true; } }); } private void showAddBlackDialog() { AlertDialog.Builder adb = new AlertDialog.Builder(this); View view = getLayoutInflater() .inflate(R.layout.add_black_dialog, null); dialog = adb.create(); final EditText black_name = (EditText) view .findViewById(R.id.blacklist_add_name); final EditText black_imsi = (EditText) view .findViewById(R.id.blacklist_add_imsi); final EditText black_imei = (EditText) view .findViewById(R.id.blacklist_add_imei); final EditText black_esn = (EditText) view .findViewById(R.id.blacklist_add_esn); final EditText black_mac = (EditText) view .findViewById(R.id.blacklist_add_mac); TextView btnOk = (TextView) view.findViewById(R.id.btn_ok); TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); btnOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String mac = " "; String name = black_name.getText().toString().trim(); String imsi = black_imsi.getText().toString().trim(); String imei = black_imei.getText().toString().trim(); String esn = black_esn.getText().toString().trim(); Pattern pattern = Pattern .compile("[0-9A-Fa-f]{8}"); Matcher matcher1 = pattern.matcher(esn); if (!TextUtils.isEmpty(black_esn.getText().toString().trim())) { esn = black_esn.getText().toString().trim().toUpperCase(); } String mac1 = black_mac.getText().toString().trim(); if (TextUtils.isEmpty(name)) { ToastUtils.showToast(WhiteActivity.this,"白名单名不能为空", Toast.LENGTH_SHORT); return; } if (TextUtils.isEmpty(imsi) && TextUtils.isEmpty(imei) && TextUtils.isEmpty(esn) && TextUtils.isEmpty(mac1)) { ToastUtils.showToast(WhiteActivity.this,"IMSI/IMEI/ESN/MAC请至少填写一个",Toast.LENGTH_SHORT); return; } if ((imsi.length() == 15) || (imei.length() == 15) || ((esn.length() == 8) && matcher1.matches()) || (mac1.length() == 12)) { if (mac1.length() == 12) { mac = mac1.substring(0, 2).toUpperCase() + ":" + mac1.substring(2, 4).toUpperCase() + ":" + mac1.substring(4, 6).toUpperCase() + ":" + mac1.substring(6, 8).toUpperCase() + ":" + mac1.substring(8, 10).toUpperCase() + ":" + mac1.substring(10, 12).toUpperCase(); Pattern p = Pattern .compile("([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}"); Matcher matcher = p.matcher(mac); if (!matcher.matches()) { ToastUtils.showToast(WhiteActivity.this,"您输入的mac包含非十六进制字符!",Toast.LENGTH_SHORT); return; } } if (imei.length() != 0 && imei.length()==15) { if (imei.charAt(14) != '0') { black_imei.setText(imei.substring(0, 14) + "0"); imei = black_imei.getText().toString().trim(); } } if ((imsi.length() != 0 && imsi.length()!=15)){ ToastUtils.showToast(WhiteActivity.this, "IMSI/IMEI格式为15位数字 ,ESN格式为8位十六进制字符串,mac格式为12位十六进制字符串!(1到9和a到f的组合)", Toast.LENGTH_LONG); return; } if ((imei.length() != 0 && imei.length()!=15)){ ToastUtils.showToast(WhiteActivity.this, "IMSI/IMEI格式为15位数字 ,ESN格式为8位十六进制字符串,mac格式为12位十六进制字符串!(1到9和a到f的组合)", Toast.LENGTH_LONG); return; } if ((esn.length() != 0 && esn.length()!=8)){ ToastUtils.showToast(WhiteActivity.this, "IMSI/IMEI格式为15位数字 ,ESN格式为8位十六进制字符串,mac格式为12位十六进制字符串!(1到9和a到f的组合)", Toast.LENGTH_LONG); return; } //注意,在这里插入到数据库中 } else { ToastUtils.showToast(WhiteActivity.this, "IMSI/IMEI格式为15位数字 ,ESN格式为8位十六进制字符串,mac格式为12位十六进制字符串!(1到9和a到f的组合)", Toast.LENGTH_LONG); return; } // 刷新页面,在页面上显示新的白名单 // 将白名单添加至集合,刷新listView BlackBean blackUser = new BlackBean(name, imsi, imei, esn, mac,1);//1为白名单 blackList.add(blackUser); // 将白名单加至集合 if (blackListAdapter == null) { // new 出来的adapter 会让listView 显示第一条数据 blackListAdapter = new BlackListAdapter(blackList, WhiteActivity.this); black_listView.setAdapter(blackListAdapter); } else { blackListAdapter.notifyDataSetChanged(); } dialog.dismiss(); } }); dialog.setCancelable(false); dialog.setView(view); //设置view dialog.show(); } } ``` CellBean.java ```package com.zed.hotsport.bean; /** * 小区的参数 * Created by Administrator on 2016/11/17. */ public class CellBean { private String frequency;//频点 private String scramble;//扰码 private int power_down;//功率衰减 private String power_rand;//功率等级 private String tac;//位置区 private String lac_period;//lac变更周期 private String CDX;//重定向 private String band;//频段 private String frequency1;//频点 private String dianPing;//最小接入电平 public String getPower_rand() { return power_rand; } public void setPower_rand(String power_rand) { this.power_rand = power_rand; } public String getFrequency() { return frequency; } public void setFrequency(String frequency) { this.frequency = frequency; } public String getScramble() { return scramble; } public void setScramble(String scramble) { this.scramble = scramble; } public int getPower_down() { return power_down; } public void setPower_down(int power) { this.power_down = power; } public String getTac() { return tac; } public void setTac(String tac) { this.tac = tac; } public String getLac_period() { return lac_period; } public void setLac_period(String lac_period) { this.lac_period = lac_period; } public String getCDX() { return CDX; } public void setCDX(String CDX) { this.CDX = CDX; } public String getBand() { return band; } public void setBand(String band) { this.band = band; } public String getFrequency1() { return frequency1; } public void setFrequency1(String frequency1) { this.frequency1 = frequency1; } public String getDianPing() { return dianPing; } public void setDianPing(String dianPing) { this.dianPing = dianPing; } } ``` TCPOutHelper.java ```package com.zed.hotsport.TCP; import android.content.Context; import android.util.Log; import com.zed.hotsport.base.BaseApplication; import com.zed.hotsport.bean.CellBean; import com.zed.hotsport.utils.ConvertCodeUtility; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Socket写入工具类 * Created by Administrator on 2016/9/19. */ public class TCPOutHelper { private final String TAG = "TCPOutHelper"; private Context context = null; private static TCPOutHelper mTCPOutHelper = null;//Socket写入工具类自身实例 private BaseApplication mBaseApplication = null;//全局环境变量 private TCPOutHelper(Context context){ this.context = context; mBaseApplication = (BaseApplication) context.getApplicationContext(); } public static TCPOutHelper getInstance(Context context){ if(mTCPOutHelper==null){ mTCPOutHelper = new TCPOutHelper(context); } return mTCPOutHelper; } /**发送Socket请求,创建消息头,并拼接成完整的消息数组发送至socket * @param client * @param msgType * @param eid * @param data * @return */ private boolean sendMsg(TCPClient client,byte[] msgType,int eid,byte[] data){ //先对client做非空判断 if(client == null){ return false; } try { byte[] sendData; if (data != null) { sendData = new byte[data.length + 8]; System.arraycopy( ConvertCodeUtility.short2Bytes((short) sendData.length), 0, sendData, 0, 2); System.arraycopy(data, 0, sendData, 8, data.length); } else { // 当为心跳响应时,data为null,仅包含消息头,还包括查询设备时间 sendData = new byte[8]; System.arraycopy(ConvertCodeUtility.short2Bytes((short) 8), 0, sendData, 0, 2); } System.arraycopy(msgType,0,sendData,2,2); System.arraycopy(ConvertCodeUtility.int2Bytes(eid),0,sendData,4,4); Socket socket = client.getSocket(); OutputStream os ; os = socket.getOutputStream(); os.write(sendData); os.flush(); return true; } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "发送Socket写入出错!"); return false; } } /** * 通信初始化类型MSG_START_ACK消息 * * @param eid * 建链设备ID * @param flag * 响应标识 * @return 结果状态 */ public boolean msgStartAck(int eid, int flag) { byte[] data = new byte[4]; System.arraycopy(ConvertCodeUtility.int2Bytes(flag),0,data,0,4); return sendMsg(mBaseApplication.getTCPClient(TCPConfig.SOCKET_CONFIG_PORT_3G), ConvertCodeUtility.short2Bytes(TCPConfig.MSG_START_ACK), eid, data); } /** * 发送开关功放请求MSG_PA_ONOFF_REQ类型 * @param eid * 建链设备ID * @param cellId * 小区ID * @param flag * 开关功放的标志位 * @return */ public boolean msgSetPA(int eid, byte cellId ,byte flag) { byte[] data = new byte[2]; data[0] = cellId; data[1] = flag; return sendMsg(mBaseApplication.getTCPClient(TCPConfig.SOCKET_CONFIG_PORT_3G), ConvertCodeUtility.short2Bytes(TCPConfig.MSG_PA_ONOFF_REQ), eid, data); } /** * 发送开关侦码请求类型MSG_CATCHING_ONOFF_REQ * @param eid * @param flag * 开关侦码标志位 * @return */ public boolean msgSetAllCatch(int eid,byte flag){ byte[] data = new byte[1]; data[0] = flag; return sendMsg(mBaseApplication.getTCPClient(TCPConfig.SOCKET_CONFIG_PORT_3G), ConvertCodeUtility.short2Bytes(TCPConfig.MSG_CATCHING_ONOFF_REQ),eid,data); } /** * 设置/同步设备时间请求类型MSG_SET_DATETIME * @param eid * @return */ public boolean msgSetDateTime(int eid){ byte[] data = new byte[14]; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA); String strDate = sdf.format(new Date()); String date1 = strDate.substring(0,4); String date2 = strDate.substring(4,8); String time1 = strDate.substring(8,10); String time2 = strDate.substring(10,12); String time3 = strDate.substring(12,14); System.arraycopy(ConvertCodeUtility.int2Bytes(Integer.parseInt(date1)),0,data,0,4); System.arraycopy(ConvertCodeUtility.int2Bytes(Integer.parseInt(date2)),0,data,4,4); System.arraycopy(ConvertCodeUtility.short2Bytes((short) Integer.parseInt(time1)),0,data,8,2); System.arraycopy(ConvertCodeUtility.short2Bytes((short) Integer.parseInt(time2)),0,data,10,2); System.arraycopy(ConvertCodeUtility.short2Bytes((short) Integer.parseInt(time3)),0,data,12,14); return sendMsg(mBaseApplication.getTCPClient(TCPConfig.SOCKET_CONFIG_PORT_3G), ConvertCodeUtility.short2Bytes(TCPConfig.MSG_SET_DATETIME),eid,data); } /** * 获取设备的时间类型MSG_GET_DATETIME,只有消息头 * @param eid * @return */ public boolean msgGetDateTime(int eid){ return sendMsg(mBaseApplication.getTCPClient(TCPConfig.SOCKET_CONFIG_PORT_3G), ConvertCodeUtility.short2Bytes(TCPConfig.MSG_GET_DATETIME),eid,null); } /** * 获取设备版本号类型MSG_GET_VERSION,只有消息头 * @param eid * @return */ public boolean msgGetVersion(int eid){ return sendMsg(mBaseApplication.getTCPClient(TCPConfig.SOCKET_CONFIG_PORT_3G), ConvertCodeUtility.short2Bytes(TCPConfig.MSG_GET_VERSION),eid,null); } /** * 重启设备请求类型MSG_RESET_REQ * @param eid * @param flag * 重启范围的标志位 * @return */ public boolean msgReset(int eid, byte flag){ byte[] data = new byte[1]; data[0] = flag; return sendMsg(mBaseApplication.getTCPClient(TCPConfig.SOCKET_CONFIG_PORT_3G), ConvertCodeUtility.short2Bytes(TCPConfig.MSG_RESET_REQ), eid, data); } /** * 获取小区参数请求类型MSG_GET_CELL_PARA_REQ,只有消息头 * @param eid * @return */ public boolean msgGetCellPara(int eid){ return sendMsg(mBaseApplication.getTCPClient(TCPConfig.SOCKET_CONFIG_PORT_3G), ConvertCodeUtility.short2Bytes(TCPConfig.MSG_GET_CELL_PARA_REQ),eid,null); } /** * 心跳回应类型MSG_HEARTBAT_ACK,只有消息头 * @param eid * @return */ public boolean msgHeartBatACK(int eid){ return sendMsg(mBaseApplication.getTCPClient(TCPConfig.SOCKET_CONFIG_PORT_3G), ConvertCodeUtility.short2Bytes(TCPConfig.MSG_HEARTBAT_ACK),eid,null); } /** * 设置小区的参数 * @return */ public boolean msgSetCellPara(int eid, CellBean cellBean,int flag,int type){ int rfcn = Integer.parseInt(cellBean.getFrequency());//频点 short tac = Short.parseShort(cellBean.getTac());//位置区 int tac_increase = Integer.parseInt(cellBean.getLac_period());//位置区更新周期 byte band = (byte) Integer.parseInt(cellBean.getBand());//频段 byte dianPing = (byte) Integer.parseInt(cellBean.getDianPing());//最小接入电平 byte power_rand = (byte) (20 - cellBean.getPower_down());//功率等级 byte[] data = new byte[22]; data[0] = 1; data[1] = (byte) flag; System.arraycopy(new byte[]{0,0},0,data,2,2); System.arraycopy(ConvertCodeUtility.int2Bytes(rfcn),0,data,4,4); System.arraycopy(ConvertCodeUtility.short2Bytes((short) 6),0,data,8,2); System.arraycopy(ConvertCodeUtility.short2Bytes(tac),0,data,10,2); System.arraycopy(ConvertCodeUtility.int2Bytes(tac_increase),0,data,12,4); data[16] = band; data[17] = (byte) type; data[18] = power_rand; data[19] = dianPing; System.arraycopy(ConvertCodeUtility.short2Bytes((short) 460),0,data,20,2); return sendMsg(mBaseApplication.getTCPClient(TCPConfig.SOCKET_CONFIG_PORT_3G), ConvertCodeUtility.short2Bytes(TCPConfig.MSG_SET_CELL_RFPARA_REQ),eid,data); } } ``` MainActivity.java ```package zed.com.layout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private ListView listView; private MyAdapter myAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); myAdapter = new MyAdapter(); listView.setAdapter(myAdapter); } private class MyAdapter extends BaseAdapter{ @Override public int getCount() { return 3; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = getLayoutInflater().inflate(R.layout.list_layout,null); TextView tv1 = (TextView) view.findViewById(R.id.tv1); TextView tv2 = (TextView) view.findViewById(R.id.tv2); TextView tv3 = (TextView) view.findViewById(R.id.tv3); TextView tv4 = (TextView) view.findViewById(R.id.tv4); TextView tv5 = (TextView) view.findViewById(R.id.tv5); tv1.setText("1234567891234567"); tv2.setText("1234567891234567"); tv3.setText("中国移动"); tv4.setText("1234-2-3 11:34:23"); tv5.setText("3"); return view; } } } ``` TCPConfig.java ```package com.zed.hotsport.TCP; /** * Created by Administrator on 2016/9/20. */ public class TCPConfig { //监听端口号 public static final int SOCKET_CONFIG_PORT_3G = 60001; //通信初始化请求类型 public static final short MSG_START_REQ = 1001; //通信初始化回应类型 public static final short MSG_START_ACK = 1002; //心跳请求类型 public static final short MSG_HEARTBEAT = 1321; //心跳回应 public static final short MSG_HEARTBAT_ACK = 1322; //小区参数配置类型 public static final short MSG_SET_CELL_RFPARA_REQ = 1011; //小区参数配置响应类型 public static final short MSG_SET_CELL_RFPARA_ACK = 1012; //小区参数查询类型 public static final short MSG_GET_CELL_PARA_REQ = 1013; //小区参数查询响应类型 public static final short MSG_GET_CELL_PARA_ACK = 1014; //设备重启请求类型 public static final short MSG_RESET_REQ = 1311; //设备重启响应类型 public static final short MSG_RESET_ACK = 1312; //小区重启请求类型 public static final short MSG_RESET_CELL_REQ = 1315; //小区重启响应类型 public static final short MSG_RESET_CELL_ACK = 1316; //数据上报类型 public static final short MSG_USERID_REPORT = 1130; //设备状态上报类型 public static final short MSG_STATE_REPORT = 1323; //设备告警上报类型 public static final short MSG_WARNING_IND = 2; //开关功放操作类型 public static final short MSG_PA_ONOFF_REQ = 1319; //开放功放响应类型 public static final short MSG_PA_ONOFF_ACK = 1320; //开关侦码操作类型 public static final short MSG_CATCHING_ONOFF_REQ = 1351; //开关侦码响应类型 public static final short MSG_CATCHING_ONOFF_ACK = 1352; //版本查询请求类型 public static final short MSG_GET_VERSION = 1317; //版本查询回应类型 public static final short MSG_GET_VERSION_ACK = 1318; //设置/同步设备时间 public static final short MSG_SET_DATETIME = 1003; //设置/同步设备时间响应 public static final short MSG_SET_DATETIME_ACK = 1004; //获取设备时间请求 public static final short MSG_GET_DATETIME = 1005; //获取设备时间响应 public static final short MSG_GET_DATETIME_ACK = 1006; } ``` BaseApplication.java ```package com.zed.hotsport.base; import android.app.Application; import android.util.Log; import com.zed.hotsport.TCP.TCPClient; import java.util.HashMap; import java.util.Map; /** * Created by Administrator on 2016/9/19. */ public final class BaseApplication extends Application{ public Map<Integer,TCPClient> mTCPClients = null; /** 当前连接设备ID **/ public static int CurrentEid = 0; public static boolean connect = false; /** * 存储已连接的对象 * @param port 连接端口号 * @param client 已连接的对象 */ public void setTCPClient(int port,TCPClient client){ if(mTCPClients==null){ Log.e("TAG","创建连接对象map集合"); mTCPClients = new HashMap<Integer, TCPClient>(); } mTCPClients.put(port,client); } /** * 获取已连接的对象 * @param port 连接端口号 * @return 连接对象 */ public TCPClient getTCPClient(int port){ TCPClient client = null; if(mTCPClients!=null){ client = mTCPClients.get(port); } return client; } /** * 移除连接客户端并关闭socket * @return 移除连接对象端口 */ public void removeClient(int port){ if(mTCPClients!=null){ Log.e("TAG","从全局类中得到连接客户端"); TCPClient client = mTCPClients.get(port); if(client!=null){ Log.e("TAG","从全局类中得到的连接客户端不为空"); client.closeSocket(client); mTCPClients.remove(port); } }else{ Log.e("TAG","连接对象为空"); } } public void setCurrentEid(int currentEid){ CurrentEid = currentEid; } public int getCurrentEid(){ return CurrentEid; } } ``` RightListAdapter.java ```package com.zed.hotsport.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.zed.hotsport.R; import com.zed.hotsport.bean.UserBean; import com.zed.hotsport.utils.ConvertCodeUtility; import java.util.ArrayList; /** * Created by Administrator on 2016/11/10. */ public class RightListAdapter extends BaseAdapter{ private Context context; private ArrayList<UserBean> data; public RightListAdapter(ArrayList<UserBean> userBeans, Context context){ this.context = context; this.data = userBeans; } @Override public int getCount() { return data.size(); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if(convertView == null){ viewHolder = new ViewHolder(); convertView = LayoutInflater.from(context).inflate(R.layout.list_layout,null); viewHolder.imei = (TextView) convertView.findViewById(R.id.tv2); viewHolder.operator = (TextView) convertView.findViewById(R.id.tv3); viewHolder.time = (TextView) convertView.findViewById(R.id.tv4); viewHolder.blackName = (TextView) convertView.findViewById(R.id.tv_name); viewHolder.TSM = (TextView) convertView.findViewById(R.id.tv_TSM); viewHolder.lac = (TextView) convertView.findViewById(R.id.tv_lac); viewHolder.power = (TextView) convertView.findViewById(R.id.tv_power); viewHolder.place = (TextView) convertView.findViewById(R.id.tv_place); viewHolder.phoneType = (TextView) convertView.findViewById(R.id.tv_type); convertView.setTag(viewHolder); }else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.imei.setText(data.get(position).getImei()); viewHolder.operator.setText(data.get(position).getOprerator()); viewHolder.blackName.setText(data.get(position).getBlackName()); String time = ConvertCodeUtility.getStrByDate(data.get(position).getTimer()).substring(11,19); viewHolder.time.setText(time); viewHolder.TSM.setText(data.get(position).getTSM()); viewHolder.lac.setText(data.get(position).getLac()); viewHolder.power.setText(data.get(position).getPower()); viewHolder.place.setText(data.get(position).getPlace()); viewHolder.phoneType.setText(data.get(position).getPhoneType()); return convertView; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } class ViewHolder{ TextView imei; TextView operator; TextView time; TextView blackName; TextView TSM; TextView lac; TextView power; TextView place; TextView phoneType; } public ArrayList<UserBean> getData() { return data; } public void setData(ArrayList<UserBean> data) { this.data = data; } } ``` BlackBean.java ```package com.zed.hotsport.bean; import java.io.Serializable; /** * Created by Administrator on 2016/11/9. */ public class BlackBean implements Serializable{ private String name; private String imsi; private String imei; private String esn; private String mac; private int flag; // 0表示黑名单,1表示白名单 // 对应于指定id的案件 public int c_id; public BlackBean(String name, String imsi, String imei, String esn, String mac, int flag) { this.name = name; this.imsi = imsi; this.imei = imei; this.esn = esn; this.mac = mac; this.flag = flag; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImsi() { return imsi; } public void setImsi(String imsi) { this.imsi = imsi; } public String getImei() { return imei; } public void setImei(String imei) { this.imei = imei; } public String getMac() { return mac; } public void setMac(String mac) { this.mac = mac; } public String getEsn() { return esn; } public void setEsn(String esn) { this.esn = esn; } public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } public int getC_id() { return c_id; } public void setC_id(int c_id) { this.c_id = c_id; } } ``` CatchSettingActivity.java ```package com.zed.hotsport.activity; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; import com.zed.hotsport.R; import com.zed.hotsport.TCP.TCPOutHelper; import com.zed.hotsport.base.BaseApplication; import com.zed.hotsport.base.Constant; import com.zed.hotsport.utils.ToastUtils; import butterknife.Bind; import butterknife.ButterKnife; public class CatchSettingActivity extends AppCompatActivity { @Bind(R.id.toolBar) Toolbar toolBar; @Bind(R.id.activity_catch_setting) LinearLayout activityCatchSetting; @Bind(R.id.all_tv_catch) TextView allTvCatch; @Bind(R.id.all_cb_catch) CheckBox allCbCatch; @Bind(R.id.dx_tv_catch) TextView dxTvCatch; @Bind(R.id.dx_cb_catch) CheckBox dxCbCatch; @Bind(R.id.lt_tv_catch) TextView ltTvCatch; @Bind(R.id.lt_cb_catch) CheckBox ltCbCatch; @Bind(R.id.mobile_tv_catch) TextView mobileTvCatch; @Bind(R.id.mobile_cb_catch) CheckBox mobileCbCatch; @Bind(R.id.mobile1_tv_catch) TextView mobile1TvCatch; @Bind(R.id.mobile1_cb_catch) CheckBox mobile1CbCatch; private SharedPreferences sp_catch_setting; private boolean allCB;//侦码是否选中 private boolean ltCB;//联通上报是否选中 private boolean dxCB;//电信上报是否选中 private boolean ydCB;//移动上报是否选中 private boolean yd1CB;//移动1上报是否选中 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_catch_setting); ButterKnife.bind(this); initToolBar(); initData(); intViewData(); } /** * 初始化控件数据 */ private void intViewData() { allCB = sp_catch_setting.getBoolean(Constant.ALLCATCH, true); ltCB = sp_catch_setting.getBoolean(Constant.LT_CATCH, true); dxCB = sp_catch_setting.getBoolean(Constant.DX_CATCH, true); ydCB = sp_catch_setting.getBoolean(Constant.YD_CATCH, true); yd1CB = sp_catch_setting.getBoolean(Constant.YD1_CATCH, true); if (!allCB) { allCbCatch.setChecked(false); allTvCatch.setText("总侦码开关已关闭"); allTvCatch.setTextColor(Color.RED); } else { allCbCatch.setChecked(true); allTvCatch.setText("总侦码开关已打开"); allTvCatch.setTextColor(getResources().getColor(R.color.color_0176da)); } if (!ltCB) { ltCbCatch.setChecked(false); ltTvCatch.setText("联通上报开关已关闭"); ltTvCatch.setTextColor(Color.RED); } else { ltCbCatch.setChecked(true); ltTvCatch.setText("联通上报开关已打开"); ltTvCatch.setTextColor(getResources().getColor(R.color.color_0176da)); } if (!dxCB) { dxCbCatch.setChecked(false); dxTvCatch.setText("电信上报开关已关闭"); dxTvCatch.setTextColor(Color.RED); } else { dxCbCatch.setChecked(true); dxTvCatch.setText("电信上报开关已打开"); dxTvCatch.setTextColor(getResources().getColor(R.color.color_0176da)); } if (!ydCB) { mobileCbCatch.setChecked(false); mobileTvCatch.setText("移动上报开关已关闭"); mobileTvCatch.setTextColor(Color.RED); } else { mobileCbCatch.setChecked(true); mobileTvCatch.setText("移动上报开关已打开"); mobileTvCatch.setTextColor(getResources().getColor(R.color.color_0176da)); } if (!yd1CB) { mobile1CbCatch.setChecked(false); mobile1TvCatch.setText("移动1上报开关已关闭"); mobile1TvCatch.setTextColor(Color.RED); } else { mobile1CbCatch.setChecked(true); mobile1TvCatch.setText("移动1上报开关已打开"); mobile1TvCatch.setTextColor(getResources().getColor(R.color.color_0176da)); } allCbCatch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (BaseApplication.connect) { SystemClock.sleep(200); if (allCB) { allCbCatch.setChecked(false); allTvCatch.setText("总侦码开关已关闭"); allTvCatch.setTextColor(Color.RED); TCPOutHelper.getInstance(CatchSettingActivity.this).msgSetAllCatch(BaseApplication.CurrentEid, (byte) 0); } else { allCbCatch.setChecked(true); allTvCatch.setText("总侦码开关已打开"); allTvCatch.setTextColor(getResources().getColor(R.color.color_0176da)); TCPOutHelper.getInstance(CatchSettingActivity.this).msgSetAllCatch(BaseApplication.CurrentEid, (byte) 1); } allCB = !allCB; sp_catch_setting.edit().putBoolean(Constant.ALLCATCH, allCB).commit(); } else { ToastUtils.showToast(CatchSettingActivity.this, "设备未连接,设置失败!", 0); } } }); ltCbCatch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (BaseApplication.connect) { SystemClock.sleep(200); if (ltCB) { ltCbCatch.setChecked(false); ltTvCatch.setText("联通上报开关已关闭"); ltTvCatch.setTextColor(Color.RED); TCPOutHelper.getInstance(CatchSettingActivity.this).msgSetPA(BaseApplication.CurrentEid,(byte)0,(byte)0); } else { ltCbCatch.setChecked(true); ltTvCatch.setText("联通上报开关已打开"); ltTvCatch.setTextColor(getResources().getColor(R.color.color_0176da)); TCPOutHelper.getInstance(CatchSettingActivity.this).msgSetPA(BaseApplication.CurrentEid,(byte)0,(byte)1); } ltCB = !ltCB; sp_catch_setting.edit().putBoolean(Constant.LT_CATCH, ltCB).commit(); } else { ToastUtils.showToast(CatchSettingActivity.this, "设备未连接,设置失败!", 0); } } }); dxCbCatch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (BaseApplication.connect) { SystemClock.sleep(200); if (dxCB) { dxCbCatch.setChecked(false); dxTvCatch.setText("电信上报开关已关闭"); dxTvCatch.setTextColor(Color.RED); TCPOutHelper.getInstance(CatchSettingActivity.this).msgSetPA(BaseApplication.CurrentEid,(byte)1,(byte)0); } else { dxCbCatch.setChecked(true); dxTvCatch.setText("电信上报开关已打开"); dxTvCatch.setTextColor(getResources().getColor(R.color.color_0176da)); TCPOutHelper.getInstance(CatchSettingActivity.this).msgSetPA(BaseApplication.CurrentEid,(byte)1,(byte)1); } dxCB = !dxCB; sp_catch_setting.edit().putBoolean(Constant.DX_CATCH, dxCB).commit(); } else { ToastUtils.showToast(CatchSettingActivity.this, "设备未连接,设置失败!", 0); } } }); mobileCbCatch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (BaseApplication.connect) { SystemClock.sleep(200); if (ydCB) { mobileCbCatch.setChecked(false); mobileTvCatch.setText("移动上报开关已关闭"); mobileTvCatch.setTextColor(Color.RED); TCPOutHelper.getInstance(CatchSettingActivity.this).msgSetPA(BaseApplication.CurrentEid,(byte)2,(byte)0); } else { mobileCbCatch.setChecked(true); mobileTvCatch.setText("移动上报开关已打开"); mobileTvCatch.setTextColor(getResources().getColor(R.color.color_0176da)); TCPOutHelper.getInstance(CatchSettingActivity.this).msgSetPA(BaseApplication.CurrentEid,(byte)2,(byte)1); } ydCB = !ydCB; sp_catch_setting.edit().putBoolean(Constant.YD_CATCH, ydCB).commit(); } else { ToastUtils.showToast(CatchSettingActivity.this, "设备未连接,设置失败!", 0); } } }); mobile1CbCatch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (BaseApplication.connect) { SystemClock.sleep(200); if (yd1CB) { mobile1CbCatch.setChecked(false); mobile1TvCatch.setText("移动1上报开关已关闭"); mobile1TvCatch.setTextColor(Color.RED); TCPOutHelper.getInstance(CatchSettingActivity.this).msgSetPA(BaseApplication.CurrentEid,(byte)3,(byte)0); } else { mobile1CbCatch.setChecked(true); mobile1TvCatch.setText("移动1上报开关已打开"); mobile1TvCatch.setTextColor(getResources().getColor(R.color.color_0176da)); TCPOutHelper.getInstance(CatchSettingActivity.this).msgSetPA(BaseApplication.CurrentEid,(byte)3,(byte)1); } yd1CB = !yd1CB; sp_catch_setting.edit().putBoolean(Constant.YD1_CATCH, yd1CB).commit(); } else { ToastUtils.showToast(CatchSettingActivity.this, "设备未连接,设置失败!", 0); } } }); } /** * 初始化数据 */ private void initData() { sp_catch_setting = getSharedPreferences(Constant.CATCH_SETTING, 0); } /** * 初始化ToolBar */ private void initToolBar() { toolBar.setNavigationIcon(R.mipmap.l_arrow); toolBar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CatchSettingActivity.this.finish(); } }); toolBar.setTitle("开关侦码设置");//设置主标题 toolBar.setTitleTextColor(getResources().getColor(R.color.color_f5f5f5)); toolBar.setTitleTextAppearance(this, R.style.ActionBarTitle); } } ``` TCPInputHelper.java ```package com.zed.hotsport.TCP; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Parcelable; import android.util.Log; import com.zed.hotsport.activity.CatchSettingActivity; import com.zed.hotsport.base.BaseApplication; import com.zed.hotsport.base.Constant; import com.zed.hotsport.bean.UserBean; import com.zed.hotsport.utils.ByteToString; import com.zed.hotsport.utils.ConvertCodeUtility; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.Socket; import java.util.ArrayList; import java.util.Date; import java.util.Timer; import java.util.TimerTask; /** * Socket读取工具类 * Created by Administrator on 2016/9/19. */ public class TCPInputHelper { private final String TAG = "SocketInputHelper"; // log标签 private static TCPInputHelper mTCPInputHelper = null;//自身实例 private BaseApplication mBaseApplication = null; /** 心跳更新时间 **/ private static long mHeartBeatTime = 0L; private Context context = null;//上下文 private int mTargetPort;//端口号 private int eid = 0; private byte[] mBuffer = null; private Timer mTimer = null; private TimerTask task = null; private static SharedPreferences sp_device_status; private static SharedPreferences sp_catch_setting; private static SharedPreferences sp_device_para; private TCPInputHelper(Context context, int port) { this.context = context; this.mTargetPort = port; mBaseApplication = (BaseApplication) context.getApplicationContext(); this.mBuffer = new byte[0]; } public static TCPInputHelper getInstance(Context context, int port) { if (mTCPInputHelper == null) { mTCPInputHelper = new TCPInputHelper(context, port); sp_device_status = context.getSharedPreferences(Constant.DEVICE_STATUS,0); sp_catch_setting = context.getSharedPreferences(Constant.CATCH_SETTING,0); sp_device_para = context.getSharedPreferences(Constant.DEVICE_PARA,0); } return mTCPInputHelper; } /** * 解读Socket消息方法,只解析消息头数据,并调用分发消息方法 * * @param socket 已建链的通信通道 */ public void readSocket(Socket socket) { try { InputStream is = socket.getInputStream(); byte[] data; if (is.available() > 0) { byte[] buffer = new byte[1024 * 3]; int length = is.read(buffer); data = ConvertCodeUtility.subByteArr(buffer, 0, length); Log.e("TAG", "消息总的长度为" + data.length); String sss = ByteToString.Byte2String(data); Log.e("收到总的数据:", sss); Log.e("数据的长度字节",ByteToString.Byte2String(ConvertCodeUtility.subByteArr(data,0,2))); Log.e("数据的长度的十六进制字节",ConvertCodeUtility.byteArrayToHex(ConvertCodeUtility.subByteArr(data,0,2))); Log.e("数据的命令字节:",ByteToString.Byte2String(ConvertCodeUtility.subByteArr(data,2,2))); Log.e("数据的命令十六进制字节:",ConvertCodeUtility.byteArrayToHex(ConvertCodeUtility.subByteArr(data,2,2))); Log.e("设备编号字节:",ByteToString.Byte2String(ConvertCodeUtility.subByteArr(data,4,4))); Log.e("设备编号十六进制字节:",ConvertCodeUtility.byteArrayToHex(ConvertCodeUtility.subByteArr(data,4,4))); //这里的逻辑是由于心跳消息只有消息头,没有消息体 if (data.length <= 8) { Log.e("TAG", "得到的数据长度小于8的消息总的长度为" + ConvertCodeUtility.bytes2Short(ConvertCodeUtility .subByteArr(data, 0, 2))); byte[] type = ConvertCodeUtility.subByteArr(data, 2, 2); short msgType = ConvertCodeUtility.bytes2Short(type); Log.e("TAG", "得到的数据长度小于8的命令:" + msgType); if (data != null) { String ss = ByteToString.Byte2String(data); Log.e("得到的数据长度小于8的数据体:", ss); } if(msgType == 1321){//如果是心跳消息 handHeartBeat(); } return; } Log.e("TAG", "开始解析数据"); Log.e("得到的总数据的十六进制字节", ConvertCodeUtility.byteArrayToHex(data)); parseStreamDataBytes(data); } } catch (IOException e) { e.printStackTrace(); } } /** * 初始化建链状态检测定时器 */ protected void startHeartBeatTimer() { this.mTimer = new Timer(); task = new TimerTask() { @Override public void run() { long newTime = System.currentTimeMillis(); // 若超过90s未更新时间,则判定为断链 Log.e("+++++++++","lte心跳!"+newTime+"mHeartBeatTime"+mHeartBeatTime+"相差时间:"+(newTime - mHeartBeatTime)); if (newTime - mHeartBeatTime >= 1000*3) { Log.e("!!!!!!!!!!!!!!!!!!!!!!!", "lte断开连接了!"); mTimer.cancel(); task.cancel(); } } }; this.mTimer.schedule(task, 1000, 1000); } /** * 取消心跳检测 */ protected void stopHeartBeatTimer() { if (mTimer != null) { mTimer.cancel(); if (task != null) { task.cancel(); } } } /** * 解析缓存及流中的字节数据,并分发处理 * * @param bytes 流中的字节数组 */ private void parseStreamDataBytes(byte[] bytes) { if (bytes == null) { //将流中的字节复制进缓存容器 int copyIndex = mBuffer.length; mBuffer = new byte[mBuffer.length + bytes.length]; System.arraycopy(bytes, 0, mBuffer, copyIndex, bytes.length); Log.e("TAG", "消息总的长度为" + mBuffer.length); } //得到码流的事件类型字节数组 byte[] type = ConvertCodeUtility.subByteArr(bytes, 2, 2); //当前设备ID eid = ConvertCodeUtility.bytes2Int(ConvertCodeUtility.subByteArr(bytes, 4, 4)); mBaseApplication.CurrentEid = eid; short msgType = ConvertCodeUtility.bytes2Short(type); Log.e("TAG", "命令" + msgType); //这里处理的逻辑是由于有的消息得到的长度大于8个,但是是心跳 if(msgType == 1321){ handHeartBeat(); return; } //消息体长度 = 消息总长度 - 消息头长度(8byte) if (ConvertCodeUtility.bytes2Short(ConvertCodeUtility .subByteArr(bytes, 0, 2)) == 0) { return; } int dataLength = ConvertCodeUtility.bytes2Short(ConvertCodeUtility .subByteArr(bytes, 0, 2)) - 8; Log.e("TAG", "消息体的长度为" + dataLength); byte[] data = ConvertCodeUtility .subByteArr(bytes, 8, dataLength); if (data != null) { String ss = ByteToString.Byte2String(data); Log.e("收到数据体:", ss); } //分发消息 dispatchMsg(msgType, data); } /** * 根据消息类型,交给指定的方法去处理 * * @param msgType 消息类型 * @param data 消息体 */ private void dispatchMsg(short msgType, byte[] data) { switch (msgType) { case TCPConfig.MSG_START_REQ://通讯初始化 handStartReq(data); break; case TCPConfig.MSG_HEARTBEAT://心跳上报 handHeartBeat(); break; case TCPConfig.MSG_SET_CELL_RFPARA_ACK://设置小区参数回应 handSetCellParaAck(data); break; case TCPConfig.MSG_RESET_ACK://设备重启响应 handResetAck(data); break; case TCPConfig.MSG_GET_CELL_PARA_ACK://获取小区参数响应 handGetCellParaAck(data); break; case TCPConfig.MSG_USERID_REPORT://数据上报 handUserReport(data); break; case TCPConfig.MSG_STATE_REPORT://状态上报 handStateReport(data); break; case TCPConfig.MSG_PA_ONOFF_ACK://小区功率开关设置回应 handPAOnOffACK(data); break; case TCPConfig.MSG_CATCHING_ONOFF_ACK://侦码开关设置回应 handCatchOnOffACK(data); break; case TCPConfig.MSG_GET_VERSION_ACK://版本查询上报回应 handGetVersionACK(data); break; case TCPConfig.MSG_GET_DATETIME_ACK://获取设备时间响应 handGetDateTimeACK(); break; case TCPConfig.MSG_SET_DATETIME_ACK://设置设备时间响应 handSetDateTimeACK(); break; } } /** * 设置时间响应 */ private void handSetDateTimeACK() { } /** * 心跳请求处理 */ private void handHeartBeat() { mHeartBeatTime = System.currentTimeMillis(); //在这里回应心跳请求 TCPOutHelper.getInstance(context).msgHeartBatACK( eid); Log.e("TAG","回应心跳"); } /** * 获取小区配置参数响应 * @param data */ private void handGetCellParaAck(byte[] data) { Log.e("TAG+++_____++++++++++++","获取小区参数数据体的十六进制字节"+ConvertCodeUtility.byteArrayToHex(data)); //有效小区的个数 int count = (int)data[4]; Log.e("TAG","有效小区的个数:"+count); for(int i = 0;i < count;i++){ byte[] partData = ConvertCodeUtility.subByteArr(data,21*i + 5,21); //小区编号 int cellId = partData[0]; //预留 byte[] reserve = ConvertCodeUtility.subByteArr(partData,1,2); //频点 byte[] rfcn = ConvertCodeUtility.subByteArr(partData,3,4); //物理小区(PCI) byte[] pci = ConvertCodeUtility.subByteArr(partData,7,2); //位置区(TAC) byte[] tac = ConvertCodeUtility.subByteArr(partData,9,2); //TAC自增周期 byte[] tac_increase = ConvertCodeUtility.subByteArr(partData,11,4); //频段 byte band = partData[15]; //运营商号 byte operator = partData[16]; //设备功率级别 byte power = partData[17]; //最小接入电平 byte dianPing = partData[18]; //国家码 byte[] countryMark = ConvertCodeUtility.subByteArr(partData,19,2); if(cellId == 0){//联通 sp_device_para.edit().putString(Constant.LT_FREQUENCY,ConvertCodeUtility.bytes2Int(rfcn)+"").commit(); sp_device_para.edit().putString(Constant.LT_FREQUENCY1,ConvertCodeUtility.bytes2Int(rfcn)+"").commit(); sp_device_para.edit().putString(Constant.LT_TAC,ConvertCodeUtility.bytes2Short(tac)+"").commit(); sp_device_para.edit().putString(Constant.LT_TAC_PERIOD,ConvertCodeUtility.bytes2Int(tac_increase)+"").commit(); sp_device_para.edit().putString(Constant.LT_BAND,(int)band+"").commit(); sp_device_para.edit().putString(Constant.LT_DIANPING,(int)dianPing+"").commit(); sp_device_para.edit().putInt(Constant.LT_DESCEND,20 - (int)power).commit(); }else if(cellId == 1){//电信 sp_device_para.edit().putString(Constant.DX_FREQUENCY,ConvertCodeUtility.bytes2Int(rfcn)+"").commit(); sp_device_para.edit().putString(Constant.DX_FREQUENCY1,ConvertCodeUtility.bytes2Int(rfcn)+"").commit(); sp_device_para.edit().putString(Constant.DX_TAC,ConvertCodeUtility.bytes2Short(tac)+"").commit(); sp_device_para.edit().putString(Constant.DX_TAC_PERIOD,ConvertCodeUtility.bytes2Int(tac_increase)+"").commit(); sp_device_para.edit().putString(Constant.DX_BAND,(int)band+"").commit(); sp_device_para.edit().putString(Constant.DX_DIANPING,(int)dianPing+"").commit(); sp_device_para.edit().putInt(Constant.DX_DESCEND,20 - (int)power).commit(); }else if(cellId == 2){//移动 sp_device_para.edit().putString(Constant.MOBILE_FREQUENCY,ConvertCodeUtility.bytes2Int(rfcn)+"").commit(); sp_device_para.edit().putString(Constant.MOBILE_FREQUENCY1,ConvertCodeUtility.bytes2Int(rfcn)+"").commit(); sp_device_para.edit().putString(Constant.MOBILE_TAC,ConvertCodeUtility.bytes2Short(tac)+"").commit(); sp_device_para.edit().putString(Constant.MOBILE_TAC_PERIOD,ConvertCodeUtility.bytes2Int(tac_increase)+"").commit(); sp_device_para.edit().putString(Constant.MOBILE_BAND,(int)band+"").commit(); sp_device_para.edit().putString(Constant.MOBILE_DIANPING,(int)dianPing+"").commit(); sp_device_para.edit().putInt(Constant.MOBILE_DESCEND,20 - (int)power).commit(); }else if(cellId == 3){//移动1 sp_device_para.edit().putString(Constant.MOBILE1_FREQUENCY,ConvertCodeUtility.bytes2Int(rfcn)+"").commit(); sp_device_para.edit().putString(Constant.MOBILE1_FREQUENCY1,ConvertCodeUtility.bytes2Int(rfcn)+"").commit(); sp_device_para.edit().putString(Constant.MOBILE1_TAC,ConvertCodeUtility.bytes2Short(tac)+"").commit(); sp_device_para.edit().putString(Constant.MOBILE1_TAC_PERIOD,ConvertCodeUtility.bytes2Int(tac_increase)+"").commit(); sp_device_para.edit().putString(Constant.MOBILE1_BAND,(int)band+"").commit(); sp_device_para.edit().putString(Constant.MOBILE1_DIANPING,(int)dianPing+"").commit(); sp_device_para.edit().putInt(Constant.MOBILE1_DESCEND,20 - (int)power).commit(); } } Intent intent = new Intent(TCPAction.ACTION_PARA); context.sendBroadcast(intent); } /** * 设备上报状态 * * @param data */ private void handStateReport(byte[] data) { Log.e("得到上报状态消息体的十六进制字节",ConvertCodeUtility.byteArrayToHex(data)); //有效小区的个数 int count = (int)data[10]; Log.e("TAG","状态上报中有效小区的个数:"+count); //设备CPU使用率 byte deviceCpu = data[0]; sp_device_status.edit().putString(Constant.CPU_STATUS,(int)deviceCpu+"%").commit(); //设备内存使用率 byte deviceMemory = data[1]; sp_device_status.edit().putString(Constant.MEMORY_STATUS,(int)deviceMemory+"%").commit(); //设备温度 byte deviceWenDu = data[3]; sp_device_status.edit().putString(Constant.WENDU,(int)deviceWenDu+" 度").commit(); //侦码开关状态 byte catchStatus = data[11]; sp_device_status.edit().putString(Constant.CATCH_STATUS,(int)catchStatus+"").commit(); for(int i = 0;i < count;i++){ byte[] partData = ConvertCodeUtility.subByteArr(data,10*i+16,10); //小区编号 int cellId = partData[0]; //小区状态 byte cellStatus = partData[1]; //功放状态 byte cellPaStatus = partData[2]; //功率衰减值 byte cellPaDown = partData[3]; //功率输出值 byte cellPa = partData[4]; if(cellId == 0){//联通 sp_device_status.edit().putString(Constant.LT_CELL_STATUS, (int)cellStatus == 0 ? "未就绪" : "就绪").commit(); sp_device_status.edit().putString(Constant.LT_PA_STATUS, (int)cellPaStatus == 0 ? "关" : "开").commit(); sp_device_status.edit().putString(Constant.LT_PA_DOWN,(int)cellPaDown+"").commit(); sp_device_status.edit().putString(Constant.LT_PA_POWER,(int)cellPa+"").commit(); }else if(cellId == 1){//电信 sp_device_status.edit().putString(Constant.DX_CELL_STATUS, (int)cellStatus == 0 ? "未就绪" : "就绪").commit(); sp_device_status.edit().putString(Constant.DX_PA_STATUS, (int)cellPaStatus == 0 ? "关" : "开").commit(); sp_device_status.edit().putString(Constant.DX_PA_DOWN,(int)cellPaDown+"").commit(); sp_device_status.edit().putString(Constant.DX_PA_POWER,(int)cellPa+"").commit(); }else if(cellId == 2){//移动 sp_device_status.edit().putString(Constant.MOBILE_CELL_STATUS, (int)cellStatus == 0 ? "未就绪" : "就绪").commit(); sp_device_status.edit().putString(Constant.MOBILE_PA_STATUS, (int)cellPaStatus == 0 ? "关" : "开").commit(); sp_device_status.edit().putString(Constant.MOBILE_PA_DOWN,(int)cellPaDown+"").commit(); sp_device_status.edit().putString(Constant.MOBILE_PA_POWER,(int)cellPa+"").commit(); }else if(cellId == 3){//移动1 sp_device_status.edit().putString(Constant.MOBILE1_CELL_STATUS, (int)cellStatus == 0 ? "未就绪" : "就绪").commit(); sp_device_status.edit().putString(Constant.MOBILE1_PA_STATUS, (int)cellPaStatus == 0 ? "关" : "开").commit(); sp_device_status.edit().putString(Constant.MOBILE1_PA_DOWN,(int)cellPaDown+"").commit(); sp_device_status.edit().putString(Constant.MOBILE1_PA_POWER,(int)cellPa+"").commit(); } } Intent intent = new Intent(TCPAction.ACTTON_STATUS); context.sendBroadcast(intent); } /** * 获取设备系统时间 */ private void handGetDateTimeACK() { } /** * 获取设备版本号 */ private void handGetVersionACK(byte[] data) { Log.e("TAG","获取版本号"); Log.e("版本号数据体十六字节表示:",ConvertCodeUtility.byteArrayToHex(data)); byte[] versionByte = ConvertCodeUtility.subByteArr(data,4,data.length-4); String version = new String(versionByte); Log.e("TAG","版本号:"+version); Intent intent = new Intent(TCPAction.ACTTON_VERSION); intent.putExtra("VERSION",version); context.sendBroadcast(intent); } /** * 设备总开关侦码响应 */ private void handCatchOnOffACK(byte[] data) { } /** * 各个小区开关功放响应 */ private void handPAOnOffACK(byte[] data) { } /** * 设置小区配置参数响应 */ private void handSetCellParaAck(byte[] data) { } /** * 重启响应 * * @param data */ private void handResetAck(byte[] data) { } /** * 数据上报 * * @param data */ private void handUserReport(byte[] data) { ArrayList<UserBean> users = new ArrayList<>(); int count = ConvertCodeUtility.bytes2Int(ConvertCodeUtility.subByteArr(data,0,4)); Log.e("TAG","得到的数据个数:"+count); for(int i = 0;i < count; i++){ byte[] mData = ConvertCodeUtility.subByteArr(data,42*i+4,42); //序列号 byte[] sequenceByte = ConvertCodeUtility.subByteArr(mData, 0, 4); //上号时间戳 byte[] TimeStampByte = ConvertCodeUtility.subByteArr(mData, 4, 4); //临时身份 byte[] tempTypeByte = ConvertCodeUtility.subByteArr(mData, 8, 1); //IMSI byte[] IMSIByte = ConvertCodeUtility.subByteArr(mData, 9, 8); //IMEI byte[] IMEIByte = ConvertCodeUtility.subByteArr(mData, 17, 8); //2G/3G数据域临时身份 byte[] TMSIByte = ConvertCodeUtility.subByteArr(mData, 25, 4); //国家码 byte[] MCCByte = ConvertCodeUtility.subByteArr(mData, 29, 2); //运营商码 byte[] MNC = ConvertCodeUtility.subByteArr(mData, 31, 1); //MME组ID byte[] MMEIDByte = ConvertCodeUtility.subByteArr(mData, 32, 2); //MME代码 byte[] MMECodeByte = ConvertCodeUtility.subByteArr(mData, 34, 1); //MME临时身份 byte[] MMETypeByte = ConvertCodeUtility.subByteArr(mData, 35, 4); //TAC号码 byte[] TACByte = ConvertCodeUtility.subByteArr(mData, 39, 2); //基站内小区编号 byte[] CellIDByte = ConvertCodeUtility.subByteArr(mData, 41, 1); Log.e("TAG","IMSI的十六进制字节:"+ConvertCodeUtility.byteArrayToHex(IMSIByte)); Log.e("TAG","IMEI的十六进制字节:"+ConvertCodeUtility.byteArrayToHex(IMEIByte)); String IMSI = ConvertCodeUtility.bcd2String(IMSIByte).substring(1); String IMEI = ConvertCodeUtility.bcd2String(IMEIByte).substring(1); Log.e("TAG","IMSI:"+IMSI); Log.e("TAG","IMEI:"+IMEI); Date timeStamp = new Date(ConvertCodeUtility.bytes2Int(TimeStampByte)); Log.e("得到的时间:",ConvertCodeUtility.getStrByDate(timeStamp)); //运营商 int MNCType = MNC[0]; Log.e("此条数据的运营商的编号:",MNCType+""); //基站内小区的编号 int cellId = CellIDByte[0]; Log.e("此条数据所在小区的编号:",cellId+""); UserBean user = new UserBean(); user.setImsi(IMSI); user.setImei(IMEI); user.setTimer(timeStamp); if(MNCType==0){ user.setOprerator("中国移动"); }else if(MNCType==1){ user.setOprerator("中国联通"); }else if(MNCType==11){ user.setOprerator("中国电信"); } users.add(user); } Intent intent = new Intent(TCPAction.ACTION_CATCH); intent.putExtra("USERS", users); context.sendBroadcast(intent); } /** * 通讯初始化请求 * * @param data */ private void handStartReq(byte[] data) { /*Log.i(TAG, "设备ID:" + String.valueOf(eid)); //设备号不存在 if(eid!=1){ //发送设备不存在的请求 TCPOutHelper.getInstance(context).msgStartAck(eid, 1); Log.i(TAG,"设备号不存在!"); return; }else{ boolean flag = TCPOutHelper.getInstance(context).msgStartAck( eid, 0); if (flag) {//通讯成功后就发起采集请求 TCPOutHelper.getInstance(context).msgStartRF(eid, (byte) 1,(byte) 1); } }*/ TCPOutHelper.getInstance(context).msgStartAck(eid, 0); BaseApplication.connect = true; //打开侦码开关和各个小区的功率 TCPOutHelper.getInstance(context).msgSetAllCatch(BaseApplication.CurrentEid,(byte)1); TCPOutHelper.getInstance(context).msgSetPA(BaseApplication.CurrentEid,(byte)0,(byte)1); TCPOutHelper.getInstance(context).msgSetPA(BaseApplication.CurrentEid,(byte)1,(byte)1); TCPOutHelper.getInstance(context).msgSetPA(BaseApplication.CurrentEid,(byte)2,(byte)1); TCPOutHelper.getInstance(context).msgSetPA(BaseApplication.CurrentEid,(byte)3,(byte)1); sp_catch_setting.edit().putBoolean(Constant.ALLCATCH,true).commit(); sp_catch_setting.edit().putBoolean(Constant.LT_CATCH,true).commit(); sp_catch_setting.edit().putBoolean(Constant.DX_CATCH,true).commit(); sp_catch_setting.edit().putBoolean(Constant.YD_CATCH,true).commit(); sp_catch_setting.edit().putBoolean(Constant.YD1_CATCH,true).commit(); Intent intent = new Intent(TCPAction.ACTTON_START); context.sendBroadcast(intent); } /** * 取消心跳检测 */ public void stopTimer() { } } ``` MainActivity.java ```package com.zed.hotsport.activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.zed.hotsport.R; import com.zed.hotsport.TCP.TCPAction; import com.zed.hotsport.TCP.TCPService; import com.zed.hotsport.adapter.LeftListAdapter; import com.zed.hotsport.adapter.RightListAdapter; import com.zed.hotsport.base.BaseApplication; import com.zed.hotsport.base.Constant; import com.zed.hotsport.bean.UserBean; import com.zed.hotsport.utils.ToastUtils; import com.zed.hotsport.utils.UtilTools; import com.zed.hotsport.view.SyncHorizontalScrollView; import java.util.ArrayList; import java.util.Date; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ @Bind(R.id.toolBar) Toolbar toolBar; @Bind(R.id.tv1_click) TextView tv1Click; @Bind(R.id.tv2_click) TextView tv2Click; @Bind(R.id.tv3_click) TextView tv3Click; @Bind(R.id.tv_timer) TextView tvTimer; @Bind(R.id.tv_name) TextView tvName; @Bind(R.id.tv_TMS) TextView tvTMS; @Bind(R.id.tv_lac) TextView tvLac; @Bind(R.id.tv_power) TextView tvPower; @Bind(R.id.tv_place) TextView tvPlace; @Bind(R.id.tv_type) TextView tvType; @Bind(R.id.myScrollView) SyncHorizontalScrollView myScrollView; @Bind(R.id.listView1) ListView listView1; @Bind(R.id.container1) LinearLayout container1; @Bind(R.id.listView2) ListView listView2; @Bind(R.id.container2) LinearLayout container2; @Bind(R.id.container_scrollView) SyncHorizontalScrollView containerScrollView; private LeftListAdapter leftListAdapter; private RightListAdapter rightListAdapter; private LayoutInflater inflater; private String[] items; private ArrayList<UserBean> users = new ArrayList<>(); private Intent tcpService; private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(TCPAction.ACTION_CATCH)) {//上报广播 ArrayList<UserBean> list = intent.getParcelableArrayListExtra("USERS"); for(int i = 0;i<list.size();i++){ users.add(0,list.get(i)); } leftListAdapter.notifyDataSetChanged(); rightListAdapter.notifyDataSetChanged(); UtilTools.setListViewHeightBasedOnChildren(listView1); UtilTools.setListViewHeightBasedOnChildren(listView2); ToastUtils.showToast(MainActivity.this,"上报数据",0); } if(action.equals(TCPAction.ACTTON_CESHI)){ ToastUtils.showToast(MainActivity.this,"链路打通,得到目标Socket",0); } if(action.equals(TCPAction.ACTTON_START)){ ToastUtils.showToast(MainActivity.this,"通讯初始化成功",0); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getSupportActionBar() != null) { getSupportActionBar().hide(); } setContentView(R.layout.activity_main); ButterKnife.bind(this); //设置两个水平控件的联动 myScrollView.setScrollView(containerScrollView); containerScrollView.setScrollView(myScrollView); initToolBar(); initData(); initReceiver(); //开始TCP通讯 startTCPService(); initListener(); } /** * 注册长按监听 */ private void initListener() { listView1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { showItemDialog(position); return true; } }); listView2.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { showItemDialog(position); return true; } }); } private void showItemDialog(int position) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(which == 0){//添加至黑名单 }else if(which == 1){//添加至白名单 } } }); builder.create().show(); } private void startTCPService() { Log.e("TAG","开启服务"); tcpService = new Intent(this, TCPService.class); startService(tcpService); } private void stopTCPService() { Log.e("TAG","销毁服务"); stopService(tcpService); } private void initReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(TCPAction.ACTION_CATCH); filter.addAction(TCPAction.ACTTON_CESHI); filter.addAction(TCPAction.ACTTON_START); registerReceiver(receiver, filter); } private void initData() { inflater = getLayoutInflater(); items = new String[]{"添加至黑名单","添加至白名单"}; for (int i = 0;i < 20;i++){ // addUser(); } leftListAdapter = new LeftListAdapter(users,MainActivity.this); rightListAdapter = new RightListAdapter(users,MainActivity.this); listView1.setAdapter(leftListAdapter); UtilTools.setListViewHeightBasedOnChildren(listView1); listView2.setAdapter(rightListAdapter); UtilTools.setListViewHeightBasedOnChildren(listView2); } private void initToolBar() { toolBar.setNavigationIcon(R.mipmap.l_arrow); toolBar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showExitDialog(); } }); toolBar.setTitle("4G热点侦码");//设置主标题 toolBar.setTitleTextColor(getResources().getColor(R.color.color_f5f5f5)); toolBar.setTitleTextAppearance(this, R.style.ActionBarTitle); toolBar.inflateMenu(R.menu.base_toolbar_menu); toolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { int menuId = item.getItemId(); switch (menuId) { case R.id.action_setting://参数配置界面 Intent setActivity = new Intent(MainActivity.this, SetActivity.class); startActivity(setActivity); break; case R.id.action_black://黑名单界面 Intent blackActivity = new Intent(MainActivity.this, BlackActivity.class); startActivity(blackActivity); break; case R.id.action_device_state://设备状态界面 Intent deviceActivity = new Intent(MainActivity.this,DeviceStatusActivity.class); startActivity(deviceActivity); break; case R.id.action_version_query://版本查询界面 Intent versionActivity = new Intent(MainActivity.this,VersionQueryActivity.class); startActivity(versionActivity); break; case R.id.action_catch_setting://开关侦码设置界面 Intent catchSettingActivity = new Intent(MainActivity.this,CatchSettingActivity.class); startActivity(catchSettingActivity); break; } return true; } }); } /** * 添加上报的信息(假数据) */ private void addUser() { UserBean userBean = new UserBean(); userBean.setImsi("12345678945612"); userBean.setImei("12345667895465"); userBean.setBlackName("张三"); userBean.setLac("123"); userBean.setOprerator("中国移动"); userBean.setPhoneType("苹果8plus"); userBean.setPlace("火星内核"); userBean.setPower("45db"); userBean.setTSM("455"); userBean.setTimer(new Date(System.currentTimeMillis())); users.add(0,userBean); } @OnClick({R.id.tv1_click, R.id.tv2_click, R.id.tv3_click, R.id.tv_timer, R.id.tv_name, R.id.tv_TMS, R.id.tv_lac, R.id.tv_power, R.id.tv_place, R.id.tv_type}) public void onClick(View view) { switch (view.getId()) { case R.id.tv1_click: break; case R.id.tv2_click: break; case R.id.tv3_click: break; case R.id.tv_timer: break; case R.id.tv_name: break; case R.id.tv_TMS: break; case R.id.tv_lac: break; case R.id.tv_power: break; case R.id.tv_place: break; case R.id.tv_type: break; } } @Override public void onBackPressed() { showExitDialog(); } /** * 退出界面的提示 */ private void showExitDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage("是否确定退出?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MainActivity.this.finish(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); builder.create().show(); } @Override protected void onDestroy() { super.onDestroy(); BaseApplication.connect = false; unregisterReceiver(receiver); stopTCPService(); //清除保存设备状态的数据 SharedPreferences sp_device_status = getSharedPreferences(Constant.DEVICE_STATUS,0); sp_device_status.edit().clear().commit(); } } ``` TCPAction.java ```package com.zed.hotsport.TCP; /** * Created by Administrator on 2016/9/22. */ public class TCPAction { /** 抓号 */ public static final String ACTION_CATCH = "ACTION_CATCH"; public static final String ACTTON_CESHI = "ACTTON_CESHI"; /** 通讯初始化 */ public static final String ACTTON_START = "ACTTON_START"; /** 状态上报 */ public static final String ACTTON_STATUS = "ACTTON_STATUS"; /** 版本上报 */ public static final String ACTTON_VERSION = "ACTTON_VERSION"; /** 设备参数上报 */ public static final String ACTION_PARA = "ACTION_PARA"; } ``` Constant.java ```package com.zed.hotsport.base; /** * Created by Administrator on 2016/11/15. */ public class Constant { public static final String DEVICE_PARA = "device_para";//存储设备参数的sp名称 public static final String DEVICE_STATUS = "device_status";//存储设备状态的sp名称 public static final String CATCH_SETTING = "catch_setting";//存储侦码开关和上报开关的sp名称 public static final String SELECTALL_CB = "select_all_cb";//参数设置选择全部小区 public static final String LT_SETTING_CB = "lt_setting_cb";//联通设置选择框 public static final String DX_SETTING_CB = "dx_setting_cb";//电信设置选择框 public static final String YD_SETTING_CB = "yd_setting_cb";//移动设置选择框 public static final String YD1_SETTING_CB = "yd1_setting_cb";//移动1设置选择框 public static final String LT_FREQUENCY = "lt_frequency";//联通频点 public static final String LT_SCRAMBLE = "lt_scramble";//联通扰码 public static final String LT_DESCEND = "lt_descend";//联通衰减值 public static final String LT_POWER_RAND = "lt_power_rand";//联通功率等级 public static final String LT_TAC = "lt_tac";//联通TAC public static final String LT_TAC_PERIOD = "lt_tac_period";//联通TAC周期 public static final String LT_CDX = "lt_cdx";//联通重定向 public static final String LT_BAND = "lt_band";//联通频段 public static final String LT_FREQUENCY1 = "lt_frequency1";//联通频点 public static final String LT_DIANPING = "lt_dianping";//联通最小接入电平 public static final String DX_FREQUENCY = "dx_frequency";//电信频点 public static final String DX_SCRAMBLE = "dx_scramble";//电信扰码 public static final String DX_DESCEND = "dx_descend";//电信衰减值 public static final String DX_POWER_RAND = "dx_power_rand";//电信功率等级 public static final String DX_TAC = "dx_tac";//电信TAC public static final String DX_TAC_PERIOD = "dx_tac_period";//电信TAC周期 public static final String DX_CDX = "dx_cdx";//电信重定向 public static final String DX_BAND = "dx_band";//电信频段 public static final String DX_FREQUENCY1 = "dx_frequency1";//电信频点 public static final String DX_DIANPING = "dx_dianping";//电信最小接入电平 public static final String MOBILE_FREQUENCY = "mobile_frequency";//移动频点 public static final String MOBILE_SCRAMBLE = "mobile_scramble";//移动扰码 public static final String MOBILE_DESCEND = "mobile_descend";//移动衰减值 public static final String MOBILE_POWER_RAND = "mobile_power_rand";//移动功率等级 public static final String MOBILE_TAC = "mobile_tac";//移动TAC public static final String MOBILE_TAC_PERIOD = "mobile_tac_period";//移动TAC周期 public static final String MOBILE_CDX = "mobile_cdx";//移动重定向 public static final String MOBILE_BAND = "mobile_band";//移动频段 public static final String MOBILE_FREQUENCY1 = "mobile_frequency1";//移动频点 public static final String MOBILE_DIANPING = "mobile_dianping";//移动最小接入电平 public static final String MOBILE1_FREQUENCY = "mobile1_frequency";//移动1频点 public static final String MOBILE1_SCRAMBLE = "mobile1_scramble";//移动1扰码 public static final String MOBILE1_DESCEND = "mobile1_descend";//移动1衰减值 public static final String MOBILE1_POWER_RAND = "mobile1_power_rand";//移动1功率等级 public static final String MOBILE1_TAC = "mobile1_tac";//移动1TAC public static final String MOBILE1_TAC_PERIOD = "mobile1_tac_period";//移动1TAC周期 public static final String MOBILE1_CDX = "mobile1_cdx";//移动1重定向 public static final String MOBILE1_BAND = "mobile1_band";//移动1频段 public static final String MOBILE1_FREQUENCY1 = "mobile1_frequency1";//移动1频点 public static final String MOBILE1_DIANPING = "mobile1_dianping";//移动1最小接入电平 public static final String CPU_STATUS = "cpu_status";//设备cpu占有率 public static final String MEMORY_STATUS = "memory_status";//设备内存占有率 public static final String WENDU = "wendu";//设备温度 public static final String CATCH_STATUS = "catch_status";//设备侦码开关状态 public static final String LT_CELL_STATUS = "lt_cell_status";//联通小区的状态 public static final String LT_PA_STATUS = "lt_pa_status";//联通功放状态 public static final String LT_PA_DOWN = "lt_pa_down";//联通功率衰减值 public static final String LT_PA_POWER = "lt_pa_power";//联通功率值 public static final String DX_CELL_STATUS = "_cell_status";//电信小区的状态 public static final String DX_PA_STATUS = "dx_pa_status";//电信功放状态 public static final String DX_PA_DOWN = "dx_pa_down";//电信功率衰减值 public static final String DX_PA_POWER = "dx_pa_power";//电信功率值 public static final String MOBILE_CELL_STATUS = "mobile_cell_status";//移动小区的状态 public static final String MOBILE_PA_STATUS = "mobile_pa_status";//移动功放状态 public static final String MOBILE_PA_DOWN = "mobile_pa_down";//移动功率衰减值 public static final String MOBILE_PA_POWER = "mobile_pa_power";//移动功率值 public static final String MOBILE1_CELL_STATUS = "mobile1_cell_status";//移动1小区的状态 public static final String MOBILE1_PA_STATUS = "mobile1_pa_status";//移动1功放状态 public static final String MOBILE1_PA_DOWN = "mobile1_pa_down";//移动1功率衰减值 public static final String MOBILE1_PA_POWER = "mobile1_pa_power";//移动1功率值 public static final String ALLCATCH = "allCatch";//总侦码开关 public static final String LT_CATCH = "lt_catch";//联通上报开关 public static final String DX_CATCH = "dx_catch";//电信上报开关 public static final String YD_CATCH = "yd_catch";//移动上报开关 public static final String YD1_CATCH = "yd1_catch";//移动1上报开关 } ``` ConvertCodeUtility.java ```package com.zed.hotsport.utils; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Administrator on 2016/9/18. */ public class ConvertCodeUtility { /** * 截取字节数组方法 * * @param data * 源字节数组 * @param start * 截取位置索引 * @param length * 截取长度 * @return byte[] 目标字节数组 */ public static byte[] subByteArr(byte[] data, int start, int length) { byte[] value = new byte[length]; if (data.length - start >= length) { System.arraycopy(data, start, value, 0, length); } return value; } /** * 将网络传输byte[]转换为short(大端模式,高字节在低地址) * * @param data * 网络传输byte[] * @return short 值 */ public static short bytes2Short(byte[] data) { short value = (short) ((data[1] & 0xFF) | ((data[0] & 0xFF) << 8)); return value; } /** * 将网络传输byte[]转换为short(小端模式,高字节在高地址) * * @param data * 网络传输byte[] * @return short 值 */ public static short bytes2Short1(byte[] data) { short value = (short) ((data[0] & 0xFF) | ((data[1] & 0xFF) << 8)); return value; } /** * 将short转换为网络字节序byte[](大端模式,高字节在低地址) * * @param value * 值 * @return 网络字节序byte[] */ public static byte[] short2Bytes(short value) { byte[] data = new byte[2]; data[0] = (byte) (value >> 8); data[1] = (byte) (value & 0xFF); return data; } /** * 将short转换为网络字节序byte[](小端模式,高字节在高地址) * * @param value * 值 * @return 网络字节序byte[] */ public static byte[] short2Bytes1(short value) { byte[] data = new byte[2]; data[1] = (byte) (value >> 8); data[0] = (byte) (value & 0xFF); return data; } /** * 将网络传输byte[]转换为int(大端模式) * * @param data * 网络传输byte[] * @return 值 */ public static int bytes2Int(byte[] data) { int value = (data[3] & 0xff) | ((data[2] & 0xff) << 8) | ((data[1] & 0xff) << 16) | ((data[0] & 0xff) << 24); return value; } /** * 将网络传输byte[]转换为int(小端模式) * * @param data * 网络传输byte[] * @return 值 */ public static int bytes2Int1(byte[] data) { int value = (data[0] & 0xff) | ((data[1] & 0xff) << 8) | ((data[2] & 0xff) << 16) | ((data[3] & 0xff) << 24); return value; } /** * 将int转换为网络字节序byte[](大端模式) * * @param value * 值 * @return 网络字节序byte[] */ public static byte[] int2Bytes(int value) { byte[] data = new byte[4]; data[0] = (byte) (value >> 24); data[1] = (byte) (value >> 16 & 0xFF); data[2] = (byte) (value >> 8 & 0xFF); data[3] = (byte) (value & 0xFF); return data; } /** * 将int转换为网络字节序byte[](小端模式) * * @param value * 值 * @return 网络字节序byte[] */ public static byte[] int2Bytes1(int value) { byte[] data = new byte[4]; data[3] = (byte) (value >> 24); data[2] = (byte) (value >> 16 & 0xFF); data[1] = (byte) (value >> 8 & 0xFF); data[0] = (byte) (value & 0xFF); return data; } /** * long整数转换为8字节的byte数组 * * @param value * long整数 * @return byte数组 */ public static byte[] longToByte8(long value) { byte[] targets = new byte[8]; for (int i = 0; i < 8; i++) { int offset = (targets.length - 1 - i) * 8; targets[i] = (byte) ((value >>> offset) & 0xFF); } return targets; } /** * BCD转换成String * * @param b * @return */ public static String bcd2String(byte[] b) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { int l = (b[i] & 0x0f) + 48; sb.append((char) l); int h = ((b[i] & 0xff) >> 4) + 48; sb.append((char) h); } return sb.toString(); } /** * 把日期类型转化为字符串型数据 * @param date * @return */ public static String getStrByDate(Date date) { String str = ""; SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); if (date != null) { str = simpleDateFormat.format(date); } return str; } /** * @brief 得到今天的日期 * @return 今天的日期如:2016-03-30 10:30:45 */ public static String getCurrentTime() { long currtime = System.currentTimeMillis(); Date date = new Date(currtime); SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); String str = simpleDateFormat.format(date); return str; } public static String byteArrayToHex(byte[] byteArray) { // 首先初始化一个字符数组,用来存放每个16进制字符 char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方)) char[] resultCharArray = new char[byteArray.length * 2]; // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去 int index = 0; for (byte b : byteArray) { resultCharArray[index++] = hexDigits[b >>> 4 & 0xf]; resultCharArray[index++] = hexDigits[b & 0xf]; } // 字符数组组合成字符串返回 return new String(resultCharArray); } } ``` TCPService.java ```package com.zed.hotsport.TCP; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.SystemClock; import android.util.Log; import com.zed.hotsport.base.BaseApplication; import java.net.Socket; public class TCPService extends Service { private BaseApplication mBaseApplication = null;//全局环境变量 private TCPClient client = null;//TCP客户端 private Socket mSocket = null;//连接通道 private boolean isConnect = true;//连接标志 private int mTargetPort = TCPConfig.SOCKET_CONFIG_PORT_3G;//监听端口 private TCPInputHelper mInputHelper = null;//Socket读取工具类 public TCPService() { } @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { if(this.mTargetPort==0){ this. mTargetPort = intent.getIntExtra("targetPort",0); } if(mBaseApplication==null){ mBaseApplication = (BaseApplication) getApplication(); } mInputHelper = TCPInputHelper.getInstance(getApplicationContext(),this.mTargetPort); if(mTargetPort!=0){ new Thread(){ @Override public void run() { client = mBaseApplication.getTCPClient(mTargetPort); if(client==null){ //每次重新获取,断链时可以清除全局变量 Log.e("TAG","从全局类中得到的Client为空"); client = new TCPClient(mTargetPort,getBaseContext()); client.listen();//获取socket mBaseApplication.setTCPClient(mTargetPort,client); new Thread(){ @Override public void run() { if(client != null){ mSocket = client.getSocket(); while (isConnect && mSocket != null && mSocket.isConnected()){ Log.e("TAG","开始监听socket中的数据"); mInputHelper.readSocket(mSocket); SystemClock.sleep(300); } } } }.start(); } SystemClock.sleep(1000); } }.start(); } return Service.START_REDELIVER_INTENT; } @Override public void onDestroy() { this.isConnect = false; disConnected(); super.onDestroy(); } /** * 断链操作方法 */ public void disConnected(){ this.client = null; mBaseApplication.removeClient(TCPConfig.SOCKET_CONFIG_PORT_3G); mBaseApplication.setCurrentEid(0); //取消心跳检测 if(mInputHelper != null){ mInputHelper.stopTimer(); } } } ``` ByteToString.java ```package com.zed.hotsport.utils; public class ByteToString { /** * 把字节数组转换成字符串的工具类 * * @param bytes * 字符数组参数 * @return */ public static String Byte2String(byte[] bytes) { StringBuilder strBuilder = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { strBuilder.append(bytes[i]); } return strBuilder.toString(); } } ``` DescendUtils.java ```package com.zed.hotsport.utils; /** * Created by Administrator on 2016/11/18. */ public class DescendUtils { } ```
zhlooking/LearnPython
zhlooking/LearnPython README.md ```LearnPython =========== A repository for python study. ``` helloworld.py ```print "Hello Python!" print "Something change to the file" print "Git is a distributed version control system" print "Git has mutable index called stage" print "Git tracks changes again and again"``` slice.py ```L = ['Micheal', 'Hanson', 'William', 'Lucy', 'Frank'] # if you want to get the first three values in a list # 1> The simplest way def getFirstThreeValueOfList1(L): subL1 = [L[0], L[1], L[2]] return subL1 # 2> Use a loop def getSubList(L = None, n = 3): if (not isinstance(L, (list)) and not isinstance(n, (int, float))): raise TypeError('bad operand type') subL2 = [] for i in range(n): subL2.append[L[i]] return subL2 # 3> Use Slice feature def getSubListBySlice(L, first = 0, last = -1): if (not isinstance(L, (list)) and not isinstance((first, last), (int, float))): raise TypeError('bad operand type') if last > 0 and last > first: return L[first:last] elif last < 0 and last + len(L) > first: return L[first:last] else: raise TypeError('Argument value error') # # Test print L print getSubListBySlice(L, 0, 2) print getSubListBySlice(L, 3) print getSubListBySlice(L, -3) print getSubListBySlice(L, 20, 30) ####If there is a list and you want to get a value every 3 values behind def getValuePerXValue(L, n): return L[::n] # Test NumList = range(100) print getValuePerXValue(NumList, 22) #### Iterator #### from collections import Iterable print isinstance('ABC', Iterable) print isinstance([], Iterable) print isinstance(123, Iterable) ``` IOTest.py ```#!/usr/bin/python f = open('workfile', 'rw') for line in f: print line f.write('This is a test.\nThis is the second line.\nThe third line.') f.close() f = open('workfile') print f for line in f: print line print 'File name is ', f.name print 'File closed or not ', f.closed print 'File open mode ', f.mode print 'File softspace flag ', f.softspace f.close() ``` Func.py ```import math def abs(x): if x < 0: return -x else: return x # This is a function that do nothing: # pass is like todo in Java, without pass there would an error def non(): pass # abs(x) more compatible def abs(x): if not isinstance(x, (int, float)): raise TypeError('bad operand type') if x < 0: return -x else: return x def move(x, y, step, angle=0): nx = x + step*math.cos(angle) my = y - step*math.sin(angle) return nx, ny # Note that the return dose not return multiple value but a tuple data struct like (nx, ny) # If there is no return syntax in a function, the function return None by default def power(x, n = 2): s = 1 while n > 0: n -= 1 s *= n; return s # To be fixed: # draw_circle(0, 0, 20, linecolor=0xffff00, fillcolor=0xff00ff, penwidth=5) # The above line will raise a NameError called: name 'draw_circle' is not defined def add_append(L[]): return L.append('END') # This will cause error when no paramater is passed to the function # Use the below instead: def add_append(L = None): if L is None: return L = [] else: return L.append('END') # The function that can change the number of paramaters # The function chage the paramaters into set or tuple by default def calc(*numbers): sum = 0 for n in numbers: sum += n * n return sum```
zhlu2010/Recommendation-System
zhlu2010/Recommendation-System MongoDBUtil.java ```package db.mongo; import java.text.ParseException; import org.bson.Document; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.IndexOptions; public class MongoDBUtil { public static final String DB_NAME = "laiproject"; } ``` MongoDBCreation.java ```package db.mongo; import java.text.ParseException; import org.bson.Document; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.IndexOptions; public class MongoDBCreation { public static void main(String[] args) { MongoClient mongoClient = MongoClients.create(); MongoDatabase db = mongoClient.getDatabase(MongoDBUtil.DB_NAME); db.getCollection("users").drop(); db.getCollection("items").drop(); IndexOptions indexOptions = new IndexOptions().unique(true); //getCollection will create a new collection if it doesn't exist db.getCollection("users").createIndex(new Document("user_id", 1), indexOptions); //1 means ascending. db.getCollection("items").createIndex(new Document("item_id", 1), indexOptions); db.getCollection("users").insertOne(new Document().append("user_id", "1111") .append("password", "3229c1097c00d497a0fd282d586be050") .append("first_name", "John").append("last_name", "Smith")); } } ``` README.md ```# Recommendation-System This is a recommend system that people can search, favorite items on our website. Use Apache tomcat as the server to wrap all the backend program. Use mysql and mongodb as databases. Use content-base recommendation algorithm ``` RecommendItem.java ```package rpc; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * * Unused servlet * * Servlet implementation class RecommendItem */ @WebServlet("/recommendItem") public class RecommendItem extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public RecommendItem() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("application/json"); JSONArray array = new JSONArray(); try { array.put(new JSONObject().put("username", "abcd").put("address", "San Francisco").put("time","01/01/9012")); array.put(new JSONObject().put("username", "1234").put("address", "New Jersey").put("time","01/01/9012")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } RpcHelper.writeJsonArray(response, array); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } ```
zhoekstra/NPCGenerator
zhoekstra/NPCGenerator FileReader.java ```/* NPCGenerator: A program for generating random NPC's for role-playing games Copyright (C) 2011 Zachary Hoekstra (zhoekstra@gmail.com) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.io.File; import java.io.FileNotFoundException; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.Scanner; public interface FileReader { static final Random rand = new Random(); public List<String> getResult(); /** * NameReader * * @author hoekstr Reads names from a first name file and a last name file */ public class NameReader implements FileReader { public final String ethnicity; private File firstname; private File lastname; private final int firstnamesize; private final int lastnamesize; public NameReader(File firstname, File lastname) throws FileNotFoundException { this.firstname = firstname; this.lastname = lastname; ethnicity = firstname.getName().split("\\.")[0]; // / Get number of lines in both files int temp = 0; Scanner scan = new Scanner(firstname); while (scan.hasNextLine()) { scan.nextLine(); ++temp; } firstnamesize = temp; if (firstnamesize < 1) System.err.println("Invalid first name file:" + this.firstname.getName()); if (lastname != null) { temp = 0; scan = new Scanner(lastname); while (scan.hasNextLine()) { scan.nextLine(); ++temp; } lastnamesize = temp; if (lastnamesize < 1) System.err.println("Invalid last name file:" + this.lastname.getName()); } else { lastnamesize = 0; } } @Override public List<String> getResult() { LinkedList<String> toreturn = new LinkedList<String>(); try { /* * Get first name and gender */ int result = rand.nextInt(firstnamesize); Scanner scan = new Scanner(firstname); String curr_name = ""; String temp = ""; while (result > 0) { temp = scan.nextLine(); --result; } String[] result_line = temp.split("\t"); curr_name += result_line[0]; String gender = "ERROR"; try { gender = result_line[1]; } catch (Exception e) { gender = "ERROR"; } if (gender.contains("m") && gender.contains("f")) gender = rand.nextBoolean() ? "Male" : "Female"; else if (gender.contains("m")) gender = "Male"; else gender = "Female"; /* * Get last name */ if (lastname != null) { result = rand.nextInt(lastnamesize); scan = new Scanner(lastname); temp = ""; while (result > 0) { temp = scan.nextLine(); --result; } curr_name += " " + temp; } toreturn.add(curr_name); toreturn.add(gender); toreturn.add(ethnicity); return toreturn; } catch (FileNotFoundException e) { e.printStackTrace(); } toreturn.add("BADNAME"); return toreturn; } } /** * TraitReader * * @author hoekstr reads traits from a trait file */ public class TraitReader implements FileReader { private File file; private final int max; public TraitReader(File f) throws FileNotFoundException { file = f; Scanner scan = new Scanner(file); int temp = 0; while (scan.hasNextLine()) { String[] curr_line = scan.nextLine().split("\t"); if (curr_line.length < 2) temp += 1; else temp += Integer.parseInt(curr_line[1]); } max = temp; } @Override public List<String> getResult() { int result = rand.nextInt(max); LinkedList<String> toreturn = new LinkedList<String>(); try { Scanner scan = new Scanner(file); int curr_val = 0; while (scan.hasNextLine()) { String[] curr_line = scan.nextLine().split("\t"); if (curr_line.length < 2) curr_val += 1; else curr_val += Integer.parseInt(curr_line[1]); if (result < curr_val) { toreturn.add(curr_line[0]); return toreturn; } } } catch (FileNotFoundException e) { e.printStackTrace(); } toreturn.add("INVALID FILE: BUG"); return toreturn; } } /** * ProbList * * @author hoekstr holds readers along with a probability. Used for * determining random ethnicity selections */ public class ProbList implements FileReader { private final LinkedList<FileReader> readers = new LinkedList<FileReader>(); private final LinkedList<Integer> probabilities = new LinkedList<Integer>(); private int max = 0; public void addReader(FileReader read, int prob) { readers.add(read); probabilities.add(prob + max); max += prob; } @Override public List<String> getResult() { int result = rand.nextInt(max); for (int i = 0; i < readers.size(); ++i) if (result < probabilities.get(i)) return readers.get(i).getResult(); return readers.peek().getResult(); } public String[] EthnicList() { String[] toreturn = new String[readers.size()]; int index = 0; for (FileReader i : readers) toreturn[index++] = ((NameReader) i).ethnicity; return toreturn; } public List<String> GenerateSpecificNPC(String ethnicity, boolean Male, boolean Female) throws Exception { for (FileReader i : readers) { if (((NameReader) i).ethnicity.equals(ethnicity)) { int cannotfind = 0; while (cannotfind++ < 200) { List<String> result = i.getResult(); if (result.get(1).equals("Male") && Male) return result; else if (result.get(1).equals("Female") && Female) return result; } } } throw new Exception( "Cannot find specified traits (Gender/Ethnicity)"); } public List<String> GenerateSpecificNPC(boolean Male, boolean Female) throws Exception { int cannotfind = 0; while (cannotfind++ < 200) { List<String> result = getResult(); if (result.get(1).equals("Male") && Male) return result; else if (result.get(1).equals("Female") && Female) return result; } throw new Exception("Cannot find specified gender traits"); } } } ``` NPCGenerator.java ```/* NPCGenerator: A program for generating random NPC's Copyright (C) 2011 Zachary Hoekstra (zhoekstra@gmail.com) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.net.URISyntaxException; import java.util.LinkedList; import java.util.List; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; /** * NPCGenerator.java * @author zach * * The GUI for the NPCGenerator. Note that on construction, takes a Generator. * Uses this Generator to generate NPC's, and handles all the display and saving */ public class NPCGenerator extends JFrame implements ActionListener, WindowListener{ /** * */ private static final long serialVersionUID = 5183908171556584362L; Generator generator; //Left panel of the generator private JPanel generator_panel_left = new JPanel(new GridLayout(0,3)); //The generator panel private JPanel generator_panel = new JPanel(new GridLayout(0,2)); //Labels for constant attributes private JLabel name_label = new JLabel("Name:"); private JLabel gender_label = new JLabel("Gender:"); private JLabel ethnicity_label = new JLabel("Ethnicity"); //Fields for constant attributes private JTextField name_field = new JTextField(); private String[] available_genders = {"Male","Female"}; private JComboBox gender_field = new JComboBox(available_genders); private JComboBox ethnicity_field; //Locks for constant attributes private JCheckBox name_lock = new JCheckBox(); private JCheckBox gender_lock = new JCheckBox(); private JCheckBox ethnicity_lock = new JCheckBox(); //Labels, fields, and locks for all other traits //TODO: Currently due to lazyness, the first 3 slots (name, gender,ethnicity) //are never used. Need to fix that private JLabel[] trait_labels; private JTextField[] trait_fields; private JCheckBox[] trait_locks; //A notes section to take notes as the game progresses private JTextArea notes = new JTextArea(); //A table section to display saved characters private DefaultTableModel table_model = new DefaultTableModel(); private JTable table = new JTable(table_model); //Buttons to generate and save private JButton generate = new JButton("Generate"); private JButton save = new JButton("Save"); //Output stream private PrintStream output; //We don't want to save a character twice, so use a flag to force the user to //change something before they save again private boolean already_saved = false; JMenuBar menubar = new JMenuBar(); /** * Contstructor: Sets up and runs the GUI for the Generator * @param g the generator this GUI is using * @throws FileNotFoundException when it cannot access the output file */ public NPCGenerator(final Generator g) throws FileNotFoundException{ super("NPC Generator"); generator = g; this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.addWindowListener(this); this.setLayout(new GridLayout(2,0)); generator_panel.add(generator_panel_left); generator_panel.add(notes); add(generator_panel); for(String i : g.attributes) table_model.addColumn(i); table_model.addColumn("Notes"); add(table); ethnicity_field = new JComboBox(g.EthnicList()); trait_labels = g.traitLabels(); trait_fields = new JTextField[trait_labels.length]; trait_locks = new JCheckBox[trait_labels.length]; for(int i = 0; i < trait_labels.length; ++i){ trait_fields[i] = new JTextField(); trait_locks[i] = new JCheckBox(); } generator_panel_left.add(name_label); generator_panel_left.add(name_field); generator_panel_left.add(name_lock); generator_panel_left.add(gender_label); generator_panel_left.add(gender_field); generator_panel_left.add(gender_lock); generator_panel_left.add(ethnicity_label); generator_panel_left.add(ethnicity_field); generator_panel_left.add(ethnicity_lock); for(int i = 3; i < trait_labels.length; ++i){ generator_panel_left.add(trait_labels[i]); generator_panel_left.add(trait_fields[i]); generator_panel_left.add(trait_locks[i]); } generate.addActionListener(this); generator_panel_left.add(generate); save.addActionListener(this); generator_panel_left.add(save); this.pack(); this.setVisible(true); } /** * A stub main class * @param args * @throws FileNotFoundException * @throws URISyntaxException */ public static void main(String[] args) throws FileNotFoundException, URISyntaxException{ if(args.length == 0){ JFileChooser choose_world = new JFileChooser(); if (choose_world.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){ NPCGenerator generator = new NPCGenerator(new Generator(choose_world.getSelectedFile())); } } else if(args.length == 2){ Generator g = new Generator(new File(args[0])); //PrintStream output = new PrintStream(new FileOutputStream(new File(args[1]))); int num_generate = Integer.parseInt(args[2]); for(int i =0; i < num_generate; ++i){ for(String str : g.generateCharacter()) System.out.print("\""+str+"\","); System.out.println(); } } } @Override /** * The actionPerformed method: handles when one of our two buttons is pushed */ public void actionPerformed(ActionEvent arg0) { /** * The Generate Button: Generates a character and displays it in the appropriate fields */ if(arg0.getActionCommand().equals("Generate")){ already_saved = false; List<String> result = new LinkedList<String>(); //Check for a lock on ethnicity and gender if (ethnicity_lock.isSelected() && gender_lock.isSelected()){ boolean Male = false; boolean Female = false; if(gender_field.getSelectedItem().equals("Male")) Male = true; else Female = true; String ethnicity = (String)ethnicity_field.getSelectedItem(); try { result = generator.generateCharacter(ethnicity, Male, Female); } catch (Exception e) { e.printStackTrace(); } } //Check for lock on ethnicity only else if (ethnicity_lock.isSelected()){ try { result = generator.generateCharacter((String)ethnicity_field.getSelectedItem()); } catch (Exception e) { e.printStackTrace(); } } //Check for a lock on gender only else if (gender_lock.isSelected()){ boolean Male = false; boolean Female = false; if(gender_field.getSelectedItem().equals("Male")) Male = true; else Female = true; try { result = generator.generateCharacter(Male, Female); } catch (Exception e) { e.printStackTrace(); } } //No special locks else{ result = generator.generateCharacter(); } /* * Set all the appropriate boxes */ if(!name_lock.isSelected()) name_field.setText(result.get(0)); if(!gender_lock.isSelected()) gender_field.setSelectedItem(result.get(1)); if(!ethnicity_lock.isSelected()) ethnicity_field.setSelectedItem(result.get(2)); for(int i = 3; i < trait_labels.length; ++i){ if(!trait_locks[i].isSelected()) trait_fields[i].setText(result.get(i)); } notes.setText(""); } /** * Save button: Saves a displayed character to our .csv */ else if(arg0.getActionCommand().equals("Save")){ if(!already_saved){ already_saved = true; /* * Add the current character to the table */ List<Object> character_list = new LinkedList<Object>(); character_list.add(name_field.getText()); character_list.add(gender_field.getSelectedItem()); character_list.add(ethnicity_field.getSelectedItem()); for(int i = 3; i < trait_fields.length; ++i) character_list.add(trait_fields[i].getText()); character_list.add(notes.getText()); table_model.addRow(character_list.toArray()); } } else{ /// We've found some other change in the editor. We can save again already_saved = false; } } @Override public void windowActivated(WindowEvent arg0) { } /** * When our application closes, save our current table to our output file */ @Override public void windowClosed(WindowEvent arg0) { JFileChooser choose_save = new JFileChooser(); int save_result = choose_save.showSaveDialog(this); if(save_result == JFileChooser.APPROVE_OPTION){ try { output = new PrintStream(new FileOutputStream(choose_save.getSelectedFile())); } catch (FileNotFoundException e) { e.printStackTrace(); } for(int row = 0; row < table.getRowCount(); ++row){ List<Object> curr_row = new LinkedList<Object>(); for(int col = 0; col < table.getColumnCount(); ++col) curr_row.add(table.getValueAt(row, col)); for(Object i : curr_row) output.print("\""+i+"\","); output.println(); } output.close(); } System.exit(0); } @Override public void windowClosing(WindowEvent arg0) { } @Override public void windowDeactivated(WindowEvent arg0) { } @Override public void windowDeiconified(WindowEvent arg0) { } @Override public void windowIconified(WindowEvent arg0) { } @Override public void windowOpened(WindowEvent arg0) { } } ``` Generator.java ```/* NPCGenerator: A program for generating random NPC's Copyright (C) 2011 Zachary Hoekstra (zhoekstra@gmail.com) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.io.File; import java.io.FileNotFoundException; import java.net.URISyntaxException; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import javax.swing.JLabel; public class Generator { ///A list of attributes that this generator provides, in order of their appearence in the list given by generateCharacter() public final List<String> attributes = new LinkedList<String>(); private static File root_dir = null; // new File(Generator.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); private static File[] first_name_files = null;//new File("./Data/name/first/").listFiles(); private static File[] last_name_files = null;//new File("./Data/name/last/").listFiles(); private static File[] trait_files = null;//new File("./Data/trait/").listFiles(); private FileReader.ProbList names = new FileReader.ProbList(); private LinkedList<FileReader> traits = new LinkedList<FileReader>(); /** * Load a world file and prepare the appropriate files * @param world_path The path to the world file to load * @throws FileNotFoundException If the world file or any of the files indicated by the world file is not found * @throws URISyntaxException If the root file cannot be found. */ public Generator(File world_path) throws FileNotFoundException, URISyntaxException{ if(root_dir == null){ root_dir = new File(Generator.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile(); System.out.println(root_dir.getPath()); first_name_files = new File(root_dir.getPath()+"/Data/name/first/").listFiles(); //System.out.println(first_name_files.getPath()); last_name_files = new File(root_dir.getPath()+"/Data/name/last/").listFiles(); //System.out.println(last_name_files.getPath()); trait_files = new File(root_dir.getPath()+"/Data/trait/").listFiles(); //System.out.println(root_dir.getPath()); } Scanner world_file = new Scanner(world_path); String temp = ""; /* * Load Name files */ while(true){ temp = world_file.nextLine(); String[] curr_line = temp.split("\t+"); if(curr_line[0].equals("TRAITS:")) break; curr_line[0]+=".txt"; int prob = curr_line.length > 1 ? Integer.parseInt(curr_line[1]) : 1; for(File i : first_name_files){ if (i.getName().equals(curr_line[0])){ File first = i; File second = null; for(File j : last_name_files) if(j.getName().equals(curr_line[0])){ second = j; break; } names.addReader(new FileReader.NameReader(first, second), prob); } } } attributes.add("Name"); attributes.add("Gender"); attributes.add("Ethnicity"); /* * Load Trait files */ while(world_file.hasNext()){ temp =world_file.next(); attributes.add(temp); temp+=".txt"; for(File i : trait_files){ if(i.getName().equals(temp)){ traits.add(new FileReader.TraitReader(i)); break; } } } } /** * generate a NPC * @return a list of Strings containing all attributes of this NPC */ public List<String> generateCharacter(){ List<String> toreturn = names.getResult(); for (FileReader file : traits) toreturn.addAll(file.getResult()); return toreturn; } public List<String> generateCharacter(String ethnicity) throws Exception{ List<String> toreturn = names.GenerateSpecificNPC(ethnicity, true, true); for (FileReader file : traits) toreturn.addAll(file.getResult()); return toreturn; } public List<String> generateCharacter(boolean Male, boolean Female) throws Exception{ List<String> toreturn = names.GenerateSpecificNPC(Male, Female); for (FileReader file : traits) toreturn.addAll(file.getResult()); return toreturn; } public List<String> generateCharacter(String ethnicity, boolean Male, boolean Female) throws Exception{ List<String> toreturn = names.GenerateSpecificNPC(ethnicity, Male, Female); for (FileReader file : traits) toreturn.addAll(file.getResult()); return toreturn; } /* public static void main(String[] args) throws FileNotFoundException{ Generator world = new Generator(args[0]); for(int i = 0; i < 100; ++i){ for(String str:world.generateCharacter()) System.out.println(str); System.out.println("------------------------------"); } } */ /**************************** * Helper methods for the GUI ****************************/ final public String[] EthnicList(){ return names.EthnicList(); } public JLabel[] traitLabels(){ JLabel[] labels = new JLabel[attributes.size()]; for(int i = 0; i < labels.length; ++i) labels[i] = new JLabel(attributes.get(i)); return labels; } } ``` NPCMenu.java ```import javax.swing.JMenuBar; public class NPCMenu extends JMenuBar { } ```
zhongguomeng/graph-based-segmentation
zhongguomeng/graph-based-segmentation PhotoIntentActivity.java ```package com.example.android.photobyintent; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.io.FileOutputStream; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.content.ContextWrapper; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.LoaderCallbackInterface; import org.opencv.android.OpenCVLoader; public class PhotoIntentActivity extends Activity { private static final int ACTION_TAKE_PHOTO = 1; private static final String BITMAP_STORAGE_KEY = "viewbitmap"; private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility"; private static final String OPENCV_TAG = "OPENCV"; private ImageView mImageView; private Bitmap mImageBitmap; private EditText kernelSizeText; private EditText sigmaText, segCText; private String imageFileName; ImageButton segBtn; private String mCurrentPhotoPath; private static final String JPEG_FILE_PREFIX = "IMG_"; private static final String JPEG_FILE_SUFFIX = ".jpg"; private AlbumStorageDirFactory mAlbumStorageDirFactory = null; // JNI static { System.loadLibrary("ImageSegmentation"); // "myjni.dll" in Windows, "libmyjni.so" in Unixes //System.loadLibrary("stlport_shared"); } static { try { System.loadLibrary("opencv_java"); //System.loadLibrary("Visualizer"); } catch (UnsatisfiedLinkError e) { Log.v("ERROR", "" + e); } } //OPENCV Manager private BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this) { @Override public void onManagerConnected(int status) { switch (status) { case LoaderCallbackInterface.SUCCESS: { Log.i(OPENCV_TAG, "OpenCV loaded successfully"); } break; default: { super.onManagerConnected(status); } break; } } }; /* Photo album for this application */ private String getAlbumName() { return getString(R.string.album_name); } private File getAlbumDir() { File storageDir = null; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName()); if (storageDir != null) { if (! storageDir.mkdirs()) { if (! storageDir.exists()){ Log.d("CameraSample", "failed to create directory"); return null; } } } } else { Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE."); } return storageDir; } private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); imageFileName = JPEG_FILE_PREFIX + timeStamp + "_"; File albumF = getAlbumDir(); File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF); return imageF; } private File createSegImageFile() throws IOException{ imageFileName = "Seg_" + imageFileName; File albumF = getAlbumDir(); File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF); //Set up photo path mCurrentPhotoPath = imageF.getAbsolutePath(); return imageF; } private File setUpPhotoFile() throws IOException { File f = createImageFile(); mCurrentPhotoPath = f.getAbsolutePath(); return f; } private void setPic() { /* There isn't enough memory to open up more than a couple camera photos */ /* So pre-scale the target bitmap into which the file is decoded */ /* Get the size of the ImageView */ int targetW = mImageView.getWidth(); int targetH = mImageView.getHeight(); /* Get the size of the image */ BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); int photoW = bmOptions.outWidth; int photoH = bmOptions.outHeight; /* Figure out which way needs to be reduced less */ int scaleFactor = 1; if ((targetW > 0) || (targetH > 0)) { scaleFactor = Math.min(photoW/targetW, photoH/targetH); } /* Set bitmap options to scale the image decode target */ bmOptions.inJustDecodeBounds = false; bmOptions.inSampleSize = 10;//scaleFactor; bmOptions.inPurgeable = true; /* Decode the JPEG file into a Bitmap */ //Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); mImageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions); /* Associate the Bitmap to the ImageView */ mImageView.setImageBitmap(mImageBitmap); mImageView.setVisibility(View.VISIBLE); } private void galleryAddPic() { Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE"); File f = new File(mCurrentPhotoPath); Uri contentUri = Uri.fromFile(f); mediaScanIntent.setData(contentUri); this.sendBroadcast(mediaScanIntent); } private void dispatchTakePictureIntent(int actionCode) { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); switch(actionCode) { case ACTION_TAKE_PHOTO: File f = null; try { f = setUpPhotoFile(); mCurrentPhotoPath = f.getAbsolutePath(); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); } catch (IOException e) { e.printStackTrace(); f = null; mCurrentPhotoPath = null; } break; default: break; } // switch startActivityForResult(takePictureIntent, actionCode); } //Handle Taking Pictures private void handleCameraPhoto() { if (mCurrentPhotoPath != null) { setPic(); galleryAddPic(); mCurrentPhotoPath = null; } } Button.OnClickListener mTakePicOnClickListener = new Button.OnClickListener() { @Override public void onClick(View v) { dispatchTakePictureIntent(ACTION_TAKE_PHOTO); } }; //Handle Taking segmentation private void handleSegmentation(){ if(mImageBitmap == null){ Log.d("ImageSegmentation","Null image"); return; } else { myImageHandle mSegment = new myImageHandle(); mSegment.setImage(mImageBitmap); //Get parameters from View mSegment.setKSize(Integer.parseInt(kernelSizeText.getText().toString())); mSegment.setSigma(Double.parseDouble(sigmaText.getText().toString())); mSegment.setC(Integer.parseInt(segCText.getText().toString())); mImageBitmap = mSegment.getSegmentation(); mImageView.setImageBitmap(mImageBitmap); } } private void saveSegmentationImage(){ File f = null; try { f = createSegImageFile(); } catch (Exception e){ e.printStackTrace(); mCurrentPhotoPath = null; }finally { if (f == null) { // e.getMessage()); return; } try { FileOutputStream fos = new FileOutputStream(f); mImageBitmap.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); fos.close(); /*MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName()); */ galleryAddPic(); }catch (IOException e) { e.printStackTrace(); } } } private String saveToInternalStorage(Bitmap bitmapImage){ ContextWrapper cw = new ContextWrapper(getApplicationContext()); // path to /data/data/yourapp/app_data/imageDir File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); // Create imageDir File mypath=new File(directory,"profile.jpg"); FileOutputStream fos = null; try { fos = new FileOutputStream(mypath); // Use the compress method on the BitMap object to write image to the OutputStream bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.close(); } catch (Exception e) { e.printStackTrace(); } return directory.getAbsolutePath(); } Button.OnClickListener mSegmentationOnClickListener = new Button.OnClickListener() { @Override public void onClick(View v) { handleSegmentation(); } }; @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_save: saveSegmentationImage(); //saveToInternalStorage(mImageBitmap); return true; default: return super.onOptionsItemSelected(item); } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //Get editext kernelSizeText = (EditText) findViewById(R.id.ksize); sigmaText = (EditText) findViewById(R.id.sigma); segCText = (EditText) findViewById(R.id.segC); //System.loadLibrary(Core.NATIVE_LIBRARY_NAME); mImageView = (ImageView) findViewById(R.id.imageView1); mImageBitmap = null; ImageButton picBtn = (ImageButton) findViewById(R.id.btnIntend); setBtnListenerOrDisable( picBtn, mTakePicOnClickListener, MediaStore.ACTION_IMAGE_CAPTURE ); segBtn = (ImageButton) findViewById(R.id.btnSegmentation); segBtn.setClickable(true); segBtn.setOnClickListener(mSegmentationOnClickListener); //segBtn.setText(getMessage()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { mAlbumStorageDirFactory = new FroyoAlbumDirFactory(); } else { mAlbumStorageDirFactory = new BaseAlbumDirFactory(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.photo_intent_action_bar, menu); return super.onCreateOptionsMenu(menu); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK && requestCode == ACTION_TAKE_PHOTO ) { handleCameraPhoto(); } } // Some lifecycle callbacks so that the image can survive orientation change @Override protected void onSaveInstanceState(Bundle outState) { outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap); outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) ); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY); mImageView.setImageBitmap(mImageBitmap); mImageView.setVisibility( savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ? ImageView.VISIBLE : ImageView.INVISIBLE ); } /** * Indicates whether the specified action can be used as an intent. This * method queries the package manager for installed packages that can * respond to an intent with the specified action. If no suitable package is * found, this method returns false. * http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html * * @param context The application's environment. * @param action The Intent action to check for availability. * * @return True if an Intent with the specified action can be sent and * responded to, false otherwise. */ public static boolean isIntentAvailable(Context context, String action) { final PackageManager packageManager = context.getPackageManager(); final Intent intent = new Intent(action); List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } private void setBtnListenerOrDisable( ImageButton btn, Button.OnClickListener onClickListener, String intentName ) { btn.setClickable(true); if (isIntentAvailable(this, intentName)) { btn.setOnClickListener(onClickListener); } else { //btn.setClickable(false); } } @Override public void onResume(){ super.onResume(); Log.i(OPENCV_TAG, "Trying to load OpenCV library"); if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_4, this, mOpenCVCallBack)) { Log.e(OPENCV_TAG, "Cannot connect to OpenCV Manager"); } } }``` myImageHandle.java ```package com.example.android.photobyintent; import android.graphics.Bitmap; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import org.opencv.android.Utils; /** * Created by weitingco on 15/2/27. */ public class myImageHandle { Mat matImg; //Bitmap image; Bitmap segmentation; int CMAX = 256; //segmentation factors double sigma = 0.8; int ks = 5; int C = 200; //For graph float weights []; int leftNodes []; int rightNodes []; public native int[] ImageSegmentation(float[] w, int[] l, int[] r, float K, int x, int y); void setSigma(double s){ if(s > 0) { sigma = s; } } void setKSize(int k){ if(k > 0) { ks = k; } } void setC(int c){ if(c>0){ C = c; } } void setImage(Bitmap input){ //CV_32F -> float[] matImg = new Mat(input.getHeight(), input.getWidth(), CvType.CV_32FC3); Mat matTemp2 = new Mat(input.getHeight(), input.getWidth(), CvType.CV_32FC3); //CV_8U -> byte[] Mat matTemp = new Mat(input.getHeight(), input.getWidth(), CvType.CV_8UC3); Utils.bitmapToMat(input,matTemp); Size ksize = new Size(ks,ks); Imgproc.cvtColor(matTemp, matTemp2, Imgproc.COLOR_RGB2Lab); Imgproc.GaussianBlur(matTemp2, matImg, ksize, sigma); matTemp.release(); matTemp2.release(); } Mat multiply(Mat a, Mat b){ int s = a.rows(); Mat A = new Mat(s,s,CvType.CV_32F); double[] e1; double[] e2; float [] r = new float[1]; for(int x = 0; x < s; x++){ e1 = a.get(x,0); for (int y = 0; y <s; y++){ e2 = b.get(y,0); r[0] = (float)(e1[0]*e2[0]); A.put(x,y,r); } } return A; } Bitmap getSegmentation(){ segmentation = Bitmap.createBitmap(matImg.cols(),matImg.rows(), Bitmap.Config.ARGB_8888); build8NGraph(1,1,1); int [] segIdx = ImageSegmentation(weights, leftNodes, rightNodes, C, matImg.rows(), matImg.cols()); //release memory weights = null; leftNodes = null; rightNodes = null; seg2Color(segIdx); Utils.matToBitmap(matImg,segmentation); return segmentation; } void seg2Color(int [] segIdx){ Map<Integer, RGB> colorMap = new HashMap<Integer, RGB>(); int imH = matImg.rows(); int imW = matImg.cols(); int num = imH*imW; matImg = new Mat(imH, imW, CvType.CV_8UC3); Random rand = new Random(); int cNode; byte [] C = new byte[3]; for (int idx = 0; idx < num; idx++){ cNode = segIdx[idx]; if(colorMap.get(cNode) == null){ //new segmentation RGB rgb = new RGB(); rgb.R = (byte)rand.nextInt(CMAX); rgb.B = (byte)rand.nextInt(CMAX); rgb.G = (byte)rand.nextInt(CMAX); C[0] = rgb.R; C[1] = rgb.B; C[2] = rgb.G; colorMap.put(cNode,rgb); } else { RGB rgb = colorMap.get(cNode); C[0] = rgb.R; C[1] = rgb.B; C[2] = rgb.G; } int rowNum = idx%imH; int colNum = (idx-rowNum)/imH; matImg.put(rowNum,colNum,C); } } float diff(int x1, int y1, int x2, int y2, float w1, float w2, float w3){ double[] p1 = matImg.get(x1,y1); double[] p2 = matImg.get(x2,y2); float d1 = (float) ((p1[0]-p2[0])*(p1[0]-p2[0])); float d2 = (float) ((p1[1]-p2[1])*(p1[1]-p2[1])); float d3 = (float) ((p1[2]-p2[2])*(p1[2]-p2[2])); return w1*d1+w2*d2+w3*d3; } void build8NGraph(float w1, float w2, float w3){ int imW = matImg.cols(); int imH = matImg.rows(); int outArraySize = (imH-1)*imW + (imW-1)*imH + 2*(imH-1)*(imW-1); weights = new float[outArraySize]; leftNodes = new int[outArraySize]; rightNodes = new int[outArraySize]; int num = 0; for(int y = 0; y < imW; y++){ for(int x = 0; x < imH; x++){ //Connect vertical edges if(x < imH - 1){ weights[num] = diff(x,y,x+1,y,w1,w2,w3); leftNodes[num] = x + y*imH; rightNodes[num] = x+1 + y*imH; num++; } //Connect horizontal edges if (y < imW-1){ weights[num] = diff(x,y,x,y+1,w1,w2,w3); leftNodes[num] = x + y*imH; rightNodes[num] = x + (y+1)*imH; num++; } //Connect up-left to down-left edges if(x < imH -1 && y < imW-1){ weights[num] = diff(x,y,x+1,y+1,w1,w2,w3); leftNodes[num] = x + y*imH; rightNodes[num] = (x+1) + (y+1)*imH; num++; } //Connect down-left to up-right edges if(x > 0 && y < imW-1){ weights[num] = diff(x,y,x-1,y+1,w1,w2,w3); leftNodes[num] = x + y*imH; rightNodes[num] = (x-1) + (y+1)*imH; num++; } } } } } ``` RGB.java ```package com.example.android.photobyintent; /** * Created by weitingco on 15/3/4. */ public class RGB { public byte R; public byte B; public byte G; } ``` README.md ```# graph-based-segmentation # Usage 1. Run 'buildMex.m' 2. Run 'TestSeg.m' and see result ## TODO ### fix MATLAB interface: compile multiple .cpp files to mex and bypass .txt files [Steven] ### Android implementation -Interface -Algorithm [Weiting] ### Graph construction in different space -Nearest neighbor search in (x,y,r,g,b) [TJ] -In other spaces ### Comparison with other implemenations C++ code: http://cs.brown.edu/~pff/segment/ Matlab code: http://www.mathworks.com/matlabcentral/fileexchange/29299-efficient-graph-based-image-segmentation ### Think about video segmentation (using time to help) ~~### Prepare slides for presentation (BY TUESDAY!!!!) [Steven]~~ ## Maybe do -use boost for disjoint set -shape recognition for object tracking http://download.springer.com/static/pdf/25/art%253A10.1007%252Fs11263-006-7934-5.pdf?auth66=1424049572_e94520cf58dfcdc9db07e7f5f0ad4b8d&ext=.pdf ``` typeUtility.h ```// // typeUtility.h // DIP_FinalProject // // Created by Lin Weiting on 2015/2/8. // Copyright (c) 2015年 Weiting. All rights reserved. // #ifndef DIP_FinalProject_typeUtility_h #define DIP_FinalProject_typeUtility_h typedef int idxSupport; typedef float WEIGHTSUPPORT; #endif ``` Seg2Color.cpp ```/* USAGE: [SegMapR SegMapG SegMapB SegNum] = SegGraph(segResult, width, height); */ #include "mex.h" #include "Seg2ColorCore.cpp" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ if(nrhs!=3) { mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs", "Three inputs required."); } if(nlhs!=4) { mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs", "Four output required."); } // inputs double* segMap = mxGetPr(prhs[0]); // edgeWeights double width = mxGetScalar(prhs[1]); // cols double height = mxGetScalar(prhs[2]); // rows int num_nodes = static_cast<int> (width*height); //output data double* R; double* G; double* B; double* numSeg; plhs[0] = mxCreateDoubleMatrix(1, num_nodes, mxREAL); //R plhs[1] = mxCreateDoubleMatrix(1, num_nodes, mxREAL); //G plhs[2] = mxCreateDoubleMatrix(1, num_nodes, mxREAL); //B plhs[3] = mxCreateDoubleMatrix(1, 1, mxREAL);// numSeg R = mxGetPr(plhs[0]); G = mxGetPr(plhs[1]); B = mxGetPr(plhs[2]); numSeg = mxGetPr(plhs[3]); size_t temp = Seg2Color(R, G, B, segMap, num_nodes); *numSeg = (double) temp; }``` edges.h ```// // edges.h // DIP_FinalProject // // Created by Lin Weiting on 2015/2/8. // Copyright (c) 2015年 Weiting. All rights reserved. // #ifndef DIP_FinalProject_edges_h #define DIP_FinalProject_edges_h #include "typeUtility.h" class edges{ public: friend bool operator<(const edges& left, const edges& right); friend bool operator>(const edges& left, const edges& right); friend bool operator==(const edges& left, const edges& right); friend bool operator!=(const edges& left, const edges& right); float w; int a,b; }; inline bool operator< (const edges& left, const edges& right){ return left.w < right.w; } inline bool operator> (const edges& left, const edges& right){ return left.w > right.w; } inline bool operator== (const edges& left, const edges& right){ return left.w == right.w; } inline bool operator!= (const edges& left, const edges& right){ return left.w == right.w; } #endif ``` main.cpp ```// // main.cpp // ConlyImp // // Created by StevenM on 3/4/15. // Copyright (c) 2015 StevenM. All rights reserved. // #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <array> // Performance measurements #include <time.h> // For boost implementations, #include <vector> #include <boost/graph/properties.hpp> #include <boost/pending/detail/disjoint_sets.hpp> using namespace cv; using namespace std; typedef pair<uint, uint> edge_list; #include "buildGraph.h" #include "Segment.h" #include "segColor.h" #include "boost_segment.h" int main( int argc, char** argv ) { float sigma=0.8; short k=200; cout << argc << endl; if( argc < 2) { cout <<" Usage: display_image ImageToLoadAndDisplay [k] [sigma]" << endl; return -1; } else if( argc == 3) { k=atoi(argv[2]); } else if (argc == 4) { k=atoi(argv[2]); sigma=atof(argv[3]); } Mat image; image = imread(argv[1], CV_LOAD_IMAGE_COLOR); // Read the file if(! image.data ) // Check for invalid input { cout << "Could not open or find the image" << std::endl ; return -1; } clock_t t_total,t; GaussianBlur( image, image, Size( 0, 0 ), sigma, sigma ); t_total=clock(); // Build the graph, uint* edgeWeight; //Allocate memory for graph //Allocating memory for the graph uint imW=image.rows; uint imH=image.cols; uint outArraySize = (imH-1)*imW + (imW-1)*imH + 2*(imH-1)*(imW-1); edgeWeight = new uint [outArraySize]; t=clock(); edge_list *vertices; vertices= new edge_list [outArraySize]; eightNeighborGridGraph(edgeWeight,vertices, image,1,1,1); t=clock()-t; printf ("Building graph took me %d clicks (%f seconds).\n",(int)t,((float)t)/CLOCKS_PER_SEC); // Return structure, double* segMap; segMap = new double [outArraySize]; t=clock(); B_Segmentation(imW*imH, outArraySize, segMap, edgeWeight, vertices, k); t=clock()-t; printf ("Segmentation took me %d clicks (%f seconds).\n",(int)t,((float)t)/CLOCKS_PER_SEC); Seg2Color(image, segMap, imW, imH); t_total = clock() - t_total; printf ("In total, it took me %d clicks (%f seconds).\n",(int)t_total,((float)t_total)/CLOCKS_PER_SEC); imwrite("./output.jpg",image); namedWindow( "Display window", WINDOW_AUTOSIZE );// Create a window for display. imshow( "Display window", image ); // Show our image inside it. waitKey(0); // Wait for a keystroke in the window return 0; }``` SegGraphAuthor.cpp ```// // mexImgSegment.cpp // DIP_FinalProject // // Created by Lin Weiting on 2015/2/7. // Copyright (c) 2015 Weiting. All rights reserved. // // /** [segResult] = SegGraph(edgeWeights, lefts, rights, imWidth, imHeight, edgeLength, K); **/ #include "mex.h" #include "SegGraphCoreAuthor.cpp" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ if(nrhs!=9) { mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs", "Nine inputs required."); } if(nlhs!=1) { mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs", "One output required."); } double* edgeW; //get 1 - D matrix double* cNodes; //get 1 - D matrix double* nNodes; //get 1 - D matrix //get scaler double pmK; double edgeNum; double height; double width; double minSize; double tempFM; bool forceMerge; //get data from matlab edgeW = mxGetPr(prhs[0]); // edgeWeights cNodes = mxGetPr(prhs[1]); nNodes = mxGetPr(prhs[2]); //Segmentation parameter width = mxGetScalar(prhs[3]); // cols height = mxGetScalar(prhs[4]); // rows edgeNum = mxGetScalar(prhs[5]); // number of edges pmK = mxGetScalar(prhs[6]); // K minSize = mxGetScalar(prhs[7]);//minSize tempFM = mxGetScalar(prhs[8]);// force merge forceMerge = (tempFM == 1); int dlength = static_cast<int>((height-1)*width + (width-1)*height + 2*(width-1)*(height-1)); int num_nodes = static_cast<int>(height*width); //output data plhs[0] = mxCreateDoubleMatrix(1, num_nodes, mxREAL); double* segMap = mxGetPr(plhs[0]); Segmentation(num_nodes, dlength, segMap, edgeW, cNodes, nNodes, pmK, minSize, forceMerge); } ``` myDisjointSet.cpp ```// // myDisjointSet.cpp // DIP_FinalProject // // Created by Lin Weiting on 2015/2/7. // Copyright (c) 2015å¹?Weiting. All rights reserved. // #include "myDisjointSet.h" myDisjointSet::myDisjointSet(int num){ nodes = new myDJSNode[num]; setNum = num; maxNum = num; //make set for (int n = 0; n < setNum; n++) { nodes[n].size = 1; nodes[n].rank = 0; nodes[n].p = n; // make every node a disjoint set nodes[n].MSTweight = 0; } A.reserve(num); } int myDisjointSet::findSet(int idx){ if (nodes[idx].p == idx) { return idx; } //vector<int> A; int c_idx = idx; //current idx /** PATH COMPRESSION **/ //collect nodes for path compression while (nodes[c_idx].p != c_idx) { //current node is not the root A.push_back(c_idx); //A[ptr] = c_idx; //ptr = ptr + 1; c_idx = nodes[c_idx].p; } //Path compression for (vector<int>::iterator it = A.begin(); it != A.end(); it++) { nodes[(*it)].p = c_idx; } /**END PATH COMPRESSION **/ //without path compression //nodes[idx].p = c_idx; A.clear(); return c_idx; } void myDisjointSet::unionSets(int u, int v){ int uParent = findSet(u); int vParent = findSet(v); if (nodes[uParent].rank == nodes[vParent].rank) { nodes[uParent].rank = nodes[uParent].rank + 1; //merge v into u nodes[vParent].p = uParent; nodes[uParent].size += nodes[vParent].size; } else if (nodes[uParent].rank > nodes[vParent].rank) { //merge v into u nodes[vParent].p = uParent; nodes[uParent].size += nodes[vParent].size; } else{ //merge u into v nodes[uParent].p = vParent; nodes[vParent].size += nodes[uParent].size; } // # of disjoint set -1 setNum = setNum - 1; } ``` segColor.h ```// // segColor.h // ConlyImp // // Created by StevenM on 3/7/15. // Copyright (c) 2015 StevenM. All rights reserved. // #ifndef ConlyImp_segColor_h #define ConlyImp_segColor_h #include <unordered_map> using namespace std; #define CMAX 255 size_t Seg2Color(Mat &img, double* segMap, uint imW, uint imH){ unordered_map<double,RGB> mymap; unordered_map<double,RGB>::iterator it; double tR; double tG; double tB; double cNode; for(uint y = 0; y < imW; y++){ for(uint x = 0; x < imH; x++){ cNode = (double)segMap[x+imH*y]; //haven't assigned the color it = mymap.find(cNode); if ( it == mymap.end() ){ //assign the color tR = rand() % CMAX; tG = rand() % CMAX; tB = rand() % CMAX; RGB* rgb = new RGB; (*rgb).R = tR; (*rgb).B = tB; (*rgb).G = tG; mymap.insert(std::pair<double,RGB>(cNode,*rgb)); } else { tR = it->second.R; tB = it->second.B; tG = it->second.G; } //Assign to Image Vec3b pix; // First pixel pix.val[0]=tR; pix.val[1]=tG; pix.val[2]=tB; img.at<Vec3b>(y,x)=pix; } } size_t temp = mymap.size(); mymap.clear(); return temp; } #endif ``` buildAnnGraph.cpp ```#include <opencv2/core/core.hpp> #include <opencv2/flann/flann.hpp> #include <vector> void buildAnnGraph(double* edgeWeight, double* vertices1, double* vertices2, double* R, double* G, double* B, int cols, int rows, int K){ double maxR=-99999,minR=99999; double maxG=-99999,minG=99999; double maxB=-99999,minB=99999; for(int i=0; i<rows*cols; i++){ if(maxR<R[i]) maxR=R[i]; if(minR>R[i]) minR=R[i]; if(maxG<G[i]) maxG=G[i]; if(minG>G[i]) minG=G[i]; if(maxB<B[i]) maxB=B[i]; if(minB>B[i]) minB=B[i]; } std::cout<<"min max done"<<std::endl; // prepare feature cv::Mat features(rows*cols,5,CV_64FC1); for(int y=0; y<rows; y++){ for(int x=0; x<cols; x++){ int id = x+y*cols; features.at<double>(id,0)=(double)x/(double)cols*256.0; features.at<double>(id,1)=(double)y/(double)rows*256.0; features.at<double>(id,2)=(R[id]-minR)/(maxR-minR)*256.0; features.at<double>(id,3)=(G[id]-minG)/(maxG-minG)*256.0; features.at<double>(id,4)=(B[id]-minB)/(maxB-minB)*256.0; //features.at<double>(id,0)=x; //features.at<double>(id,1)=y; //features.at<double>(id,2)=R[id]; //features.at<double>(id,3)=G[id]; //features.at<double>(id,4)=B[id]; }} std::cout<<"feature prepare done"<<std::endl; // construct flann indexing cv::flann::GenericIndex<cv::flann::L2<double>> index(features, cvflann::AutotunedIndexParams()); std::cout<<"index constructed"<<std::endl; // query for every pixel cv::Mat indices(rows*cols, K+1, CV_32S); cv::Mat dist(rows*cols, K+1, CV_64F); index.knnSearch(features, indices, dist, K+1, cvflann::SearchParams(32)); std::cout<<"ANN found"<<std::endl; // construct edges int num=0; for(int y=0; y<rows; y++){ for(int x=0; x<cols; x++){ int i=x+y*cols; for(int j=0; j<K+1; j++){ if(indices.at<int>(i,j)==i) continue; edgeWeight[num]=sqrt(dist.at<double>(i,j)); vertices1[num]=i; vertices2[num]=indices.at<int>(i,j); num++; } }} std::cout<<"graph constructed"<<std::endl; }``` buildGraph8N1C.cpp ```/* * Build eight nieghbor grid graph * * Input : a one-channel imH x imW image * Outputs : edge weights and end vertices * * The calling syntax is: * * [edgeWeights, vertices1, vertices2] = buildGraph8N1C(C); * C: single-channel img data * * This is a MEX-file for MATLAB. */ #include "mex.h" #include "buildGraphCore.cpp" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ if(nrhs!=1) { mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs", "One inputs required."); } if(nlhs!=3) { mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs", "Three output required."); } // input double* inMatrix; //get 1 - D matrix // output double* edgeWeights; double* vertices1; double* vertices2; /* create a pointer to the real data in the input matrix */ inMatrix = mxGetPr(prhs[0]); /* initialize helper variables */ mwSize imW = mxGetN(prhs[0]); //get # of column mwSize imH = mxGetM(prhs[0]); //get # of row long outArraySize = (imH-1)*imW + (imW-1)*imH + 2*(imH-1)*(imW-1); /* create a pointer to the real data in the output matrix */ plhs[0] = mxCreateDoubleMatrix(1, outArraySize, mxREAL); edgeWeights = mxGetPr(plhs[0]); plhs[1] = mxCreateDoubleMatrix(1, outArraySize, mxREAL); vertices1 = mxGetPr(plhs[1]); plhs[2] = mxCreateDoubleMatrix(1, outArraySize, mxREAL); vertices2 = mxGetPr(plhs[2]); /* call the computational routine */ buildGraph8N1C(edgeWeights, vertices1, vertices2, inMatrix,imW, imH); } ``` Segment.h ```// // Segment.h // ConlyImp // // Created by StevenM on 3/7/15. // Copyright (c) 2015 StevenM. All rights reserved. // #ifndef ConlyImp_Segment_h #define ConlyImp_Segment_h // // mexImgSegment.cpp // DIP_FinalProject // // Created by Lin Weiting on 2015/2/7. // Copyright (c) 2015 Weiting. All rights reserved. // // /** [SegMapR SegMapG SegMapB SegNum] = SegGraph(edgeWeights, lefts, rights, imWidth, imHeight, edgeLength, K); **/ //#include <stdio.h> //#include <iostream> //#include <fstream> //#include <sstream> #include <algorithm> #include "0_utils/myDisjointSet.h" #include "0_utils/myDisjointSet.cpp" #define CMAX 255 typedef struct { uint R, G, B; } RGB; float MInt(const myDJSNode& a, const myDJSNode& b, double K); float MInt(const float w1, const float w2, float K); inline float max3(double a, double b, double c); void Segmentation(int node_num, int edge_num, double* segMap, uint* edgeW, edge_list * vertices, int K); edges* constructGraph(uint* w, edge_list * vertices, int num); myDisjointSet* constructSegment(edges* graph, int num, double K, int edge_num); void Segmentation(int node_num, int edge_num, double* segMap, uint* edgeW, edge_list * vertices, int K){ edges* Graph = constructGraph( edgeW, vertices, edge_num); // This is the most time consuming part myDisjointSet* Segments = constructSegment(Graph, node_num, K,edge_num); for (int idx = 0; idx < node_num; ++idx) { segMap[idx] = static_cast<double> (Segments->findSet(idx)); } } edges* constructGraph(uint* w, edge_list * vertices, int num){ edges* graph = new edges[num]; for (uint idx=0; idx < num;++idx) { graph[idx].w = static_cast<float>(w[idx]); graph[idx].a = static_cast<int>(vertices[idx].first+0.5); graph[idx].b = static_cast<int>(vertices[idx].second+0.5); } return graph; } float MInt(const myDJSNode& a, const myDJSNode& b, double K){ double tempW1 = a.MSTweight + K/(a.size); double tempW2 = b.MSTweight + K/(b.size); return ( (tempW1 < tempW2) ? tempW1 : tempW2); } inline float max3(double a, double b, double c){ float temp = ( (a > b) ? a:b ); return ( (temp > c) ? temp:c ); } myDisjointSet* constructSegment(edges* graph, int num, double K, int edge_num){ myDisjointSet* segmentGraph = new myDisjointSet(num); //assign internal difference for (int temp_idx; temp_idx < num; temp_idx++) { //singalton segmentGraph->assignMSTW(temp_idx, 0); } std::sort(graph, graph + edge_num); clock_t t; t=clock(); for (int idx = 0; idx < edge_num; idx++) { int minSize=400; bool forceMerge=true; //scanIdx = static_cast<int>(sortedIdx[idx]+0.5); edges* c_edge = &graph[idx]; //the current edge //find components through the representitives int s1 = segmentGraph->findSet(c_edge->a); int s2 = segmentGraph->findSet(c_edge->b); float w1 = (*segmentGraph)[s1].MSTweight; float w2 = (*segmentGraph)[s2].MSTweight; if (s1 != s2) { //compute predicate MInt float threshold = MInt((*segmentGraph)[s1], (*segmentGraph)[s2], K); if (c_edge->w <= threshold) { segmentGraph->unionSets(s1, s2); //update MST weight int rep = segmentGraph->findSet(s1); (*segmentGraph)[rep].MSTweight = max3(w1, w2, c_edge->w); } else if(((*segmentGraph)[s1].size < minSize || (*segmentGraph)[s2].size < minSize) && forceMerge){ segmentGraph->unionSets(s1, s2); //update MST weight int rep = segmentGraph->findSet(s1); //forced merge, keep the MST weight as the largest segment if ((*segmentGraph)[s1].size <= (*segmentGraph)[s2].size){ (*segmentGraph)[rep].MSTweight = w2; }else{ (*segmentGraph)[rep].MSTweight = w1; } } else { //do nothing } } } //end segmentation t=clock()-t; printf ("Running Loop in Segmen took me %d clicks (%f seconds).\n",(int)t,((float)t)/CLOCKS_PER_SEC); return segmentGraph; } #endif ``` buildKnnGraph.cpp ```#include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/index/rtree.hpp> // to store queries results #include <vector> // just for output #include <boost/foreach.hpp> namespace bg = boost::geometry; namespace bgi = boost::geometry::index; typedef bg::model::point<float, 5, bg::cs::cartesian> Feature; // (x,y,r,g,b) typedef std::pair<Feature, unsigned int> Node; void buildKnnGraph(double* edgeWeight, double* vertices1, double* vertices2, double* R, double* G, double* B, int cols, int rows, int K){ // initialize R-Tree bgi::rtree<Node, bgi::quadratic<16> > rtree; // construct R-Tree unsigned int num=0; for(int y=0; y<rows; y++){ for(int x=0 ; x<cols ; x++){ // create a feature point Feature f; bg::set<0>(f,x); bg::set<1>(f,y); bg::set<2>(f,R[x+y*cols]); bg::set<3>(f,G[x+y*cols]); bg::set<4>(f,B[x+y*cols]); // insert new value rtree.insert(std::make_pair(f, num)); num++; }} // find K nearest value to every feature point num=0; std::vector<Node> q_result; for(int y=0; y<rows; y++){ for(int x=0 ; x<cols ; x++){ // create a feature point Feature target; bg::set<0>(target,x); bg::set<1>(target,y); bg::set<2>(target,R[x+y*cols]); bg::set<3>(target,G[x+y*cols]); bg::set<4>(target,B[x+y*cols]); // find K+1 nearest neighbor (including itself) rtree.query(bgi::nearest(target, K+1), std::back_inserter(q_result)); // construct edges for(auto it=q_result.begin(); it!=q_result.end(); it++){ if(boost::geometry::equals(target, (*it).first)) continue; edgeWeight[num] = bg::distance(target,(*it).first); vertices1[num] = x+y*cols; vertices2[num] = (*it).first.get<0>()+(*it).first.get<1>()*cols; num++; } q_result.clear(); }} }``` main.cpp ```#include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/index/rtree.hpp> // to store queries results #include <vector> // just for output #include <boost/foreach.hpp> #include "..\..\graph-based-segmentation\1_buildGraph\buildKnnGraph.cpp" #include "..\..\graph-based-segmentation\1_buildGraph\buildAnnGraph.cpp" #include "..\..\graph-based-segmentation\1_buildGraph\buildGraphCore.cpp" #include "..\..\graph-based-segmentation\2_segmentation\segGraphCore.cpp" #include "..\..\graph-based-segmentation\3_seg2color\Seg2ColorCore.cpp" namespace bg = boost::geometry; namespace bgi = boost::geometry::index; typedef bg::model::point<float, 2, bg::cs::cartesian> point; typedef bg::model::box<point> box; typedef std::pair<box, unsigned int> value; typedef bg::model::point<float, 5, bg::cs::cartesian> myPoint; typedef std::pair<myPoint, unsigned int> myV; typedef bg::model::point<float, 5, bg::cs::cartesian> feature; typedef std::pair<feature, unsigned int> node; void seg8N3C(); // test func for 8N3C void segKnn(char*, char*); // test func for Knn void segAnn(char*, char*); // test func for Ann void mat2array(double*,cv::Mat&); // util int main(){ //seg8N3C(); //segKnn("../lena128seg.png","../lena128color.tiff"); //segKnn("../lena256seg.png","../lena256color.tiff"); //segKnn("../lena512seg.png","../lena512color.tiff"); //segAnn("../lena128Ann.png","../lena128color.tiff"); //segAnn("../lena256Ann.png","../lena256color.tiff"); segAnn("../lena512HSV.png","../lena512color.tiff"); //segAnn("../beachAnn.png","../beach.jpg"); //system("PAUSE"); return 0; } void segAnn(char* dst, char* src){ cv::Mat imageC3 = cv::imread(src); // 8-bit unsigned int std::cout<<imageC3.rows<<' '<<imageC3.cols<<' '<<imageC3.channels()<<std::endl; int rows = imageC3.rows; int cols = imageC3.cols; cv::GaussianBlur( imageC3, imageC3, cv::Size(5,5), 0.8 ); cv::cvtColor(imageC3, imageC3, CV_BGR2HSV); cv::Mat channels[3]; cv::split(imageC3,channels); channels[0].convertTo(channels[0], CV_64F); channels[1].convertTo(channels[1], CV_64F); channels[2].convertTo(channels[2], CV_64F); double *R, *G, *B; B = new double[rows*cols*8]; G = new double[rows*cols*8]; R = new double[rows*cols*8]; mat2array(R,channels[0]); mat2array(G,channels[1]); mat2array(B,channels[2]); // build graph int K=6; int edgeNum = 6*rows*cols; double* edgeWeight = new double[edgeNum]; double* vertices1 = new double[edgeNum]; double* vertices2 = new double[edgeNum]; buildAnnGraph(edgeWeight, vertices1, vertices2, R,G,B, cols, rows,K); // segmentation double* segMap = new double[rows*cols]; Segmentation(rows*cols,edgeNum,segMap,edgeWeight,vertices1, vertices2, 200,20,true); // seg to color double* segB = new double[rows*cols*channels[0].elemSize()]; double* segG = new double[rows*cols*channels[1].elemSize()]; double* segR = new double[rows*cols*channels[2].elemSize()]; size_t segNum = Seg2Color(segR,segG,segB,segMap,rows*cols); cv::Mat resultRGB[3]; resultRGB[0]=cv::Mat(rows,cols,CV_64FC1,segR); resultRGB[1]=cv::Mat(rows,cols,CV_64FC1,segG); resultRGB[2]=cv::Mat(rows,cols,CV_64FC1,segB); cv::Mat result(rows,cols,CV_64FC3); cv::merge(resultRGB,3,result); result.convertTo(result,CV_8U); //cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );// Create a window for display. //cv::imshow( "Display window", result ); // Show our image inside it. cv::imwrite(dst,result); //cv::waitKey(0); delete [] R; delete [] G; delete [] B; delete [] edgeWeight; delete [] vertices1; delete [] vertices2; delete [] segMap; delete [] segB; delete [] segG; delete [] segR; } void segKnn(char* dst, char* src){ cv::Mat imageC3 = cv::imread(src); // 8-bit unsigned int int rows = imageC3.rows; int cols = imageC3.cols; //std::cout<<imageC3.channels()<<std::endl; cv::Mat channels[3]; cv::split(imageC3,channels); channels[0].convertTo(channels[0], CV_64F); channels[1].convertTo(channels[1], CV_64F); channels[2].convertTo(channels[2], CV_64F); //std::cout<<channels[0].at<double>(0,0)<<std::endl; double *R, *G, *B; B = new double[rows*cols*8]; G = new double[rows*cols*8]; R = new double[rows*cols*8]; mat2array(R,channels[0]); mat2array(G,channels[1]); mat2array(B,channels[2]); // build graph int K=6; int edgeNum = 6*rows*cols; double* edgeWeight = new double[edgeNum]; double* vertices1 = new double[edgeNum]; double* vertices2 = new double[edgeNum]; buildKnnGraph(edgeWeight, vertices1, vertices2, R,G,B, cols, rows,K); // segmentation double* segMap = new double[rows*cols]; Segmentation(rows*cols,edgeNum,segMap,edgeWeight,vertices1, vertices2, 200,20, true); // seg to color double* segB = new double[rows*cols*channels[0].elemSize()]; double* segG = new double[rows*cols*channels[1].elemSize()]; double* segR = new double[rows*cols*channels[2].elemSize()]; size_t segNum = Seg2Color(segR,segG,segB,segMap,rows*cols); cv::Mat resultRGB[3]; resultRGB[0]=cv::Mat(rows,cols,CV_64FC1,segR); resultRGB[1]=cv::Mat(rows,cols,CV_64FC1,segG); resultRGB[2]=cv::Mat(rows,cols,CV_64FC1,segB); cv::Mat result(rows,cols,CV_64FC3); cv::merge(resultRGB,3,result); result.convertTo(result,CV_8U); //cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );// Create a window for display. //cv::imshow( "Display window", result ); // Show our image inside it. cv::imwrite(dst,result); //cv::waitKey(0); delete [] R; delete [] G; delete [] B; delete [] edgeWeight; delete [] vertices1; delete [] vertices2; delete [] segMap; delete [] segB; delete [] segG; delete [] segR; } void seg8N3C(){ cv::Mat imageC3 = cv::imread("../lena512color.tiff"); // 8-bit unsigned int int rows = imageC3.rows; int cols = imageC3.cols; //std::cout<<imageC3.channels()<<std::endl; cv::Mat channels[3]; cv::split(imageC3,channels); channels[0].convertTo(channels[0], CV_64F); channels[1].convertTo(channels[1], CV_64F); channels[2].convertTo(channels[2], CV_64F); //std::cout<<channels[0].at<double>(0,0)<<std::endl; double *R, *G, *B; B = new double[rows*cols*8]; G = new double[rows*cols*8]; R = new double[rows*cols*8]; mat2array(R,channels[0]); mat2array(G,channels[1]); mat2array(B,channels[2]); // build graph int edgeNum = (rows-1)*cols + (cols-1)*rows + 2*(rows-1)*(cols-1); double* edgeWeight = new double[edgeNum]; double* vertices1 = new double[edgeNum]; double* vertices2 = new double[edgeNum]; buildGraph8N3C(edgeWeight, vertices1, vertices2, R,G,B, cols, rows, 1,1,1); // segmentation double* segMap = new double[rows*cols]; Segmentation(rows*cols,edgeNum,segMap,edgeWeight,vertices1, vertices2, 200,20,true); // seg to color double* segB = new double[rows*cols*channels[0].elemSize()]; double* segG = new double[rows*cols*channels[1].elemSize()]; double* segR = new double[rows*cols*channels[2].elemSize()]; size_t segNum = Seg2Color(segR,segG,segB,segMap,rows*cols); cv::Mat resultRGB[3]; resultRGB[0]=cv::Mat(rows,cols,CV_64FC1,segR); resultRGB[1]=cv::Mat(rows,cols,CV_64FC1,segG); resultRGB[2]=cv::Mat(rows,cols,CV_64FC1,segB); cv::Mat result(rows,cols,CV_64FC3); cv::merge(resultRGB,3,result); result.convertTo(result,CV_8U); cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );// Create a window for display. cv::imshow( "Display window", result ); // Show our image inside it. cv::waitKey(0); delete [] R; delete [] G; delete [] B; delete [] edgeWeight; delete [] vertices1; delete [] vertices2; delete [] segMap; delete [] segB; delete [] segG; delete [] segR; } void mat2array(double* dst, cv::Mat& src){ bool continuous = src.isContinuous(); if (continuous) memcpy(dst, src.ptr(),src.rows*src.cols*src.elemSize1()); else { for (int i = 0; i < src.rows; i++) { memcpy(dst+src.cols*src.elemSize1(),src.ptr(i),src.rows*src.cols*src.elemSize1()); } } }``` ImageSegmentation.cpp ```#include <jni.h> #include <stdio.h> #include "SegGraph.h" #include <math.h> #include <stdlib.h> #include <android/log.h> //#include "include/HelloJNI.h" #define CMAX 255 typedef struct { int R, G, B; } RGB; //size_t Seg2Color(int* R, int* G, int*B, float* segMap, int len); /* jint JNI_OnLoad(JavaVM* vm, void* reserved) { //cache objects //create global references return JNI_VERSION_1_6; } void JNI_OnUnload(JavaVM *vm, void *reserved); */ extern "C"{ void Segmentation(int node_num, int edge_num, int* segMap, float* edgeW, int* l, int* r, float K); //Utility inline float max3(float a, float b, float c){ float temp = ( (a > b) ? a:b ); return ( (temp > c) ? temp:c ); } float MInt(const myDJSNode& a, const myDJSNode& b, float K){ float tempW1 = a.MSTweight + K/(a.size); float tempW2 = b.MSTweight + K/(b.size); return ( (tempW1 < tempW2) ? tempW1 : tempW2); } int compareEdges (const void * a, const void * b) { if ( *(edges*)a < *(edges*)b ) return -1; if ( *(edges*)a == *(edges*)b ) return 0; if ( *(edges*)a > *(edges*)b ) return 1; } JNIEXPORT jintArray JNICALL Java_com_example_android_photobyintent_myImageHandle_ImageSegmentation (JNIEnv *env, jobject thisObj, jfloatArray w, jintArray l, jintArray r, float K, int x, int y) { __android_log_print(ANDROID_LOG_VERBOSE, "ImageSegmentation", "Start..."); //parameters for segmentation jsize dlength = (env)->GetArrayLength(w); int num_nodes = x*y; //get array from java jint* jlNodes = (env)->GetIntArrayElements(l,NULL); jint* jrNodes = (env)->GetIntArrayElements(r,NULL); jfloat* jedgeW = (env)->GetFloatArrayElements(w,NULL); __android_log_print(ANDROID_LOG_VERBOSE, "ImageSegmentation", "Assignment done..."); int* cNodes = jlNodes; int* nNodes = jrNodes; float* edgeW = jedgeW; jintArray result = (env)->NewIntArray(num_nodes); int* segMap = new int[num_nodes]; __android_log_print(ANDROID_LOG_VERBOSE, "ImageSegmentation", "Start Seg..."); Segmentation(num_nodes, dlength, segMap, edgeW, cNodes, nNodes, K); // move from the temp structure to the java structure (env)->SetIntArrayRegion(result, 0, num_nodes, segMap); //delete [] mySeg; return result; } edges* constructGraph(float* w, int* l, int* r, int num){ edges* graph = new edges[num]; for (int idx = 0; idx < num; idx++) { graph[idx].w = w[idx]; graph[idx].a = l[idx]; graph[idx].b = r[idx]; } return graph; } myDisjointSet* constructSegment(edges* graph, int num, float K, int edge_num){ myDisjointSet* segmentGraph = new myDisjointSet(num); int scanIdx = 0; //assign internal difference for (int temp_idx; temp_idx < num; temp_idx++) { //singalton segmentGraph->assignMSTW(temp_idx, 0); } //std::sort(graph, graph + edge_num); qsort(graph, edge_num, sizeof(edges), compareEdges); for (int idx = 0; idx < edge_num; idx++) { //scanIdx = static_cast<int>(sortedIdx[idx]+0.5); edges* c_edge = &graph[idx]; //the current edge //find components through the representitives int s1 = segmentGraph->findSet(c_edge->a); int s2 = segmentGraph->findSet(c_edge->b); float w1 = (*segmentGraph)[s1].MSTweight; float w2 = (*segmentGraph)[s2].MSTweight; if (s1 != s2) { //compute predicate MInt float threshold = MInt((*segmentGraph)[s1], (*segmentGraph)[s2], K); if (c_edge->w <= threshold) { segmentGraph->unionSets(s1, s2); //update MST weight int rep = segmentGraph->findSet(s1); (*segmentGraph)[rep].MSTweight = max3(w1, w2, c_edge->w); } } } //end segmentation return segmentGraph; } void Segmentation(int node_num, int edge_num, int* segMap, float* edgeW, int* l, int* r, float K){ edges* Graph = constructGraph(edgeW, l, r, edge_num); myDisjointSet* Segments = constructSegment(Graph, node_num, K,edge_num); int rep; for (int idx = 0; idx < node_num; ++idx) { rep = Segments->findSet(idx); segMap[idx] = rep; } } /* size_t Seg2Color(int* R, int* G, int*B, int* segMap, int len){ std::map<int,RGB> mymap; std::map<int,RGB>::iterator it; int tR; int tG; int tB; int cNode; for (int i = 0; i < len; ++i){ cNode = segMap[i]; //haven't assigned the color it = mymap.find(cNode); if ( it == mymap.end() ){ //assign the color tR = round(rand() % CMAX); tG = round(rand() % CMAX); tB = round(rand() % CMAX); RGB* rgb = new RGB; (*rgb).R = tR; (*rgb).B = tB; (*rgb).G = tG; mymap.insert(std::pair<double,RGB>(cNode,*rgb)); } else { tR = it->second.R; tB = it->second.B; tG = it->second.G; } R[i] = tR; G[i] = tG; B[i] = tB; } size_t temp = mymap.size(); mymap.clear(); return temp; } */ } ``` buildGraphCore.cpp ```/* mex core graph building c/c++ functions */ #include <math.h> #include <iostream> #include <fstream> ////////////////// 1 Channel ////////////////// // dissimilarity measure between pixels static inline double diff(int x1, int y1, int x2, int y2, int colNum, double* c) { return abs(c[x1 + y1*colNum] - c[x2 + y2*colNum]); } void buildGraph8N1C(double* edgeWeight, double* vertices1, double*vertices2, double* c, int imW, int imH){ long num = 0; // 4 byte int for(int y = 0; y < imH; y++){ for(int x = 0; x < imW; x++){ //Connect vertical edges if(x < imW - 1){ edgeWeight[num] = diff(x,y,x+1,y,imW, c); vertices1[num] = x + y*imW; vertices2[num] = x+1 + y*imW; num++; } //Connect horizontal edges if (y < imH-1){ edgeWeight[num] = diff(x,y,x,y+1,imW, c); vertices1[num] = x + y*imW; vertices2[num] = x + (y+1)*imW; num++; } //Connect top-left to bot-right edges if(x < imW -1 && y < imH-1){ edgeWeight[num] = diff(x,y,x+1,y+1,imW, c); vertices1[num] = x + y*imW; vertices2[num] = (x+1) + (y+1)*imW; num++; } //Connect bot-left to top-right edges if(x > 0 && y < imH-1){ edgeWeight[num] = diff(x,y,x-1,y+1,imW, c); vertices1[num] = x + y*imW; vertices2[num] = (x-1) + (y+1)*imW; num++; } }} } ///////////// 3 Channel /////////////// // dissimilarity measure between pixels static inline double diff(int x1, int y1, int x2, int y2, int colNum, double* R, double* G, double* B, double w1, double w2, double w3, int num) { double Rd = R[x1 + y1*colNum] - R[x2 + y2*colNum]; double Gd = G[x1 + y1*colNum] - G[x2 + y2*colNum]; double Bd = B[x1 + y1*colNum] - B[x2 + y2*colNum]; return sqrt(w1*Rd*Rd+w2*Gd*Gd+w3*Bd*Bd); } void buildGraph8N3C(double* edgeWeight, double* vertices1, double* vertices2, double* R, double* G, double* B, int imW, int imH, double w1, double w2, double w3){ int num = 0; // 4 byte int for(int y = 0; y < imH; y++){ for(int x = 0; x < imW; x++){ //Connect vertical edges if(x < imW - 1){ edgeWeight[num] = diff(x,y,x+1,y,imW,R, G, B, w1, w2, w3,num); vertices1[num] = x + y*imW; vertices2[num] = x+1 + y*imW; num++; } //Connect horizontal edges if (y < imH-1){ edgeWeight[num] = diff(x,y,x,y+1,imW, R, G, B, w1, w2, w3,num); vertices1[num] = x + y*imW; vertices2[num] = x + (y+1)*imW; num++; } //Connect top-left to bot-right edges if(x < imW -1 && y < imH-1){ edgeWeight[num] = diff(x,y,x+1,y+1,imW, R, G, B, w1, w2, w3,num); vertices1[num] = x + y*imW; vertices2[num] = (x+1) + (y+1)*imW; num++; } //Connect bot-left to top-right edges if(x > 0 && y < imH-1){ edgeWeight[num] = diff(x,y,x-1,y+1,imW, R, G, B, w1, w2, w3,num); vertices1[num] = x + y*imW; vertices2[num] = (x-1) + (y+1)*imW; num++; } }} }``` Seg2ColorCore.cpp ```#include <map> using namespace std; #define CMAX 255 typedef struct { double R, G, B; } RGB; size_t Seg2Color(double* R, double* G, double*B, double* segMap, int len){ map<double,RGB> mymap; map<double,RGB>::iterator it; double tR; double tG; double tB; double cNode; for (int i = 0; i < len; ++i){ cNode = (double)segMap[i]; //haven't assigned the color it = mymap.find(cNode); if ( it == mymap.end() ){ //assign the color tR = rand() % CMAX; tG = rand() % CMAX; tB = rand() % CMAX; RGB* rgb = new RGB; (*rgb).R = tR; (*rgb).B = tB; (*rgb).G = tG; mymap.insert(std::pair<double,RGB>(cNode,*rgb)); } else { tR = it->second.R; tB = it->second.B; tG = it->second.G; } R[i] = tR; G[i] = tG; B[i] = tB; } size_t temp = mymap.size(); mymap.clear(); return temp; }``` buildGraph8N3C.cpp ```/* * Build eight nieghbor grid graph * * Input : a three-channel imH x imW image * Outputs : edge weights and end vertices * * The calling syntax is: * * [edgeWeights, vertices1, vertices2] = buildGraph8N3C(R,G,B,w1,w2,w3); * R,G,B : in general it can be any three channels for images * w1,w2,w3 : differnet weights for measuring the difference * * This is a MEX-file for MATLAB. */ #include "mex.h" #include "buildGraphCore.cpp" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ if(nrhs!=6) { mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs", "Six inputs required."); } if(nlhs!=3) { mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs", "Three output required."); } // input double* inMatrixR; //get 1 - D matrix double* inMatrixG; //get 1 - D matrix double* inMatrixB; //get 1 - D matrix double *w1,*w2,*w3; // output double* edgeWeights; double* vertices1; double* vertices2; /* create a pointer to the real data in the input matrix */ inMatrixR = mxGetPr(prhs[0]); inMatrixG = mxGetPr(prhs[1]); inMatrixB = mxGetPr(prhs[2]); w1 = mxGetPr(prhs[3]); w2 = mxGetPr(prhs[4]); w3 = mxGetPr(prhs[5]); /* initialize helper variables */ mwSize imH = mxGetN(prhs[0]); //get # of column mwSize imW = mxGetM(prhs[0]); //get # of row long outArraySize = (imH-1)*imW + (imW-1)*imH + 2*(imH-1)*(imW-1); /* create a pointer to the real data in the output matrix */ plhs[0] = mxCreateDoubleMatrix(1, outArraySize, mxREAL); edgeWeights = mxGetPr(plhs[0]); plhs[1] = mxCreateDoubleMatrix(1, outArraySize, mxREAL); vertices1 = mxGetPr(plhs[1]); plhs[2] = mxCreateDoubleMatrix(1, outArraySize, mxREAL); vertices2 = mxGetPr(plhs[2]); /* call the computational routine */ buildGraph8N3C(edgeWeights, vertices1, vertices2, inMatrixR, inMatrixG, inMatrixB, imW, imH, *w1, *w2, *w3); }``` SegGraphCore.cpp ```// // mexImgSegment.cpp // DIP_FinalProject // // Created by Lin Weiting on 2015/2/7. // Copyright (c) 2015 Weiting. All rights reserved. // // /** [SegMapR SegMapG SegMapB SegNum] = SegGraph(edgeWeights, lefts, rights, imWidth, imHeight, edgeLength, K); **/ //#include <stdio.h> //#include <iostream> //#include <fstream> //#include <sstream> #include <algorithm> #include "../0_utils/myDisjointSet.h" #include "../0_utils/myDisjointSet.cpp" float MInt(const myDJSNode& a, const myDJSNode& b, double K); float MInt(const float w1, const float w2, float K); inline float max3(double a, double b, double c); void Segmentation(int node_num, int edge_num, double* segMap, double* edgeW, double* l, double* r, double K, double minSize, bool forceMerge); edges* constructGraph(double* w, double* l, double* r,int num); myDisjointSet* constructSegment(edges* graph, int num, double K, int edge_num, double minSize, bool forceMerge); //string ToString(size_t sz) { // stringstream ss; // ss << sz; // return ss.str(); //} void Segmentation(int node_num, int edge_num, double* segMap, double* edgeW, double* l, double* r, double K, double minSize, bool forceMerge){ edges* Graph = constructGraph(edgeW, l, r, edge_num); myDisjointSet* Segments = constructSegment(Graph, node_num, K,edge_num, minSize, forceMerge); for (int idx = 0; idx < node_num; ++idx) { segMap[idx] = static_cast<double> (Segments->findSet(idx)); } } edges* constructGraph(double* w, double* l, double* r, int num){ edges* graph = new edges[num]; for (int idx = 0; idx < num; idx++) { graph[idx].w = static_cast<float>(w[idx]); graph[idx].a = static_cast<int>(l[idx]+0.5); graph[idx].b = static_cast<int>(r[idx]+0.5); } return graph; } float MInt(const myDJSNode& a, const myDJSNode& b, double K){ double tempW1 = a.MSTweight + K/(a.size); double tempW2 = b.MSTweight + K/(b.size); return ( (tempW1 < tempW2) ? tempW1 : tempW2); } inline float max3(double a, double b, double c){ float temp = ( (a > b) ? a:b ); return ( (temp > c) ? temp:c ); } myDisjointSet* constructSegment(edges* graph, int num, double K, int edge_num, double minSize, bool forceMerge){ myDisjointSet* segmentGraph = new myDisjointSet(num); int scanIdx = 0; //assign internal difference for (int temp_idx=0; temp_idx < num; temp_idx++) { //singalton segmentGraph->assignMSTW(temp_idx, 0); } std::sort(graph, graph + edge_num); for (int idx = 0; idx < edge_num; idx++) { //scanIdx = static_cast<int>(sortedIdx[idx]+0.5); edges* c_edge = &graph[idx]; //the current edge //find components through the representitives int s1 = segmentGraph->findSet(c_edge->a); int s2 = segmentGraph->findSet(c_edge->b); float w1 = (*segmentGraph)[s1].MSTweight; float w2 = (*segmentGraph)[s2].MSTweight; if (s1 != s2) { //compute predicate MInt float threshold = MInt((*segmentGraph)[s1], (*segmentGraph)[s2], K); if (c_edge->w <= threshold) { segmentGraph->unionSets(s1, s2); //update MST weight int rep = segmentGraph->findSet(s1); (*segmentGraph)[rep].MSTweight = max3(w1, w2, c_edge->w); } else if(((*segmentGraph)[s1].size < minSize || (*segmentGraph)[s2].size < minSize) && forceMerge){ segmentGraph->unionSets(s1, s2); //update MST weight int rep = segmentGraph->findSet(s1); //forced merge, keep the MST weight as the largest segment if ((*segmentGraph)[s1].size <= (*segmentGraph)[s2].size){ (*segmentGraph)[rep].MSTweight = w2; }else{ (*segmentGraph)[rep].MSTweight = w1; } } else { //do nothing } } } //end segmentation return segmentGraph; } ``` myDisjointSet.h ```// // myDisjointSet.h // DIP_FinalProject // // Created by Lin Weiting on 2015/2/7. // Copyright (c) 2015年 Weiting. All rights reserved. // #ifndef __DIP_FinalProject__myDisjointSet__ #define __DIP_FinalProject__myDisjointSet__ #include <stdio.h> #include <vector> #include "edges.h" using namespace std; //#include "typeUtility.h" class myDJSNode{ //copy constructor public: int p; //index to the parent int rank; int size; //size of the disjoint set float MSTweight; }; class myDisjointSet{ public: myDisjointSet(int num); ~myDisjointSet(){ delete [] nodes;} //Disjoint Set methods //makeSet is already performed in initialization //void makeSet(int idx); int findSet(int idx); //return the representitive void unionSets(int u, int v); int size(int idx){ return nodes[idx].size; } int numOfSet(){ return setNum; } inline void assignMSTW(int idx, float w){ nodes[idx].MSTweight = w; } inline float weight(int idx){ return nodes[idx].MSTweight; } inline myDJSNode& operator[](const int idx){ return nodes[idx]; } inline myDJSNode& operator[](const int idx) const { return nodes[idx]; } private: myDJSNode* nodes; int setNum; //the number of disjoint sets int maxNum; vector<int> A; }; #endif /* defined(__DIP_FinalProject__myDisjointSet__) */ ``` boost_segment.h ```// // boost_segment.h // ConlyImp // // Created by StevenM on 3/12/15. // Copyright (c) 2015 StevenM. All rights reserved. // #ifndef ConlyImp_boost_segment_h #define ConlyImp_boost_segment_h typedef std::vector<int> VecInt; void B_Segmentation(int, int, double*, uint*, edge_list, int); void B_Segmentation(int nNodes, int nEdges, double * segMap, uint * edgeWeight, edge_list vertices, int k) { VecInt rank (100); VecInt parent (100); boost::disjoint_sets<int*,int*> ds(&rank[0], &parent[0]); } #endif ``` buildGraph.h ```// // buildGraph.h // ConlyImp // // Created by StevenM on 3/4/15. // Copyright (c) 2015 StevenM. All rights reserved. // #ifndef ConlyImp_buildGraph_h #define ConlyImp_buildGraph_h /* * Build eight nieghbor grid graph * * Input : a three-channel imH x imW image * Outputs : edge weights and end vertices * * The calling syntax is: * <<<<<<< HEAD:build_8N_GridGraph_RGB.cpp * [edgeWeights, vertices] = build_8N_GridGraph_RGB(R,G,B,w1,w2,w3); ======= * [edgeWeights, vertices] = eightNeighborGridGraph(R,G,B,w1,w2,w3); >>>>>>> ba306a3c3d3ea1a60d4fa880ce79f241a7951339:eightNeighborGridGraph.cpp * R,G,B : in general it can be any three channels for images * w1,w2,w3 : differnet weights for measuring the difference * * This is a MEX-file for MATLAB. */ #include <math.h> static inline float diff(int x1, int y1, int x2, int y2, Mat &img, double w1, double w2, double w3) { uchar R1,R2,G1,G2,B1,B2; Vec3b pix; // First pixel pix=img.at<Vec3b>(y1,x1); R1=pix.val[0]; G1=pix.val[1]; B1=pix.val[2]; // Second pixel pix=img.at<Vec3b>(y2,x2); R2=pix.val[0]; G2=pix.val[1]; B2=pix.val[2]; float Rd = R1 - R2; float Gd = G1 - G2; float Bd = B1 - B2; return sqrt(w1*Rd*Rd+w2*Gd*Gd+w3*Bd*Bd); } void eightNeighborGridGraph(uint* edgeWeight, edge_list *vertices, Mat &img, double w1=1, double w2=1, double w3=1){ //Allocating memory for the graph uint imW=img.rows; uint imH=img.cols; uint num = 0; for(uint y = 0; y < imW; y++){ for(uint x = 0; x < imH; x++){ //Connect vertical edges if(x < imH - 1){ //edgeWeight[num] = diff(x,y,x+1,y,imH,R, G, B, w1, w2, w3); edgeWeight[num]= diff(x,y,x+1,y,img, w1, w2, w3); vertices[num].first=x + y*imH; vertices[num].second=x+1 + y*imH; num++; } //Connect horizontal edges if (y < imW-1){ edgeWeight[num] = diff(x,y,x,y+1,img,w1, w2, w3); vertices[num].first=x + y*imH; vertices[num].second=x + (y+1)*imH; num++; } //Connect up-left to down-left edges if(x < imH -1 && y < imW-1){ edgeWeight[num] = diff(x,y,x+1,y+1,img, w1, w2, w3); vertices[num].first=x + y*imH; vertices[num].second=(x+1) + (y+1)*imH; num++; } //Connect down-left to up-right edges if(x > 0 && y < imW-1){ edgeWeight[num] = diff(x,y,x-1,y+1,img, w1, w2, w3); vertices[num].first=x + y*imH; vertices[num].second=(x-1) + (y+1)*imH; num++; } } } } #endif ``` SegGraph.h ```// // meximgSegment.h // DIP_FinalProject // // Created by Lin Weiting on 2015/2/8. // Copyright (c) 2015�?Weiting. All rights reserved. // #ifndef DIP_FinalProject_meximgSegment_h #define DIP_FinalProject_meximgSegment_h #include "myDisjointSet.h" #include "myDisjointSet.cpp" #include "typeUtility.h" #endif ```
zhongnanshan/osgopenvrviewer
zhongnanshan/osgopenvrviewer testplanets.cpp ```#include <osg/Node> #include <osgViewer/Viewer> osg::Node* createEarth(); void main() { osgViewer::Viewer viewer; viewer.setSceneData( createEarth() ); viewer.run(); }``` planets.cpp ``` #include <osg/Node> #include <osg/Geode> #include <osg/Vec4> #include <osg/Texture2D> #include <osg/Geometry> #include <osg/TexEnvCombine> #include <osg/MatrixTransform> #include <osg/Image> #include <osgDB/ReadFile> osg::Geode* createPlanet(double radius, const std::string& name, const osg::Vec4& color, const std::string& textureName) { // create a container that makes the sphere drawable osg::Geometry *sPlanetSphere = new osg::Geometry(); { // set the single colour so bind overall osg::Vec4Array* colours = new osg::Vec4Array(1); (*colours)[0] = color; sPlanetSphere->setColorArray(colours, osg::Array::BIND_OVERALL); // now set up the coords, normals and texcoords for geometry unsigned int numX = 100; unsigned int numY = 50; unsigned int numVertices = numX*numY; osg::Vec3Array* coords = new osg::Vec3Array(numVertices); sPlanetSphere->setVertexArray(coords); osg::Vec3Array* normals = new osg::Vec3Array(numVertices); sPlanetSphere->setNormalArray(normals, osg::Array::BIND_PER_VERTEX); osg::Vec2Array* texcoords = new osg::Vec2Array(numVertices); sPlanetSphere->setTexCoordArray(0, texcoords); sPlanetSphere->setTexCoordArray(1, texcoords); double delta_elevation = osg::PI / (double)(numY - 1); double delta_azim = 2.0*osg::PI / (double)(numX - 1); float delta_tx = 1.0 / (float)(numX - 1); float delta_ty = 1.0 / (float)(numY - 1); double elevation = -osg::PI*0.5; float ty = 0.0; unsigned int vert = 0; unsigned j; for (j = 0; j<numY; ++j, elevation += delta_elevation, ty += delta_ty) { double azim = 0.0; float tx = 0.0; for (unsigned int i = 0; i<numX; ++i, ++vert, azim += delta_azim, tx += delta_tx) { osg::Vec3 direction(cos(azim)*cos(elevation), sin(azim)*cos(elevation), sin(elevation)); (*coords)[vert].set(direction*radius); (*normals)[vert].set(direction); (*texcoords)[vert].set(tx, ty); } } for (j = 0; j<numY - 1; ++j) { unsigned int curr_row = j*numX; unsigned int next_row = curr_row + numX; osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(GL_QUAD_STRIP); for (unsigned int i = 0; i<numX; ++i) { elements->push_back(next_row + i); elements->push_back(curr_row + i); } sPlanetSphere->addPrimitiveSet(elements); } } // set the object color //sPlanetSphere->setColor( color ); // create a geode object to as a container for our drawable sphere object osg::Geode* geodePlanet = new osg::Geode(); geodePlanet->setName(name); if (!textureName.empty()) { osg::Image* image = osgDB::readImageFile(textureName); if (image) { osg::Texture2D* tex2d = new osg::Texture2D(image); tex2d->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT); tex2d->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT); geodePlanet->getOrCreateStateSet()->setTextureAttributeAndModes(0, tex2d, osg::StateAttribute::ON); // reset the object color to white to allow the texture to set the colour. //sPlanetSphere->setColor( osg::Vec4(1.0f,1.0f,1.0f,1.0f) ); } } // add our drawable sphere to the geode container geodePlanet->addDrawable(sPlanetSphere); return(geodePlanet); }// end SolarSystem::createPlanet osg::Geode* createPlanet(double radius, const std::string& name, const osg::Vec4& color, const std::string& textureName1, const std::string& textureName2) { osg::Geode* geodePlanet = createPlanet(radius, name, color, textureName1); if (!textureName2.empty()) { osg::Image* image = osgDB::readImageFile(textureName2); if (image) { osg::StateSet* stateset = geodePlanet->getOrCreateStateSet(); osg::TexEnvCombine* texenv = new osg::TexEnvCombine; texenv->setCombine_RGB(osg::TexEnvCombine::INTERPOLATE); texenv->setSource0_RGB(osg::TexEnvCombine::PREVIOUS); texenv->setOperand0_RGB(osg::TexEnvCombine::SRC_COLOR); texenv->setSource1_RGB(osg::TexEnvCombine::TEXTURE); texenv->setOperand1_RGB(osg::TexEnvCombine::SRC_COLOR); texenv->setSource2_RGB(osg::TexEnvCombine::PRIMARY_COLOR); texenv->setOperand2_RGB(osg::TexEnvCombine::SRC_COLOR); stateset->setTextureAttribute(1, texenv); osg::Texture2D* tex2d = new osg::Texture2D(image); tex2d->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT); tex2d->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT); stateset->setTextureAttributeAndModes(1, tex2d, osg::StateAttribute::ON); } } return(geodePlanet); }// end SolarSystem::createPlanet class RotateCallback : public osg::NodeCallback { public: RotateCallback() : osg::NodeCallback(), enabled_(true), velocityScale(0.1) {} void operator()(osg::Node* node, osg::NodeVisitor *nv) { osg::MatrixTransform *xform = dynamic_cast<osg::MatrixTransform *>(node); if (xform && enabled_) { double t = nv->getFrameStamp()->getSimulationTime(); xform->setMatrix(osg::Matrix::rotate(velocityScale * t, osg::Vec3(0, 0, 1))); } traverse(node, nv); } bool enabled_; double velocityScale; }; osg::Node* createEarth() { osg::Group* root = new osg::Group; osg::ClearNode* clearNode = new osg::ClearNode; clearNode->setClearColor(osg::Vec4(0.0f, 0.0f, 0.0f, 1.0f)); root->addChild(clearNode); std::string mapEarth = "Images/land_shallow_topo_2048.jpg"; std::string mapEarthNight = "Images/land_ocean_ice_lights_2048.jpg"; osg::Node* earth = createPlanet(100.0f, "Earth", osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f), mapEarth, mapEarthNight); osg::MatrixTransform* earthRotate = new osg::MatrixTransform; earthRotate->addUpdateCallback(new RotateCallback()); earthRotate->addChild(earth); return earthRotate; } ```
zhongren/hshb-admin
zhongren/hshb-admin edit.js ```/** * Created by HQ on 2017/1/8. */ var p = ((function () { //返回当前 URL 的查询部分(问号 ? 之后的部分)。 var urlParameters = location.search; //声明并初始化接收请求参数的对象 var requestParameters = new Object(); //如果该求青中有请求的参数,则获取请求的参数,否则打印提示此请求没有请求的参数 if (urlParameters.indexOf('?') != -1) { //获取请求参数的字符串 var parameters = decodeURI(urlParameters.substr(1)); //将请求的参数以&分割中字符串数组 parameterArray = parameters.split('&'); //循环遍历,将请求的参数封装到请求参数的对象之中 for (var i = 0; i < parameterArray.length; i++) { requestParameters[parameterArray[i].split('=')[0]] = (parameterArray[i].split('=')[1]); } console.info('theRequest is =====', requestParameters); } else { console.info('There is no request parameters'); } return requestParameters; })()); console.log(p); function edit(action) { if (action === "save") { addUser(); console.log("save"); } else if (action === "update") { updateUser(); console.log("update"); } } function addUser() { var depart=[]; $( ".m_depart:checked").each(function(){depart.push(this.value);}); var user_image=$("#m_user_image").val(); var name = $("#m_name").val(); var sex = $("#m_sex").val(); var position = $("#m_position").val(); var edu = $("#m_edu").val(); var phoneNumber = $("#m_phoneNumber").val(); var remark = $("#m_remark").val(); if (!validator.validate()) return false; $.ajaxInvoke({ url: G_CTX_ROOT + "/user/save", type: "post", datatype: "json", data: { name: name, pic: user_image, sex: sex, eduLevel: edu, position: position, phone: phoneNumber, desc: remark, departmentIds: depart }, success: function (data) { $("#myModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } function updateUser() { var depart=[]; $( ".m_depart:checked").each(function(){depart.push(this.value);}); var id=$("#id").val(); var user_image=$("#m_user_image").val(); var name = $("#m_name").val(); var sex = $("#m_sex").val(); var position = $("#m_position").val(); var edu = $("#m_edu").val(); var phoneNumber = $("#m_phoneNumber").val(); var remark = $("#m_remark").val(); if (!validator.validate()) return false; $.ajaxInvoke({ url: G_CTX_ROOT + "/user/update", type: "post", datatype: "json", data: { id:id, name: name, pic: user_image, sex: sex, eduLevel: edu, position: position, phone: phoneNumber, desc: remark, departmentIds: depart }, success: function (data) { $("#myModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } ``` PictureService.java ```package com.lebao.service.impl; import com.google.gson.Gson; import com.lebao.common.utils.FtpUtil; import com.lebao.common.utils.Sequence; import com.lebao.service.i.IPictureService; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.util.HashMap; import java.util.Map; /** * Created by Server on 2016/7/15. */ @Service public class PictureService implements IPictureService { private String FTP_ADDRESS; private int FTP_PORT; private String FTP_USERNAME; private String FTP_PASSWORD; private String FTP_BATH_PATH; private String IMAGE_BATH_URL; public String uploadPicture(MultipartFile uploadFile) { Map result = new HashMap(); Gson gson = new Gson(); try { String oldNmae = uploadFile.getOriginalFilename(); String newName = Sequence.nextId() + getSuffix(oldNmae); String filePath = new DateTime().toString("/yyyy/MM/dd"); boolean struts = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, FTP_BATH_PATH, filePath, newName, uploadFile.getInputStream()); // 返回结果 // System.out.println(struts); if (!struts) {// 上传失败 result.put("error", 1); result.put("message", "上传失败"); return gson.toJson(result); } else { result.put("error", 0); result.put("url", IMAGE_BATH_URL + filePath + "/" + newName); return gson.toJson(result); } } catch (Exception e) { e.printStackTrace(); result.put("error", 1); result.put("message", "上传失败"); return gson.toJson(result); } } /** * 获取后缀名 * * @param str * @return */ public String getSuffix(String str) { return str.substring(str.indexOf(".")); } } ``` goods.js ```$(document) .ready( function () { setting.sAjaxSource = G_CTX_ROOT + "/goods/query"; setting.aoColumns = [ { "sTitle": "<center>游戏编号</center>", //显示标题 "mData": "id", //属性 "bSortable": true,//排序 "sClass": "center", "sWidth": "3%" }, { "sTitle": "<center>名称</center>", //显示标题 "mData": "name", //属性 "bSortable": false,//排序 "sClass": "center", "sWidth": "4%" }, /* { "sTitle": "<center>区服</center>", //显示标题 "mData": "server", //属性 "bSortable": false,//排序 "sClass": "center", "sWidth": "1%" }, */ { "sTitle": "<center>状态</center>", //显示标题 "mData": "state", //属性 "bSortable": true,//排序 "sClass": "center", "sWidth": "1%" }, { "sTitle": "<center>是否推荐</center>", //显示标题 "mData": "tuijian", //属性 "bSortable": true,//排序 "sClass": "center", "sWidth": "1%" }, { "sTitle" : "<center>创建时间</center>", // 显示标题 "mData" : "createTime", // 属性 "bSortable" : true,// 排序 "sClass" : "center", "sWidth" : "4%" }, { "sTitle": "<center>操作</center>", // 显示标题 "bSortable": false,// 排序 "mData": "id", // 属性 "sClass": "center", "sWidth": "3%", "mRender": function (data, style, obj) { console.log(obj) var xqDom = "<a class=\"btn btn-round btn-info btn-xs\" href=\"/goods/preUpdate/" + obj.id + "\" >查看详情</a>"; var delDom = "<a class=\"btn btn-round btn-danger btn-xs\" onclick=\"preDel(" + obj.id + ")\" >下架</a>"; var reAddDom = "<a class=\"btn btn-round btn-danger btn-xs\" onclick=\"preReAdd(" + obj.id + ")\" >上架</a>"; var tuijianDom = "<a class=\"btn btn-round btn-danger btn-xs\" onclick=\"tuijian(" + obj.id + ")\" >推荐</a>"; var delTuijianDom = "<a class=\"btn btn-round btn-danger btn-xs\" onclick=\"delTuijianDom(" + obj.id + ")\" >取消推荐</a>"; return xqDom + "&nbsp;" + delDom + "&nbsp;" + reAddDom + "&nbsp;" + tuijianDom + "&nbsp;" + delTuijianDom; } }]; setting.aaSorting = [[3, "desc"]]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); var rule = { m_name: { name: "类型名称", method: { required: true } }, m_price: { name: "充值单价", method: { required: true, isNum: true } }, m_price_base_user: { name: "普通会员价", method: { required: true, isNum: true } }, m_price_hy_user: { name: "普通会员价", method: { required: true, isNum: true } }, m_score: { name: "点券兑换比率", method: { required: true, isNum: true } }, m_server: { name: "区服(可以填默认)", method: { required: true } }, m_rate_base_user: { name: "普通会员折扣", method: { required: true, isNum: true } }, m_rate_hy_user: { name: "付费会员折扣", method: { required: true, isNum: true } }, m_type_id: { name: "商品类型", method: { required: true } } }; validator.init(rule); $("#picUrl").uploadify({ height: 20, removeCompleted: true, buttonText: '选择文件', swf: G_CTX_ROOT + '/staticUploadify/uploadify.swf', width: 100, uploader: "/upload/goods/picUrl", fileSizeLimit: 1000 * 1024, fileTypeExts: '*.jpg;*.png;*.gif;*.bmp;', fileTypeDesc: '请选择图片!', onSelect: function (e, queueId, fileObj) { }, onClearQueue: function (queueItemCount) { //mAlert(queueItemCount); }, onSelectError: function (file, errorCode, errorMsg) {//当文件选定发生错误时触发 /* alert( 'onSelectErrorid: ' + file.id   + ' - 索引: ' + file.index   + ' - 文件名: ' + file.name   + ' - 文件大小: ' + file.size   + ' - 类型: ' + file.type   + ' - 创建日期: ' + file.creationdate   + ' - 修改日期: ' + file.modificationdate   + ' - 文件状态: ' + file.filestatus   + ' - 错误代码: ' + errorCode   + ' - 错误信息: ' + errorMsg);*/ if (file.size > 1000 * 1024) { $("#picUrlClass").html("<font color=red >图片超出上传限制,请重选择!</font>"); //$("#picUrl").uploadifyCancel(file.id); //onClearQueue(); } else { $("#picUrlClass").html(""); } }, onQueueComplete: function (stats) {//当队列中的所有文件全部完成上传时触发 /*alert( '成功上传的文件数: ' + stats.successful_uploads   + ' - 上传出错的文件数: ' + stats.upload_errors   + ' - 取消上传的文件数: ' + stats.upload_cancelled   + ' - 出错的文件数' + stats.queue_errors);*/ }, onUploadStart: function (file) {//上传开始时触发(每个文件触发一次) /*alert( 'onUploadStart id: ' + file.id   + ' - 索引: ' + file.index   + ' - 文件名: ' + file.name   + ' - 文件大小: ' + file.size   + ' - 类型: ' + file.type   + ' - 创建日期: ' + file.creationdate   + ' - 修改日期: ' + file.modificationdate   + ' - 文件状态: ' + file.filestatus ); */ if (file.size > 1000 * 1024) { //mAlert("文件超过1MB,请重新选择!","信息提示"); $("#picUrlClass").html("<font color=red>文件超出上传限制,请重选择!</font>"); onClearQueue(); } else { $("#picUrlClass").html(""); } }, onUploadSuccess: function (file, data, response) { //var json =jQuery.parseJSON(data); uploadPicUrl2 = true; //div显示文件的名称 以及删除 $("#picUrlName").css("display", ""); $("#picUrlName").html(file.name); $("#picUrlDel").css("display", "block"); $("#picUrlVal").val(data); }, onUploadError: function (file, errorCode, errorMsg, errorString, swfuploadifyQueue) {//上传文件出错是触发(每个出错文件触发一次) /*alert( ' onUploadError id: ' + file.id   + ' - 索引: ' + file.index   + ' - 文件名: ' + file.name   + ' - 文件大小: ' + file.size   + ' - 类型: ' + file.type   + ' - 创建日期: ' + file.creationdate   + ' - 修改日期: ' + file.modificationdate   + ' - 文件状态: ' + file.filestatus   + ' - 出错的文件数: ' + swfuploadifyQueue.filesErrored   + ' - 错误信息: ' + swfuploadifyQueue.errorMsg   + ' - 要添加至队列的数量: ' + swfuploadifyQueue.filesSelected   + ' - 添加至对立的数量: ' + swfuploadifyQueue.filesQueued   + ' - 队列长度: ' + swfuploadifyQueue.queueLength); */ //alert(errorCode + ",file :" +file); //console.log(" file " + file); $("#picUrl").uploadifyCancel(errorCode); }, onError: function (event, queueId, fileObj, errorObj) { //alert("onError"); if (errorObj.type === "File Size") { alert('文件超出上传大小限制!'); $("#picUrl").uploadifyCancel(ID); } } }); $("#picUrl2").uploadify({ height: 20, buttonText: '选择文件', removeCompleted: true, swf: G_CTX_ROOT + '/staticUploadify/uploadify.swf', width: 100, uploader: "/upload/goods/picUrl2", fileSizeLimit: 1000 * 1024, fileTypeExts: '*.jpg;*.png;*.gif;*.bmp;', fileTypeDesc: '请选择图片!', onSelect: function (e, queueId, fileObj) { }, onClearQueue: function (queueItemCount) { //mAlert(queueItemCount); }, onSelectError: function (file, errorCode, errorMsg) {//当文件选定发生错误时触发 /* alert( 'onSelectErrorid: ' + file.id   + ' - 索引: ' + file.index   + ' - 文件名: ' + file.name   + ' - 文件大小: ' + file.size   + ' - 类型: ' + file.type   + ' - 创建日期: ' + file.creationdate   + ' - 修改日期: ' + file.modificationdate   + ' - 文件状态: ' + file.filestatus   + ' - 错误代码: ' + errorCode   + ' - 错误信息: ' + errorMsg);*/ if (file.size > 1000 * 1024) { $("#picUrl2Class").html("<font color=red >图片超出上传限制,请重选择!</font>"); //$("#picUrl").uploadifyCancel(file.id); onClearQueue(); } else { $("#picUrl2Class").html(""); } }, onQueueComplete: function (stats) {//当队列中的所有文件全部完成上传时触发 /*alert( '成功上传的文件数: ' + stats.successful_uploads   + ' - 上传出错的文件数: ' + stats.upload_errors   + ' - 取消上传的文件数: ' + stats.upload_cancelled   + ' - 出错的文件数' + stats.queue_errors);*/ }, onUploadStart: function (file) {//上传开始时触发(每个文件触发一次) /*alert( 'onUploadStart id: ' + file.id   + ' - 索引: ' + file.index   + ' - 文件名: ' + file.name   + ' - 文件大小: ' + file.size   + ' - 类型: ' + file.type   + ' - 创建日期: ' + file.creationdate   + ' - 修改日期: ' + file.modificationdate   + ' - 文件状态: ' + file.filestatus ); */ if (file.size > 1000 * 1024) { //mAlert("文件超过1MB,请重新选择!","信息提示"); $("#picUrl2Class").html("<font color=red>文件超出上传限制,请重选择!</font>"); onClearQueue(); } else { $("#picUrl2Class").html(""); } }, onUploadSuccess: function (file, data, response) { //var json =jQuery.parseJSON(data); uploadPicUrl2 = true; //div显示文件的名称 以及删除 $("#picUrl2Name").css("display", ""); $("#picUrl2Name").html(file.name); $("#picUrl2Del").css("display", "block"); /* $("#imgBox").val("${loginuser.infoUserTab.u_url}"); */ $("#picUrl2Val").val(data); //alert(data); }, onUploadError: function (file, errorCode, errorMsg, errorString, swfuploadifyQueue) {//上传文件出错是触发(每个出错文件触发一次) /*alert( ' onUploadError id: ' + file.id   + ' - 索引: ' + file.index   + ' - 文件名: ' + file.name   + ' - 文件大小: ' + file.size   + ' - 类型: ' + file.type   + ' - 创建日期: ' + file.creationdate   + ' - 修改日期: ' + file.modificationdate   + ' - 文件状态: ' + file.filestatus   + ' - 出错的文件数: ' + swfuploadifyQueue.filesErrored   + ' - 错误信息: ' + swfuploadifyQueue.errorMsg   + ' - 要添加至队列的数量: ' + swfuploadifyQueue.filesSelected   + ' - 添加至对立的数量: ' + swfuploadifyQueue.filesQueued   + ' - 队列长度: ' + swfuploadifyQueue.queueLength); */ //alert(errorCode + ",file :" +file); //console.log(" file " + file); $("#picUrl2").uploadifyCancel(errorCode); }, onError: function (event, queueId, fileObj, errorObj) { //alert("onError"); if (errorObj.type === "File Size") { alert('文件超出上传大小限制!'); $("#picUrl2").uploadifyCancel(ID); } } }); }); function doSearch() { dataTable.fnDraw(); } //删除图片 function delFj1(id) { $("#" + id).css("display", "none"); //进行删除处理操作 var fileUrl = $("#picUrlVal").val();// $.ajaxInvoke({ url: G_CTX_ROOT + "/upload/delFj/goods", type: "post", data: { "fileUrl": fileUrl }, //success : "操作成功", success: function (data) { msgBox(data.state, data.msg); $("#picUrlVal").val(""); $("#picUrlName").css("display", "none"); }, error: "操作失败" }); } //删除图片 function delFj2(id) { $("#" + id).css("display", "none"); //进行删除处理操作 var fileUrl = $("#picUrl2Val").val();// $.ajaxInvoke({ url: G_CTX_ROOT + "/upload/delFj/goods", type: "post", data: { "fileUrl": fileUrl }, //success : "操作成功", success: function (data) { msgBox(data.state, data.msg); $("#picUrl2Val").val(""); $("#picUrl2Name").css("display", "none"); }, error: "操作失败" }); } function addGoods() { editor.sync(); var photo1 = $("#m_photo1").val(); var photo2 = $("#m_photo2").val(); var name = $("#m_name").val(); var server = $("#m_server").val(); var type_id = $("#m_type_id").val(); var price_base_user = $("#m_price_base_user").val(); var price_hy_user = $("#m_price_hy_user").val(); var price = $("#m_price").val(); var score = $("#m_score").val(); var rate_base_user = $("#m_rate_base_user").val(); var rate_hy_user = $("#m_rate_hy_user").val(); var url = $("#m_url").val(); //var desc = UE.getEditor('editor').getContent(); var desc = $('#editor').val(); if (!validator.validate()) return false; $.ajaxInvoke({ url: G_CTX_ROOT + "/goods/add", type: "post", datatype: "json", data: { p_type_id: type_id, p_server: server, p_name: name, p_photo1: photo1, p_photo2: photo2, p_price: price, p_price_base_user:price_base_user, p_price_hy_user:price_hy_user, p_score: score, p_rate_base_user: rate_base_user, p_rate_hy_user: rate_hy_user, p_url: url, p_sequence: 1, p_desc: desc }, success: function (data) { msgBox(data.state, data.msg); }, }); } function updGoods() { editor.sync(); var photo1 = $("#m_photo1").val();//小图片 var photo2 = $("#m_photo2").val();//大图片 var id = $("#m_id").val(); var name = $("#m_name").val(); var server = $("#m_server").val(); var type_id = $("#m_type_id").val(); var price = $("#m_price").val(); var price_base_user = $("#m_price_base_user").val(); var price_hy_user = $("#m_price_hy_user").val(); var score = $("#m_score").val(); var rate_base_user = $("#m_rate_base_user").val(); var rate_hy_user = $("#m_rate_hy_user").val(); var url = $("#m_url").val(); var desc = $('#editor').val(); //alert(server) if (!validator.validate()) return false; $.ajaxInvoke({ url: G_CTX_ROOT + "/goods/update", type: "post", datatype: "json", data: { p_id: id, p_type_id: type_id, p_name: name, p_server: server, p_photo1: photo1, p_photo2: photo2, p_price: price, p_score: score, p_rate_base_user: rate_base_user, p_rate_hy_user: rate_hy_user, p_url: url, p_sequence: 1, p_desc: desc, p_price_base_user:price_base_user, p_price_hy_user:price_hy_user, }, success: function (data) { msgBox(data.state, data.msg); }, }); } function preReAdd(id) { //alert(id); $("#myModal2").modal("show").css({ 'top': '60px' }); $("#reAdd").attr("onClick", "reAdd(" + id + ")"); } function reAdd(id) { $.ajaxInvoke({ url: G_CTX_ROOT + "/goods/reAdd/", type: "post", datatype: "json", data: { p_id: id }, success: function (data) { $("#myModal2").modal("hide") msgBox(data.state, data.msg); dataTable.fnDraw(); }, }); } function preDel(id) { //alert(id); $("#myModal").modal("show").css({ 'top': '60px' }); $("#del").attr("onClick", "del(" + id + ")"); } function del(id) { $.ajaxInvoke({ url: G_CTX_ROOT + "/goods/delete/", type: "post", datatype: "json", data: { p_id: id }, success: function (data) { $("#myModal").modal("hide") msgBox(data.state, data.msg); dataTable.fnDraw(); }, }); } function tuijian(id) { $.ajaxInvoke({ url: G_CTX_ROOT + "/goods/tuijian/", type: "post", datatype: "json", data: { p_id: id }, success: function (data) { msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } function delTuijianDom(id) { $.ajaxInvoke({ url: G_CTX_ROOT + "/goods/delTuijian/", type: "post", datatype: "json", data: { p_id: id }, success: function (data) { msgBox(data.state, data.msg); dataTable.fnDraw(); } }); }``` TypeController.java ```package com.lebao.controller; import com.lebao.bean.SearchParam; import com.lebao.bean.TypeBean; import com.lebao.common.dbhelp.page.Page; import com.lebao.service.i.ITypeService; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.Map; /** * Created by Server on 2016/3/29. */ @Controller @RequestMapping(value = "type") public class TypeController extends BaseController { private Logger logger = Logger.getLogger(TypeController.class); @Autowired private ITypeService typeService; @RequestMapping("/list") public ModelAndView list() { ModelAndView view = new ModelAndView(); view.addObject("title", "广告类型管理>>类型查询"); view.setViewName("admin/type/list"); return view; } @RequestMapping(value = "/query", produces = "plain/text; charset=UTF-8") @ResponseBody public String query(HttpServletRequest request) { Map<String, Object> obj = this.getParametersStartWidth(request, "s_"); String name = (String) obj.get("name"); DataTableVo dt = this.parseData4DT(request); int start = dt.getiDisplayStart(); int length = dt.getiDisplayLength(); int curPage = 0; if (dt.getiDisplayStart() > 0) { curPage = start / length + 1; } String json = null; try { SearchParam s = new SearchParam(); if (StringUtils.isNotBlank(name)) { s.setName(name); } s.setPageNow(curPage); s.setPageSize(length); Page<TypeBean> pages = typeService.getTypes(s); dt.setData(pages.getData()); dt.setiTotalRecords(dt.getiTotalRecords()); dt.setiTotalRecords(pages.getRecordCount()); json = formateData2DT(dt); } catch (Exception e) { logger.error(e); } return json; } @RequestMapping(value = "/preAdd") public ModelAndView preAdd(HttpServletRequest request) { ModelAndView view = new ModelAndView(); view.addObject("title", "广告类型管理>>广告类型添加"); view.setViewName("admin/type/add"); return view; } @RequestMapping("/add") @ResponseBody public String add( TypeBean tb) { try { typeService.addType(tb); return this.buildSuccessMessage("shoper_add_success", ResultModal.MESSAGE); } catch (Exception e) { logger.error("添加商家失败", e); return this.buildFailMessage("shoper_add_fail", ResultModal.MESSAGE); } } @RequestMapping(value = "/preUpdate/{id}") public ModelAndView preUpdate(@PathVariable String id) { ModelAndView view = new ModelAndView(); view.addObject("title", "广告类型管理>>广告类型详情"); try { TypeBean tb = typeService.getTypeById(id); view.addObject("TypeBean", tb); } catch (Exception e) { logger.error("商品查询失败", e); } view.setViewName("admin/type/update"); return view; } @RequestMapping("/update") @ResponseBody public String update( TypeBean tb) { try { typeService.updType(tb); return this.buildSuccessMessage("shoper_update_success", ResultModal.MESSAGE); } catch (Exception e) { logger.error("更新商家失败", e); return this.buildFailMessage("shoper_update_fail", ResultModal.MESSAGE); } } @RequestMapping("/delete") @ResponseBody public String delete(HttpServletRequest request) { String id = request.getParameter("p_id"); try { typeService.delType(id); return this.buildSuccessMessage("shoper_delete_success", ResultModal.MESSAGE); } catch (Exception e) { logger.error("删除商家失败", e); return this.buildFailMessage("shoper_delete_fail2", ResultModal.MESSAGE); } } @RequestMapping("/reAdd") @ResponseBody public String reAdd(HttpServletRequest request) { String p_id = request.getParameter("p_id"); try { typeService.reAddType(p_id); return this.buildSuccessMessage("shoper_add_success", ResultModal.MESSAGE); } catch (Exception e) { logger.error("上架商家失败", e); return this.buildFailMessage("shoper_add_fail", ResultModal.MESSAGE); } } } ``` liushui.js ```$(document) .ready( function() { setting.sAjaxSource = G_CTX_ROOT+"/liushui/query"; setting.aoColumns = [ { "sTitle" : "订单编号", //显示标题 "mData" : "id", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "用户编号", //显示标题 "mData" : "user_id", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "金额", //显示标题 "mData" : "price", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "充值时间", //显示标题 "mData" : "create_time", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "5%" }, ]; setting.aaSorting = [ [ 3, "desc" ] ]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); }); function doSearch() { dataTable.fnDraw(); } ``` SysRolePermissionMap.java ```package com.lebao.modules.permission.entity; /** * Created by Server on 2016/5/5. */ public class SysRolePermissionMap { private String p_permission_id = null; // 表字段名称为:f_permission_id 相应注释为:权限ID。 private String p_role_id = null; // 表字段名称为:f_role_id 相应注释为:角色ID。 private String p_id = null; // 表字段名称为:p_id 相应注释为:ID。 private String p_create_time = null; // 表字段名称为:s_create_time 相应注释为:创建时间。 public String getP_permission_id() { return p_permission_id; } public void setP_permission_id(String p_permission_id) { this.p_permission_id = p_permission_id; } public String getP_role_id() { return p_role_id; } public void setP_role_id(String p_role_id) { this.p_role_id = p_role_id; } public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } } ``` UserDao.java ```package com.lebao.dao.user; import com.lebao.common.beans.SearchBean; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.po.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; @Repository public class UserDao { @Autowired UserRepo userRepo; @Autowired DbHelper dbHelper; public Page<User> getPage(SearchBean searchBean) throws SQLException { String sql = " SELECT * from tb_user where 1=1 "; List<Object> list = new ArrayList<Object>(); Map<Object, Object> map = searchBean.getParamMap(); if (map.containsKey("name")) { sql += " and tb_user.name like ? "; list.add("%" + map.get("name") + "%"); } sql += " order by " + searchBean.getSortField() + " " + searchBean.getSortType() + " "; return dbHelper.getPage(sql, User.class, searchBean.getCurrentPage(), searchBean.getPageSize(), list.toArray()); } public User save(User user) { return userRepo.save(user); } public void update(User user) { userRepo.save(user); } public void delete(User user) { userRepo.delete(user); } public User findOne(Long id) { return userRepo.findOne(id); } } ``` GoodsDao.java ```package com.lebao.modules.goods.dao; import com.lebao.bean.SearchParam; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.common.utils.Sequence; import com.lebao.common.utils.TimeUtil; import com.lebao.modules.BaseDao; import com.lebao.modules.goods.entity.GoodsEntity; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.sql.SQLException; import java.util.Date; /** * Created by Server on 2016/4/1. */ @Repository public class GoodsDao<T> extends BaseDao<T>{ @Resource(name = "dbHelper") private DbHelper dbHelper; public int add(GoodsEntity ge) throws SQLException { String p_id = Sequence.nextId(); String p_type_id = ge.getP_type_id(); String p_name = ge.getP_name(); String p_photo1 = ge.getP_photo1(); String p_photo2 = ge.getP_photo2(); Float p_price = ge.getP_price(); Float p_score = ge.getP_score(); Float p_rate_base_user = ge.getP_rate_base_user(); Float p_rate_hy_user = ge.getP_rate_hy_user(); String p_desc = ge.getP_desc(); String p_url = ge.getP_url(); String p_state = ge.getP_state(); Integer p_sequence = ge.getP_sequence(); String p_create_time = TimeUtil.format(new Date(), TimeUtil.TARGET_1); String sql = "INSERT INTO t_goods(p_id,p_type_id,p_name,p_photo1,p_photo2,p_price,p_score,p_rate_base_user,p_rate_hy_user,p_desc, p_url,p_state,p_sequence,p_create_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; return dbHelper.execute(sql, p_id, p_type_id, p_name, p_photo1,p_photo2, p_price, p_score,p_rate_base_user,p_rate_hy_user, p_desc, p_url, p_state, p_sequence, p_create_time); } public int delete(String p_id) throws SQLException { String sql = "update t_goods set p_state = '-1' where p_id=?"; return dbHelper.execute(sql,p_id); } public int reAdd(String p_id) throws SQLException { String sql = "update t_goods set p_state = '1' where p_id=?"; return dbHelper.execute(sql, p_id); } public int addTuijian(String p_id) throws SQLException { String sql = "update t_goods set p_tuijian = '1' where p_id=?"; return dbHelper.execute(sql, p_id); } public int delTuijian(String p_id) throws SQLException { String sql = "update t_goods set p_tuijian = '-1' where p_id=?"; return dbHelper.execute(sql, p_id); } public GoodsEntity getGoodsEntity(String p_id) throws SQLException { String sql = "select * from t_goods where p_id=?"; return dbHelper.getBean(sql, GoodsEntity.class, p_id); } public Page<GoodsEntity> getGoodsEntities(SearchParam s) throws SQLException { String sql = " select * from t_goods where 1=1"; if( StringUtils.isNotBlank(s.getName())){ sql +=" and t_goods.p_name like '%"+s.getName()+"%' "; } sql += " order by " + s.getSortField() + " " + s.getSortType() + " "; System.out.println(sql); return dbHelper.getPage(sql, GoodsEntity.class, s.getPageNow(),s.getPageSize()); } } ``` UserController.java ```package com.lebao.controller; import java.util.*; import javax.servlet.http.HttpServletRequest; import com.lebao.common.utils.CommonUtil; import com.lebao.common.utils.UrlUtil; import com.lebao.converter.UserConverter; import com.lebao.file.AppConfig; import com.lebao.po.*; import com.lebao.service.*; import com.lebao.vo.SysUserVo; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.lebao.common.beans.SearchBean; import com.lebao.common.dbhelp.page.Page; import com.lebao.vo.UserVo; /** * Author: zr Date : 2017/1/10 18:00 */ @Controller @RequestMapping("/user") public class UserController extends BaseController { @Autowired private AppConfig appConfig; @Autowired private UserService userService; @Autowired private UserDepartmentRelService userDepartmentRelService; @Autowired private EduLevelService eduLevelService; @Autowired private DepartmentService departmentService; @Autowired private PositionService positionService; @Autowired private UserConverter userConverter; /** * 页面入口 * * @return */ @RequestMapping("/index") public ModelAndView index() { ModelAndView view = new ModelAndView(); view.addObject("title", "系统管理>>用户查询"); view.setViewName("admin/user/index"); return view; } @RequestMapping("/userQR") public ModelAndView userQR() { ModelAndView view = new ModelAndView(); //view.addObject("title", "系统管理>>用户查询"); view.setViewName("admin/user/userQR"); return view; } @RequestMapping("/edit") public ModelAndView edit(@RequestParam("module") String module, @RequestParam("action") String action, @RequestParam(value = "id", required = false) Long id) { ModelAndView view = new ModelAndView(); List<EduLevel> eduLevelList = eduLevelService.findAll(); List<Position> positionList = positionService.findAll(); List<Department> departmentList = departmentService.findAll(); view.addObject("eduLevelList", eduLevelList); view.addObject("positionList", positionList); view.addObject("departmentList", departmentList); if ("save".equals(action)) { view.setViewName("admin/user/edit"); } else if ("update".equals(action)) { UserVo userVo = userService.findOne(id); view.addObject("userVo", userVo); view.setViewName("admin/user/edit"); } return view; } /** * 分页数据查询 * * @param request * @return */ @RequestMapping(value = "/query", produces = "plain/text; charset=UTF-8") @ResponseBody public String query(HttpServletRequest request) { Map<String, Object> obj = this.getParametersStartWidth(request, "s_"); String name = (String) obj.get("name"); BaseController.DataTableVo dt = this.parseData4DT(request); int start = dt.getiDisplayStart(); int length = dt.getiDisplayLength(); int curPage = 0; if (dt.getiDisplayStart() > 0) { curPage = start / length + 1; } String json = null; try { SearchBean s = new SearchBean(); if (StringUtils.isNotBlank(name)) { s.getParamMap().put("name", name); } if (dt.getSortField().equals("user_id")) { s.setSortField("id"); } s.setSortType(dt.getSortType()); s.setCurrentPage(curPage); s.setPageSize(length); Page<UserVo> pages = userService.getPage(s); dt.setData(pages.getData()); dt.setiTotalRecords(dt.getiTotalRecords()); dt.setiTotalRecords(pages.getRecordCount()); json = formateData2DT(dt); } catch (Exception e) { e.printStackTrace(); } return json; } /** * 添加用户 * * @param name * @param pic * @param sex * @param eduLevel * @param position * @param phone * @param desc * @param departmentIds * @return */ @RequestMapping(value = "/save", produces = "plain/text; charset=UTF-8") @ResponseBody public String save( @RequestParam(value = "name", required = true) String name, @RequestParam(value = "pic", required = true) String pic, @RequestParam(value = "sex", required = true) Integer sex, @RequestParam(value = "eduLevel", required = true) Long eduLevel, @RequestParam(value = "position", required = true) Long position, @RequestParam(value = "phone", required = true) String phone, @RequestParam(value = "desc", required = true) String desc, @RequestParam(value = "departmentIds[]", required = false) Long departmentIds[]) { try { UserVo userVo = new UserVo(); userVo.setName(name); userVo.setPic(pic); userVo.setSex(sex); userVo.setEduLevel(eduLevel); userVo.setPosition(position); userVo.setPhone(phone); userVo.setRemark(desc); User user = userConverter.convert2P(userVo); userService.save(user); if (!CommonUtil.isEmpty(Arrays.asList(departmentIds))) { for (Long id : departmentIds) { UserDepartmentRel userDepartmentRel = new UserDepartmentRel(); userDepartmentRel.setUid(user.getId()); userDepartmentRel.setDid(id); userDepartmentRelService.save(userDepartmentRel); } } String qr = userService.saveQR(user); user.setQr(qr); userService.update(user); return this.buildSuccessMessage("员工添加成功", ResultModal.MESSAGE); } catch (Exception e) { e.printStackTrace(); return this.buildFailMessage("员工添加失败", ResultModal.MESSAGE); } } /** * @param id * @param name * @param pic * @param sex * @param eduLevel * @param position * @param phone * @param desc * @param departmentIds * @return */ @RequestMapping(value = "/update", produces = "plain/text; charset=UTF-8") @ResponseBody public String update( @RequestParam(value = "id", required = true) Long id, @RequestParam(value = "name", required = true) String name, @RequestParam(value = "pic", required = true) String pic, @RequestParam(value = "sex", required = true) Integer sex, @RequestParam(value = "eduLevel", required = true) Long eduLevel, @RequestParam(value = "position", required = true) Long position, @RequestParam(value = "phone", required = true) String phone, @RequestParam(value = "desc", required = true) String desc, @RequestParam(value = "departmentIds[]", required = false) Long departmentIds[]) { try { UserVo userVo = userService.findOne(id); if (userVo == null) { return this.buildFailMessage("员工不存在", ResultModal.MESSAGE); } userVo.setName(name); userVo.setPic(pic); userVo.setSex(sex); userVo.setEduLevel(eduLevel); userVo.setPosition(position); userVo.setPhone(phone); userVo.setRemark(desc); User user = userConverter.convert2P(userVo); userService.save(user); List<UserDepartmentRel> oldUserDepartmentRelList = userDepartmentRelService .findByUid(userVo.getId()); List<Long> oldDepartmentIds = new ArrayList<Long>(); for (UserDepartmentRel userDepartmentRel : oldUserDepartmentRelList) { oldDepartmentIds.add(userDepartmentRel.getId()); } userDepartmentRelService.deleteBatch(oldDepartmentIds); for (Long did : departmentIds) { UserDepartmentRel userDepartmentRel = new UserDepartmentRel(); userDepartmentRel.setUid(userVo.getId()); userDepartmentRel.setDid(did); userDepartmentRelService.save(userDepartmentRel); } if (userService.deleteQR(user.getId())) { String qr = userService.saveQR(user); user.setQr(qr); userService.update(user); } return this.buildSuccessMessage("员工更新成功", ResultModal.MESSAGE); } catch (Exception e) { e.printStackTrace(); return this.buildFailMessage("员工更新失败", ResultModal.MESSAGE); } } /** * 删除用户 * * @param id * @return */ @RequestMapping("/delete") @ResponseBody public String delete(@RequestParam(value = "id", required = true) Long id) { try { userService.delete(id); return this.buildSuccessMessage("员工删除成功", ResultModal.MESSAGE); } catch (Exception e) { e.printStackTrace(); return this.buildFailMessage("员工删除失败", ResultModal.MESSAGE); } } } ``` NewsType.java ```package com.lebao.po; import javax.persistence.*; /** * Created by ZR on 2016/12/8. */ @Entity @Table(name="tb_newstype") public class NewsType { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private Long fid; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getFid() { return fid; } public void setFid(Long fid) { this.fid = fid; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "newstype{" + "id=" + id + ", fid=" + fid + ", name='" + name + '\'' + '}'; } } ``` GoodsBean.java ```package com.lebao.bean; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Server on 2016/3/30. */ public class GoodsBean { @JsonProperty("id") private String p_id;//bigint(20) NOT NULL id @JsonProperty("type_id") private String p_type_id;//bigint(20) NOT NULL type_id @JsonProperty("name") private String p_name;//varchar(20) NULL 商品名称 @JsonProperty("server") private String p_server; @JsonProperty("photo1") private String p_photo1;//varchar(20) NULL 图片名称 @JsonProperty("photo2") private String p_photo2;//varchar(20) NULL 图片名称 @JsonProperty("price") private Float p_price;//float(15,2) NOT NULL 价格 @JsonProperty("score") private Float p_score;//float(15,2) NOT 点券(游戏币)<->充值单价,兑换比率 @JsonProperty("rate_base_user") private Float p_rate_base_user;//float(15,2) NOT NULL普通会员充值折扣(比率) @JsonProperty("rate_hy_user") private Float p_rate_hy_user;//float(15,2) NOT NULL 付费会员充值折扣(比率) @JsonProperty("url") private String p_url;//varchar(20) NULL 链接 @JsonProperty("description") private String p_desc;//varchar(255) NULL 描述 @JsonProperty("state") private String p_state;//tinyint(1) NOT NULL 状态(1可用,-1不可用) @JsonProperty("tuijian") private String p_tuijian;//tinyint(1) NOT NULL 状态(1推荐,-1不推荐) private Integer p_sequence;//int(20) NOT NULL 序号 @JsonProperty("createTime") private String p_create_time;//timestamp NULL创建时间 private String p_update_time;//timestamp NULL更新时间 @JsonProperty("price_base_user") private Float p_price_base_user;//普通用户的价格 @JsonProperty("price_hy_user")//会员价 private Float p_price_hy_user; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_type_id() { return p_type_id; } public void setP_type_id(String p_type_id) { this.p_type_id = p_type_id; } public String getP_name() { return p_name; } public void setP_name(String p_name) { this.p_name = p_name; } public String getP_photo1() { return p_photo1; } public void setP_photo1(String p_photo1) { this.p_photo1 = p_photo1; } public String getP_photo2() { return p_photo2; } public void setP_photo2(String p_photo2) { this.p_photo2 = p_photo2; } public Float getP_price() { return p_price; } public void setP_price(Float p_price) { this.p_price = p_price; } public Float getP_rate_hy_user() { return p_rate_hy_user; } public void setP_rate_hy_user(Float p_rate_hy_user) { this.p_rate_hy_user = p_rate_hy_user; } public Float getP_rate_base_user() { return p_rate_base_user; } public void setP_rate_base_user(Float p_rate_base_user) { this.p_rate_base_user = p_rate_base_user; } public Float getP_score() { return p_score; } public void setP_score(Float p_score) { this.p_score = p_score; } public String getP_url() { return p_url; } public void setP_url(String p_url) { this.p_url = p_url; } public String getP_desc() { return p_desc; } public void setP_desc(String p_desc) { this.p_desc = p_desc; } public String getP_state() { return p_state; } public void setP_state(String p_state) { this.p_state = p_state; } public Integer getP_sequence() { return p_sequence; } public void setP_sequence(Integer p_sequence) { this.p_sequence = p_sequence; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public String getP_update_time() { return p_update_time; } public void setP_update_time(String p_update_time) { this.p_update_time = p_update_time; } public String getP_tuijian() { return p_tuijian; } public void setP_tuijian(String p_tuijian) { this.p_tuijian = p_tuijian; } public String getP_server() { return p_server; } public void setP_server(String p_server) { this.p_server = p_server; } public Float getP_price_base_user() { return p_price_base_user; } public void setP_price_base_user(Float p_price_base_user) { this.p_price_base_user = p_price_base_user; } public Float getP_price_hy_user() { return p_price_hy_user; } public void setP_price_hy_user(Float p_price_hy_user) { this.p_price_hy_user = p_price_hy_user; } @Override public String toString() { return "GoodsBean{" + "p_id='" + p_id + '\'' + ", p_type_id='" + p_type_id + '\'' + ", p_name='" + p_name + '\'' + ", p_photo1='" + p_photo1 + '\'' + ", p_photo2='" + p_photo2 + '\'' + ", p_price=" + p_price + ", p_rate_base_user=" + p_rate_base_user + ", p_rate_hy_user=" + p_rate_hy_user + ", p_url='" + p_url + '\'' + ", p_desc='" + p_desc + '\'' + ", p_state='" + p_state + '\'' + ", p_tuijian='" + p_tuijian + '\'' + ", p_sequence=" + p_sequence + ", p_create_time=" + p_create_time + ", p_update_time=" + p_update_time + '}'; } } ``` GoodsSearchParam.java ```package com.lebao.bean; /** * Created by Server on 2016/4/8. */ public class GoodsSearchParam { private String name; private int pageSize = 15; private int curPage = 0; private String sortField = "p_create_time"; private String sortType = "desc"; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurPage() { return curPage; } public void setCurPage(int curPage) { this.curPage = curPage; } public String getSortField() { return sortField; } public void setSortField(String sortField) { this.sortField = sortField; } public String getSortType() { return sortType; } public void setSortType(String sortType) { this.sortType = sortType; } } ``` UserService.java ```package com.lebao.service; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.lebao.common.beans.SearchBean; import com.lebao.common.dbhelp.page.Page; import com.lebao.common.utils.QRUtil; import com.lebao.common.utils.TimeUtil; import com.lebao.common.utils.UrlUtil; import com.lebao.converter.UserConverter; import com.lebao.dao.user.UserDao; import com.lebao.file.AppConfig; import com.lebao.po.User; import com.lebao.vo.UserVo; import org.apache.commons.io.FileUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Author: zr * Date : 2016/12/6 18:13 */ @Service public class UserService { @Autowired private AppConfig appConfig; @Autowired UserDao userDao; @Autowired UserConverter userConverter; public Page<UserVo> getPage(SearchBean s) throws SQLException { int myPageSize = 0;//每页记录数 int curPage = 0;//显示页 int pageCount = 0;//页数 int recordCount = 0;//总记录数 Page<User> userPage = userDao.getPage(s); List<UserVo> list = userConverter.convert2V(userPage.getData()); recordCount = userPage.getRecordCount(); pageCount = userPage.getPageCount(); curPage = userPage.getCurPage(); myPageSize = userPage.getPageSize(); Page<UserVo> pageBean = new Page<UserVo>(myPageSize, list, curPage, pageCount, recordCount); return pageBean; } public User save(User user) { user.setCreateTime(TimeUtil.str2Date(TimeUtil.now())); user.setUpdateTime(TimeUtil.str2Date(TimeUtil.now())); return userDao.save(user); } public User update(User user) { user.setUpdateTime(TimeUtil.str2Date(TimeUtil.now())); return userDao.save(user); } public void delete(Long id) { UserVo vo = findOne(id); User user = userConverter.convert2P(vo); userDao.delete(user); } public UserVo findOne(Long id) { User user = userDao.findOne(id); return userConverter.convert2V(user); } /** * 生成二维码 * @param user * @return * @throws Exception */ public String saveQR(User user) throws Exception { String content = appConfig.getSERVER_NAME() + "/qr/user?uid=" + user.getId(); String path = appConfig.getUSER_QR(); MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Map hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = null; bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400, hints); File file1 = new File(path, user.getName()+".jpg"); QRUtil.writeToFile(bitMatrix, "jpg", file1); return appConfig.getSERVER_USER_QR()+"/" + user.getName()+".jpg"; } public boolean deleteQR(Long uid) throws Exception { String path = appConfig.getUSER_QR(); UserVo u=findOne(uid); File file = new File(path, u.getName()+".jpg"); if(file.exists()){ file.delete(); } return true; } } ``` InitController.java ```package com.lebao.controller.hshb; import java.util.List; import com.lebao.common.constant.Hshb; import com.lebao.po.Position; import com.lebao.service.PositionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.lebao.common.beans.AjaxResult; import com.lebao.po.Department; import com.lebao.po.EduLevel; import com.lebao.service.DepartmentService; import com.lebao.service.EduLevelService; @RestController public class InitController { @Autowired private Hshb hshb; @Autowired private DepartmentService departmentService; @Autowired private EduLevelService eduLevelService; @Autowired private PositionService positionService; @RequestMapping(value = "init") public AjaxResult createDepartment() { try { List<Department> departmentList = hshb.createDepartment(); for (Department department : departmentList) { departmentService.save(department); } List<EduLevel> eduLevelList = hshb.createEduLevel(); for (EduLevel eduLevel : eduLevelList) { eduLevelService.save(eduLevel); } List<Position> positionList=hshb.createPosition(); for (Position position : positionList) { positionService.save(position); } return AjaxResult.success("初始化成功"); } catch (Exception e) { e.printStackTrace(); return AjaxResult.fail("初始化失败"); } } } ``` User.java ```package com.lebao.po; import javax.persistence.*; import java.util.Date; /** * Created by ZR on 2017/1/8. */ @Entity @Table(name = "tb_user") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } private String name; private String pic; private String qr; private Integer sex; private Long eduLevel; private Long position; private String phone; private String remark; private Date createTime; private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public Long getEduLevel() { return eduLevel; } public void setEduLevel(Long eduLevel) { this.eduLevel = eduLevel; } public Long getPosition() { return position; } public void setPosition(Long position) { this.position = position; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getQr() { return qr; } public void setQr(String qr) { this.qr = qr; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public User() { } public String getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pic='" + pic + '\'' + ", sex=" + sex + ", eduLevel=" + eduLevel + ", position=" + position + ", phone='" + phone + '\'' + ", remark='" + remark + '\'' + ", createTime=" + createTime + ", updateTime=" + updateTime + '}'; } } ``` NewsBean.java ```package com.lebao.bean; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Server on 2016/4/21. */ public class NewsBean { @JsonProperty("id") private String p_id;//编号 @JsonProperty("user_id") private String p_user_id;//创建人编号 @JsonProperty("title") private String p_title;//标题 @JsonProperty("htmlPart") private String p_htmlPart;//html内容 @JsonProperty("browseTime") private String p_browseTime;//浏览次数 @JsonProperty("p_type_id") private String p_type_id;//广告类型 @JsonProperty("photo1") private String p_photo1;//大图 @JsonProperty("photo2") private String p_photo2;//小图 @JsonProperty("create_time") private String p_create_time;//创建时间 @JsonProperty("update_time") private String p_update_time;//更新时间 @JsonProperty("url") private String p_url;//url地址 @JsonProperty("status") private String p_status;//状态 public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_user_id() { return p_user_id; } public void setP_user_id(String p_user_id) { this.p_user_id = p_user_id; } public String getP_title() { return p_title; } public void setP_title(String p_title) { this.p_title = p_title; } public String getP_htmlPart() { return p_htmlPart; } public void setP_htmlPart(String p_htmlPart) { this.p_htmlPart = p_htmlPart; } public String getP_browseTime() { return p_browseTime; } public void setP_browseTime(String p_browseTime) { this.p_browseTime = p_browseTime; } public String getP_type_id() { return p_type_id; } public void setP_type_id(String p_type_id) { this.p_type_id = p_type_id; } public String getP_photo1() { return p_photo1; } public void setP_photo1(String p_photo1) { this.p_photo1 = p_photo1; } public String getP_photo2() { return p_photo2; } public void setP_photo2(String p_photo2) { this.p_photo2 = p_photo2; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public String getP_update_time() { return p_update_time; } public void setP_update_time(String p_update_time) { this.p_update_time = p_update_time; } public String getP_url() { return p_url; } public void setP_url(String p_url) { this.p_url = p_url; } public String getP_status() { return p_status; } public void setP_status(String p_status) { this.p_status = p_status; } @Override public String toString() { return "NewsBean{" + "p_id='" + p_id + '\'' + ", p_user_id='" + p_user_id + '\'' + ", p_title='" + p_title + '\'' + ", p_htmlPart='" + p_htmlPart + '\'' + ", p_browseTime='" + p_browseTime + '\'' + ", p_type_id='" + p_type_id + '\'' + ", p_photo1='" + p_photo1 + '\'' + ", p_photo2='" + p_photo2 + '\'' + ", p_create_time='" + p_create_time + '\'' + ", p_update_time='" + p_update_time + '\'' + ", p_url='" + p_url + '\'' + ", p_status='" + p_status + '\'' + '}'; } } ``` Hshb.java ```package com.lebao.common.constant; import com.lebao.po.Department; import com.lebao.po.EduLevel; import com.lebao.po.Position; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by ZR on 2017/1/8. */ @Component public class Hshb { public List<Department> createDepartment() { List<Department> departmentList = new ArrayList<Department>(); departmentList.add(new Department(1L, "管理层")); departmentList.add(new Department(2L, "总经理室")); departmentList.add(new Department(3L, "财务部")); departmentList.add(new Department(4L, "业务部")); departmentList.add(new Department(5L, "内控部")); departmentList.add(new Department(6L, "行政人事部")); departmentList.add(new Department(7L, "废液处置部")); departmentList.add(new Department(8L, "技术研发部")); departmentList.add(new Department(9L, "生产部")); departmentList.add(new Department(10L, "固废处置部")); departmentList.add(new Department(11L, "维修部")); departmentList.add(new Department(12L, "安全部")); departmentList.add(new Department(13L, "物流部")); departmentList.add(new Department(14L, "押运")); departmentList.add(new Department(15L, "其他")); return departmentList; } public List<EduLevel> createEduLevel() { List<EduLevel> eduLevelList = new ArrayList<EduLevel>(); eduLevelList.add(new EduLevel(1L, "初中")); eduLevelList.add(new EduLevel(2L, "高中")); eduLevelList.add(new EduLevel(3L, "中专")); eduLevelList.add(new EduLevel(4L, "大专")); eduLevelList.add(new EduLevel(5L, "本科")); eduLevelList.add(new EduLevel(6L, "硕士")); eduLevelList.add(new EduLevel(7L, "博士")); eduLevelList.add(new EduLevel(8L, "其他")); eduLevelList.add(new EduLevel(9L, "保密")); return eduLevelList; } public List<Position> createPosition() { List<Position> positionList = new ArrayList<Position>(); positionList.add(new Position(1L, "总经理")); positionList.add(new Position(2L, "副总经理")); positionList.add(new Position(3L, "经理")); positionList.add(new Position(4L, "主管")); positionList.add(new Position(5L, "员工")); return positionList; } } ``` OrderDetailSearchParam.java ```package com.lebao.bean; /** * Created by Server on 2016/4/8. */ public class OrderDetailSearchParam { private String order_id;//订单号 private int pageSize = 15; private int curPage = 0; public String getOrder_id() { return order_id; } public void setOrder_id(String order_id) { this.order_id = order_id; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurPage() { return curPage; } public void setCurPage(int curPage) { this.curPage = curPage; } } ``` SysMenuBean.java ```package com.lebao.bean; import com.lebao.modules.permission.entity.SysPermissionEntity; import java.util.List; public class SysMenuBean { private String p_id;//int(10) NOT NULL private String p_fid;//int(10) NOT NULL private String p_name;//varchar(50) NULL private String p_url; private List<SysMenuBean> fmenus; private SysPermissionEntity permission ; private String p_icon = "icon-book"; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_fid() { return p_fid; } public void setP_fid(String p_fid) { this.p_fid = p_fid; } public String getP_name() { return p_name; } public void setP_name(String p_name) { this.p_name = p_name; } public List<SysMenuBean> getFmenus() { return fmenus; } public void setFmenus(List<SysMenuBean> fmenus) { this.fmenus = fmenus; } public String getP_url() { return p_url; } public void setP_url(String p_url) { this.p_url = p_url; } public String getP_icon() { return p_icon; } public void setP_icon(String p_icon) { this.p_icon = p_icon; } public SysPermissionEntity getPermission() { return permission; } public void setPermission(SysPermissionEntity permission) { this.permission = permission; } @Override public String toString() { return "SysMenuBean{" + "p_id='" + p_id + '\'' + ", p_fid='" + p_fid + '\'' + ", p_name='" + p_name + '\'' + ", p_url='" + p_url + '\'' + ", fmenus=" + fmenus + ", permission=" + permission + ", p_icon='" + p_icon + '\'' + '}'; } } ``` NewsController.java ```package com.lebao.controller; import com.lebao.common.beans.SearchBean; import com.lebao.common.dbhelp.page.Page; import com.lebao.service.NewsService; import com.lebao.service.NewsTypeService; import com.lebao.vo.NewsTypeVo; import com.lebao.vo.NewsVo; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.sql.SQLException; import java.util.List; import java.util.Map; /** * Created by ZR on 2016/12/6. */ @Controller @RequestMapping(value = "news") public class NewsController extends BaseController { @Autowired NewsService newsService; @Autowired NewsTypeService newsTypeService; /** * 页面入口 * * @return */ @RequestMapping("/index") public ModelAndView index() { ModelAndView view = new ModelAndView(); view.addObject("title", "文章管理>>文章查询"); view.setViewName("admin/news/newsindex"); return view; } /** * 分页数据查询 * * @param request * @return */ @RequestMapping(value = "/query", produces = "plain/text; charset=UTF-8") @ResponseBody public String query(HttpServletRequest request) { Map<String, Object> obj = this.getParametersStartWidth(request, "s_"); String name = (String) obj.get("name"); DataTableVo dt = this.parseData4DT(request); int start = dt.getiDisplayStart(); int length = dt.getiDisplayLength(); int curPage = 0; if (dt.getiDisplayStart() > 0) { curPage = start / length + 1; } String json = null; try { SearchBean s = new SearchBean(); if (StringUtils.isNotBlank(name)) { s.getParamMap().put("name", name); } if (dt.getSortField().equals("id")) { s.setSortField("id"); } s.setSortType(dt.getSortType()); s.setCurrentPage(curPage); s.setPageSize(length); Page<NewsVo> pages = newsService.getPage(s); dt.setData(pages.getData()); dt.setiTotalRecords(dt.getiTotalRecords()); dt.setiTotalRecords(pages.getRecordCount()); json = formateData2DT(dt); } catch (Exception e) { e.printStackTrace(); } return json; } /** * 预添加 * * @return */ @RequestMapping("/preSave") public ModelAndView preSave() { ModelAndView view = new ModelAndView(); view.addObject("title", "文章管理>>文章添加"); List<NewsTypeVo> list = null; try { list = newsTypeService.queryAll(); view.addObject("newsTypeList", list); } catch (SQLException e) { e.printStackTrace(); } view.setViewName("admin/news/newssave"); return view; } /** * 添加文章 * * @param newsVo * @return */ @RequestMapping(value = "/save", produces = "plain/text; charset=UTF-8") @ResponseBody public String save(NewsVo newsVo) { try { System.out.println(newsVo.toString()); newsService.save(newsVo); return this.buildSuccessMessage("文章添加成功", ResultModal.MESSAGE); } catch (Exception e) { return this.buildFailMessage("文章添加失败", ResultModal.MESSAGE); } } /** * 预更新 * @return */ @RequestMapping("/preUpdate/{id}") public ModelAndView preUpdate( @PathVariable Long id) { ModelAndView view = new ModelAndView(); view.addObject("title", "文章管理>>文章修改"); List<NewsTypeVo> list = null; try { NewsVo newsVo=newsService.findOne(id); list = newsTypeService.queryAll(); view.addObject("newsTypeList", list); view.addObject("news", newsVo); } catch (SQLException e) { e.printStackTrace(); } view.setViewName("admin/news/newsupdate"); return view; } /** * 更新文章 * * @param id * @param name * @return */ @RequestMapping(value = "/update", produces = "plain/text; charset=UTF-8") @ResponseBody public String update(@RequestParam(value = "id", required = true) Long id, @RequestParam(value = "typeId", required = true) Long typeId, @RequestParam(value = "name", required = true) String name, @RequestParam(value = "content", required = true) String content, @RequestParam(value = "author", required = true) String author, @RequestParam(value = "picSmall", required = false) String picSmall, @RequestParam(value = "picBig", required = false) String picBig, @RequestParam(value = "recommend", required = true) Integer recommend ) { try { NewsVo newsVo = newsService.findOne(id); newsVo.setPicSmall(picSmall); newsVo.setPicBig(picBig); newsVo.setRecommend(recommend); newsVo.setTypeId(typeId); newsVo.setName(name); newsVo.setContent(content); newsVo.setAuthor(author); newsService.update(newsVo); return this.buildSuccessMessage("文章更新成功", ResultModal.MESSAGE); } catch (Exception e) { return this.buildFailMessage("文章更新失败", ResultModal.MESSAGE); } } @ResponseBody @RequestMapping(value = "/queryById", produces = "plain/text; charset=UTF-8") public String queryUser(@RequestParam(value = "id", required = true) Long id) { try { NewsVo newsVo = newsService.findOne(id); return this.buildMessage(ResultModal.SUCCESS, ResultModal.SUCCESS_CODE, "文章获取成功", newsVo, ResultModal.DATA); } catch (Exception e) { return this.buildFailMessage("文章获取失败", ResultModal.MESSAGE); } } /** * 删除文章 * * @param id * @return */ @RequestMapping("/delete") @ResponseBody public String delete(@RequestParam(value = "id", required = true) Long id) { try { newsService.delete(id); return this.buildSuccessMessage("文章删除成功", ResultModal.MESSAGE); } catch (Exception e) { return this.buildFailMessage("文章删除失败", ResultModal.MESSAGE); } } } ``` SearchBean.java ```package com.lebao.common.beans; import java.util.HashMap; import java.util.Map; /** * Created by zr on 2016/10/4. * 通用查询类 */ public class SearchBean { private String name; private String id; private String value; private String createTime; private String updateTime; private int pageSize = 20; private int currentPage = 0; private String sortField; private String sortType; private Map<Object,Object> paramMap=new HashMap<Object,Object>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public String getSortField() { return sortField; } public void setSortField(String sortField) { this.sortField = sortField; } public String getSortType() { return sortType; } public void setSortType(String sortType) { this.sortType = sortType; } public Map<Object, Object> getParamMap() { return paramMap; } public void setParamMap(Map<Object, Object> paramMap) { this.paramMap = paramMap; } } ``` UploadUtil.java ```package com.lebao.file; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * 上传工具类 * */ @Service public class UploadUtil { private static final Logger log = Logger.getLogger(UploadUtil.class); @Autowired private AppConfig appConfig; @Autowired private PicDwind picServer; @Autowired private PubUpload pubUploadServer; public static final String PIC_NEWS_KEY = "pic_news_key"; public static final String PIC_HEADIMG_KEY = "pic_headimg_key"; public static final String DATA_TEACHER_KEY = "data_teacher_key"; public static final String PIC_SCORESHOP_KEY = "pic_scoreshop_key"; public static final String PIC_GOODS_KEY = "pic_goods_key"; public static final String PIC_SHOPER_KEY = "pic_shoper_key"; public static final String PIC_ADV_KEY = "pic_adv_key"; //定义shoppickey public static final String PIC_SHOPTOP_KEY = "pic_shopTop_key"; public static final String PIC_SHOPPIC_KEY = "pic_shopPic_key"; /** 通过传入页面读取到的文件,处理后保存到本地磁盘,并返回一个已经创建好的File * @param imgFile 从页面中读取到的文件 * @return * @throws IOException */ @SuppressWarnings({ "rawtypes" }) public String getFile(MultipartFile imgFile,String picType) { //图片返回总路径 String returnImgUrl = null; //大图片存储路径 String imgFolderName = ""; //小图片存储路径 String imgSmallFolderName = ""; //大图片返回路径 String imgReturnPath = ""; if(picType.equals("") || picType == null){ imgFolderName = appConfig.getRootDir(); imgSmallFolderName = appConfig.getRootSmallDir(); imgReturnPath = appConfig.getRootPath(); } else if(picType.equals("pic_news_key")){ imgFolderName = appConfig.getNewsDir(); imgSmallFolderName = appConfig.getNewsSmallDir(); }else if(picType.equals("pic_scoreshop_key")){ imgFolderName = appConfig.getScoreshopDir(); imgSmallFolderName = appConfig.getScoreshopSmallDir(); }else if(picType.equals("pic_goods_key")){ imgFolderName = appConfig.getGoodsDir(); imgSmallFolderName = appConfig.getGoodsSmallDir(); }else if(picType.equals("pic_shoper_key")){ imgFolderName = appConfig.getShoperDir(); imgSmallFolderName = appConfig.getShoperSmallDir(); }else if(picType.equals("pic_adv_key")){ imgFolderName = appConfig.getAdvDir(); imgSmallFolderName = appConfig.getAdvSmallDir(); } //取得可上传的文件类型 List fileTypes = this.getAllowFiles(appConfig.getImageAllowFiles()); String fileName = imgFile.getOriginalFilename(); //获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名 String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length()); //对扩展名进行小写转换 ext = ext.toLowerCase(); //新的图片文件名 String newFileName = new SimpleDateFormat("yyyyMMddHHmmssms").format(new Date()) + (int)(Math.random()*10000) + "." + ext; File file = null; if(fileTypes.contains(ext)) { //如果扩展名属于允许上传的类型,则创建文件 try { String floderName = new SimpleDateFormat("yyyyMMdd").format(new Date()); file = this.creatFolder(imgFolderName, floderName, newFileName); imgFile.transferTo(file); //压缩图片 File smallFile = null; smallFile = this.creatFolder(imgSmallFolderName, floderName, newFileName); String path = smallFile.getPath().toString().replaceAll("\\\\", "/"); picServer.compressPic(file, path.substring(0, path.lastIndexOf("/")+1), newFileName, 120, 120, true); String folderNameYear = floderName.substring(0, 4); String folderNameMonth = floderName.substring(4, 6); String folderNameDay = floderName.substring(6, 8); returnImgUrl = folderNameYear + "/" + folderNameMonth + "/" + folderNameDay + "/" + newFileName; returnImgUrl = returnImgUrl.replaceAll("\\\\", "/"); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return returnImgUrl; } //上传图片 @SuppressWarnings("rawtypes") public String uploadDatasFile(MultipartFile datasFile,String type){ String returnDatasUrl = null; String datasDir = ""; String datasPath = ""; if(type.equals("") || type == null){ datasDir = appConfig.getRootDir(); datasPath = appConfig.getRootPath(); } else if (type.equals("pic_news_key")){ datasDir = appConfig.getDatasDir(); datasPath = appConfig.getDatasPath(); } //取得可上传的文件类型 List fileTypes = this.getAllowFiles(appConfig.getDatasAllowFiles()); String fileName = datasFile.getOriginalFilename(); //获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名 String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length()); //对扩展名进行小写转换 ext = ext.toLowerCase(); //新的文件名 String newFileName = new SimpleDateFormat("yyyyMMddHHmmssms").format(new Date()) + (int)(Math.random()*10000) + "." + ext; File file = null; if(fileTypes.contains(ext)){ try { String floderName = new SimpleDateFormat("yyyyMMdd").format(new Date()); file = this.creatFolder(datasDir, floderName, newFileName); datasFile.transferTo(file); String folderNameYear = floderName.substring(0, 4); String folderNameMonth = floderName.substring(4, 6); String folderNameDay = floderName.substring(6, 8); returnDatasUrl = folderNameYear + "/" + folderNameMonth + "/" + folderNameDay + "/" + newFileName; returnDatasUrl = returnDatasUrl.replaceAll("\\\\", "/"); returnDatasUrl = datasPath + returnDatasUrl; } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }else{ returnDatasUrl = "error"; } return returnDatasUrl; } /** * 取得可上传的文件类型 * @param allowFiles * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public List getAllowFiles(String allowFiles){ List fileTypes = new ArrayList(); String types[] = allowFiles.split(","); for(int i = 0;i<types.length;i++){ fileTypes.add(types[i]); } return fileTypes; } /** * 转换文件大小 * @param fileS * @return */ public String formetFileSize(long fileS) { DecimalFormat df = new DecimalFormat("#.00"); String fileSizeString = ""; if (fileS < 1024) { fileSizeString = df.format((double) fileS) + "B"; } else if (fileS < 1048576) { fileSizeString = df.format((double) fileS / 1024) + "K"; } else if (fileS < 1073741824) { fileSizeString = df.format((double) fileS / 1048576) + "M"; } else { fileSizeString = df.format((double) fileS / 1073741824) + "G"; } return fileSizeString; } /** * 创建文件夹 * @param imgFolderName 图片存储路径 * @param folderName 二级文件夹 * @param fileName 文件名 * @return */ public File creatFolder(String imgFolderName,String folderName,String fileName) { File file = null; //imgFolderName = imgFolderName.replaceAll("/", ""); //去掉"/" imgFolderName = imgFolderName.replaceAll(" ", ""); //替换半角空格 imgFolderName = imgFolderName.replaceAll(" ", ""); //替换全角空格 //folderName = folderName.replaceAll("/", ""); //去掉"/" folderName = folderName.replaceAll(" ", ""); //替换半角空格 folderName = folderName.replaceAll(" ", ""); //替换全角空格 File firstFolder = new File(imgFolderName); //一级文件夹 if(firstFolder.exists()) { //如果一级文件夹存在,则检测二级文件夹 file = createSonFolder(firstFolder,folderName,fileName); }else { //如果一级不存在,则创建一级文件夹 firstFolder.mkdir(); file = createSonFolder(firstFolder,folderName,fileName); } return file; } /** * 创建年月日三级文件夹 * @param firstFolder 根文件 * @param folderName 年月日文件夹名 * @param fileName 文件名 * @return */ public File createSonFolder(File firstFolder,String folderName,String fileName){ File file = null; String folderNameYear = folderName.substring(0, 4); String folderNameMonth = folderName.substring(4, 6); String folderNameDay = folderName.substring(6, 8); File yearFolder = new File(firstFolder,folderNameYear); if(yearFolder.exists()) { //如果二级文件夹也存在,则创建文件 File monthFolder = new File(yearFolder,folderNameMonth); //三级文件夹 if(monthFolder.exists()){ File dayFolder = new File(monthFolder,folderNameDay); //四级文件夹 if(dayFolder.exists()){ file = new File(dayFolder,fileName); }else{ dayFolder.mkdir(); file = new File(dayFolder,fileName); } }else{ monthFolder.mkdir(); File dayFolder = new File(monthFolder,folderNameDay); if(dayFolder.exists()){ file = new File(dayFolder,fileName); }else{ dayFolder.mkdir(); file = new File(dayFolder,fileName); } } }else { //如果二级文件夹不存在,则创建二级文件夹 yearFolder.mkdir(); //创建完二级文件夹后,再合建文件 File monthFolder = new File(yearFolder,folderNameMonth); if(monthFolder.exists()){ File dayFolder = new File(monthFolder,folderNameDay); if(dayFolder.exists()){ file = new File(dayFolder,fileName); }else{ dayFolder.mkdir(); file = new File(dayFolder,fileName); } }else{ monthFolder.mkdir(); File dayFolder = new File(monthFolder,folderNameDay); if(dayFolder.exists()){ file = new File(dayFolder,fileName); }else{ dayFolder.mkdir(); file = new File(dayFolder,fileName); } } } return file; } // public void folder(String imgFolderName,String folderName,String fileName){ // File file = null; // //imgFolderName = imgFolderName.replaceAll("/", ""); //去掉"/" // imgFolderName = imgFolderName.replaceAll(" ", ""); //替换半角空格 // imgFolderName = imgFolderName.replaceAll(" ", ""); //替换全角空格 // // //folderName = folderName.replaceAll("/", ""); //去掉"/" // folderName = folderName.replaceAll(" ", ""); //替换半角空格 // folderName = folderName.replaceAll(" ", ""); //替换全角空格 // // File firstFolder = new File(imgFolderName); //一级文件夹 // if(firstFolder.exists()) { //如果一级文件夹存在,则检测二级文件夹 // File secondFolder = new File(firstFolder,folderName); // if(secondFolder.exists()) { //如果二级文件夹也存在,则创建文件 // file = new File(secondFolder,fileName); // }else { //如果二级文件夹不存在,则创建二级文件夹 // secondFolder.mkdir(); // file = new File(secondFolder,fileName); //创建完二级文件夹后,再合建文件 // } // }else { //如果一级不存在,则创建一级文件夹 // firstFolder.mkdir(); // File secondFolder = new File(firstFolder,folderName); // if(secondFolder.exists()) { //如果二级文件夹也存在,则创建文件 // file = new File(secondFolder,fileName); // }else { //如果二级文件夹不存在,则创建二级文件夹 // secondFolder.mkdir(); // file = new File(secondFolder,fileName); // } // } // } } ``` UserDepartmentRelDao.java ```package com.lebao.dao.user; import com.lebao.po.UserDepartmentRel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class UserDepartmentRelDao { @Autowired UserDepartmentRelRepo userDepartmentRelRepo; public void save(UserDepartmentRel userDepartmentRel) { userDepartmentRelRepo.save(userDepartmentRel); } public void update(UserDepartmentRel userDepartmentRel) { userDepartmentRelRepo.save(userDepartmentRel); } public void delete(UserDepartmentRel userDepartmentRel) { userDepartmentRelRepo.save(userDepartmentRel); } public UserDepartmentRel findOne(Long id) { return userDepartmentRelRepo.findOne(id); } public List<UserDepartmentRel> findByUid(Long uid) { return userDepartmentRelRepo.findByUid(uid); } } ``` OrderBean.java ```package com.lebao.bean; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Server on 2016/4/8. */ public class OrderBean { @JsonProperty("id") private String p_id ;//bigint(20) NOT NULLid @JsonProperty("user_id") private String p_user_id;//bigint(20) NOT NULL user_id @JsonProperty("user_account") private String p_user_account; @JsonProperty("goods_id") private String p_goods_id; @JsonProperty("goods_name") private String p_goods_name; @JsonProperty("server") private String p_server; @JsonProperty("total_price") private Float p_total_price;//float(15,2) NOT NULL总充值金额 @JsonProperty("status") private String p_status;//tinyint(1) NOT NULL ( -1未完成 0 已付款 1 完成 ) @JsonProperty("create_time") private String p_create_time; //timestamp NULL创建时间 @JsonProperty("update_time") private String p_update_time; //timestamp NULL创建时间 @JsonProperty("dealuser_id") private String p_dealuser_id; @JsonProperty("dealuser_name") private String p_dealuser_name; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_user_id() { return p_user_id; } public void setP_user_id(String p_user_id) { this.p_user_id = p_user_id; } public String getP_user_account() { return p_user_account; } public void setP_user_account(String p_user_account) { this.p_user_account = p_user_account; } public String getP_goods_id() { return p_goods_id; } public void setP_goods_id(String p_goods_id) { this.p_goods_id = p_goods_id; } public String getP_goods_name() { return p_goods_name; } public void setP_goods_name(String p_goods_name) { this.p_goods_name = p_goods_name; } public String getP_server() { return p_server; } public void setP_server(String p_server) { this.p_server = p_server; } public Float getP_total_price() { return p_total_price; } public void setP_total_price(Float p_total_price) { this.p_total_price = p_total_price; } public String getP_status() { return p_status; } public void setP_status(String p_status) { this.p_status = p_status; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public String getP_update_time() { return p_update_time; } public void setP_update_time(String p_update_time) { this.p_update_time = p_update_time; } public String getP_dealuser_id() { return p_dealuser_id; } public void setP_dealuser_id(String p_dealuser_id) { this.p_dealuser_id = p_dealuser_id; } public String getP_dealuser_name() { return p_dealuser_name; } public void setP_dealuser_name(String p_dealuser_name) { this.p_dealuser_name = p_dealuser_name; } @Override public String toString() { return "OrderBean{" + "p_id='" + p_id + '\'' + ", p_user_id='" + p_user_id + '\'' + ", p_user_account='" + p_user_account + '\'' + ", p_goods_id='" + p_goods_id + '\'' + ", p_goods_name='" + p_goods_name + '\'' + ", p_server='" + p_server + '\'' + ", p_total_price='" + p_total_price + '\'' + ", p_status='" + p_status + '\'' + ", p_create_time='" + p_create_time + '\'' + ", p_update_time='" + p_update_time + '\'' + ", p_dealuser_id='" + p_dealuser_id + '\'' + ", p_dealuser_name='" + p_dealuser_name + '\'' + '}'; } } ``` OrderDetailDao.java ```package com.lebao.modules.orderdetail.dao; import com.lebao.bean.OrderDetailSearchParam; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.modules.order.entity.OrderEntity; import com.lebao.modules.orderdetail.entity.OrderDetailEntity; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.sql.SQLException; import java.sql.Timestamp; /** * Created by Server on 2016/4/5. */ @Repository public class OrderDetailDao { @Resource(name = "dbHelper") private DbHelper dbHelper; private int pageSize = 10; private int pages = 0; public int addOrder(OrderEntity oe) throws SQLException { /* String p_id = Sequence.nextId(); String p_user_id = oe.getP_user_id(); String p_product_id = oe.getP_product_id(); String p_account = oe.getP_account(); String p_password = oe.getP_password(); Float p_price = oe.getP_price(); Integer p_num = oe.getP_num(); Integer p_state = oe.getP_state(); Timestamp p_create_time = oe.getP_create_time(); //timestamp NULL创建时间 String sql = "INSERT INTO t_order(p_id,p_user_id,p_product_id,p_account,p_password,p_price,p_num,p_state,p_create_time) VALUES(?,?,?,?,?,?,?,?,?)"; return dbHelper.execute(sql, p_id, p_user_id, p_product_id, p_account, p_password, p_price, p_num, p_state, p_create_time); */ return 0; } public int deleteOrder(String p_id) throws SQLException { String sql = "update t_order set p_state = '-1' where p_id=?"; return dbHelper.execute(sql, p_id); } public int updateOrder(OrderEntity oe) throws SQLException { String p_id = oe.getP_id(); // Integer p_state = oe.getP_status(); // Timestamp p_update_time = oe.getP_update_time(); // sql = "update t_order set p_status=?,p_update_time=? where p_id=?"; return 1; } public OrderEntity getOrderEntity(String p_id) throws SQLException { String sql = "select * from t_order where p_id=?"; return dbHelper.getBean(sql, OrderEntity.class, p_id); } /* SELECT t_user_base.p_user_name , t_order.* FROM t_order JOIN t_user_base ON t_user_base.p_id=t_order.p_user_id and t_user_base.p_user_name like '%z%' and t_order.p_order_id='1' */ public Page<OrderDetailEntity> getOrderDetailEntities(OrderDetailSearchParam s) throws SQLException { String sql = "select * from t_order_detail where p_order_id = '"+s.getOrder_id()+"'" ; return dbHelper.getPage(sql, OrderDetailEntity.class, s.getCurPage(), s.getPageSize()); } } ``` QRController.java ```package com.lebao.controller; import com.lebao.po.User; import com.lebao.service.UserService; import com.lebao.vo.UserVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; /** * Created by Server on 2016/7/15. */ @Controller @RequestMapping("/qr") public class QRController { @Autowired UserService userService; @RequestMapping("/user") public ModelAndView testKind(@RequestParam(value = "uid", required = true) Long uid) { ModelAndView view = new ModelAndView(); UserVo user=userService.findOne(uid); view.addObject("user",user); view.setViewName("admin/user/userQR"); return view; } } ``` EduLevelService.java ```package com.lebao.service; import com.lebao.dao.user.EduLevelDao; import com.lebao.po.EduLevel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Author: zr * Date : 2016/12/6 18:13 */ @Service public class EduLevelService { @Autowired EduLevelDao eduLevelDao; public EduLevel findOne(Long id) { return eduLevelDao.findOne(id); } public void save(EduLevel eduLevel){ eduLevelDao.save(eduLevel); } public List<EduLevel> findAll(){ return eduLevelDao.findAll(); } } ``` ScoreTest.java ```/** * Created by Server on 2016/7/5. */ public class ScoreTest { public static void main( String [] ars ){ } } ``` xunzhong.java ```import com.google.gson.Gson; import com.lebao.common.utils.TimeUtil; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import sun.misc.BASE64Encoder; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by Server on 2016-07-20. */ public class xunzhong { /** * post请求 * @param url * @param json * @return */ public static String doPost(String url,String json,String Authorization ){ DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); String response = null; post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/json;charset=utf-8"); post.setHeader("Authorization", Authorization); try { StringEntity s = new StringEntity(json); s.setContentEncoding("UTF-8"); s.setContentType("application/json");//发送json数据需要设置contentType post.setEntity(s); HttpResponse res = client.execute(post); if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ HttpEntity entity = res.getEntity(); String result = EntityUtils.toString(res.getEntity());// 返回json格式: response = result; } } catch (Exception e) { throw new RuntimeException(e); } System.out.println(response); return response; } // 加密 public static String getBase64(String str) { byte[] b = null; String s = null; try { b = str.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (b != null) { s = new BASE64Encoder().encode(b); } return s; } private static String MD5(String sourceStr) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(sourceStr.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString(); System.out.println("MD5(" + sourceStr + ",32) = " + result); System.out.println("MD5(" + sourceStr + ",16) = " + buf.toString().substring(8, 24)); } catch (NoSuchAlgorithmException e) { System.out.println(e); } return result; } public static void main( String [] ars ){ /* System.out.println(Authorization); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json;charset=utf-8"); httpPost.setHeader("Authorization", Authorization); String AUTH_TOKEN="8d646e9b411a4cbdb30170f441ea3982"; String ACCOUNT_SID="aedb86df8da740a2804eb2da63aecd2a"; String time=TimeUtil.format(new Date(), TimeUtil.SOURCE_1); String jiami=ACCOUNT_SID+"|"+time; String Authorization= getBase64(jiami); String temp=ACCOUNT_SID+AUTH_TOKEN+time; String Sign=MD5(temp); String url="http://api.ytx.net/201512/sid/aedb86df8da740a2804eb2da63aecd2a/sms/TemplateSMS.wx?Sign="+Sign+""; Map<String,Object> map=new HashMap<String, Object>(); map.put("action","templateSms"); map.put("appid","3f9af51f60a644daa8f7c2dc335c981b"); map.put("mobile","13073339156"); map.put("templateId","1"); String datas[]={"0001","1"}; map.put("datas",datas); Gson gson=new Gson(); String json=gson.toJson(map); doPost(url,json,Authorization); */ xunzhong xunzhong=new xunzhong(); xunzhong.aaa(); } class JinTongResult{ // 响应业务状态 private Integer status; // 响应消息 private String msg; // 响应中的数据 private Object data; JinTongResult(Object data) { this.status = 1; this.msg = "success"; this.data = data; } } public void aaa(){ JinTongResult jinTongResult=new JinTongResult("hello"); Gson gson=new Gson(); System.out.println(gson.toJson(jinTongResult)); } }``` LiushuiEntity.java ```package com.lebao.modules.sys.entity; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; /** * Created by Server on 2016-07-23. */ @Table(name="t_liushui") public class LiushuiEntity { @Id @Column(name="p_id") private String p_id ;//bigint(20) NOT NULLid private String p_user_id; private Float p_price; private String p_create_time; private Integer p_status; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_user_id() { return p_user_id; } public void setP_user_id(String p_user_id) { this.p_user_id = p_user_id; } public Float getP_price() { return p_price; } public void setP_price(Float p_price) { this.p_price = p_price; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public Integer getP_status() { return p_status; } public void setP_status(Integer p_status) { this.p_status = p_status; } } ``` UserDepartmentRelRepo.java ```package com.lebao.dao.user; import com.lebao.po.UserDepartmentRel; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface UserDepartmentRelRepo extends JpaRepository<UserDepartmentRel,Long> { List<UserDepartmentRel> findByUid(Long uid); } ``` BaseDao.java ```package com.lebao.modules; import com.lebao.common.dbhelp.DbHelper; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import org.springframework.stereotype.Repository; import org.springframework.util.StringUtils; import javax.annotation.Resource; import javax.persistence.Id; import javax.persistence.Table; import java.lang.reflect.Field; import java.sql.SQLException; /** * Created by Server on 2016/6/19. */ @Repository public class BaseDao<T> { @Resource(name = "dbHelper") private DbHelper dbHelper; public void save(T bean) throws SQLException { StringBuffer sqlBuffer = new StringBuffer("insert into "); sqlBuffer.append(" " + getTableName(bean) + " ("); Field[] fields = bean.getClass().getDeclaredFields(); Object[] params = new Object[30]; int paramIndex = 0; String tempFields = ""; String valueParams = "("; for (Field field : fields) { if (getPropertyValue(field, bean) != null) { tempFields += field.getName() + ","; valueParams += "?,"; params[paramIndex] = getPropertyValue(field, bean); // System.out.println(getPropertyValue(field ,bean )); paramIndex++; } } Object[] inParams = new Object[paramIndex]; System.arraycopy(params, 0, inParams, 0, paramIndex); sqlBuffer.append(dealSuffix(tempFields, ",") + " )values"); sqlBuffer.append(dealSuffix(valueParams, ",") + ")"); String sql = sqlBuffer.toString(); /* * for (int i = 0; i < inParams.length; i++) { Object object = * inParams[i]; System.out.println(object); } */ dbHelper.execute(sql, inParams); } public void update(T bean) throws SQLException { StringBuffer sqlBuffer = new StringBuffer("update"); sqlBuffer.append(" " + getTableName(bean) + " set "); Field[] fields = bean.getClass().getDeclaredFields(); Object[] params = new Object[30]; int paramIndex = 0; String tempFields = ""; for (Field field : fields) { if (getPropertyValue(field, bean) != null) { if (!field.getName().equals(getPrimaryKey(bean))) { tempFields += field.getName() + "=?,"; params[paramIndex] = getPropertyValue(field, bean); paramIndex++; } } } Object[] inParams = new Object[paramIndex + 1]; System.arraycopy(params, 0, inParams, 0, paramIndex); for (Field field : fields) { if (getPropertyValue(field, bean) != null) { if (field.getName().equals(getPrimaryKey(bean))) { inParams[paramIndex] = getPropertyValue(field, bean); } } } sqlBuffer.append(dealSuffix(tempFields, ",") + " where " + getPrimaryKey(bean) + " =? "); String sql = sqlBuffer.toString(); dbHelper.execute(sql, inParams); } public void deleteByPrimaryKey(T bean) throws SQLException { update(bean); } public T selectByPrimaryKey(T bean) throws SQLException { StringBuffer sqlBuffer = new StringBuffer( "select * from " + getTableName(bean) + " where " + getPrimaryKey(bean) + " = ?"); String sql = sqlBuffer.toString(); Object primaryValue = ""; Field[] fields = bean.getClass().getDeclaredFields(); for (Field field : fields) { if (getPropertyValue(field, bean) != null) { if (field.getName().equals(getPrimaryKey(bean))) { primaryValue = getPropertyValue(field, bean); } } } return (T) dbHelper.getBean(sql, bean.getClass(), primaryValue); } private String dealSuffix(String source, String prefix) { if (StringUtils.isEmpty(source) || prefix == null) { return source; } if (source.trim().endsWith(prefix)) { return source.trim().substring(0, source.trim().length() - prefix.length()); } return source; } private Object getPropertyValue(Field field, T bean) { BeanWrapper bw = new BeanWrapperImpl(bean); // System.out.println(bw.getPropertyValue( field.getName() )); return bw.getPropertyValue(field.getName()); } private String getTableName(T bean) { if (!bean.getClass().isAnnotationPresent(Table.class)) { throw new IllegalArgumentException(bean.getClass() + " is not table enttiy ."); } Table table = (Table) bean.getClass().getAnnotation(Table.class); System.out.println(table.name()); return table.name(); } private String getPrimaryKey(T bean) { Field[] fields = bean.getClass().getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Id.class)) { return findTableColumn(field); } } throw new IllegalArgumentException("not find primary key."); } private String findTableColumn(Field field) { return dealTableColumn(field.getName()); } private String dealTableColumn(String field) { return field; } } ``` SysUser.java ```package com.lebao.po; import javax.persistence.*; @Entity @Table(name = "tb_sysuser") public class SysUser { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String password; private Integer type; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } @Override public String toString() { return "SysUser{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + ", type=" + type + '}'; } } ``` SysMenuEntity.java ```package com.lebao.modules.sys.entity; public class SysMenuEntity { private String p_id;//int(10) NOT NULL private String p_fid;//int(10) NOT NULL private String p_name;//varchar(50) NULL private int p_type;//tinyint(1) NULL private int p_status; private String p_url; private String p_icon; public String getP_url() { return p_url; } public void setP_url(String p_url) { this.p_url = p_url; } public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_fid() { return p_fid; } public void setP_fid(String p_fid) { this.p_fid = p_fid; } public String getP_name() { return p_name; } public void setP_name(String p_name) { this.p_name = p_name; } public int getP_type() { return p_type; } public void setP_type(int p_type) { this.p_type = p_type; } public int getP_status() { return p_status; } public void setP_status(int p_status) { this.p_status = p_status; } public String getP_icon() { return p_icon; } public void setP_icon(String p_icon) { this.p_icon = p_icon; } } ``` ShoperDao.java ```package com.lebao.modules.shoper.dao; import com.lebao.bean.SearchParam; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.common.utils.Sequence; import com.lebao.common.utils.TimeUtil; import com.lebao.modules.CountEntity; import com.lebao.modules.shoper.entity.ShoperEntity; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.sql.SQLException; import java.util.Date; import java.util.List; @Repository public class ShoperDao { @Resource(name = "dbHelper") private DbHelper dbHelper; public void addShoper(ShoperEntity se) throws SQLException { String p_id = Sequence.nextId(); String p_name = se.getP_name(); String p_desc = se.getP_desc(); String p_photo1 = se.getP_photo1(); String p_url = se.getP_url(); String p_phone = se.getP_phone(); String p_keys = se.getP_keys(); String p_status = se.getP_status(); String p_create_time = TimeUtil.format(new Date(), TimeUtil.TARGET_1); String sql = "INSERT INTO t_shoper(p_id,p_name,p_desc,p_photo1,p_url,p_phone,p_keys,p_status,p_create_time) VALUES(?,?,?,?,?,?,?,?,?)"; dbHelper.execute(sql, p_id, p_name, p_desc, p_photo1, p_url, p_phone, p_keys, p_status, p_create_time); } public Page<ShoperEntity> getShopers(SearchParam s) throws SQLException { String sql = "select * from t_shoper where 1=1"; if (StringUtils.isNotBlank(s.getName())) { sql += " and p_name like '" + s.getName() + "%' "; } sql += " order by " + s.getSortField() + " " + s.getSortType() + " "; return dbHelper.getPage(sql, ShoperEntity.class, s.getPageNow(), s.getPageSize()); } public List<ShoperEntity> getShopers() throws SQLException { String sql = "select * from t_shoper where p_status='1' "; return dbHelper.getBeanList(sql,ShoperEntity.class); } public ShoperEntity getShoperById(String shoperId) throws SQLException { String sql = "select * from t_shoper where t_shoper.p_id=?"; return dbHelper.getBean(sql, ShoperEntity.class, shoperId); } public void updShoper(ShoperEntity se) throws SQLException { String p_id = se.getP_id(); String p_name = se.getP_name(); String p_desc = se.getP_desc(); String p_photo1 = se.getP_photo1(); String p_url = se.getP_url(); String p_phone = se.getP_phone(); String p_keys = se.getP_keys(); //String p_status = se.getP_status(); String p_update_time = TimeUtil.format(new Date(), TimeUtil.TARGET_1); String sql = "update t_shoper set p_name=?,p_desc=?,p_photo1=?,p_url=?,p_phone=?,p_keys=?,p_update_time=? where p_id=?"; dbHelper.execute(sql, p_name, p_desc, p_photo1, p_url, p_phone, p_keys, p_update_time, p_id); } public void delShoper(String shoperId) throws SQLException { String sql = "update t_shoper set p_status='-1' where p_id = ?"; dbHelper.execute(sql, shoperId); } public boolean checkGoodsIsUsing(String shoperId) throws SQLException { String sql = "select count(1) as num from t_goods where p_type_id = ? and p_state = ? "; CountEntity ce = dbHelper.getBean(sql, CountEntity.class, shoperId,1); return ce!=null&&ce.getNum()>0; } public void reAddShoper(String shoperId) throws SQLException { String sql = "update t_shoper set p_status = '1' where p_id=?"; dbHelper.execute(sql, shoperId); } } ``` BaseDaoTest.java ```//import java.sql.SQLException; // //import com.lebao.common.utils.Sequence; //import com.lebao.modules.BaseDao; //import com.lebao.modules.user.entity.UserEntity; // ///** // * Created by Server on 2016/6/19. // */ //public class BaseDaoTest { // // public static void main( String [] ars ){ // BaseDao<UserEntity> userDao = new BaseDao<UserEntity>() ; // UserEntity user = new UserEntity() ; // String p_id = Sequence.nextId(); // user.setP_user_phone("1307339156"); // user.setP_state(1); // user.setP_id(p_id); // user.setP_account("大"); // try { // //userDao.save(user); // userDao.update(user); // } catch (SQLException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } //} ``` UserEntity.java ```package com.lebao.modules.user.entity; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; @Table(name="t_user_base") public class UserEntity { @Id @Column(name="p_id") private String p_id ;//bigint(20) NOT NULLid private String p_user_name;//varchar(20) NULL姓名 private String p_account;//varchar(20) NULL用户名 private String p_user_phone;//varchar(11) NULL电话 private String p_password;//varchar(255) NULL密码 private float p_point1; //float(15,2) NOT NULL邀请码1的积分 private String p_invitation_code2;//bigint(20) NULL邀请码2 private String p_regist_code; //bigint(20) NOT NULL注册码 private int p_state;//tinyint(1) NOT NULL状态 private String p_type;//tinyint(1) NOT NULL-1:非会员 1:会员 private String p_create_time; //timestamp NULL创建时间 private String p_lastlogin_time;//timestamp NULL最后登录时间 private float p_point2;//float NOT NULL邀请码2的积分 private String p_invitation_code1; private int p_grade_point; private String p_parent_code;//上一级用户的id private String p_child_code1;//下一级用户的id 左 private String p_child_code2;//下一级用户的id 右 private int p_shouchong;//首充-1 未完成 1 完成 private float p_point; //float(15,2) NOT NULL积分 private String p_qq; private String p_address; private String p_email; private String p_hy_end_time; private Float p_lebi; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_user_name() { return p_user_name; } public void setP_user_name(String p_user_name) { this.p_user_name = p_user_name; } public String getP_account() { return p_account; } public void setP_account(String p_account) { this.p_account = p_account; } public String getP_user_phone() { return p_user_phone; } public void setP_user_phone(String p_user_phone) { this.p_user_phone = p_user_phone; } public String getP_password() { return p_password; } public void setP_password(String p_password) { this.p_password = p_password; } public float getP_point1() { return p_point1; } public void setP_point1(float p_point1) { this.p_point1 = p_point1; } public String getP_invitation_code2() { return p_invitation_code2; } public void setP_invitation_code2(String p_invitation_code2) { this.p_invitation_code2 = p_invitation_code2; } public String getP_regist_code() { return p_regist_code; } public void setP_regist_code(String p_regist_code) { this.p_regist_code = p_regist_code; } public int getP_state() { return p_state; } public void setP_state(int p_state) { this.p_state = p_state; } public String getP_type() { return p_type; } public void setP_type(String p_type) { this.p_type = p_type; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public String getP_lastlogin_time() { return p_lastlogin_time; } public void setP_lastlogin_time(String p_lastlogin_time) { this.p_lastlogin_time = p_lastlogin_time; } public float getP_point2() { return p_point2; } public void setP_point2(float p_point2) { this.p_point2 = p_point2; } public String getP_invitation_code1() { return p_invitation_code1; } public void setP_invitation_code1(String p_invitation_code1) { this.p_invitation_code1 = p_invitation_code1; } public int getP_grade_point() { return p_grade_point; } public void setP_grade_point(int p_grade_point) { this.p_grade_point = p_grade_point; } public String getP_parent_code() { return p_parent_code; } public void setP_parent_code(String p_parent_code) { this.p_parent_code = p_parent_code; } public String getP_child_code1() { return p_child_code1; } public void setP_child_code1(String p_child_code1) { this.p_child_code1 = p_child_code1; } public String getP_child_code2() { return p_child_code2; } public void setP_child_code2(String p_child_code2) { this.p_child_code2 = p_child_code2; } public int getP_shouchong() { return p_shouchong; } public void setP_shouchong(int p_shouchong) { this.p_shouchong = p_shouchong; } public float getP_point() { return p_point; } public void setP_point(int p_point) { this.p_point = p_point; } public void setP_point(float p_point) { this.p_point = p_point; } public String getP_qq() { return p_qq; } public void setP_qq(String p_qq) { this.p_qq = p_qq; } public String getP_address() { return p_address; } public void setP_address(String p_address) { this.p_address = p_address; } public String getP_email() { return p_email; } public void setP_email(String p_email) { this.p_email = p_email; } public String getP_hy_end_time() { return p_hy_end_time; } public void setP_hy_end_time(String p_hy_end_time) { this.p_hy_end_time = p_hy_end_time; } public Float getP_lebi() { return p_lebi; } public void setP_lebi(Float p_lebi) { this.p_lebi = p_lebi; } @Override public String toString() { return "UserEntity{" + "p_id='" + p_id + '\'' + ", p_user_name='" + p_user_name + '\'' + ", p_account='" + p_account + '\'' + ", p_user_phone='" + p_user_phone + '\'' + ", p_password='" + p_password + '\'' + ", p_point1=" + p_point1 + ", p_invitation_code2='" + p_invitation_code2 + '\'' + ", p_regist_code='" + p_regist_code + '\'' + ", p_state=" + p_state + ", p_type=" + p_type + ", p_create_time='" + p_create_time + '\'' + ", p_lastlogin_time='" + p_lastlogin_time + '\'' + ", p_point2=" + p_point2 + ", p_invitation_code1='" + p_invitation_code1 + '\'' + ", p_grade_point=" + p_grade_point + ", p_parent_code='" + p_parent_code + '\'' + ", p_child_code1='" + p_child_code1 + '\'' + ", p_child_code2='" + p_child_code2 + '\'' + ", p_shouchong=" + p_shouchong + ", p_point=" + p_point + '}'; } } ``` ScoreShopBean.java ```package com.lebao.bean; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Server on 2016/3/30. */ public class ScoreShopBean { @JsonProperty("id") private String p_id; @JsonProperty("name") private String p_name; @JsonProperty("desc") private String p_desc; @JsonProperty("photo1") private String p_photo1; @JsonProperty("status") private String p_status; @JsonProperty("score") private Integer p_score; @JsonProperty("type") private String p_type; @JsonProperty("url") private String p_url; @JsonProperty("stock") private Integer p_stock; @JsonProperty("create_time") private String p_create_time; @JsonProperty("update_time") private String p_update_time; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_name() { return p_name; } public void setP_name(String p_name) { this.p_name = p_name; } public String getP_desc() { return p_desc; } public void setP_desc(String p_desc) { this.p_desc = p_desc; } public String getP_photo1() { return p_photo1; } public void setP_photo1(String p_photo1) { this.p_photo1 = p_photo1; } public String getP_status() { return p_status; } public void setP_status(String p_status) { this.p_status = p_status; } public Integer getP_score() { return p_score; } public void setP_score(Integer p_score) { this.p_score = p_score; } public String getP_type() { return p_type; } public void setP_type(String p_type) { this.p_type = p_type; } public String getP_url() { return p_url; } public void setP_url(String p_url) { this.p_url = p_url; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public String getP_update_time() { return p_update_time; } public void setP_update_time(String p_update_time) { this.p_update_time = p_update_time; } public Integer getP_stock() { return p_stock; } public void setP_stock(Integer p_stock) { this.p_stock = p_stock; } @Override public String toString() { return "ScoreShopBean{" + "p_id='" + p_id + '\'' + ", p_name='" + p_name + '\'' + ", p_desc='" + p_desc + '\'' + ", p_photo1='" + p_photo1 + '\'' + ", p_status='" + p_status + '\'' + ", p_score=" + p_score + ", p_type='" + p_type + '\'' + ", p_url='" + p_url + '\'' + ", p_stock=" + p_stock + ", p_create_time='" + p_create_time + '\'' + ", p_update_time='" + p_update_time + '\'' + '}'; } } ``` NewsTypeRepo.java ```package com.lebao.dao.newstype; import com.lebao.po.NewsType; import com.lebao.po.SysUser; import org.springframework.data.repository.CrudRepository; public interface NewsTypeRepo extends CrudRepository<NewsType,Long> { } ``` ScoreRecordDao.java ```package com.lebao.modules.scorerecord.dao; import com.lebao.modules.BaseDao; import org.springframework.stereotype.Repository; /** * Created by Server on 2016/6/21. */ @Repository public class ScoreRecordDao<T> extends BaseDao<T> { } ``` SysUserEntity.java ```package com.lebao.modules.lebao.entity; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; /** * Created by Server on 2016/5/19. */ @Table(name="t_sys_user") public class SysUserEntity { @Id @Column(name="p_id") private String p_id; private String p_account; private String p_password; private String p_phone; private String p_email; private String p_real_name; private String p_role_id; private String p_role_name; private Integer p_type;//(0:系统管理员, 1:代理商管理员,2:业务员, 3:运维用户, 4:其他)。 private String p_status;//(0:禁用,1:激活) private String p_create_time; private String p_last_login_time; private String p_invitation_code; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_account() { return p_account; } public void setP_account(String p_acccount) { this.p_account = p_acccount; } public String getP_password() { return p_password; } public void setP_password(String p_password) { this.p_password = p_password; } public String getP_phone() { return p_phone; } public void setP_phone(String p_phone) { this.p_phone = p_phone; } public String getP_email() { return p_email; } public void setP_email(String p_email) { this.p_email = p_email; } public String getP_real_name() { return p_real_name; } public void setP_real_name(String p_real_name) { this.p_real_name = p_real_name; } public String getP_role_id() { return p_role_id; } public void setP_role_id(String p_role_id) { this.p_role_id = p_role_id; } public String getP_role_name() { return p_role_name; } public void setP_role_name(String p_role_name) { this.p_role_name = p_role_name; } public Integer getP_type() { return p_type; } public void setP_type(Integer p_type) { this.p_type = p_type; } public String getP_status() { return p_status; } public void setP_status(String p_status) { this.p_status = p_status; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public String getP_last_login_time() { return p_last_login_time; } public void setP_last_login_time(String p_last_login_time) { this.p_last_login_time = p_last_login_time; } public String getP_invitation_code() { return p_invitation_code; } public void setP_invitation_code(String p_invitation_code) { this.p_invitation_code = p_invitation_code; } @Override public String toString() { return "SysUserEntity{" + "p_id='" + p_id + '\'' + ", p_account='" + p_account + '\'' + ", p_password='" + p_password + '\'' + ", p_phone='" + p_phone + '\'' + ", p_email='" + p_email + '\'' + ", p_real_name='" + p_real_name + '\'' + ", p_role_id='" + p_role_id + '\'' + ", p_role_name='" + p_role_name + '\'' + ", p_type=" + p_type + ", p_status='" + p_status + '\'' + ", p_create_time='" + p_create_time + '\'' + ", p_last_login_time='" + p_last_login_time + '\'' + ", p_invitation_code='" + p_invitation_code + '\'' + '}'; } } ``` LoginController.java ```package com.lebao.controller; import com.lebao.service.SysUserService; import com.lebao.vo.SysUserVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * Created by Server on 2016/3/31. */ @RequestMapping("/login") @Controller public class LoginController { @Autowired private SysUserService sysUserService; @RequestMapping("") public String loginPre() { return "admin/login"; } @RequestMapping("/deal") public Object deal( @RequestParam(value = "name", required = true) String name, @RequestParam(value = "password", required = true) String password) { ModelAndView view = new ModelAndView(); view.setViewName("admin/index"); try { SysUserVo sysUserVo = sysUserService.findByNameAndPassword(name, password); if (sysUserVo == null) { view.setViewName("admin/login"); view.addObject("msg", "用户名或密码错误!"); return view; } view.addObject("sysUserVo",sysUserVo); } catch (Exception e) { e.printStackTrace(); } return view; } } ``` ScoreDuihuanDao.java ```package com.lebao.modules.scoreduihuan.dao; import com.lebao.bean.SearchParam; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.modules.BaseDao; import com.lebao.modules.scoreduihuan.entity.ScoreDuihuanEntity; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.sql.SQLException; /** * Created by Server on 2016/6/21. */ @Repository public class ScoreDuihuanDao<T> extends BaseDao<T> { @Resource(name = "dbHelper") private DbHelper dbHelper; public Page<ScoreDuihuanEntity> getScoreDuihuans(SearchParam s) throws SQLException { String sql = "select * from t_score_duihuan where 1=1"; if (StringUtils.isNotBlank(s.getId())) { sql += " and p_user_id = '" + s.getId() + "' "; } /* if (StringUtils.isNotBlank(s.getUserName())) { sql += " and p_user_name like '%" + s.getUserName() + "%' "; } if (StringUtils.isNotBlank(s.getAccount())) { sql += " and p_account like '%" + s.getAccount() + "%' "; } */ // System.out.println(sql); sql += " order by " + s.getSortField() + " " + s.getSortType() + " "; return dbHelper.getPage(sql, ScoreDuihuanEntity.class, s.getPageNow(), s.getPageSize()); } public ScoreDuihuanEntity getScoreDuihuanById(String id) throws SQLException { String sql = "select * from t_score_duihuan where t_score_duihuan.p_id=?"; return dbHelper.getBean(sql, ScoreDuihuanEntity.class, id); } } ``` ShareCode.java ```import com.lebao.common.utils.ShareCodeUtil; /** * Created by Server on 2016/6/22. */ public class ShareCode { public static void main( String [] ars ){ System.out.println(ShareCodeUtil.toSerialCode(123)); System.out.println(ShareCodeUtil.toSerialCode(123)); } } ``` NewsTypeController.java ```package com.lebao.controller; import com.lebao.common.beans.SearchBean; import com.lebao.common.dbhelp.page.Page; import com.lebao.service.NewsTypeService; import com.lebao.vo.NewsTypeVo; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; /** * Created by ZR on 2016/12/6. */ @Controller @RequestMapping(value = "newsType") public class NewsTypeController extends BaseController { @Autowired NewsTypeService newsTypeService; /** * 页面入口 * * @return */ @RequestMapping("/index") public ModelAndView index() { ModelAndView view = new ModelAndView(); view.addObject("title", "文章管理>>类型查询"); view.setViewName("admin/news/typeindex"); return view; } /** * 分页数据查询 * * @param request * @return */ @RequestMapping(value = "/query", produces = "plain/text; charset=UTF-8") @ResponseBody public String query(HttpServletRequest request) { System.out.println("查询"); Map<String, Object> obj = this.getParametersStartWidth(request, "s_"); String name = (String) obj.get("name"); DataTableVo dt = this.parseData4DT(request); int start = dt.getiDisplayStart(); int length = dt.getiDisplayLength(); int curPage = 0; if (dt.getiDisplayStart() > 0) { curPage = start / length + 1; } String json = null; try { SearchBean s = new SearchBean(); if (StringUtils.isNotBlank(name)) { s.getParamMap().put("name", name); } if (dt.getSortField().equals("id")) { s.setSortField("id"); } s.setSortType(dt.getSortType()); s.setCurrentPage(curPage); s.setPageSize(length); Page<NewsTypeVo> pages = newsTypeService.getPage(s); dt.setData(pages.getData()); dt.setiTotalRecords(dt.getiTotalRecords()); dt.setiTotalRecords(pages.getRecordCount()); json = formateData2DT(dt); } catch (Exception e) { e.printStackTrace(); } return json; } /** * 获取所有类型 * @return @RequestMapping(value = "/queryAll", produces = "plain/text; charset=UTF-8") @ResponseBody public String queryAll() { try { List<NewsTypeVo> list = newsTypeService.queryAll(); return this.buildMessage(ResultModal.SUCCESS, ResultModal.SUCCESS_CODE, "所有类型获取成功", list, ResultModal.DATA); } catch (Exception e) { return this.buildFailMessage("所有类型获取失败", ResultModal.MESSAGE); } } */ /** * 添加类型 * * @param newsTypeVo * @return */ @RequestMapping(value = "/save", produces = "plain/text; charset=UTF-8") @ResponseBody public String save(NewsTypeVo newsTypeVo) { try { newsTypeService.save(newsTypeVo); return this.buildSuccessMessage("类型添加成功", ResultModal.MESSAGE); } catch (Exception e) { return this.buildFailMessage("类型添加失败", ResultModal.MESSAGE); } } /** * 更新类型 * * @param id * @param name * @return */ @RequestMapping(value = "/update", produces = "plain/text; charset=UTF-8") @ResponseBody public String update(@RequestParam(value = "id", required = true) Long id, @RequestParam(value = "name", required = true) String name ) { try { NewsTypeVo newsTypeVo = newsTypeService.findOne(id); newsTypeVo.setName(name); newsTypeService.update(newsTypeVo); return this.buildSuccessMessage("类型更新成功", ResultModal.MESSAGE); } catch (Exception e) { return this.buildFailMessage("类型更新失败", ResultModal.MESSAGE); } } @ResponseBody @RequestMapping(value = "/queryById", produces = "plain/text; charset=UTF-8") public String queryUser(@RequestParam(value = "id", required = true) Long id) { try { NewsTypeVo newsTypeVo = newsTypeService.findOne(id); return this.buildMessage(ResultModal.SUCCESS, ResultModal.SUCCESS_CODE, "类型获取成功", newsTypeVo, ResultModal.DATA); } catch (Exception e) { return this.buildFailMessage("类型获取失败", ResultModal.MESSAGE); } } /** * 删除类型 * * @param id * @return */ @RequestMapping("/delete") @ResponseBody public String delete(@RequestParam(value = "id", required = true) Long id) { try { newsTypeService.delete(id); return this.buildSuccessMessage("类型删除成功", ResultModal.MESSAGE); } catch (Exception e) { return this.buildFailMessage("类型删除失败", ResultModal.MESSAGE); } } } ``` NewsConverter.java ```package com.lebao.converter; import com.lebao.common.Constant; import com.lebao.po.News; import com.lebao.po.SysUser; import com.lebao.service.NewsService; import com.lebao.service.NewsTypeService; import com.lebao.service.SysUserService; import com.lebao.vo.NewsTypeVo; import com.lebao.vo.NewsVo; import com.lebao.vo.SysUserVo; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Created by ZR on 2016/12/6. */ @Component public class NewsConverter extends BaseConverter<News, NewsVo> { @Autowired private NewsService newsService; @Autowired private NewsTypeService newsTypeService; @Override public News convert2P(NewsVo vo) { if (vo == null) { return null; } News po = null; try { po = new News(); BeanUtils.copyProperties(vo, po); } catch (Exception e) { e.printStackTrace(); } return po; } @Override public NewsVo convert2V(News po) { if (po == null) { return null; } NewsVo vo = new NewsVo(); try { BeanUtils.copyProperties(po, vo); String newsType=newsTypeService.findOne(vo.getTypeId()).getName(); vo.setTypeName(newsType); if(vo.getRecommend()== Constant.NEWS_RECOMMEND_TRUE){ vo.setRecommendValue("是"); } else if(vo.getRecommend()== Constant.NEWS_RECOMMEND_FALSE){ vo.setRecommendValue("否"); }else { vo.setRecommendValue("否"); } // return updateTime.replaceAll("\\s\\d{1,2}:\\d{1,2}:\\d{1,2}(\\.\\d)?$",""); } catch (Exception e) { e.printStackTrace(); } return vo; } } ``` NewsTypeService.java ```package com.lebao.service; import com.lebao.common.beans.SearchBean; import com.lebao.common.dbhelp.page.Page; import com.lebao.converter.NewsTypeConverter; import com.lebao.dao.newstype.NewsTypeDao; import com.lebao.po.NewsType; import com.lebao.vo.NewsTypeVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.sql.SQLException; import java.util.List; /** * Author: zr * Date : 2016/12/6 18:13 */ @Service public class NewsTypeService { @Autowired NewsTypeDao newsTypeDao; @Autowired NewsTypeConverter newsTypeConverter; public Page<NewsTypeVo> getPage(SearchBean s) throws SQLException { int myPageSize = 0;//每页记录数 int curPage = 0;//显示页 int pageCount = 0;//页数 int recordCount = 0;//总记录数 Page<NewsType> newsTypePage = newsTypeDao.getPage(s); List<NewsTypeVo> list = newsTypeConverter.convert2V(newsTypePage.getData()); recordCount = newsTypePage.getRecordCount(); pageCount = newsTypePage.getPageCount(); curPage = newsTypePage.getCurPage(); myPageSize = newsTypePage.getPageSize(); Page<NewsTypeVo> pageBean = new Page<NewsTypeVo>(myPageSize, list, curPage, pageCount, recordCount); return pageBean; } public List<NewsTypeVo> queryAll ()throws SQLException { List<NewsType> newsTypeList=newsTypeDao.findAll(); List<NewsTypeVo> newsTypeVoList= newsTypeConverter.convert2V(newsTypeList); return newsTypeVoList; } public void save(NewsTypeVo vo) { NewsType newsType = newsTypeConverter.convert2P(vo); newsTypeDao.save(newsType); } public void update(NewsTypeVo vo) { NewsType newsType = newsTypeConverter.convert2P(vo); newsTypeDao.save(newsType); } public void delete(Long id) { NewsTypeVo vo = findOne(id); NewsType newsType = newsTypeConverter.convert2P(vo); newsTypeDao.delete(newsType); } public NewsTypeVo findOne(Long id) { NewsType newsType = newsTypeDao.findOne(id); NewsTypeVo newsTypeVo = newsTypeConverter.convert2V(newsType); return newsTypeVo; } } ``` RoleBean.java ```package com.lebao.bean; import com.fasterxml.jackson.annotation.JsonProperty; public class RoleBean { @JsonProperty("id") private String p_id = null; // 表字段名称为:p_id 相应注释为:ID。 private String p_creater_time = null; // 表字段名称为:p_creater_time 相应注释为:创建时间。 @JsonProperty("desc") private String p_desc = null; // 表字段名称为:p_desc 相应注释为:角色描述。 @JsonProperty("name") private String p_name = null; // 表字段名称为:p_name 相应注释为:角色名称。 private String p_type = null; // 表字段名称为:p_type 相应注释为:角色类型。 private String p_update_time = null; // 表字段名称为:p_update_time 相应注释为:。 public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_creater_time() { return p_creater_time; } public void setP_creater_time(String p_creater_time) { this.p_creater_time = p_creater_time; } public String getP_desc() { return p_desc; } public void setP_desc(String p_desc) { this.p_desc = p_desc; } public String getP_name() { return p_name; } public void setP_name(String p_name) { this.p_name = p_name; } public String getP_type() { return p_type; } public void setP_type(String p_type) { this.p_type = p_type; } public String getP_update_time() { return p_update_time; } public void setP_update_time(String p_update_time) { this.p_update_time = p_update_time; } @Override public String toString() { return "RoleBean{" + "p_id='" + p_id + '\'' + ", p_creater_time='" + p_creater_time + '\'' + ", p_desc='" + p_desc + '\'' + ", p_name='" + p_name + '\'' + ", p_type='" + p_type + '\'' + ", p_update_time='" + p_update_time + '\'' + '}'; } } ``` MarketEntity.java ```package com.lebao.modules.market.entity; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; @Table(name="t_market") public class MarketEntity { @Id @Column(name="p_user_id") private String p_user_id ;//bigint(20) NOT NULLid private String p_sys_user_id ; private String p_create_time; private String p_sys_user_name ; public String getP_sys_user_name() { return p_sys_user_name; } public void setP_sys_user_name(String p_sys_user_name) { this.p_sys_user_name = p_sys_user_name; } public String getP_user_id() { return p_user_id; } public void setP_user_id(String p_user_id) { this.p_user_id = p_user_id; } public String getP_sys_user_id() { return p_sys_user_id; } public void setP_sys_user_id(String p_sys_user_id) { this.p_sys_user_id = p_sys_user_id; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } @Override public String toString() { return "MarketEntity{" + "p_user_id='" + p_user_id + '\'' + ", p_sys_user_id='" + p_sys_user_id + '\'' + ", p_create_time='" + p_create_time + '\'' + '}'; } } ``` TypeBean.java ```package com.lebao.bean; import com.fasterxml.jackson.annotation.JsonProperty; import java.sql.Timestamp; /** * Created by Server on 2016/3/29. */ public class TypeBean { @JsonProperty("id") private String p_id; @JsonProperty("name") private String p_name; @JsonProperty("status") private String p_status;//1可用,-1不可用 private Timestamp p_create_time; private Timestamp p_update_time; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_name() { return p_name; } public void setP_name(String p_name) { this.p_name = p_name; } public String getP_status() { return p_status; } public void setP_status(String p_status) { this.p_status = p_status; } public Timestamp getP_create_time() { return p_create_time; } public void setP_create_time(Timestamp p_create_time) { this.p_create_time = p_create_time; } public Timestamp getP_update_time() { return p_update_time; } public void setP_update_time(Timestamp p_update_time) { this.p_update_time = p_update_time; } @Override public String toString() { return "TypeBean{" + "p_id='" + p_id + '\'' + ", p_name='" + p_name + '\'' + ", p_status='" + p_status + '\'' + ", p_create_time=" + p_create_time + ", p_update_time=" + p_update_time + '}'; } } ``` SysUserRepo.java ```package com.lebao.dao.sysuser; import com.lebao.po.SysUser; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.CrudRepository; public interface SysUserRepo extends JpaRepository<SysUser,Long> { SysUser findByNameAndPassword(String name,String password); int countByName(String name); } ``` package-info.java ```/** * 对不同数据库类型进行个性化处理 * */ package com.lebao.common.dbhelp.dialect;``` DepartmentDao.java ```package com.lebao.dao.user; import com.lebao.common.dbhelp.DbHelper; import com.lebao.po.Department; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class DepartmentDao { @Autowired DepartmentRepo departmentRepo; @Autowired DbHelper dbHelper; public Department findOne(Long id) { return departmentRepo.findOne(id); } public void save(Department department) { departmentRepo.save(department); } public List<Department> findAll(){ return departmentRepo.findAll(); } } ``` SysUserService.java ```package com.lebao.service; import com.lebao.common.Constant; import com.lebao.common.beans.SearchBean; import com.lebao.common.dbhelp.page.Page; import com.lebao.common.utils.Sequence; import com.lebao.converter.SysUserConverter; import com.lebao.dao.sysuser.SysUserDao; import com.lebao.po.SysUser; import com.lebao.vo.SysUserVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.sql.SQLException; import java.util.List; /** * Author: zr * Date : 2016/12/6 18:13 */ @Service public class SysUserService { @Autowired SysUserDao sysUserDao; @Autowired SysUserConverter sysUserConverter; public Page<SysUserVo> getPage(SearchBean s) throws SQLException { int myPageSize = 0;//每页记录数 int curPage = 0;//显示页 int pageCount = 0;//页数 int recordCount = 0;//总记录数 Page<SysUser> sysUserPage = sysUserDao.getPage(s); List<SysUserVo> list = sysUserConverter.convert2V(sysUserPage.getData()); recordCount = sysUserPage.getRecordCount(); pageCount = sysUserPage.getPageCount(); curPage = sysUserPage.getCurPage(); myPageSize = sysUserPage.getPageSize(); Page<SysUserVo> pageBean = new Page<SysUserVo>(myPageSize, list, curPage, pageCount, recordCount); return pageBean; } public void save(SysUserVo vo) { vo.setType(Constant.USER_ADMIN); SysUser sysUser = sysUserConverter.convert2P(vo); sysUserDao.save(sysUser); System.out.println(sysUser.toString()); } public void update(SysUserVo vo) { SysUser sysUser = sysUserConverter.convert2P(vo); sysUserDao.save(sysUser); } public void delete(Long id) { SysUserVo vo=findOne(id); SysUser sysUser = sysUserConverter.convert2P(vo); sysUserDao.delete(sysUser); } public SysUserVo findOne(Long id) { SysUser sysUser=sysUserDao.findOne(id); SysUserVo sysUserVo = sysUserConverter.convert2V(sysUser); return sysUserVo; } public SysUserVo findByNameAndPassword(String name,String password){ SysUser sysUser=sysUserDao.findByNameAndPassword(name,password); SysUserVo sysUserVo = sysUserConverter.convert2V(sysUser); return sysUserVo; } public boolean checkSysUserIsExist(String name){ return sysUserDao.checkSysUserIsExist(name); } } ``` ShoperBean.java ```package com.lebao.bean; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Server on 2016/5/26. */ public class ShoperBean { @JsonProperty("id") private String p_id;//varchar(255) NULLid @JsonProperty("name") private String p_name;//varchar(255) NULL 商家名称 @JsonProperty("desc") private String p_desc;//varchar(255) NULL 商家描述 @JsonProperty("photo1") private String p_photo1;//varchar(20) NULL 商家图片 @JsonProperty("url") private String p_url;//varchar(20) NULL 链接 @JsonProperty("phone") private String p_phone;//varchar(20) NULL 电话 @JsonProperty("keys") private String p_keys;//varchar(20) NULL 关键字 @JsonProperty("status") private String p_status;//tinyint(1) NOT NULL 状态 private String p_create_time;//timestamp NULL创建时间 private String p_update_time;//timestamp NULL更新时间 public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_name() { return p_name; } public void setP_name(String p_name) { this.p_name = p_name; } public String getP_desc() { return p_desc; } public void setP_desc(String p_desc) { this.p_desc = p_desc; } public String getP_photo1() { return p_photo1; } public void setP_photo1(String p_photo1) { this.p_photo1 = p_photo1; } public String getP_url() { return p_url; } public void setP_url(String p_url) { this.p_url = p_url; } public String getP_phone() { return p_phone; } public void setP_phone(String p_phone) { this.p_phone = p_phone; } public String getP_status() { return p_status; } public void setP_status(String p_status) { this.p_status = p_status; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public String getP_update_time() { return p_update_time; } public void setP_update_time(String p_update_time) { this.p_update_time = p_update_time; } public String getP_keys() { return p_keys; } public void setP_keys(String p_keys) { this.p_keys = p_keys; } @Override public String toString() { return "ShoperEntity{" + "p_id='" + p_id + '\'' + ", p_name='" + p_name + '\'' + ", p_desc='" + p_desc + '\'' + ", p_photo1='" + p_photo1 + '\'' + ", p_url='" + p_url + '\'' + ", p_phone='" + p_phone + '\'' + ", p_keys='" + p_keys + '\'' + ", p_status='" + p_status + '\'' + ", p_create_time=" + p_create_time + ", p_update_time=" + p_update_time + '}'; } } ``` MarketBean.java ```package com.lebao.bean; import com.fasterxml.jackson.annotation.JsonProperty; public class MarketBean { @JsonProperty("user_id") private String p_user_id ;//bigint(20) NOT NULLid @JsonProperty("sys_user_id") private String p_sys_user_id ; @JsonProperty("create_time") private String p_create_time; @JsonProperty("sys_user_name") private String p_sys_user_name ; public String getP_sys_user_name() { return p_sys_user_name; } public void setP_sys_user_name(String p_sys_user_name) { this.p_sys_user_name = p_sys_user_name; } public String getP_user_id() { return p_user_id; } public void setP_user_id(String p_user_id) { this.p_user_id = p_user_id; } public String getP_sys_user_id() { return p_sys_user_id; } public void setP_sys_user_id(String p_sys_user_id) { this.p_sys_user_id = p_sys_user_id; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } @Override public String toString() { return "MarketEntity{" + "p_user_id='" + p_user_id + '\'' + ", p_sys_user_id='" + p_sys_user_id + '\'' + ", p_create_time='" + p_create_time + '\'' + '}'; } } ``` AdvEntity.java ```package com.lebao.modules.adv.entity; public class AdvEntity { private String p_id; private String p_goods_id; private String p_title; private String p_content; private String p_photo; private String p_url; private String p_create_time; private String p_update_time; private String p_type; private String p_status; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_goods_id() { return p_goods_id; } public void setP_goods_id(String p_goods_id) { this.p_goods_id = p_goods_id; } public String getP_title() { return p_title; } public void setP_title(String p_title) { this.p_title = p_title; } public String getP_content() { return p_content; } public void setP_content(String p_content) { this.p_content = p_content; } public String getP_photo() { return p_photo; } public void setP_photo(String p_photo) { this.p_photo = p_photo; } public String getP_url() { return p_url; } public void setP_url(String p_url) { this.p_url = p_url; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public String getP_update_time() { return p_update_time; } public void setP_update_time(String p_update_time) { this.p_update_time = p_update_time; } public String getP_type() { return p_type; } public void setP_type(String p_type) { this.p_type = p_type; } public String getP_status() { return p_status; } public void setP_status(String p_status) { this.p_status = p_status; } @Override public String toString() { return "AdvEntity{" + "p_id='" + p_id + '\'' + ", p_goods_id='" + p_goods_id + '\'' + ", p_title='" + p_title + '\'' + ", p_content='" + p_content + '\'' + ", p_photo='" + p_photo + '\'' + ", p_url='" + p_url + '\'' + ", p_create_time='" + p_create_time + '\'' + ", p_update_time='" + p_update_time + '\'' + ", p_type='" + p_type + '\'' + ", p_status='" + p_status + '\'' + '}'; } } ``` NewsTypeSetting.java ```package com.lebao.common.constant; /** * Created by ZR on 2016/12/11. */ public class NewsTypeSetting { /** * Hshb */ public static final int TYPE_NEWS_CENTER = 1; public static final int TYPE_NEWS_INFO = 2; public static final int TYPE_NEWS_JOBOFFER = 3; public static final int TYPE_NEWS_COMPANY = 4; public static final int TYPE_NEWS_SERVICE = 5; } ``` LiushuiDao.java ```package com.lebao.modules.sys.dao; import com.lebao.bean.SearchParam; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.common.utils.TimeUtil; import com.lebao.modules.BaseDao; import com.lebao.modules.sys.entity.LiushuiEntity; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.sql.SQLException; import java.util.Date; @Repository public class LiushuiDao extends BaseDao { @Resource(name = "dbHelper") private DbHelper dbHelper; public Page<LiushuiEntity> getLishuis(SearchParam s) throws SQLException { String sql = "select * from t_liushui where 1=1 and p_status=1 "; if (StringUtils.isNotBlank(s.getId())) { sql += " and p_user_id = '" + s.getId() + "' "; } if (StringUtils.isNotBlank(s.getTime1())) { sql += " and p_create_time between '"+s.getTime1()+"' and "; if(StringUtils.isNotBlank(s.getTime2())){ sql += " '"+s.getTime2() +"' "; }else { sql += " '"+ TimeUtil.format(new Date(), TimeUtil.TARGET_1) +"' "; } } sql += " order by " + s.getSortField() + " " + s.getSortType() + " "; // System.out.println(sql); return dbHelper.getPage(sql, LiushuiEntity.class, s.getPageNow(), s.getPageSize()); } public LiushuiEntity getLiushuiByUserId(String uid) throws SQLException { String sql = "select * from t_liushui where p_user_id = ? and p_status =1"; return dbHelper.getBean(sql, LiushuiEntity.class, uid); } } ``` SysRoleEntity.java ```package com.lebao.modules.permission.entity; public class SysRoleEntity { private String p_id = null; // 表字段名称为:p_id 相应注释为:ID。 private String p_creater_time = null; // 表字段名称为:p_creater_time 相应注释为:创建时间。 private String p_desc = null; // 表字段名称为:p_desc 相应注释为:角色描述。 private String p_name = null; // 表字段名称为:p_name 相应注释为:角色名称。 private String p_type = null; // 表字段名称为:p_type 相应注释为:角色类型。 private String p_update_time = null; // 表字段名称为:p_update_time 相应注释为:。 public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_creater_time() { return p_creater_time; } public void setP_creater_time(String p_creater_time) { this.p_creater_time = p_creater_time; } public String getP_desc() { return p_desc; } public void setP_desc(String p_desc) { this.p_desc = p_desc; } public String getP_name() { return p_name; } public void setP_name(String p_name) { this.p_name = p_name; } public String getP_type() { return p_type; } public void setP_type(String p_type) { this.p_type = p_type; } public String getP_update_time() { return p_update_time; } public void setP_update_time(String p_update_time) { this.p_update_time = p_update_time; } } ``` NewsDao.java ```package com.lebao.dao.news; import com.lebao.common.beans.SearchBean; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.po.News; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; @Repository public class NewsDao { @Autowired NewsRepo newsRepo; @Autowired DbHelper dbHelper; public Page<News> getPage(SearchBean searchBean) throws SQLException { String sql = " SELECT * from tb_news where 1=1 "; List<Object> list = new ArrayList<Object>(); Map<Object, Object> map = searchBean.getParamMap(); if (map.containsKey("name")) { sql += " and tb_news.name like ? "; list.add("%" + map.get("name") + "%"); } if (map.containsKey("typeId")) { sql += " and tb_news.typeId = ? "; list.add( map.get("typeId")); } sql += " order by " + searchBean.getSortField() + " " + searchBean.getSortType() + " "; return dbHelper.getPage(sql, News.class, searchBean.getCurrentPage(), searchBean.getPageSize(), list.toArray()); } public void save(News news) { newsRepo.save(news); } public void update(News news) { newsRepo.save(news); } public void delete(News news) { newsRepo.delete(news); } public News findOne(Long id) { return newsRepo.findOne(id); } /** * 首页的内容 */ public Page<News> indexList(SearchBean searchBean) throws SQLException{ String sql = " SELECT * from tb_news where 1=1 "; List<Object> list = new ArrayList<Object>(); Map<Object, Object> map = searchBean.getParamMap(); if (map.containsKey("typeId")) { sql += " and typeId = ? "; list.add( map.get("typeId")); } sql+="order by updateTime desc"; return dbHelper.getPage(sql, News.class, searchBean.getCurrentPage(), searchBean.getPageSize(), list.toArray()); } /** * 首页滚动 */ public List<News> indexList1() throws SQLException{ String sql = " SELECT * from tb_news where recommend =1 "; sql+="order by updateTime desc"; return dbHelper.getBeanList(sql, News.class); } } ``` Constant.java ```package com.lebao.common; import java.util.HashMap; import java.util.Map; /** * Created by Server on 2016/5/4. */ public class Constant { static { Map<Integer,String> sexMap=new HashMap<Integer,String>(); sexMap.put(1,"男"); sexMap.put(0,"女"); sexMap.put(2,"其他"); } public static final int USER_ADMIN = 1 ; /** * 新闻推荐 */ public static final int NEWS_RECOMMEND_TRUE = 1 ; public static final int NEWS_RECOMMEND_FALSE = 0 ; /** * User is locked */ public static final int USER_STATUS_LOCKED = -2 ; /** * User is disabled */ public static final int USER_STATUS_DISABLED = -1 ; /** * User is active */ public static final int USER_STATUS_ACTIVE = 1 ; public static final String SUPPER_USER_FLAG = "0" ; public static final int LEBAO_USER_TYPE_ADMIN = 0; //系统管理员 public static final int LEBAO_USER_TYPE_AGENT = 1; //代理商 public static final int LEBAO_USER_TYPE_SALESMAN = 2; //业务员 public static final int LEBAO_USER_TYPE_OPRATION = 3; //运维人员 public static final int LEBAO_USER_TYPE_OTHER = 4; //运维人员 } ``` PositionDao.java ```package com.lebao.dao.user; import com.lebao.common.dbhelp.DbHelper; import com.lebao.po.EduLevel; import com.lebao.po.Position; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class PositionDao { @Autowired PositionRepo positionRepo; @Autowired DbHelper dbHelper; public Position findOne(Long id) { return positionRepo.findOne(id); } public void save(Position position) { positionRepo.save(position); } public List<Position> findAll(){ return positionRepo.findAll(); } } ``` UserBean.java ```package com.lebao.bean; import com.fasterxml.jackson.annotation.JsonProperty; public class UserBean { @JsonProperty("id") private String p_id ;//bigint(20) NOT NULLid @JsonProperty("userName") private String p_user_name;//varchar(20) NULL姓名 @JsonProperty("userAccount") private String p_account;//varchar(20) NULL用户名 @JsonProperty("userPhone") private String p_user_phone;//varchar(11) NULL电话 private String p_password;//varchar(255) NULL密码 private float p_point1; //float(15,2) NOT NULL邀请码1的积分 private String p_invitation_code2;//bigint(20) NULL邀请码2 private String p_regist_code; //bigint(20) NOT NULL注册码 private int p_state;//tinyint(1) NOT NULL状态 @JsonProperty("userType") private String p_type;//tinyint(1) NOT NULL-1:非会员 1:会员 @JsonProperty("createTime") private String p_create_time; //timestamp NULL创建时间 @JsonProperty("lastLoginTime") private String p_lastlogin_time;//timestamp NULL最后登录时间 private float p_point2;//float NOT NULL邀请码2的积分 private String p_invitation_code1; private int p_grade_point; private String p_parent_code;//上一级用户的id private String p_child_code1;//下一级用户的id 左 private String p_child_code2;//下一级用户的id 右 private int p_shouchong;//首充-1 未完成 1 完成 private float p_point; //float(15,2) NOT NULL积分 private String p_qq; private String p_address; private String p_email; @JsonProperty("hyEndTime") private String p_hy_end_time; @JsonProperty("lebi") private Float p_lebi; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_user_name() { return p_user_name; } public void setP_user_name(String p_user_name) { this.p_user_name = p_user_name; } public String getP_account() { return p_account; } public void setP_account(String p_account) { this.p_account = p_account; } public String getP_user_phone() { return p_user_phone; } public void setP_user_phone(String p_user_phone) { this.p_user_phone = p_user_phone; } public String getP_password() { return p_password; } public void setP_password(String p_password) { this.p_password = p_password; } public float getP_point1() { return p_point1; } public void setP_point1(float p_point1) { this.p_point1 = p_point1; } public String getP_invitation_code2() { return p_invitation_code2; } public void setP_invitation_code2(String p_invitation_code2) { this.p_invitation_code2 = p_invitation_code2; } public String getP_regist_code() { return p_regist_code; } public void setP_regist_code(String p_regist_code) { this.p_regist_code = p_regist_code; } public int getP_state() { return p_state; } public void setP_state(int p_state) { this.p_state = p_state; } public String getP_type() { return p_type; } public void setP_type(String p_type) { this.p_type = p_type; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public String getP_lastlogin_time() { return p_lastlogin_time; } public void setP_lastlogin_time(String p_lastlogin_time) { this.p_lastlogin_time = p_lastlogin_time; } public float getP_point2() { return p_point2; } public void setP_point2(float p_point2) { this.p_point2 = p_point2; } public String getP_invitation_code1() { return p_invitation_code1; } public void setP_invitation_code1(String p_invitation_code1) { this.p_invitation_code1 = p_invitation_code1; } public int getP_grade_point() { return p_grade_point; } public void setP_grade_point(int p_grade_point) { this.p_grade_point = p_grade_point; } public String getP_parent_code() { return p_parent_code; } public void setP_parent_code(String p_parent_code) { this.p_parent_code = p_parent_code; } public String getP_child_code1() { return p_child_code1; } public void setP_child_code1(String p_child_code1) { this.p_child_code1 = p_child_code1; } public String getP_child_code2() { return p_child_code2; } public void setP_child_code2(String p_child_code2) { this.p_child_code2 = p_child_code2; } public int getP_shouchong() { return p_shouchong; } public void setP_shouchong(int p_shouchong) { this.p_shouchong = p_shouchong; } public float getP_point() { return p_point; } public void setP_point(float p_point) { this.p_point = p_point; } public String getP_qq() { return p_qq; } public void setP_qq(String p_qq) { this.p_qq = p_qq; } public String getP_address() { return p_address; } public void setP_address(String p_address) { this.p_address = p_address; } public String getP_email() { return p_email; } public void setP_email(String p_email) { this.p_email = p_email; } public String getP_hy_end_time() { return p_hy_end_time; } public void setP_hy_end_time(String p_hy_end_time) { this.p_hy_end_time = p_hy_end_time; } public Float getP_lebi() { return p_lebi; } public void setP_lebi(Float p_lebi) { this.p_lebi = p_lebi; } @Override public String toString() { return "UserBean{" + "p_id='" + p_id + '\'' + ", p_user_name='" + p_user_name + '\'' + ", p_account='" + p_account + '\'' + ", p_user_phone='" + p_user_phone + '\'' + ", p_password='" + p_password + '\'' + ", p_point1=" + p_point1 + ", p_invitation_code2='" + p_invitation_code2 + '\'' + ", p_regist_code='" + p_regist_code + '\'' + ", p_state=" + p_state + ", p_type=" + p_type + ", p_create_time='" + p_create_time + '\'' + ", p_lastlogin_time='" + p_lastlogin_time + '\'' + ", p_point2=" + p_point2 + ", p_invitation_code1='" + p_invitation_code1 + '\'' + ", p_grade_point=" + p_grade_point + ", p_parent_code='" + p_parent_code + '\'' + ", p_child_code1='" + p_child_code1 + '\'' + ", p_child_code2='" + p_child_code2 + '\'' + ", p_shouchong=" + p_shouchong + ", p_point=" + p_point + '}'; } } ``` IndexController.java ```package com.lebao.controller.hshb; import com.lebao.common.constant.NewsTypeSetting; import com.lebao.common.beans.SearchBean; import com.lebao.common.dbhelp.page.Page; import com.lebao.service.NewsService; import com.lebao.service.NewsTypeService; import com.lebao.vo.NewsTypeVo; import com.lebao.vo.NewsVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import java.util.List; /** * Created by ZR on 2016/12/11. */ @Controller public class IndexController { @Autowired NewsService newsService; @Autowired NewsTypeService newsTypeService; /** * 首页 * * @return */ @RequestMapping("") public ModelAndView index() { ModelAndView view = new ModelAndView(); try { int curPage = 0; int pageSize = 5; /** * 新闻中心 */ SearchBean searchBean = new SearchBean(); searchBean.getParamMap().put("typeId", NewsTypeSetting.TYPE_NEWS_CENTER); searchBean.setCurrentPage(curPage); searchBean.setPageSize(pageSize); List<NewsVo> indexNewsList = newsService.indexList(searchBean); view.addObject("indexNewsList", indexNewsList); /** * 信息公示 */ SearchBean searchBean1 = new SearchBean(); searchBean1.getParamMap().put("typeId", NewsTypeSetting.TYPE_NEWS_INFO); searchBean1.setCurrentPage(curPage); searchBean1.setPageSize(pageSize); List<NewsVo> indexInfosList = newsService.indexList(searchBean1); view.addObject("indexInfosList", indexInfosList); /** * 招聘 SearchBean searchBean2 = new SearchBean(); searchBean2.getParamMap().put("typeId", NewsTypeSetting.TYPE_NEWS_JOBOFFER); searchBean2.setCurrentPage(curPage); searchBean2.setPageSize(pageSize); List<NewsVo> indexJobofferList = newsService.indexList(searchBean2); view.addObject("indexJobofferList", indexJobofferList); /** * 关于和顺 SearchBean searchBean3 = new SearchBean(); searchBean3.getParamMap().put("typeId", NewsTypeSetting.TYPE_NEWS_COMPANY); searchBean3.setCurrentPage(curPage); searchBean3.setPageSize(pageSize); List<NewsVo> indexCompanyList = newsService.indexList(searchBean3); view.addObject("indexCompanyList", indexCompanyList); */ /** * 服务项目 */ SearchBean searchBean4 = new SearchBean(); searchBean4.getParamMap().put("typeId", NewsTypeSetting.TYPE_NEWS_SERVICE); searchBean4.setCurrentPage(curPage); searchBean4.setPageSize(pageSize); List<NewsVo> indexServicesList = newsService.indexList(searchBean4); view.addObject("indexServicesList", indexServicesList); /** * 首页滚动 */ List<NewsVo> indexRecommendList = newsService.indexList1(); view.addObject("indexRecommendList", indexRecommendList); } catch (Exception e) { e.printStackTrace(); } view.setViewName("index/index"); return view; } @RequestMapping("/content") public ModelAndView content(@RequestParam(value = "id", required = true) Long id) { ModelAndView view = new ModelAndView(); try { NewsVo news = newsService.findOne(id); view.addObject("news", news); } catch (Exception e) { e.printStackTrace(); } view.setViewName("index/content"); return view; } /* @RequestMapping("/joboffer") public ModelAndView joboffer() { ModelAndView view = new ModelAndView(); view.setViewName("index/joboffer"); return view; } */ /** * 更多 * * @param typeId * @return */ @RequestMapping("/newslist") public ModelAndView newslist(@RequestParam(value = "typeId", required = true) Long typeId, @RequestParam(value = "page", required = false, defaultValue = "0") Integer curPage) { ModelAndView view = new ModelAndView(); int pageSize = 15; try { NewsTypeVo newsTypeVo=newsTypeService.findOne(typeId); view.addObject("newsTypeVo", newsTypeVo); SearchBean s = new SearchBean(); s.getParamMap().put("typeId", typeId); s.setSortType("desc"); s.setSortField("updateTime"); s.setCurrentPage(curPage); s.setPageSize(pageSize); Page<NewsVo> page = newsService.getPage(s); view.addObject("page", page); } catch (Exception e) { e.printStackTrace(); } view.setViewName("index/newslist"); return view; } } ``` SysUserConverter.java ```package com.lebao.converter; import com.lebao.po.SysUser; import com.lebao.service.SysUserService; import com.lebao.vo.SysUserVo; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Created by ZR on 2016/12/6. */ @Component public class SysUserConverter extends BaseConverter<SysUser, SysUserVo> { @Autowired SysUserService sysUserService; @Override public SysUser convert2P(SysUserVo vo) { if (vo == null) { return null; } SysUser po = null; try { po = new SysUser(); BeanUtils.copyProperties(vo, po); } catch (Exception e) { e.printStackTrace(); } return po; } @Override public SysUserVo convert2V(SysUser po) { if (po == null) { return null; } SysUserVo vo = new SysUserVo(); try { BeanUtils.copyProperties(po, vo); } catch (Exception e) { e.printStackTrace(); } return vo; } } ``` scoreduihuan.js ```$(document) .ready( function() { setting.sAjaxSource = G_CTX_ROOT+"/scoreduihuan/query"; setting.aoColumns = [ { "sTitle" : "商品名", //显示标题 "mData" : "score_name", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "会员编号", //显示标题 "mData" : "user_id", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "姓名", //显示标题 "mData" : "user_name", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "1%" }, { "sTitle" : "电话", //显示标题 "mData" : "user_phone", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "2%" }, { "sTitle" : "地址", //显示标题 "mData" : "user_address", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "4%" }, { "sTitle" : "状态", //显示标题 "mData" : "status", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "1%" }, { "sTitle" : "创建时间", //显示标题 "mData" : "create_time", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "完成时间", //显示标题 "mData" : "update_time", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "处理人", //显示标题 "mData" : "dealuser_name", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "1%" }, { "sTitle": "<center>操作</center>", // 显示标题 "bSortable": false,// 排序 "mData": "id", // 属性 "sClass": "center", "sWidth": "3%", "mRender": function (data, style, obj) { var xqDom = "<a class=\"btn btn-round btn-info btn-xs\" onclick=\"finish(" + obj.id + ")\" >完成兑换</a>"; return xqDom ; } } ]; setting.aaSorting = [ [ 3, "desc" ] ]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); }); function doSearch() { dataTable.fnDraw(); } function preFinish(id) { //alert(id); $("#myModal").modal("show").css({ 'top' : '60px' }); $("#finish").attr("onClick","finish("+id+")"); } function finish(id) { //alert(id); $.ajaxInvoke({ url : G_CTX_ROOT+"/scoreduihuan/finish/", type : "post", datatype : "json", data : { p_id : id }, success : function(data) { //alert(data); $("#myModal").modal("hide") msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } function deal(id) { //alert(id); $.ajaxInvoke({ url : G_CTX_ROOT+"/order/deal/", type : "post", datatype : "json", data : { p_id : id }, success : function(data) { //alert(data); $("#myModal").modal("hide") msgBox(data.state, data.msg); dataTable.fnDraw(); }, }); }``` AdvSearchParam.java ```package com.lebao.bean; public class AdvSearchParam { private String type; private int pageSize = 15; private int pageNow = 0; private String sortField = "p_create_time"; private String sortType = "desc"; public String getType() { return type; } public void setType(String type) { this.type = type; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getPageNow() { return pageNow; } public void setPageNow(int pageNow) { this.pageNow = pageNow; } public String getSortField() { return sortField; } public void setSortField(String sortField) { this.sortField = sortField; } public String getSortType() { return sortType; } public void setSortType(String sortType) { this.sortType = sortType; } } ``` roleAdd.js ```$(document) .ready( function() { var roleId=$("#roleId").val(); //console.log(roleId); var role={}; if(roleId != ""){ role.roleId=roleId; $.ajaxInvoke({ url : G_CTX_ROOT+"/role/getAllPermissionByRoleId" , data :role, success : function(returnData){ returnData= JSON.parse(returnData); console.log(returnData); $.each(returnData.aaData, function(key,value) { $('.permission-checkbox').each(function(key1,value1){ var policyidcheckbox=$.trim($(this).attr("value")); if(value.p_permission_id==policyidcheckbox){ $(this).prop("checked",true); //$(this).prop("disabled",true); } }); }); }, error : "操作失败", dataType: "html" }); } }); function addPermission(){ var role={}; role.roleName=$("#roleName").val(); role.roleDesc=$("#roleDesc").val(); var permList=""; $('input:checkbox:checked').each(function() { var id=$.trim($(this).attr("value")); permList=permList+";"+id; }); var postURL = G_CTX_ROOT+"/role/add"; role.permissionlist=permList; $.ajaxInvoke({ url : postURL, type : "post", data : role, success : function(data) { msgBox(data.state, data.msg); }, }); } function updatePermission(){ var role={}; role.roleName=$("#roleName").val(); role.roleDesc=$("#roleDesc").val(); role.roleId=$("#roleId").val(); var permList=""; $('input:checkbox:checked').each(function() { var id=$.trim($(this).attr("value")); permList=permList+";"+id; }); var postURL = G_CTX_ROOT+"/role/update"; role.permissionlist=permList; $.ajaxInvoke({ url : postURL, type : "post", data : role, success : function(data) { msgBox(data.state, data.msg); } }); } ``` UserDepartmentRelService.java ```package com.lebao.service; import com.lebao.dao.user.UserDepartmentRelDao; import com.lebao.po.UserDepartmentRel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Author: zr * Date : 2016/12/6 18:13 */ @Service public class UserDepartmentRelService { @Autowired UserDepartmentRelDao userDepartmentRelDao; public void save(UserDepartmentRel userDepartmentRel) { userDepartmentRelDao.save(userDepartmentRel); } public void update(UserDepartmentRel userDepartmentRel) { userDepartmentRelDao.save(userDepartmentRel); } public void delete(Long id) { UserDepartmentRel userDepartmentRel = findOne(id); userDepartmentRelDao.delete(userDepartmentRel); } public void deleteBatch(List<Long> ids) { for(Long id:ids){ UserDepartmentRel userDepartmentRel = findOne(id); userDepartmentRelDao.delete(userDepartmentRel); } } public UserDepartmentRel findOne(Long id) { UserDepartmentRel userDepartmentRel = userDepartmentRelDao.findOne(id); return userDepartmentRel; } public List<UserDepartmentRel> findByUid(Long uid) { List<UserDepartmentRel> userDepartmentRelList = userDepartmentRelDao.findByUid(uid); return userDepartmentRelList; } } ``` news.js ```$(document) .ready( function () { setting.sAjaxSource = G_CTX_ROOT + "/news/query"; setting.aoColumns = [ { "sTitle": "<center>编号</center>", // 显示标题 "mData": "id", // 属性 "bSortable": true,// 排序 "sClass": "center", "sWidth": "1%" }, { "sTitle": "<center>标题</center>", // 显示标题 "mData": "name", // 属性 "bSortable": false,// 排序 "sClass": "center", "sWidth": "5%" }, { "sTitle": "<center>类型</center>", // 显示标题 "mData": "typeName", // 属性 "bSortable": false,// 排序 "sClass": "center", "sWidth": "4%" }, { "sTitle": "<center>首页滚动</center>", // 显示标题 "mData": "recommendValue", // 属性 "bSortable": false,// 排序 "sClass": "center", "sWidth": "1%" }, { "sTitle": "<center>更新时间</center>", // 显示标题 "mData": "updateTime", // 属性 "bSortable": false,// 排序 "sClass": "center", "sWidth": "4%" }, { "sTitle": "<center>操作</center>", // 显示标题 "bSortable": false,// 排序 "mData": "id", // 属性 "sClass": "center", "sWidth": "2%", "mRender": function (data, style, obj) { // console.log(obj); // <a class="btn btn-info" href="${ctx}/news/preSave" var xqDom = "<a class=\"btn btn-round btn-info btn-xs\" href=\"/news/preUpdate/" + obj.id + "\" >修改</a>"; var delDom = "<a class=\"btn btn-round btn-danger btn-xs\" onclick=\"preDel(" + obj.id + ")\" >删除</a>"; return xqDom + "&nbsp;&nbsp;&nbsp;&nbsp;" + delDom; } }]; setting.aaSorting = [[0, "desc"]]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); var rule = { m_name: { name: "标题", method: { required: true, lt: 50 } }, m_author: { name: "作者", method: { required: true, lt: 20 } }, m_typeId: { name: "文章类型", method: { required: true } } }; validator.init(rule); }); /** * 查询 */ function doSearch() { dataTable.fnDraw(); } /** * 发送添加请求 * @returns {boolean} */ function save() { editor.sync(); var name = $("#m_name").val(); var author = $("#m_author").val(); var typeId = $("#m_typeId").val(); var content = $('#editor').val(); var picSmall =$("#m_picSmall").val(); var picBig =$("#m_picBig").val(); var recommend =$("#m_recommend").val(); console.log("picSmall"+picSmall); console.log("picBig"+picBig); console.log("recommend"+recommend); if (!validator.validate()) return false; $.ajaxInvoke({ url: G_CTX_ROOT + "/news/save", type: "post", datatype: "json", data: { typeId: typeId, name: name, author: author, content: content, picSmall:picSmall, picBig:picBig, recommend:recommend }, success: function (data) { msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } /** * 发送更新请求 */ function update() { editor.sync(); var id = $("#m_id").val(); var name = $("#m_name").val(); var author = $("#m_author").val(); var typeId = $("#m_typeId").val(); var content = $('#editor').val(); var picSmall =$("#m_picSmall").val(); var picBig =$("#m_picBig").val(); var recommend =$("#m_recommend").val(); $.ajaxInvoke({ url: G_CTX_ROOT + "/news/update", type: "post", datatype: "json", data: { id: id, name: name, author: author, typeId: typeId, content: content, picSmall:picSmall, picBig:picBig, recommend:recommend }, success: function (data) { msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } /** * 显示删除窗口 */ function preDel(id) { $("#deleteButton").replaceWith("<button type=\"button\" onclick=\"del(" + id + ")\" class=\"btn btn-danger\" id=\"deleteButton\">确认删除</button>"); $("#deleteModal").modal("show").css({ 'top': '60px' }); } /** * 发送删除请求 * @param id */ function del(id) { $.ajaxInvoke({ url: G_CTX_ROOT + "/news/delete", type: "post", datatype: "json", data: { id: id }, success: function (data) { $("#deleteModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } ``` NewsTypeConverter.java ```package com.lebao.converter; import com.lebao.po.NewsType; import com.lebao.po.SysUser; import com.lebao.service.SysUserService; import com.lebao.vo.NewsTypeVo; import com.lebao.vo.SysUserVo; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Created by ZR on 2016/12/6. */ @Component public class NewsTypeConverter extends BaseConverter<NewsType, NewsTypeVo> { @Autowired SysUserService sysUserService; @Override public NewsType convert2P(NewsTypeVo vo) { if (vo == null) { return null; } NewsType po = null; try { po = new NewsType(); BeanUtils.copyProperties(vo, po); } catch (Exception e) { e.printStackTrace(); } return po; } @Override public NewsTypeVo convert2V(NewsType po) { if (po == null) { return null; } NewsTypeVo vo = new NewsTypeVo(); try { BeanUtils.copyProperties(po, vo); } catch (Exception e) { e.printStackTrace(); } return vo; } } ``` marketInfo_liushui.js ```$(document) .ready( function () { setting.sAjaxSource = G_CTX_ROOT + "/marketInfo/queryLiushui"; setting.aoColumns = [ { "sTitle": "会员编号", //显示标题 "mData": "user_id", //属性 "bSortable": true,//排序 "sClass": "center", "sWidth": "3%" }, { "sTitle": "充值金额", //显示标题 "mData": "price", //属性 "bSortable": false,//排序 "sClass": "center", "sWidth": "3%" }, { "sTitle": "充值时间", //显示标题 "mData": "create_time", //属性 "bSortable": true,//排序 "sClass": "center", "sWidth": "5%" } ]; setting.aaSorting = [[2, "desc"]]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); }); function doSearch() { dataTable.fnDraw(); } ``` UserConverter.java ```package com.lebao.converter; import com.lebao.common.utils.TimeUtil; import com.lebao.po.Department; import com.lebao.po.User; import com.lebao.po.UserDepartmentRel; import com.lebao.service.DepartmentService; import com.lebao.service.PositionService; import com.lebao.service.UserDepartmentRelService; import com.lebao.vo.UserVo; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; /** * Created by ZR on 2016/12/6. */ @Component public class UserConverter extends BaseConverter<User, UserVo> { @Autowired DepartmentService departmentService; @Autowired PositionService positionService; @Override public User convert2P(UserVo vo) { if (vo == null) { return null; } User po = null; try { po = new User(); BeanUtils.copyProperties(vo, po); po.setCreateTime(TimeUtil.str2Date(vo.getCreateTime())); po.setUpdateTime(TimeUtil.str2Date(vo.getUpdateTime())); } catch (Exception e) { e.printStackTrace(); } return po; } @Override public UserVo convert2V(User po) { if (po == null) { return null; } UserVo vo = new UserVo(); try { BeanUtils.copyProperties(po, vo); vo.setCreateTime(TimeUtil.format(po.getCreateTime())); vo.setUpdateTime(TimeUtil.format(po.getUpdateTime())); vo.setPositionValue(positionService.findOne(vo.getPosition()).getName()); List<Department> departmentList=departmentService.findByUid(vo.getId()); vo.setDepartmentList(departmentList); } catch (Exception e) { e.printStackTrace(); } return vo; } } ``` js.js ``` //footerdocument.body.scrollHeight window.onload = function () { document.getElementById("footer").style.top = (document.body.scrollHeight+20) + 'px' } $(function(){ $(".nav_mobile img").click(function(){ $(".nav").toggle(); }) }) ``` SysUserBean.java ```package com.lebao.bean; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Server on 2016/5/19. */ public class SysUserBean { @JsonProperty("id") private String p_id; @JsonProperty("account") private String p_account; @JsonProperty("password") private String p_password; @JsonProperty("phone") private String p_phone; @JsonProperty("email") private String p_email; @JsonProperty("realName") private String p_real_name; @JsonProperty("roleId") private String p_role_id; @JsonProperty("roleName") private String p_role_name; @JsonProperty("type") private Integer p_type;//(0:系统管理员, 1:代理商管理员,2:业务员, 3:运维用户, 4:其他)。 @JsonProperty("status") private String p_status;//(0:禁用,1:激活) @JsonProperty("createTime") private String p_create_time; @JsonProperty("lastLoginTime") private String p_last_login_time; @JsonProperty("invitation_code") private String p_invitation_code; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_account() { return p_account; } public void setP_account(String p_acccount) { this.p_account = p_acccount; } public String getP_password() { return p_password; } public void setP_password(String p_password) { this.p_password = p_password; } public String getP_phone() { return p_phone; } public void setP_phone(String p_phone) { this.p_phone = p_phone; } public String getP_email() { return p_email; } public void setP_email(String p_email) { this.p_email = p_email; } public String getP_real_name() { return p_real_name; } public void setP_real_name(String p_real_name) { this.p_real_name = p_real_name; } public String getP_role_id() { return p_role_id; } public void setP_role_id(String p_role_id) { this.p_role_id = p_role_id; } public String getP_role_name() { return p_role_name; } public void setP_role_name(String p_role_name) { this.p_role_name = p_role_name; } public Integer getP_type() { return p_type; } public void setP_type(Integer p_type) { this.p_type = p_type; } public String getP_status() { return p_status; } public void setP_status(String p_status) { this.p_status = p_status; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public String getP_last_login_time() { return p_last_login_time; } public void setP_last_login_time(String p_last_login_time) { this.p_last_login_time = p_last_login_time; } public String getP_invitation_code() { return p_invitation_code; } public void setP_invitation_code(String p_invitation_code) { this.p_invitation_code = p_invitation_code; } @Override public String toString() { return "SysUserBean{" + "p_id='" + p_id + '\'' + ", p_account='" + p_account + '\'' + ", p_password='" + p_password + '\'' + ", p_phone='" + p_phone + '\'' + ", p_email='" + p_email + '\'' + ", p_real_name='" + p_real_name + '\'' + ", p_role_id='" + p_role_id + '\'' + ", p_role_name='" + p_role_name + '\'' + ", p_type=" + p_type + ", p_status='" + p_status + '\'' + ", p_create_time='" + p_create_time + '\'' + ", p_last_login_time='" + p_last_login_time + '\'' + '}'; } } ``` personalinfo.js ```$(document) .ready( function () { var rule = { m_oldpass: { name: "旧密码", method: { required: true, } }, m_newpass: { name: "新密码", method: { required: true, } }, m_newpass2: { name: "新密码确认", method: { required: true } } }; validator.init(rule); }); function updatePersonalinfo() { var userId = $("#m_userId").val(); var account = $("#m_account").val(); var oldpass = $("#m_oldpass").val(); var newpass = $("#m_newpass").val(); var newpass2 = $("#m_newpass2").val(); $.ajaxInvoke({ url: G_CTX_ROOT + "/personalinfo/update", type: "post", datatype: "json", data: { p_id:userId, p_account: account, p_oldpass: oldpass, p_newpass: newpass, p_newpass2: newpass2 }, success: function (data) { $("#myModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } ``` IPictureService.java ```package com.lebao.service.i; import org.springframework.web.multipart.MultipartFile; public interface IPictureService { public String uploadPicture(MultipartFile uploadFile); } ``` orderDetail.js ```$(document) .ready( function() { var order_id=$("#order_id").val(); setting.sAjaxSource = G_CTX_ROOT+"/orderDetail/query/"+order_id+""; setting.aoColumns = [ { "sTitle" : "商品编号", //显示标题 "mData" : "goods_id", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "4%" }, { "sTitle" : "购买数量", //显示标题 "mData" : "num", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "金额", //显示标题 "mData" : "price", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "充值账户", //显示标题 "mData" : "account", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "账户密码", //显示标题 "mData" : "account_password", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, ] setting.aaSorting = [ [ 3, "desc" ] ]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); }); function doSearch() { dataTable.fnDraw(); } function updateGoodsType() { var id=$("#m_id").val(); var name = $("#m_name").val(); var desc = $("#m_desc").val(); if (!validator.validate()) return false; $.ajaxInvoke({ url : G_CTX_ROOT+"/goodsType/update", type : "post", datatype : "json", data : { p_id:id, p_type_name : name, p_desc : desc, }, success : function(data) { msgBox(data.state, data.msg); }, }); } function preDel(id) { //alert(id); $("#myModal").modal("show").css({ 'top' : '60px' }); $("#d").attr("onClick","del("+id+")"); } function del(id) { $.ajaxInvoke({ url : G_CTX_ROOT+"/goodsType/delete/", type : "post", datatype : "json", data : { p_id : id, }, success : function(data) { $("#myModal").modal("hide") msgBox(data.state, data.msg); dataTable.fnDraw(); }, }); }``` newsType.js ```$(document) .ready( function () { setting.sAjaxSource = G_CTX_ROOT + "/newsType/query"; setting.aoColumns = [ { "sTitle": "<center>编号</center>", // 显示标题 "mData": "id", // 属性 "bSortable": true,// 排序 "sClass": "center", "sWidth": "5%" }, { "sTitle": "<center>类型名</center>", // 显示标题 "mData": "name", // 属性 "bSortable": false,// 排序 "sClass": "center", "sWidth": "5%" }, { "sTitle": "<center>操作</center>", // 显示标题 "bSortable": false,// 排序 "mData": "id", // 属性 "sClass": "center", "sWidth": "2%", "mRender": function (data, style, obj) { // console.log(obj); var xqDom = "<a class=\"btn btn-round btn-info btn-xs\" onclick=\"preUpdate("+obj.id+")\" >修改</a>"; var delDom ="<a class=\"btn btn-round btn-danger btn-xs\" onclick=\"preDel("+obj.id+")\" >删除</a>"; return xqDom + "&nbsp;&nbsp;&nbsp;&nbsp;" + delDom; } }]; setting.aaSorting = [[0, "desc"]]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); var rule = { m_name: { name: "类型名", method: { required: true, lt: 10 } } }; validator.init(rule); }); /** * 查询 */ function doSearch() { dataTable.fnDraw(); } /** * 显示添加窗口 */ function preSave() { $("#m_name").val(""); $("#saveModal").modal("show").css({ 'top': '60px' }); } /** * 发送添加请求 * @returns {boolean} */ function save() { var name = $("#m_name").val(); if (!validator.validate()) return false; $.ajaxInvoke({ url: G_CTX_ROOT + "/newsType/save", type: "post", datatype: "json", data: { name: name }, success: function (data) { $("#saveModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } /** * 显示更新窗口 * @param id */ function preUpdate(id) { $.ajaxInvoke({ url: G_CTX_ROOT + "/newsType/queryById", type: "post", datatype: "json", data: { id: id }, success: function (data) { var user=data; $("#m_name1").val(user.data.name); console.log(user); } }); $("#updateButton").replaceWith("<button type=\"button\" onclick=\"update("+id+")\" class=\"btn btn-info\" id=\"updateButton\">确认修改</button>"); $("#updateModal").modal("show").css({ 'top': '60px' }); } /** * 发送更新请求 * @param id */ function update(id) { var name = $("#m_name1").val(); $.ajaxInvoke({ url: G_CTX_ROOT + "/newsType/update", type: "post", datatype: "json", data: { id:id, name: name }, success: function (data) { $("#updateModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } /** * 显示删除窗口 */ function preDel(id) { $("#deleteButton").replaceWith("<button type=\"button\" onclick=\"del("+id+")\" class=\"btn btn-danger\" id=\"deleteButton\">确认删除</button>"); $("#deleteModal").modal("show").css({ 'top': '60px' }); } /** * 发送删除请求 * @param id */ function del(id) { $.ajaxInvoke({ url: G_CTX_ROOT + "/newsType/delete", type: "post", datatype: "json", data: { id: id }, success: function (data) { $("#deleteModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); }``` NewsSearchParam.java ```package com.lebao.bean; /** * Created by Server on 2016/4/28. */ public class NewsSearchParam { private String title; private String id; private int pageSize = 15; private int curPage = 0; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurPage() { return curPage; } public void setCurPage(int curPage) { this.curPage = curPage; } } ``` order.js ```$(document) .ready( function() { setting.sAjaxSource = G_CTX_ROOT+"/order/query"; setting.aoColumns = [ { "sTitle" : "订单号", //显示标题 "mData" : "id", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "用户编号", //显示标题 "mData" : "user_id", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "充值账号", //显示标题 "mData" : "user_account", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "商品编号", //显示标题 "mData" : "goods_id", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "商品名称", //显示标题 "mData" : "goods_name", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "3%" }, /* { "sTitle" : "区服", //显示标题 "mData" : "server", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "3%" }, */ { "sTitle" : "金额", //显示标题 "mData" : "total_price", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "下单时间", //显示标题 "mData" : "create_time", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "4%" }, { "sTitle" : "完成时间", //显示标题 "mData" : "update_time", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "4%" }, { "sTitle" : "订单状态", //显示标题 "mData" : "status", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "处理人", //显示标题 "mData" : "dealuser_name", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "2%" }, { "sTitle" : "<center>操作</center>", // 显示标题 "bSortable" : false,// 排序 "mData" : "id", // 属性 "sClass" : "center", "sWidth" : "5%", "mRender" : function(data, style, obj) { var xqDom = "<a class=\"btn btn-round btn-info btn-xs\" onclick=\"preDeal(" + obj.id + ")\" >完成订单</a>"; var delDom = "<a class=\"btn btn-round btn-danger btn-xs\" onclick=\"preCancel("+obj.id+")\" >取消订单</a>"; return xqDom + "&nbsp;&nbsp;" + delDom; } }]; setting.aaSorting = [ [ 7, "desc" ] ]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); }); function doSearch() { dataTable.fnDraw(); } function updateGoodsType() { var id=$("#m_id").val(); var name = $("#m_name").val(); var desc = $("#m_desc").val(); if (!validator.validate()) return false; $.ajaxInvoke({ url : G_CTX_ROOT+"/goodsType/update", type : "post", datatype : "json", data : { p_id:id, p_type_name : name, p_desc : desc, }, success : function(data) { msgBox(data.state, data.msg); }, }); } function preDeal(id) { //alert(id); $("#myModal").modal("show").css({ 'top' : '60px' }); $("#deal").attr("onClick","deal("+id+")"); } function preCancel(id) { //alert(id); $("#myModal2").modal("show").css({ 'top' : '60px' }); $("#cancel").attr("onClick","cancel("+id+")"); } function deal(id) { //alert(id); $.ajaxInvoke({ url : G_CTX_ROOT+"/order/deal/", type : "post", datatype : "json", data : { p_id : id }, success : function(data) { //alert(data); $("#myModal").modal("hide") msgBox(data.state, data.msg); dataTable.fnDraw(); }, }); } function cancel(id) { //alert(id); $.ajaxInvoke({ url : G_CTX_ROOT+"/order/cancel/", type : "post", datatype : "json", data : { p_id : id }, success : function(data) { //alert(data); $("#myModal2").modal("hide") msgBox(data.state, data.msg); dataTable.fnDraw(); }, }); }``` news2.js ```$(document) .ready( function() { setting.sAjaxSource = G_CTX_ROOT+"/news/query"; setting.aoColumns = [ { "sTitle" : "<center>标题</center>", //显示标题 "mData" : "title", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "5%" }, { "sTitle" : "<center>创建人</center>", //显示标题 "mData" : "user_id", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "<center>浏览次数</center>", //显示标题 "mData" : "browseTime", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "<center>状态</center>", //显示标题 "mData" : "status", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "<center>操作</center>", // 显示标题 "bSortable" : false,// 排序 "mData" : "id", // 属性 "sClass" : "center", "sWidth" : "5%", "mRender" : function(data, style, obj) { //console.log(obj); var xqDom = "<a class=\"btn btn-round btn-info btn-xs\" href=\"/news/preUpdate/"+obj.id+"\" >查看详情</a>"; var delDom = "<a class=\"btn btn-round btn-danger btn-xs\" onclick=\"preDel("+obj.id+")\" >删除</a>"; return xqDom + "&nbsp;&nbsp;&nbsp;&nbsp;" + delDom; } }]; setting.aaSorting = [ [ 3, "desc" ] ]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); var rule = { m_title : { name : "标题", method : { required : true, } } }; validator.init(rule); }); function doSearch() { dataTable.fnDraw(); } function preAdd() { $("#myModal").modal("show").css({ 'top' : '60px' }); } function addNews() { var photo=$("#picUrlVal").val(); var title= $("#m_title").val(); var type_id = $("#m_type_id").val(); var url = $("#m_url").val(); //getContent(); var htmlPart = UE.getEditor('editor').getContent(); //alert("123"+UE.getEditor('editor').getContent()); if (!validator.validate()) return false; $.ajaxInvoke({ url : G_CTX_ROOT+"/news/add", type : "post", datatype : "json", data : { p_type_id : type_id, p_title :title, p_photo1 : photo, p_url : url, p_htmlPart : htmlPart }, success : function(data) { msgBox(data.state, data.msg); } }); } function updateNews() { var photo=$("#picUrlVal").val(); var id= $("#m_id").val(); var title= $("#m_title").val(); var type_id = $("#m_type_id").val(); var url = $("#m_url").val(); //getContent(); var htmlPart = UE.getEditor('editor').getContent(); //alert("123"+UE.getEditor('editor').getContent()); if (!validator.validate()) return false; $.ajaxInvoke({ url : G_CTX_ROOT+"/news/update", type : "post", datatype : "json", data : { p_id:id, p_type_id : type_id, p_title :title, p_photo1: photo, p_url : url, p_htmlPart : htmlPart }, success : function(data) { msgBox(data.state, data.msg); } }); } function preDel(id) { //alert(id); $("#myModal").modal("show").css({ 'top' : '60px' }); $("#d").attr("onClick","del("+id+")"); } function del(id) { $.ajaxInvoke({ url : G_CTX_ROOT+"/news/delete/", type : "post", datatype : "json", data : { p_id : id }, success : function(data) { $("#myModal").modal("hide") msgBox(data.state, data.msg); dataTable.fnDraw(); }, }); } //实例化编辑器 //建议使用工厂方法getEditor创建和引用编辑器实例,如果在某个闭包下引用该编辑器,直接调用UE.getEditor('editor')就能拿到相关的实例 //var ue = UE.getEditor('editor'); //ue.loadServerConfig(); function isFocus(e){ alert(UE.getEditor('editor').isFocus()); UE.dom.domUtils.preventDefault(e) } function setblur(e){ UE.getEditor('editor').blur(); UE.dom.domUtils.preventDefault(e) } function insertHtml() { var value = prompt('插入html代码', ''); UE.getEditor('editor').execCommand('insertHtml', value) } function createEditor() { enableBtn(); UE.getEditor('editor'); } function getAllHtml() { alert(UE.getEditor('editor').getAllHtml()) } function getContent() { var arr = []; arr.push("使用editor.getContent()方法可以获得编辑器的内容"); arr.push("内容为:"); arr.push(UE.getEditor('editor').getContent()); alert(arr.join("\n")); } function getPlainTxt() { var arr = []; arr.push("使用editor.getPlainTxt()方法可以获得编辑器的带格式的纯文本内容"); arr.push("内容为:"); arr.push(UE.getEditor('editor').getPlainTxt()); alert(arr.join('\n')) } function setContent(isAppendTo) { var arr = []; arr.push("使用editor.setContent('欢迎使用ueditor')方法可以设置编辑器的内容"); UE.getEditor('editor').setContent('欢迎使用ueditor', isAppendTo); alert(arr.join("\n")); } function setDisabled() { UE.getEditor('editor').setDisabled('fullscreen'); disableBtn("enable"); } function setEnabled() { UE.getEditor('editor').setEnabled(); enableBtn(); } function getText() { //当你点击按钮时编辑区域已经失去了焦点,如果直接用getText将不会得到内容,所以要在选回来,然后取得内容 var range = UE.getEditor('editor').selection.getRange(); range.select(); var txt = UE.getEditor('editor').selection.getText(); alert(txt) } function getContentTxt() { var arr = []; arr.push("使用editor.getContentTxt()方法可以获得编辑器的纯文本内容"); arr.push("编辑器的纯文本内容为:"); arr.push(UE.getEditor('editor').getContentTxt()); alert(arr.join("\n")); } function hasContent() { var arr = []; arr.push("使用editor.hasContents()方法判断编辑器里是否有内容"); arr.push("判断结果为:"); arr.push(UE.getEditor('editor').hasContents()); alert(arr.join("\n")); } function setFocus() { UE.getEditor('editor').focus(); } function deleteEditor() { disableBtn(); UE.getEditor('editor').destroy(); } function disableBtn(str) { var div = document.getElementById('btns'); var btns = UE.dom.domUtils.getElementsByTagName(div, "button"); for (var i = 0, btn; btn = btns[i++];) { if (btn.id == str) { UE.dom.domUtils.removeAttributes(btn, ["disabled"]); } else { btn.setAttribute("disabled", "true"); } } } function enableBtn() { var div = document.getElementById('btns'); var btns = UE.dom.domUtils.getElementsByTagName(div, "button"); for (var i = 0, btn; btn = btns[i++];) { UE.dom.domUtils.removeAttributes(btn, ["disabled"]); } } function getLocalData () { alert(UE.getEditor('editor').execCommand( "getlocaldata" )); } function clearLocalData () { UE.getEditor('editor').execCommand( "clearlocaldata" ); alert("已清空草稿箱") } $(document).ready(function(){ $(function() { $("#uploadify").uploadify({ height : 20, removeCompleted:true, swf : G_CTX_ROOT+'/staticUploadify/uploadify.swf', width : 100, uploader: "/upload/pic", fileSizeLimit : 1000*1024 , fileTypeExts : '*.jpg;*.png;*.gif', fileTypeDesc : '请选择图片!', onSelect: function(e, queueId, fileObj){ }, onClearQueue : function (queueItemCount){ //mAlert(queueItemCount); }, onSelectError : function(file,errorCode,errorMsg) {//当文件选定发生错误时触发 /* alert( 'onSelectErrorid: ' + file.id   + ' - 索引: ' + file.index   + ' - 文件名: ' + file.name   + ' - 文件大小: ' + file.size   + ' - 类型: ' + file.type   + ' - 创建日期: ' + file.creationdate   + ' - 修改日期: ' + file.modificationdate   + ' - 文件状态: ' + file.filestatus   + ' - 错误代码: ' + errorCode   + ' - 错误信息: ' + errorMsg);*/ if(file.size > 1000*1024){ $("#picUrl2Class").html("<font color=red >文件超出上传限制,请重选择!</font>"); //$("#picUrl").uploadifyCancel(file.id); onClearQueue(); }else{ $("#picUrl2Class").html(""); } }, onQueueComplete : function(stats) {//当队列中的所有文件全部完成上传时触发 /*alert( '成功上传的文件数: ' + stats.successful_uploads   + ' - 上传出错的文件数: ' + stats.upload_errors   + ' - 取消上传的文件数: ' + stats.upload_cancelled   + ' - 出错的文件数' + stats.queue_errors);*/ }, onUploadStart: function(file) {//上传开始时触发(每个文件触发一次) /*alert( 'onUploadStart id: ' + file.id   + ' - 索引: ' + file.index   + ' - 文件名: ' + file.name   + ' - 文件大小: ' + file.size   + ' - 类型: ' + file.type   + ' - 创建日期: ' + file.creationdate   + ' - 修改日期: ' + file.modificationdate   + ' - 文件状态: ' + file.filestatus ); */ if(file.size > 1000*1024){ //mAlert("文件超过1MB,请重新选择!","信息提示"); $("#picUrl2Class").html("<font color=red>文件超出上传限制,请重选择!</font>"); onClearQueue(); }else{ $("#picUrl2Class").html(""); } }, onUploadSuccess:function(file, data, response){ //var json =jQuery.parseJSON(data); uploadPicUrl2 = true; //div显示文件的名称 以及删除 $("#advice-required-picUrl2").css("display",""); $("#advice-required-picUrl2").html(file.name); $("#picUrl2Btn-picUrl").css("display","block"); /* $("#imgBox").val("${loginuser.infoUserTab.u_url}"); */ $("#picUrlVal").val(data); //alert(data); }, onUploadError : function(file,errorCode,errorMsg,errorString,swfuploadifyQueue) {//上传文件出错是触发(每个出错文件触发一次) /*alert( ' onUploadError id: ' + file.id   + ' - 索引: ' + file.index   + ' - 文件名: ' + file.name   + ' - 文件大小: ' + file.size   + ' - 类型: ' + file.type   + ' - 创建日期: ' + file.creationdate   + ' - 修改日期: ' + file.modificationdate   + ' - 文件状态: ' + file.filestatus   + ' - 出错的文件数: ' + swfuploadifyQueue.filesErrored   + ' - 错误信息: ' + swfuploadifyQueue.errorMsg   + ' - 要添加至队列的数量: ' + swfuploadifyQueue.filesSelected   + ' - 添加至对立的数量: ' + swfuploadifyQueue.filesQueued   + ' - 队列长度: ' + swfuploadifyQueue.queueLength); */ //alert(errorCode + ",file :" +file); //console.log(" file " + file); $("#uploadify").uploadifyCancel(errorCode); }, onError:function(event,queueId,fileObj,errorObj){ //alert("onError"); if (errorObj.type === "File Size"){ alert('文件超出上传大小限制!'); $("#uploadify").uploadifyCancel(ID); } } }); }); });``` DepartmentService.java ```package com.lebao.service; import com.lebao.dao.user.DepartmentDao; import com.lebao.po.Department; import com.lebao.po.EduLevel; import com.lebao.po.UserDepartmentRel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * Author: zr * Date : 2016/12/6 18:13 */ @Service public class DepartmentService { @Autowired DepartmentDao departmentDao; @Autowired UserDepartmentRelService userDepartmentRelService; public Department findOne(Long id) { return departmentDao.findOne(id); } public void save(Department department){ departmentDao.save(department); } public List<Department> findAll(){ return departmentDao.findAll(); } public List<Department> findByUid(Long uid){ List<UserDepartmentRel> oldUserDepartmentRelList = userDepartmentRelService .findByUid(uid); List<Department> departmentList = new ArrayList<Department>(); for (UserDepartmentRel userDepartmentRel : oldUserDepartmentRelList) { departmentList.add(findOne(userDepartmentRel.getDid())); } return departmentList; } } ``` market.js ```$(document) .ready( function() { setting.sAjaxSource = G_CTX_ROOT+"/market/query"; setting.aoColumns = [ { "sTitle" : "会员编号", //显示标题 "mData" : "user_id", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "销售员编号", //显示标题 "mData" : "sys_user_id", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "销售员姓名", //显示标题 "mData" : "sys_user_name", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "3%" }, { "sTitle" : "创建时间", //显示标题 "mData" : "create_time", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "5%" }, ]; setting.aaSorting = [ [ 3, "desc" ] ]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); var rule = { m_sys_user_id: { name: "销售员编号", method: { required: true, } }, m_user_id: { name: "会员编号", method: { required: true, } } }; validator.init(rule); }); function doSearch() { dataTable.fnDraw(); } function add() { var user_id=$("#m_user_id").val(); var sys_user_id = $("#m_sys_user_id").val(); if (!validator.validate()) return false; $.ajaxInvoke({ url : G_CTX_ROOT+"/market/add", type : "post", datatype : "json", data : { p_user_id:user_id, p_sys_user_id : sys_user_id }, success : function(data) { msgBox(data.state, data.msg); } }); } function preDeal(id) { //alert(id); $("#myModal").modal("show").css({ 'top' : '60px' }); $("#deal").attr("onClick","deal("+id+")"); } function deal(id) { //alert(id); $.ajaxInvoke({ url : G_CTX_ROOT+"/order/deal/", type : "post", datatype : "json", data : { p_id : id }, success : function(data) { //alert(data); $("#myModal").modal("hide") msgBox(data.state, data.msg); dataTable.fnDraw(); }, }); }``` package-info.java ```/** * mysql数据库个性处理 * */ package com.lebao.common.dbhelp.dialect.mysql;``` ComponentController.java ```package com.lebao.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * Created by ZR on 2016/12/8. */ @Controller @RequestMapping(value="component") public class ComponentController { /** * 页面入口 * @return */ @RequestMapping("/index") public ModelAndView index() { ModelAndView view = new ModelAndView(); view.addObject("title","系统管理>>用户查询"); view.setViewName("admin/component"); return view; } } ``` role.js ```$(document) .ready( function() { setting.sAjaxSource = G_CTX_ROOT+"/role/query"; setting.aoColumns = [ { "sTitle" : "<center>权限角色名称</center>", //显示标题 "mData" : "name", //属性 "bSortable" : false,//排序 "sClass" : "center", "sWidth" : "5%", }, { "sTitle" : "<center>备注</center>", //显示标题 "mData" : "desc", //属性 "bSortable" : true,//排序 "sClass" : "center", "sWidth" : "5%" }, { "sTitle" : "<center>操作</center>", // 显示标题 "bSortable" : false,// 排序 "mData" : "id", // 属性 "sClass" : "center", "sWidth" : "5%", "mRender" : function(data, style, obj) { var xqDom = "<a class=\"btn btn-round btn-info btn-xs\" href=\"/role/preUpdate/"+obj.id+"\" >修改</a>"; var delDom = "<a class=\"btn btn-round btn-danger btn-xs\" onclick=\"preDel("+obj.id+")\" >删除</a>"; return xqDom + "&nbsp;&nbsp;&nbsp;&nbsp;" + delDom; } }]; setting.aaSorting = [ [ 3, "desc" ] ]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); var rule = { m_type_name : { name : "角色名称", method : { required : true, }, }, m_desc : { name : "描述", method : { required : true, }, }, }; validator.init(rule); }); function doSearch() { dataTable.fnDraw(); } function preAdd() { $("#myModal").modal("show").css({ 'top' : '60px' }); } function preDel(p_id) { $("#myModal").modal("show").css({ 'top' : '60px' }); $("#del").attr("onClick","del("+p_id+")"); } function del(id) { $.ajaxInvoke({ url : G_CTX_ROOT+"/role/delete/", type : "post", datatype : "json", data : { p_id : id }, success : function(data) { $("#myModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } ``` LiushuiBean.java ```package com.lebao.bean; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Server on 2016-07-23. */ public class LiushuiBean { @JsonProperty("id") private String p_id ;//bigint(20) NOT NULLid @JsonProperty("user_id") private String p_user_id; @JsonProperty("price") private Float p_price; @JsonProperty("create_time") private String p_create_time; @JsonProperty("status") private Integer p_status; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_user_id() { return p_user_id; } public void setP_user_id(String p_user_id) { this.p_user_id = p_user_id; } public Float getP_price() { return p_price; } public void setP_price(Float p_price) { this.p_price = p_price; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public Integer getP_status() { return p_status; } public void setP_status(Integer p_status) { this.p_status = p_status; } @Override public String toString() { return "LiushuiBean{" + "p_id='" + p_id + '\'' + ", p_user_id='" + p_user_id + '\'' + ", p_price=" + p_price + ", p_create_time='" + p_create_time + '\'' + ", p_status=" + p_status + '}'; } } ``` AdvDao.java ```package com.lebao.modules.adv.dao; import com.lebao.bean.AdvSearchParam; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.common.utils.Sequence; import com.lebao.common.utils.TimeUtil; import com.lebao.modules.adv.entity.AdvEntity; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.sql.SQLException; import java.util.Date; import java.util.List; @Repository public class AdvDao { @Resource(name="dbHelper") private DbHelper dbHelper; public void addAdv(AdvEntity ae) throws SQLException { String p_id = Sequence.nextId(); String p_goods_id = ae.getP_goods_id(); String p_title = ae.getP_title(); String p_content = ae.getP_content(); String p_photo = ae.getP_photo(); String p_url = ae.getP_url(); String p_type =ae.getP_type(); String p_status = ae.getP_status(); String p_create_time = TimeUtil.format(new Date(), TimeUtil.TARGET_1); String sql = "INSERT INTO t_adv(p_id,p_goods_id,p_title,p_content,p_photo,p_url,p_type,p_status,p_create_time) VALUES(?,?,?,?,?,?,?,?,?)"; dbHelper.execute(sql, p_id, p_goods_id, p_title, p_content, p_photo, p_url, p_type, p_status, p_create_time); } public List<AdvEntity> getAdvs() throws SQLException { String sql = "select * from t_adv where p_status='1' "; return dbHelper.getBeanList(sql,AdvEntity.class); } public Page<AdvEntity> getAdvs(AdvSearchParam s) throws SQLException { String sql = "select * from t_adv where 1=1"; if (StringUtils.isNotBlank(s.getType())) { sql += " and p_name like '" + s.getType() + "%' "; } sql += " order by " + s.getSortField() + " " + s.getSortType() + " "; return dbHelper.getPage(sql, AdvEntity.class, s.getPageNow(), s.getPageSize()); } public AdvEntity getAdvById(String advId) throws SQLException { String sql = "select * from t_adv where t_adv.p_id=?"; return dbHelper.getBean(sql, AdvEntity.class, advId); } public void updAdv(AdvEntity ae) throws SQLException { String p_id = ae.getP_id(); String p_goods_id = ae.getP_goods_id(); String p_title = ae.getP_title(); String p_content = ae.getP_content(); String p_photo = ae.getP_photo(); String p_url = ae.getP_url(); String p_type =ae.getP_type(); String p_update_time = TimeUtil.format(new Date(), TimeUtil.TARGET_1); String sql = "update t_adv set p_goods_id=?,p_title=?,p_content=?,p_photo=?,p_url=?,p_type=?,p_update_time=? where p_id=?"; dbHelper.execute(sql, p_goods_id, p_title, p_content, p_photo, p_url, p_type,p_update_time, p_id); } public void delAdv(String advId) throws SQLException { String sql = "update t_adv set p_status='-1' where p_id = ?"; dbHelper.execute(sql, advId); } public void reAddAdv(String advId) throws SQLException { String sql = "update t_adv set p_status = '1' where p_id=?"; dbHelper.execute(sql, advId); } } ``` NewsService.java ```//package com.lebao.service.impl; // //import com.lebao.bean.NewsBean; //import com.lebao.bean.NewsSearchParam; //import com.lebao.common.dbhelp.page.Page; //import com.lebao.modules.news.dao.NewsDao; //import com.lebao.modules.news.entity.NewsEntity; //import com.lebao.service.i.INewsService; //import org.springframework.beans.BeanUtils; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.stereotype.Service; // //import java.sql.SQLException; //import java.util.ArrayList; //import java.util.List; // ///** // * Created by Server on 2016/3/30. // */ //@Service //public class NewsService implements INewsService { // @Autowired // private NewsDao newsDao; // // // public NewsBean getNews(String p_id) throws SQLException { // NewsEntity gte = newsDao.getNewsEntity(p_id); // NewsBean gtb = new NewsBean(); // BeanUtils.copyProperties(gte,gtb); // return gtb; // } // // public int delete(String id) throws SQLException { // return newsDao.delete(id,"-1"); // } // // public int add(NewsBean gtb) throws SQLException { // NewsEntity gte = new NewsEntity(); // BeanUtils.copyProperties(gtb,gte); // return newsDao.add(gte); // } // // public int update(NewsBean gtb) throws SQLException { // NewsEntity gte = new NewsEntity(); // BeanUtils.copyProperties(gtb,gte); // return newsDao.update(gte); // } // // // // public Page<NewsBean> getNews(NewsSearchParam s) throws SQLException { // int myPageSize = 0;//每页记录数 // int curPage = 0;//显示页 // int pageCount = 0;//页数 // int recordCount = 0;//总记录数 // List<NewsBean> list = new ArrayList<NewsBean>(); // NewsBean newsBean = null; // Page<NewsEntity> pageEntity = newsDao.getNewsEntitys(s); // // if(null!=pageEntity){ // List<NewsEntity> listEntity = pageEntity.getData(); // for(NewsEntity e:listEntity){ // newsBean= new NewsBean(); // BeanUtils.copyProperties(e, newsBean); // list.add(newsBean); // } // recordCount = pageEntity.getRecordCount(); // pageCount = pageEntity.getPageCount(); // curPage = pageEntity.getCurPage(); // myPageSize = pageEntity.getPageSize(); // } // Page<NewsBean> pageBean = new Page<NewsBean>(myPageSize, list, curPage, pageCount, recordCount); // // return pageBean; // } // // //} ``` TypeService.java ```package com.lebao.service.impl; import com.lebao.bean.SearchParam; import com.lebao.bean.TypeBean; import com.lebao.common.dbhelp.page.Page; import com.lebao.modules.type.dao.TypeDao; import com.lebao.modules.type.entity.TypeEntity; import com.lebao.service.i.ITypeService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @Service public class TypeService implements ITypeService { @Autowired private TypeDao typeDao; public TypeBean getTypeById(String p_id) throws SQLException { TypeEntity gte=typeDao.getType(p_id); TypeBean gtb=new TypeBean(); BeanUtils.copyProperties(gte,gtb); return gtb; } public int delType(String p_id) throws SQLException { return typeDao.delType(p_id); } public int addType(TypeBean gtb) throws SQLException { TypeEntity gte=new TypeEntity(); BeanUtils.copyProperties(gtb,gte); return typeDao.addType(gte); } public int updType(TypeBean gtb) throws SQLException { TypeEntity gte=new TypeEntity(); BeanUtils.copyProperties(gtb,gte); return typeDao.updType(gte); } public Page<TypeBean> getTypes(SearchParam s) throws SQLException { int myPageSize = 0;//每页记录数 int curPage = 0;//显示页 int pageCount = 0;//页数 int recordCount = 0;//总记录数 List<TypeBean> list = new ArrayList<TypeBean>(); TypeBean tb = null; Page<TypeEntity> pageEntity = typeDao.getTypes(s); if(null!=pageEntity){ List<TypeEntity> listEntity = pageEntity.getData(); for(TypeEntity te:listEntity){ tb= new TypeBean(); BeanUtils.copyProperties(te, tb); if(te.getP_status().equals("1")){ tb.setP_status("已上架"); }else { tb.setP_status("已下架"); } list.add(tb); } recordCount = pageEntity.getRecordCount(); pageCount = pageEntity.getPageCount(); curPage = pageEntity.getCurPage(); myPageSize = pageEntity.getPageSize(); } Page<TypeBean> pageBean = new Page<TypeBean>(myPageSize, list, curPage, pageCount, recordCount); return pageBean; } public List<TypeBean> getTypes() throws SQLException { List<TypeEntity> entities=typeDao.getTypes(); List<TypeBean> list=new ArrayList<TypeBean>(); TypeBean tb; for(TypeEntity e:entities){ tb= new TypeBean(); BeanUtils.copyProperties(e, tb); list.add(tb); } return list; } public void reAddType(String typeId) throws SQLException { typeDao.reAddType(typeId); } } ``` EduLevelDao.java ```package com.lebao.dao.user; import com.lebao.common.dbhelp.DbHelper; import com.lebao.po.Department; import com.lebao.po.EduLevel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class EduLevelDao { @Autowired EduLevelRepo eduLevelRepo; @Autowired DbHelper dbHelper; public EduLevel findOne(Long id) { return eduLevelRepo.findOne(id); } public void save(EduLevel eduLevel) { eduLevelRepo.save(eduLevel); } public List<EduLevel> findAll(){ return eduLevelRepo.findAll(); } } ``` TypeDao.java ```package com.lebao.modules.type.dao; import com.lebao.bean.SearchParam; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.common.utils.Sequence; import com.lebao.common.utils.TimeUtil; import com.lebao.modules.type.entity.TypeEntity; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.sql.SQLException; import java.util.Date; import java.util.List; /** * Created by Server on 2016/4/1. */ @Repository public class TypeDao { @Resource(name = "dbHelper") private DbHelper dbHelper; public int addType(TypeEntity te) throws SQLException { String p_id = Sequence.nextId(); String p_name = te.getP_name(); String p_status = "1"; String p_create_time = TimeUtil.format(new Date(), TimeUtil.TARGET_1); String sql = "insert into t_type (p_id,p_name,p_status,p_create_time) values (?,?,?,?)"; return dbHelper.execute(sql, p_id, p_name, p_status, p_create_time); } public int delType(String p_id) throws SQLException { String sql = "update t_type set p_status = '-1' where p_id=?"; return dbHelper.execute(sql, p_id); } public int updType(TypeEntity te) throws SQLException { String p_id = te.getP_id(); String p_name = te.getP_name(); String p_update_time = TimeUtil.format(new Date(), TimeUtil.TARGET_1); String sql = "update t_type set p_name = ?,p_update_time=? where p_id=?"; return dbHelper.execute(sql, p_name, p_update_time, p_id); } public TypeEntity getType(String p_id) throws SQLException { String sql = "select * from t_type where p_id=?"; return dbHelper.getBean(sql, TypeEntity.class, p_id); } public Page<TypeEntity> getTypes(SearchParam s) throws SQLException{ String sql = "select * from t_type where 1=1 "; if(StringUtils.isNotBlank(s.getName())){ sql += " and p_name like '%"+s.getName()+"%' "; } return dbHelper.getPage(sql, TypeEntity.class, s.getPageNow(),s.getPageSize()); } public List<TypeEntity> getTypes()throws SQLException{ String sql = "select * from t_type where p_status !=-1 "; return dbHelper.getBeanList(sql,TypeEntity.class); } public void reAddType(String typeId) throws SQLException { String sql = "update t_type set p_status = '1' where p_id=?"; dbHelper.execute(sql, typeId); } } ``` package-info.java ```/** * 内部一些公用方法 * */ package com.lebao.common.dbhelp.util;``` TestController.java ```package com.lebao.controller; import com.lebao.service.i.IPictureService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; /** * Created by Server on 2016/7/15. */ @Controller public class TestController { @Autowired private IPictureService pictureService; @RequestMapping("/testKind") public ModelAndView testKind() { ModelAndView view = new ModelAndView(); view.setViewName("admin/test"); return view; } /* @RequestMapping("/testUpload") @ResponseBody public String testUpload(MultipartFile uploadFile) { System.out.println("开始上传"); return pictureService.uploadPicture(uploadFile); } */ } ``` AdminController.java ```package com.lebao.controller; import com.google.gson.Gson; import com.lebao.bean.SysMenuBean; import com.lebao.bean.SysUserBean; import com.lebao.common.Constant; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.List; @Controller public class AdminController { private Logger logger = Logger.getLogger(AdminController.class); @RequestMapping("/home") public ModelAndView home(HttpServletRequest request) { ModelAndView view = new ModelAndView(); //initSideMenu(view); view.setViewName("admin/home"); return view; } @RequestMapping(value={"/admin"}) public ModelAndView index(HttpServletRequest request) { ModelAndView view = new ModelAndView(); //initSideMenu(view); view.setViewName("admin/login"); return view; } @RequestMapping("/orderList") public ModelAndView orderList(HttpServletRequest request) { ModelAndView view = new ModelAndView(); //initSideMenu(view); view.setViewName("admin/orderList"); return view; } /* @RequestMapping("/index") public ModelAndView index(){ ModelAndView view = new ModelAndView(); try{ Subject user = SecurityUtils.getSubject(); SysUserBean sub = (SysUserBean) user.getPrincipal() ; logger.debug(new Gson().toJson(sub)); List<SysMenuBean> menus =sysService.buildMenu( sysService.getMenusByUserId(sub.getP_id())) ; view.setViewName("admin/index"); view.addObject("sysUser", sub); view.addObject("sysMenus", menus); }catch(Exception e){ logger.error("load menu fail" , e); e.printStackTrace(); } return view ; } */ /* * 用于js脚本的全局变量 */ @RequestMapping(value = "/static/global.js", produces = { "application/x-javascript", "text/javascript", "application/javascript" }) @ResponseBody public String jsGlobal(WebRequest webRequest) { StringBuilder sb = new StringBuilder(); sb.append("var G_CTX_ROOT = '").append(webRequest.getContextPath()).append("';\n"); return sb.toString(); } } ``` SysService.java ```//package com.lebao.service.impl; // //import com.lebao.bean.SysMenuBean; //import com.lebao.bean.SysPermissionBean; //import com.lebao.modules.permission.entity.SysPermissionEntity; //import com.lebao.modules.sys.dao.SysDao; //import com.lebao.modules.sys.entity.SysMenuEntity; //import com.lebao.service.i.ISysService; //import org.springframework.beans.BeanUtils; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.stereotype.Service; // //import java.sql.SQLException; //import java.util.ArrayList; //import java.util.HashSet; //import java.util.List; //import java.util.Set; // //@Service //public class SysService implements ISysService { // @Autowired // private SysDao sysDao; // // public List<SysMenuBean> getMenusByUserId(String userId) throws SQLException { // List<SysMenuBean> list = new ArrayList<SysMenuBean>(); // List<SysMenuEntity> entities; // SysMenuBean smb; // entities = sysDao.getMenus(userId); // for (SysMenuEntity sme : entities) { // smb = new SysMenuBean(); // BeanUtils.copyProperties(sme, smb); // list.add(smb); // } // return list; // } // // public List<SysPermissionBean> getPermissionByUserId(String userId) throws SQLException { // List<SysPermissionBean> list = new ArrayList<SysPermissionBean>(); // List<SysPermissionEntity> entities; // SysPermissionBean spb; // entities = sysDao.getPermissions(userId); // for (SysPermissionEntity spe : entities) { // spb = new SysPermissionBean(); // BeanUtils.copyProperties(spe, spb); // list.add(spb); // } // return list; // } // // public List<SysMenuBean> buildMenu(List<SysMenuBean> menus) { // List<SysMenuBean> list = new ArrayList<SysMenuBean>(); // for (SysMenuBean m : menus) { // if (m.getP_fid().equals("0")) { // list.add(m); // } // } // for (SysMenuBean m : list) { // List<SysMenuBean> fmenus = new ArrayList<SysMenuBean>(); // for (SysMenuBean m2 : menus) { // if (m2.getP_fid().equals(m.getP_id())) { // fmenus.add(m2); // m.setFmenus(fmenus); // } // } // } // return list; // } // // // /** // * 构建权限集合(shiro) // * // * @param userId // * @return // */ // public Set<String> buildPermissionSetByUserId(String userId) { // Set<String> pudcPerms = null; // try { // List<SysPermissionBean> perms = getPermissionByUserId(userId); // List<SysMenuBean> menus = getMenusByUserId(userId); // pudcPerms = new HashSet<String>(); // String url = ""; // for (SysPermissionBean spb : perms) { // for (SysMenuBean smb : menus) { // if (smb.getP_id().equals(spb.getP_sys_menu_id())) { // url = smb.getP_url() + ":" + spb.getP_mapping(); // } // } // pudcPerms.add(url); // } // } catch (Exception e) { // e.printStackTrace(); // // } // return pudcPerms == null ? new HashSet<String>() : pudcPerms; // } // //} ``` KeyValueBean.java ```package com.lebao.common.beans; import java.io.Serializable; public class KeyValueBean implements Serializable{ private String hkey; private Object value; public String getHkey() { return hkey; } public void setHkey(String hkey) { this.hkey = hkey; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public KeyValueBean(String hkey, Object value) { super(); this.hkey = hkey; this.value = value; } public KeyValueBean() { super(); } } ``` EduLevelRepo.java ```package com.lebao.dao.user; import com.lebao.po.EduLevel; import org.springframework.data.jpa.repository.JpaRepository; public interface EduLevelRepo extends JpaRepository<EduLevel,Long> { } ``` ScoreDuihuanEntity.java ```package com.lebao.modules.scoreduihuan.entity; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; /** * Created by Server on 2016/3/30. */ @Table(name="t_score_duihuan") public class ScoreDuihuanEntity { @Id @Column(name="p_id") private String p_id; private String p_score_id; private String p_score_name; private String p_user_id; private String p_user_name; private String p_user_phone; private String p_user_address; private String p_status; private String p_create_time; private String p_update_time; private Integer p_score; private String p_dealuser_id; private String p_dealuser_name; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_score_id() { return p_score_id; } public void setP_score_id(String p_score_id) { this.p_score_id = p_score_id; } public String getP_score_name() { return p_score_name; } public void setP_score_name(String p_score_name) { this.p_score_name = p_score_name; } public String getP_user_id() { return p_user_id; } public void setP_user_id(String p_user_id) { this.p_user_id = p_user_id; } public String getP_user_name() { return p_user_name; } public void setP_user_name(String p_user_name) { this.p_user_name = p_user_name; } public String getP_user_phone() { return p_user_phone; } public void setP_user_phone(String p_user_phone) { this.p_user_phone = p_user_phone; } public Integer getP_score() { return p_score; } public void setP_score(Integer p_score) { this.p_score = p_score; } public String getP_user_address() { return p_user_address; } public void setP_user_address(String p_user_address) { this.p_user_address = p_user_address; } public String getP_status() { return p_status; } public void setP_status(String p_status) { this.p_status = p_status; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public String getP_update_time() { return p_update_time; } public void setP_update_time(String p_update_time) { this.p_update_time = p_update_time; } public String getP_dealuser_id() { return p_dealuser_id; } public void setP_dealuser_id(String p_dealuser_id) { this.p_dealuser_id = p_dealuser_id; } public String getP_dealuser_name() { return p_dealuser_name; } public void setP_dealuser_name(String p_dealuser_name) { this.p_dealuser_name = p_dealuser_name; } @Override public String toString() { return "ScoreDuihuanBean{" + "p_id='" + p_id + '\'' + ", p_score_id='" + p_score_id + '\'' + ", p_score_name='" + p_score_name + '\'' + ", p_user_id='" + p_user_id + '\'' + ", p_user_name='" + p_user_name + '\'' + ", p_user_phone=" + p_user_phone + ", p_user_address='" + p_user_address + '\'' + ", p_status='" + p_status + '\'' + ", p_create_time='" + p_create_time + '\'' + ", p_update_time='" + p_update_time + '\'' + '}'; } } ``` NewsDao.java ```//package com.lebao.modules.news.dao; // //import com.lebao.bean.NewsSearchParam; //import com.lebao.common.dbhelp.DbHelper; //import com.lebao.common.dbhelp.page.Page; //import com.lebao.common.utils.Sequence; //import com.lebao.common.utils.TimeUtil; //import com.lebao.modules.news.entity.NewsEntity; //import org.apache.commons.lang.StringUtils; //import org.springframework.stereotype.Repository; // //import javax.annotation.Resource; //import java.sql.SQLException; //import java.util.Date; // ///** // * Created by Server on 2016/4/1. // */ //@Repository //public class NewsDao { // @Resource(name = "dbHelper") // private DbHelper dbHelper; // public int add(NewsEntity ne) throws SQLException { // String p_id = Sequence.nextId(); // String p_type_id = ne.getP_type_id(); // String p_user_id=ne.getP_user_id(); // String p_title = ne.getP_title(); // String p_htmlPart = ne.getP_htmlPart(); // // String p_browseTime=ne.getP_browseTime(); // String p_photo1=ne.getP_photo1(); // String p_photo2=ne.getP_photo2(); // String p_create_time = TimeUtil.format(new Date(), TimeUtil.TARGET_1); // String p_url = ne.getP_url(); // String p_status = ne.getP_status(); // System.out.println(ne.toString()); // String sql = "INSERT INTO t_news(p_id,p_type_id,p_user_id,p_title,p_htmlPart,p_photo1, p_photo2,p_create_time,p_url,p_status) VALUES(?,?,?,?,?,?,?,?,?,?)"; // return dbHelper.execute(sql, p_id, p_type_id, p_user_id, p_title, p_htmlPart, p_photo1, p_photo2, p_create_time, p_url, p_status); // } // // public int delete(String p_id,String p_state) throws SQLException { // String sql = "update t_news set p_status = ? where p_id=?"; // return dbHelper.execute(sql,p_state, p_id); // } // // public int update(NewsEntity ne) throws SQLException { // String p_id = ne.getP_id(); // String p_user_id=ne.getP_user_id(); // String p_title = ne.getP_title(); // String p_htmlPart = ne.getP_htmlPart(); // String p_photo1=ne.getP_photo1(); // String p_photo2=ne.getP_photo2(); // String p_update_time = TimeUtil.format(new Date(), TimeUtil.TARGET_1); // String p_url = ne.getP_url(); // String p_status = ne.getP_status(); // String sql = "update t_news set p_user_id = ?,p_title = ?, p_htmlPart=?,p_photo1=?,p_photo2=?,p_update_time=?,p_url=?,p_status=? where p_id=?"; // return dbHelper.execute(sql, p_user_id, p_title, p_htmlPart, p_photo1, p_photo2, p_update_time, p_url, p_status, p_id); // } // // public NewsEntity getNewsEntity(String p_id) throws SQLException { // String sql = "select * from t_news where p_id=?"; // return dbHelper.getBean(sql, NewsEntity.class, p_id); // } // // /* // SELECT t_goods_type.p_type_name , t_goods.* //FROM t_goods //JOIN t_goods_type //ON t_goods_type.p_id=t_goods.p_type_id // */ // public Page<NewsEntity> getNewsEntitys(NewsSearchParam s) throws SQLException { // String sql = " SELECT t_type.p_type_name , t_news.*\n" + // " FROM t_news\n" + // " JOIN t_type\n" + // " ON t_type.p_id=t_news.p_type_id "; // // if( StringUtils.isNotBlank(s.getTitle())){ // sql +=" and t_news.p_name like '%"+s.getTitle()+"%' "; // } // sql +=" and t_news.p_status !=-1"; // // System.out.println(sql); // return dbHelper.getPage(sql, NewsEntity.class, s.getCurPage(),s.getPageSize()); // // } // //} ``` SysPermissionBean.java ```package com.lebao.bean; public class SysPermissionBean { private String p_id ; private String p_sys_menu_id ; private String p_desc ; private String p_mapping ; private String p_name ; private String p_status ; private String p_type ; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_sys_menu_id() { return p_sys_menu_id; } public void setP_sys_menu_id(String p_sys_menu_id) { this.p_sys_menu_id = p_sys_menu_id; } public String getP_desc() { return p_desc; } public void setP_desc(String p_desc) { this.p_desc = p_desc; } public String getP_mapping() { return p_mapping; } public void setP_mapping(String p_mapping) { this.p_mapping = p_mapping; } public String getP_name() { return p_name; } public void setP_name(String p_name) { this.p_name = p_name; } public String getP_status() { return p_status; } public void setP_status(String p_status) { this.p_status = p_status; } public String getP_type() { return p_type; } public void setP_type(String p_type) { this.p_type = p_type; } @Override public String toString() { return "SysPermissionBean{" + "p_id='" + p_id + '\'' + ", p_sys_menu_id='" + p_sys_menu_id + '\'' + ", p_desc='" + p_desc + '\'' + ", p_mapping='" + p_mapping + '\'' + ", p_name='" + p_name + '\'' + ", p_status='" + p_status + '\'' + ", p_type='" + p_type + '\'' + '}'; } } ``` RoleSearchParam.java ```package com.lebao.bean; /** * Created by Server on 2016/4/8. */ public class RoleSearchParam { private String name; private int pageSize = 15; private int curPage = 0; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurPage() { return curPage; } public void setCurPage(int curPage) { this.curPage = curPage; } } ``` SysUserController.java ```package com.lebao.controller; import com.lebao.common.beans.AjaxResult; import com.lebao.common.beans.SearchBean; import com.lebao.common.dbhelp.page.Page; import com.lebao.service.SysUserService; import com.lebao.vo.SysUserVo; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.Map; /** * Created by ZR on 2016/12/6. */ @Controller @RequestMapping(value="sysUser") public class SysUserController extends BaseController{ @Autowired private SysUserService sysUserService; /** * 页面入口 * @return */ @RequestMapping("/index") public ModelAndView index() { ModelAndView view = new ModelAndView(); view.addObject("title","系统管理>>用户查询"); view.setViewName("admin/sysuser/index"); return view; } /** * 分页数据查询 * @param request * @return */ @RequestMapping(value = "/query",produces="plain/text; charset=UTF-8") @ResponseBody public String query(HttpServletRequest request) { Map<String, Object> obj = this.getParametersStartWidth(request, "s_"); String name = (String) obj.get("name"); DataTableVo dt = this.parseData4DT(request); int start = dt.getiDisplayStart(); int length = dt.getiDisplayLength(); int curPage = 0; if (dt.getiDisplayStart() > 0) { curPage =start / length + 1; } String json = null; try { SearchBean s = new SearchBean(); if (StringUtils.isNotBlank(name)) { s.getParamMap().put("name",name); } if(dt.getSortField().equals("user_id")){ s.setSortField("id"); } s.setSortType(dt.getSortType()); s.setCurrentPage(curPage); s.setPageSize(length); Page<SysUserVo> pages =sysUserService.getPage(s); dt.setData(pages.getData()); dt.setiTotalRecords(dt.getiTotalRecords()); dt.setiTotalRecords(pages.getRecordCount()); json = formateData2DT(dt); } catch (Exception e) { e.printStackTrace(); } return json; } /** * 添加用户 * @param sysUserVo * @return */ @RequestMapping(value = "/save",produces="plain/text; charset=UTF-8") @ResponseBody public String save(SysUserVo sysUserVo) { try { boolean exist=sysUserService.checkSysUserIsExist(sysUserVo.getName()); if(exist){ return this.buildFailMessage("用户名已存在", ResultModal.MESSAGE); } sysUserService.save(sysUserVo); return this.buildSuccessMessage("用户添加成功", ResultModal.MESSAGE); } catch (Exception e) { return this.buildFailMessage("用户添加失败", ResultModal.MESSAGE); } } /** * 更新用户 * @param id * @param name * @param password * @return */ @RequestMapping(value = "/update",produces="plain/text; charset=UTF-8") @ResponseBody public String update( @RequestParam(value = "id", required = true) Long id, @RequestParam(value = "name", required = true) String name, @RequestParam(value = "password", required = true) String password) { try { SysUserVo sysUserVo=sysUserService.findOne(id); sysUserVo.setPassword(password); sysUserVo.setName(name); sysUserService.update(sysUserVo); return this.buildSuccessMessage("用户更新成功", ResultModal.MESSAGE); } catch (Exception e) { return this.buildFailMessage("用户更新失败", ResultModal.MESSAGE); } } @ResponseBody @RequestMapping(value = "/queryById",produces="plain/text; charset=UTF-8") public String queryUser(@RequestParam(value = "id", required = true) Long id) { try { SysUserVo sysUserVo= sysUserService.findOne(id); return this.buildMessage(ResultModal.SUCCESS,ResultModal.SUCCESS_CODE,"用户获取成功",sysUserVo, ResultModal.DATA); } catch (Exception e) { return this.buildFailMessage("用户获取失败", ResultModal.MESSAGE); } } /** * 删除用户 * @param id * @return */ @RequestMapping("/delete") @ResponseBody public String delete(@RequestParam(value = "id", required = true) Long id) { try { SysUserVo sysUserVo=sysUserService.findOne(id); if (sysUserVo.getName().equals("admin")){ return this.buildFailMessage("admin用户无法删除", ResultModal.MESSAGE); } sysUserService.delete(id); return this.buildSuccessMessage("用户删除成功", ResultModal.MESSAGE); } catch (Exception e) { return this.buildFailMessage("用户删除失败", ResultModal.MESSAGE); } } } ``` SysUserDao.java ```package com.lebao.dao.sysuser; import com.lebao.common.beans.SearchBean; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.po.SysUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; @Repository public class SysUserDao { @Autowired SysUserRepo sysUserRepo; @Autowired DbHelper dbHelper; public Page<SysUser> getPage(SearchBean searchBean) throws SQLException { String sql = " SELECT * from tb_sysuser where tb_sysuser.type >0 "; List<Object> list = new ArrayList<Object>(); Map<Object, Object> map = searchBean.getParamMap(); if (map.containsKey("name")) { sql += " and tb_sysuser.name like ? "; list.add("%" + map.get("name") + "%"); } sql += " order by " + searchBean.getSortField() + " " + searchBean.getSortType() + " "; return dbHelper.getPage(sql, SysUser.class, searchBean.getCurrentPage(), searchBean.getPageSize(), list.toArray()); } public void save(SysUser sysUser) { sysUserRepo.save(sysUser); } public void update(SysUser sysUser) { sysUserRepo.save(sysUser); } public void delete(SysUser sysUser) { sysUserRepo.delete(sysUser); } public SysUser findOne(Long id) { return sysUserRepo.findOne(id); } public SysUser findByNameAndPassword(String name,String password){ return sysUserRepo.findByNameAndPassword(name,password); } public boolean checkSysUserIsExist(String name){ int count=sysUserRepo.countByName(name); if(count>0){ return true; }else { return false; } } } ``` NewsService.java ```package com.lebao.service; import com.lebao.common.beans.SearchBean; import com.lebao.common.dbhelp.page.Page; import com.lebao.common.utils.TimeUtil; import com.lebao.converter.NewsConverter; import com.lebao.dao.news.NewsDao; import com.lebao.po.News; import com.lebao.vo.NewsVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.sql.SQLException; import java.util.List; /** * Author: zr * Date : 2016/12/6 18:13 */ @Service public class NewsService { @Autowired NewsDao newsDao; @Autowired NewsConverter newsConverter; public Page<NewsVo> getPage(SearchBean s) throws SQLException { int myPageSize = 0;//每页记录数 int curPage = 0;//显示页 int pageCount = 0;//页数 int recordCount = 0;//总记录数 Page<News> newsPage = newsDao.getPage(s); List<NewsVo> list = newsConverter.convert2V(newsPage.getData()); recordCount = newsPage.getRecordCount(); pageCount = newsPage.getPageCount(); curPage = newsPage.getCurPage(); myPageSize = newsPage.getPageSize(); Page<NewsVo> pageBean = new Page<NewsVo>(myPageSize, list, curPage, pageCount, recordCount); return pageBean; } public void save(NewsVo vo) { News news = newsConverter.convert2P(vo); news.setCreateTime(TimeUtil.now()); news.setUpdateTime(TimeUtil.now()); newsDao.save(news); System.out.println(news.toString()); } public void update(NewsVo vo) { News news = newsConverter.convert2P(vo); news.setUpdateTime(TimeUtil.now()); newsDao.save(news); } public void delete(Long id) { NewsVo vo = findOne(id); News news = newsConverter.convert2P(vo); newsDao.delete(news); } public NewsVo findOne(Long id) { News news = newsDao.findOne(id); NewsVo newsVo = newsConverter.convert2V(news); return newsVo; } /** * 下面都是返回首页内容,根据写死的typeId查询 */ public List<NewsVo> indexList(SearchBean searchBean) throws SQLException { Page<News> newsPage=newsDao.indexList(searchBean); List<News> newsList = newsPage.getData(); List<NewsVo> newsVoList = newsConverter.convert2V(newsList); return newsVoList; } /** * 首页滚动 * @return * @throws SQLException */ public List<NewsVo> indexList1() throws SQLException { List<News> newsList=newsDao.indexList1(); List<NewsVo> newsVoList = newsConverter.convert2V(newsList); return newsVoList; } } ``` ScoreShopDao.java ```package com.lebao.modules.scoreshop.dao; import com.lebao.bean.SearchParam; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.modules.BaseDao; import com.lebao.modules.scoreshop.entity.ScoreShopEntity; import com.lebao.modules.shoper.entity.ShoperEntity; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.sql.SQLException; import java.util.List; @Repository public class ScoreShopDao extends BaseDao{ @Resource(name = "dbHelper") private DbHelper dbHelper; public Page<ScoreShopEntity> getScoreShops(SearchParam s) throws SQLException { String sql = "select * from t_score_shop where 1=1"; if (StringUtils.isNotBlank(s.getName())) { sql += " and p_name like '" + s.getName() + "%' "; } sql += " order by " + s.getSortField() + " " + s.getSortType() + " "; return dbHelper.getPage(sql, ScoreShopEntity.class, s.getPageNow(), s.getPageSize()); } public List<ShoperEntity> getShopers() throws SQLException { String sql = "select * from t_shoper where p_status='1' "; return dbHelper.getBeanList(sql,ShoperEntity.class); } } ``` AppConfig.java ```package com.lebao.file; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class AppConfig { @Value("#{appSetting['server_name']}") public String SERVER_NAME; @Value("#{appSetting['server_user_qr']}") public String SERVER_USER_QR; @Value("#{appSetting['user_qr']}") public String USER_QR; @Value("#{appSetting['image_allow_type']}") public String IMAGE_ALLOW_TYPE; @Value("#{appSetting['news_image_content']}") public String NEWS_IMAGE_CONTENT; @Value("#{appSetting['root']}") public String ROOT; @Value("#{appSetting['root_dir']}") private String rootDir; @Value("#{appSetting['root_small_dir']}") private String rootSmallDir; @Value("#{appSetting['scoreshop_dir']}") private String scoreshopDir; @Value("#{appSetting['scoreshop_small_dir']}") private String scoreshopSmallDir; @Value("#{appSetting['goods_dir']}") private String goodsDir; @Value("#{appSetting['goods_small_dir']}") private String goodsSmallDir; @Value("#{appSetting['shoper_dir']}") private String shoperDir; @Value("#{appSetting['shoper_small_dir']}") private String shoperSmallDir; @Value("#{appSetting['adv_dir']}") private String advDir; @Value("#{appSetting['adv_small_dir']}") private String advSmallDir; @Value("#{appSetting['news_dir']}") private String newsDir; @Value("#{appSetting['image_max_size']}") private String imageMaxSize; @Value("#{appSetting['image_allow_files']}") private String imageAllowFiles; @Value("#{appSetting['root_path']}") private String rootPath; @Value("#{appSetting['news_path']}") private String newsPath; @Value("#{appSetting['news_small_dir']}") private String newsSmallDir; @Value("#{appSetting['datas_dir']}") private String datasDir; @Value("#{appSetting['datas_path']}") private String datasPath; @Value("#{appSetting['datas_allow_files']}") private String datasAllowFiles; @Value("#{appSetting['HTMLDIR']}") private String HTMLDIR; @Value("#{appSetting['HTMLURLBASE']}") private String HTMLURLBASE; public String getScoreshopDir() { return scoreshopDir; } public void setScoreshopDir(String scoreshopDir) { this.scoreshopDir = scoreshopDir; } public String getScoreshopSmallDir() { return scoreshopSmallDir; } public void setScoreshopSmallDir(String scoreshopSmallDir) { this.scoreshopSmallDir = scoreshopSmallDir; } public String getAdvDir() { return advDir; } public void setAdvDir(String advDir) { this.advDir = advDir; } public String getAdvSmallDir() { return advSmallDir; } public void setAdvSmallDir(String advSmallDir) { this.advSmallDir = advSmallDir; } public String getShoperDir() { return shoperDir; } public void setShoperDir(String shoperDir) { this.shoperDir = shoperDir; } public String getShoperSmallDir() { return shoperSmallDir; } public void setShoperSmallDir(String shoperSmallDir) { this.shoperSmallDir = shoperSmallDir; } public String getRootDir() { return rootDir; } public void setRootDir(String rootDir) { this.rootDir = rootDir; } public String getRootSmallDir() { return rootSmallDir; } public void setRootSmallDir(String rootSmallDir) { this.rootSmallDir = rootSmallDir; } public String getSERVER_NAME() { return SERVER_NAME; } public void setSERVER_NAME(String SERVER_NAME) { this.SERVER_NAME = SERVER_NAME; } public String getGoodsDir() { return goodsDir; } public void setGoodsDir(String goodsDir) { this.goodsDir = goodsDir; } public String getGoodsSmallDir() { return goodsSmallDir; } public void setGoodsSmallDir(String goodsSmallDir) { this.goodsSmallDir = goodsSmallDir; } public String getNewsDir() { return newsDir; } public void setNewsDir(String newsDir) { this.newsDir = newsDir; } public String getNewsPath() { return newsPath; } public void setNewsPath(String newsPath) { this.newsPath = newsPath; } public String getNewsSmallDir() { return newsSmallDir; } public void setNewsSmallDir(String newsSmallDir) { this.newsSmallDir = newsSmallDir; } public String getHTMLDIR() { return HTMLDIR; } public void setHTMLDIR(String hTMLDIR) { HTMLDIR = hTMLDIR; } public String getHTMLURLBASE() { return HTMLURLBASE; } public void setHTMLURLBASE(String hTMLURLBASE) { HTMLURLBASE = hTMLURLBASE; } public String getDatasAllowFiles() { return datasAllowFiles; } public void setDatasAllowFiles(String datasAllowFiles) { this.datasAllowFiles = datasAllowFiles; } public String getDatasDir() { return datasDir; } public void setDatasDir(String datasDir) { this.datasDir = datasDir; } public String getDatasPath() { return datasPath; } public void setDatasPath(String datasPath) { this.datasPath = datasPath; } public String getRootPath() { return rootPath; } public void setRootPath(String rootPath) { this.rootPath = rootPath; } public String getImageMaxSize() { return imageMaxSize; } public void setImageMaxSize(String imageMaxSize) { this.imageMaxSize = imageMaxSize; } public String getImageAllowFiles() { return imageAllowFiles; } public void setImageAllowFiles(String imageAllowFiles) { this.imageAllowFiles = imageAllowFiles; } public String getUSER_QR() { return USER_QR; } public String getSERVER_USER_QR() { return SERVER_USER_QR; } public void setSERVER_USER_QR(String SERVER_USER_QR) { this.SERVER_USER_QR = SERVER_USER_QR; } public void setUSER_QR(String USER_QR) { this.USER_QR = USER_QR; } public String getIMAGE_ALLOW_TYPE() { return IMAGE_ALLOW_TYPE; } public void setIMAGE_ALLOW_TYPE(String IMAGE_ALLOW_TYPE) { this.IMAGE_ALLOW_TYPE = IMAGE_ALLOW_TYPE; } public String getNEWS_IMAGE_CONTENT() { return NEWS_IMAGE_CONTENT; } public void setNEWS_IMAGE_CONTENT(String NEWS_IMAGE_CONTENT) { this.NEWS_IMAGE_CONTENT = NEWS_IMAGE_CONTENT; } public String getROOT() { return ROOT; } public void setROOT(String ROOT) { this.ROOT = ROOT; } } ``` OrderDetailBean.java ```package com.lebao.bean; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Server on 2016/4/20. */ public class OrderDetailBean { @JsonProperty("id") private String p_id ;//bigint(20) NOT NULLid @JsonProperty("order_id") private String p_order_id;//bigint(20) NOT NULL user_id @JsonProperty("goods_id") private String p_goods_id;//bigint(20) NOT NULL user_id @JsonProperty("num") private Integer p_num;//bigint(20) NOT NULL user_id @JsonProperty("price") private Integer p_price;//bigint(20) NOT NULL user_id @JsonProperty("account") private String p_account;//bigint(20) NOT NULL user_id @JsonProperty("account_password") private String p_account_password;//bigint(20) NOT NULL user_id public String getP_account_password() { return p_account_password; } public void setP_account_password(String p_account_password) { this.p_account_password = p_account_password; } public String getP_account() { return p_account; } public void setP_account(String p_account) { this.p_account = p_account; } public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_order_id() { return p_order_id; } public void setP_order_id(String p_order_id) { this.p_order_id = p_order_id; } public String getP_goods_id() { return p_goods_id; } public void setP_goods_id(String p_goods_id) { this.p_goods_id = p_goods_id; } public Integer getP_num() { return p_num; } public void setP_num(Integer p_num) { this.p_num = p_num; } public Integer getP_price() { return p_price; } public void setP_price(Integer p_price) { this.p_price = p_price; } } ``` SysRoleDao.java ```package com.lebao.modules.permission.dao; import com.lebao.bean.RoleSearchParam; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.common.utils.TimeUtil; import com.lebao.modules.CountEntity; import com.lebao.modules.permission.entity.SysPermissionEntity; import com.lebao.modules.permission.entity.SysRoleEntity; import com.lebao.modules.permission.entity.SysRolePermissionMap; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.sql.SQLException; import java.util.Date; import java.util.List; /** * Created by Server on 2016/4/1. */ @Repository public class SysRoleDao { @Resource(name = "dbHelper") private DbHelper dbHelper; public List<SysRoleEntity> getRoleEntities() throws SQLException { String sql = "select * from t_sys_role "; return dbHelper.getBeanList(sql, SysRoleEntity.class); } public Page<SysRoleEntity> getRoleEntities(RoleSearchParam s) throws SQLException { String sql = "select * from t_sys_role where 1=1 "; if (StringUtils.isNotBlank(s.getName())) { sql += " and p_name like '%" + s.getName() + "%' "; } return dbHelper.getPage(sql, SysRoleEntity.class, s.getCurPage(), s.getPageSize()); } public SysRoleEntity getRoleEntityById(String id) throws SQLException { String sql = "select * from t_sys_role where t_sys_role.p_id=?"; return dbHelper.getBean(sql, SysRoleEntity.class, id); } public List<SysPermissionEntity> getAllPermission() throws SQLException { List<SysPermissionEntity> list = dbHelper.getBeanList("SELECT * FROM t_sys_permission", SysPermissionEntity.class); return list; } public List<SysRolePermissionMap> getAllPermissionByRoleId(String roleId) throws SQLException { List<SysRolePermissionMap> list = dbHelper.getBeanList("SELECT p_permission_id FROM t_sys_role_permission_map where p_role_id=?", SysRolePermissionMap.class, roleId); return list; } public void addSysRole(SysRoleEntity re) throws SQLException { String p_id = re.getP_id(); String p_name = re.getP_name(); String p_desc = re.getP_desc(); String p_create_time = TimeUtil.format(new Date(), TimeUtil.TARGET_1); String p_type = re.getP_type(); String sql = "INSERT INTO t_sys_role (p_id,p_name,p_desc,p_type,p_create_time) VALUES(?,?,?,?,?)"; dbHelper.execute(sql, p_id, p_name, p_desc, p_type, p_create_time); } public void updateSysRole(SysRoleEntity re) throws SQLException { String p_id = re.getP_id(); String p_name = re.getP_name(); String p_desc = re.getP_desc(); String p_update_time = TimeUtil.format(new Date(), TimeUtil.TARGET_1); String p_type = re.getP_type(); String sql = "update t_sys_role set p_name=?,p_desc=?,p_type=?,p_update_time=? where p_id=?"; dbHelper.execute(sql, p_name, p_desc, p_type, p_update_time, p_id); } public boolean checkSysRoleIsUsing(String roleId) throws SQLException { String sql = "select count(1) as num from t_sys_user_role_map where p_role_id = ?"; CountEntity ce = dbHelper.getBean(sql, CountEntity.class, roleId); return ce!=null&&ce.getNum()>0; } public void updateSysUser(String roleId,String roleName) throws SQLException { String sql = "update t_sys_user set p_role_name= ? where p_role_id=?"; dbHelper.execute(sql,roleName,roleId); } public void deleteSysRole(String id) throws SQLException { String sql = "delete from t_sys_role where p_role_id=?"; dbHelper.execute(sql, id); } } ``` UrlUtil.java ```package com.lebao.common.utils; import javax.servlet.http.HttpServletRequest; public class UrlUtil { public static String getBaseUrl(HttpServletRequest request){ String path=request.getSession().getServletContext().getRealPath(""); return path; } } ``` ITypeService.java ```package com.lebao.service.i; import com.lebao.bean.SearchParam; import com.lebao.bean.TypeBean; import com.lebao.common.dbhelp.page.Page; import java.sql.SQLException; import java.util.List; public interface ITypeService { public TypeBean getTypeById(String p_id) throws SQLException; public int delType(String id)throws SQLException; public int addType(TypeBean gtb) throws SQLException; public int updType(TypeBean gtb) throws SQLException; public Page<TypeBean> getTypes(SearchParam s) throws SQLException; public List<TypeBean> getTypes()throws SQLException; public void reAddType(String typeId) throws SQLException; } ``` package-info.java ```/** * oracle数据库个性处理 * */ package com.lebao.common.dbhelp.dialect.oracle;``` UploadResult.java ```package com.lebao.common.beans; import com.google.gson.Gson; import java.util.HashMap; import java.util.Map; /* //成功时 { "error" : 0, "url" : "http://www.example.com/path/to/file.ext" } //失败时 { "error" : 1, "message" : "错误信息" } */ public class UploadResult { public static String success(String url) { Map<String, Object> result = new HashMap<String, Object>(); result.put("error", 0); result.put("url", url); Gson gson = new Gson(); return gson.toJson(result); } public static String fail(String errorMsg) { Map<String, Object> result = new HashMap<String, Object>(); result.put("error", 1); result.put("message", errorMsg); Gson gson = new Gson(); return gson.toJson(result); } } ``` UserVo.java ```package com.lebao.vo; import com.fasterxml.jackson.annotation.JsonProperty; import com.lebao.po.Department; import java.util.List; /** * Created by ZR on 2017/1/8. */ public class UserVo { @JsonProperty("user_id") private Long id; private String name; private String pic; private String qr; private Integer sex; private List<Department> departmentList; private Long eduLevel; private String eduLevelValue; private Long position; private String positionValue; private String phone; private String remark; public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } private String createTime; private String updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public List<Department> getDepartmentList() { return departmentList; } public void setDepartmentList(List<Department> departmentList) { this.departmentList = departmentList; } public Long getEduLevel() { return eduLevel; } public void setEduLevel(Long eduLevel) { this.eduLevel = eduLevel; } public Long getPosition() { return position; } public void setPosition(Long position) { this.position = position; } public String getQr() { return qr; } public void setQr(String qr) { this.qr = qr; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public UserVo() { } public String getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } public String getEduLevelValue() { return eduLevelValue; } public void setEduLevelValue(String eduLevelValue) { this.eduLevelValue = eduLevelValue; } public String getPositionValue() { return positionValue; } public void setPositionValue(String positionValue) { this.positionValue = positionValue; } @Override public String toString() { return "UserVo{" + "id=" + id + ", name='" + name + '\'' + ", pic='" + pic + '\'' + ", sex=" + sex + ", departmentList=" + departmentList + ", eduLevel=" + eduLevel + ", eduLevelValue='" + eduLevelValue + '\'' + ", position=" + position + ", positionValue='" + positionValue + '\'' + ", phone='" + phone + '\'' + ", remark='" + remark + '\'' + ", createTime='" + createTime + '\'' + ", updateTime='" + updateTime + '\'' + '}'; } } ``` NewsRepo.java ```package com.lebao.dao.news; import com.lebao.po.News; import org.springframework.data.repository.CrudRepository; public interface NewsRepo extends CrudRepository<News,Long> { } ``` TypeEntity.java ```package com.lebao.modules.type.entity; import java.sql.Timestamp; /** * Created by Server on 2016/4/1. */ public class TypeEntity { private String p_id; private String p_name; private String p_status;//1可用,-1不可用 private Timestamp p_create_time; private Timestamp p_update_time; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_name() { return p_name; } public void setP_name(String p_name) { this.p_name = p_name; } public String getP_status() { return p_status; } public void setP_status(String p_status) { this.p_status = p_status; } public Timestamp getP_create_time() { return p_create_time; } public void setP_create_time(Timestamp p_create_time) { this.p_create_time = p_create_time; } public Timestamp getP_update_time() { return p_update_time; } public void setP_update_time(Timestamp p_update_time) { this.p_update_time = p_update_time; } } ``` NewsVo.java ```package com.lebao.vo; /** * Created by ZR on 2016/12/8. */ public class NewsVo { private Long id; private Long userId; private Long typeId; private String name; private String content; private String author; private String createTime; private String updateTime; private String picSmall; private String picBig; private Integer recommend; private String recommendValue; private String displayUpdateTime; private String displayCreateTime; private String typeName; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Long getTypeId() { return typeId; } public void setTypeId(Long typeId) { this.typeId = typeId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public String getPicSmall() { return picSmall; } public void setPicSmall(String picSmall) { this.picSmall = picSmall; } public String getPicBig() { return picBig; } public void setPicBig(String picBig) { this.picBig = picBig; } public Integer getRecommend() { return recommend; } public void setRecommend(Integer recommend) { this.recommend = recommend; } public String getDisplayUpdateTime() { return updateTime.replaceAll("\\s\\d{1,2}:\\d{1,2}:\\d{1,2}(\\.\\d)?$",""); } public void setDisplayUpdateTime(String displayUpdateTime) { this.displayUpdateTime = displayUpdateTime; } public String getDisplayCreateTime() { return displayCreateTime; } public void setDisplayCreateTime(String displayCreateTime) { this.displayCreateTime = displayCreateTime; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getRecommendValue() { return recommendValue; } public void setRecommendValue(String recommendValue) { this.recommendValue = recommendValue; } @Override public String toString() { return "NewsVo{" + "id=" + id + ", userId=" + userId + ", typeId=" + typeId + ", name='" + name + '\'' + ", content='" + content + '\'' + ", author='" + author + '\'' + ", createTime='" + createTime + '\'' + ", updateTime='" + updateTime + '\'' + ", picSmall='" + picSmall + '\'' + ", picBig='" + picBig + '\'' + '}'; } } ``` PositionRepo.java ```package com.lebao.dao.user; import com.lebao.po.Position; import org.springframework.data.jpa.repository.JpaRepository; public interface PositionRepo extends JpaRepository<Position,Long> { } ``` INewsService.java ```package com.lebao.service.i; import com.lebao.bean.NewsBean; import com.lebao.bean.NewsSearchParam; import com.lebao.common.dbhelp.page.Page; import java.sql.SQLException; public interface INewsService { public NewsBean getNews(String p_id) throws SQLException; public int delete(String id)throws SQLException; public int add(NewsBean gtb) throws SQLException; public int update(NewsBean gtb) throws SQLException; public Page<NewsBean> getNews(NewsSearchParam param) throws SQLException; } ``` SysUserRoleMap.java ```package com.lebao.modules.permission.entity; public class SysUserRoleMap { private String p_id ; private String p_user_id ; private String p_role_id ; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_user_id() { return p_user_id; } public void setP_user_id(String p_user_id) { this.p_user_id = p_user_id; } public String getP_role_id() { return p_role_id; } public void setP_role_id(String p_role_id) { this.p_role_id = p_role_id; } @Override public String toString() { return "SysUserRoleMap{" + "p_id='" + p_id + '\'' + ", p_user_id='" + p_user_id + '\'' + ", p_role_id='" + p_role_id + '\'' + '}'; } }``` PubUpload.java ```package com.lebao.file; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.lang.RandomStringUtils; import org.springframework.stereotype.Service; /** * * @author * 功能:文件上传核心算法,将file转换成流,再以字节流的形式创建新的文件 */ @Service public class PubUpload { void copy(File f1, File f2) { try { InputStream fr = new FileInputStream(f1); OutputStream fw = new FileOutputStream(f2); byte buffer[] = new byte[1024]; int length = 0; while ((length = fr.read(buffer)) != -1) { fw.write(buffer, 0, length); } fw.close(); fr.close(); } catch (IOException ioe) { //System.out.println(ioe); } catch (Exception e) { //System.out.println(e); } } public String bcopy(File f1, File f2, String fs) { File f3; String returnValue = "0"; if (f1.exists()) { if (!f2.exists()) { f2.mkdirs(); } f3 = new File(f2, fs); copy(f1, f3); returnValue = "1"; } else { //System.out.println("要拷贝的文件不存在!"); } return returnValue; } public static void main(String[] args) { // TODO Auto-generated method stub /*PubUpload fc = new PubUpload(); File f1, f2; f1 = new File("G:/GlemJC/pro/com.zend.php.core_9.0.2.201202240955.jar"); f2 = new File("G:/GlemJC/upload");// 创建新的目录名称,服务器存放文件的目录 fc.bcopy(f1, f2, "com.zend.php.core_9.0.2.201202240955.jar");*/ SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); String str1 = sdf.format(new Date()); long id = new Date().getTime(); long l1 = id / (2000 * 2000); long l2 = (id % (2000 * 2000)) / 2000; long l3 = id % 2000; System.out.println(String.format("%d/%d/%d/N0/", l1, l2, l3)+"------"+str1+"------"+RandomStringUtils.randomAlphanumeric(5)); // filename = String.format("p_%d%d%d_%s.%s", l1, l2, l3, TimeStamp.getTime(TimeStamp.YYYYMMDDhhmmssxxx), ext); } } ``` MarketDao.java ```package com.lebao.modules.market.dao; import com.lebao.bean.SearchParam; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.common.utils.TimeUtil; import com.lebao.modules.BaseDao; import com.lebao.modules.market.entity.MarketEntity; import com.lebao.modules.shoper.entity.ShoperEntity; import com.lebao.modules.sys.entity.LiushuiEntity; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.sql.SQLException; import java.util.Date; import java.util.List; @Repository public class MarketDao extends BaseDao{ @Resource(name = "dbHelper") private DbHelper dbHelper; public Page<MarketEntity> getMarkets(SearchParam s) throws SQLException { String sql = "select * from t_market where 1=1"; if (StringUtils.isNotBlank(s.getId())) { sql += " and p_sys_user_id = '" + s.getId() + "' "; } if (StringUtils.isNotBlank(s.getTime1())) { sql += " and p_create_time between '"+s.getTime1()+"' and "; if(StringUtils.isNotBlank(s.getTime2())){ sql += " '"+s.getTime2() +"' "; }else { sql += " '"+ TimeUtil.format(new Date(), TimeUtil.TARGET_1) +"' "; } } sql += " order by " + s.getSortField() + " " + s.getSortType() + " "; return dbHelper.getPage(sql, MarketEntity.class, s.getPageNow(), s.getPageSize()); } public Page<LiushuiEntity> getMarketLiushui(SearchParam s) throws SQLException { String sql = "select * from t_liushui where 1=1 and p_status = 1 "; if (StringUtils.isNotBlank(s.getId())) { sql += " and p_user_id IN (SELECT p_user_id FROM t_market WHERE p_sys_user_id= '"+s.getId()+"' ) "; } if (StringUtils.isNotBlank(s.getTime1())) { sql += " and p_create_time between '"+s.getTime1()+"' and "; if(StringUtils.isNotBlank(s.getTime2())){ sql += " '"+s.getTime2() +"' "; }else { sql += " '"+ TimeUtil.format(new Date(), TimeUtil.TARGET_1) +"' "; } } sql += " order by " + s.getSortField() + " " + s.getSortType() + " "; System.out.println(sql); return dbHelper.getPage(sql, LiushuiEntity.class, s.getPageNow(), s.getPageSize()); } //个人 /* public Page<MarketEntity> getMarketsInfo(SearchParam s) throws SQLException { String sql = "select t_market.*,t_user_base.p_regist_code from t_market,t_user_base where 1=1 "; if (StringUtils.isNotBlank(s.getId())) { sql += " and p_sys_user_id = '" + s.getId() + "' "; } sql+=" and t_market.p_user_id = t_user_base.p_regist_code "; sql += " order by t_market." + s.getSortField() + " " + s.getSortType() + " "; return dbHelper.getPage(sql, MarketEntity.class, s.getPageNow(), s.getPageSize()); } */ public Page<MarketEntity> getMarketsInfo(SearchParam s) throws SQLException { String sql = "select * from t_market where 1=1"; if (StringUtils.isNotBlank(s.getId())) { sql += " and p_sys_user_id = '" + s.getId() + "' "; } sql += " order by " + s.getSortField() + " " + s.getSortType() + " "; return dbHelper.getPage(sql, MarketEntity.class, s.getPageNow(), s.getPageSize()); } public List<ShoperEntity> getShopers() throws SQLException { String sql = "select * from t_shoper where p_status='1' "; return dbHelper.getBeanList(sql,ShoperEntity.class); } public ShoperEntity getShoperById(String shoperId) throws SQLException { String sql = "select * from t_shoper where t_shoper.p_id=?"; return dbHelper.getBean(sql, ShoperEntity.class, shoperId); } } ``` SysDao.java ```package com.lebao.modules.sys.dao; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.utils.Sequence; import com.lebao.common.utils.TimeUtil; import com.lebao.modules.permission.entity.SysPermissionEntity; import com.lebao.modules.permission.entity.SysRolePermissionMap; import com.lebao.modules.sys.entity.SysMenuEntity; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.sql.SQLException; import java.util.Date; import java.util.List; @Repository public class SysDao { @Resource(name = "dbHelper") private DbHelper dbHelper; /** * 查询用户的所有操作权限 * * @return List<> */ public List<SysPermissionEntity> getPermissions(String userID) throws SQLException { List<SysPermissionEntity> list = dbHelper.getBeanList("SELECT * FROM t_sys_permission WHERE p_id IN (SELECT p_permission_id FROM t_sys_role_permission_map WHERE p_role_id IN (SELECT p_role_id FROM t_sys_user_role_map WHERE p_user_id = ?)) ORDER BY p_sys_menu_id", SysPermissionEntity.class, userID); return list; } /** * 查询管理员的所有操作权限 */ public List<SysPermissionEntity> getPermissions4Admin() throws SQLException { List<SysPermissionEntity> entities = dbHelper.getBeanList("SELECT * FROM t_sys_permission", SysPermissionEntity.class); return entities; } /** * 查询用户的所有菜单 * * @return List<> */ public List<SysMenuEntity> getMenus(String userID) throws SQLException { List<SysMenuEntity> list = dbHelper.getBeanList("SELECT DISTINCT( t_sys_menu.`p_id`),t_sys_menu.* FROM t_sys_menu,t_sys_permission,t_sys_role_permission_map, \n" + "t_sys_user_role_map \n" + "WHERE t_sys_menu.p_id = t_sys_permission.p_sys_menu_id AND t_sys_permission.p_id = t_sys_role_permission_map.p_permission_id AND t_sys_role_permission_map.p_role_id = t_sys_user_role_map.p_role_id AND t_sys_user_role_map.p_user_id = ? order by t_sys_menu.p_id", SysMenuEntity.class, userID); return list; } /** * 查询管理员的所有菜单 */ public List<SysMenuEntity> getMenus4Admin() throws SQLException { List<SysMenuEntity> entities = dbHelper.getBeanList("SELECT * FROM t_sys_menu", SysMenuEntity.class); return entities; } public void addSysRolePermissionMap(SysRolePermissionMap rpm) throws SQLException { String p_id = Sequence.nextId(); String p_permission_id=rpm.getP_permission_id(); String role_id=rpm.getP_role_id(); String p_create_time = TimeUtil.format(new Date(), TimeUtil.TARGET_1); String sql = "INSERT INTO t_sys_role_permission_map (p_id,p_permission_id,p_role_id,p_create_time) VALUES(?,?,?,?)"; dbHelper.execute(sql, p_id,p_permission_id,role_id,p_create_time); } public void delSysRolePermissionMap(String roleId) throws SQLException { String sql="delete from t_sys_role_permission_map where p_role_id=?"; dbHelper.execute(sql,roleId); } } ``` News.java ```package com.lebao.po; import javax.persistence.*; /** * Created by ZR on 2016/12/8. */ @Entity @Table(name="tb_news") public class News { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private Long userId; private Long typeId; private String name; private String content; private String author; private String createTime; private String updateTime; private String picSmall; private String picBig; private Integer recommend; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Long getTypeId() { return typeId; } public void setTypeId(Long typeId) { this.typeId = typeId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public String getPicSmall() { return picSmall; } public void setPicSmall(String picSmall) { this.picSmall = picSmall; } public String getPicBig() { return picBig; } public void setPicBig(String picBig) { this.picBig = picBig; } public Integer getRecommend() { return recommend; } public void setRecommend(Integer recommend) { this.recommend = recommend; } } ``` package-info.java ```/** * 翻页实现。 * <p> * 通过调用PageFactory的方法获取封装好的翻页对象,用于在前台展示。 * */ package com.lebao.common.dbhelp.page;``` OrderSearchParam.java ```package com.lebao.bean; /** * Created by Server on 2016/4/8. */ public class OrderSearchParam { private String order_id;//订单号 private String user_name;//用户名 private String user_id;//用户编号 private String status;//-2 取消 -1未付款 0未完成 1 完成 private int pageSize = 15; private int curPage = 0; private String sortField = "p_create_time"; private String sortType = "desc"; public String getOrder_id() { return order_id; } public void setOrder_id(String order_id) { this.order_id = order_id; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurPage() { return curPage; } public void setCurPage(int curPage) { this.curPage = curPage; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getSortField() { return sortField; } public void setSortField(String sortField) { this.sortField = sortField; } public String getSortType() { return sortType; } public void setSortType(String sortType) { this.sortType = sortType; } } ``` common.js ```/** * parse data table */ (function(win){ var isHistoryFlag = $("#isHistory").val() ; $("#isHistory").val("0") ; var loadFirst = true ; var postDT = { parseDT : function( sSource , aoData , fnCallback ){ var contextArgs = {} ; if(self.frameElement && self.frameElement.tagName == "IFRAME" && parent.window.contextArgs){ contextArgs = parent.window.contextArgs ; } $("[name^='s_']").each(function(){ var name = $(this).attr("name") ; var value = $(this).val() ; if(self.frameElement && self.frameElement.tagName == "IFRAME" && parent.window.contextArgs && loadFirst && isHistoryFlag =="0" ){ if( parent.window.contextArgs[name] ){ value = parent.window.contextArgs[name] ; $("[name='" + name + "']").val( parent.window.contextArgs[name] ) ; $("select[name='"+name+"']").attr("preVal" , parent.window.contextArgs[name] ) ; } } aoData.push({"name" : name , "value" : value }) ; contextArgs[name] = value ; }); if(self.frameElement && self.frameElement.tagName == "IFRAME" ){ parent.window.contextArgs = contextArgs ; } $.ajax({ url : sSource , type : "post" , async : true , data : aoData , success : fnCallback , dataType: "json" , statusCode : { 401 : function(){ console.error("401:"+sSource) ; //location.href="/admin/login?statusCode=401&url="+sSource ; }, 404 : function(){ console.error("404:"+sSource) ; }, 500 : function(){ console.error("500:"+sSource) ; }, 408 : function(){ console.error("408:"+sSource) ; //location.href=G_CTX_ROOT+"/login?statusCode=408&url="+sSource ; }, }, }); loadFirst = false ; $("#selfFlag").val("1"); }, paseStatus: function( data , status , fnCallback ){ } , }; win.util = postDT ; })(window) ; $(".hide-tab-panel").show(); $('.slide-tab li.active').addClass("selected1"); $(".slide-tab li.active").click(function(){ $(".hide-tab-panel").slideToggle("fast"); $(this).toggleClass("selected1"); }); /** * DataTable Setting */ //DataTable language setting (function(win){ var lan = { "sLengthMenu": "每页显示 _MENU_ 条记录", "sZeroRecords": "没有检索到数据", "sInfo": "共有 _TOTAL_ 条记录", "sInfoEmtpy": "没有数据", "sProcessing": "<img src='"+G_CTX_ROOT+"/staticAdmin/img/lding.gif'/>", "search" : "查询" , "sInfoEmpty": "共 0 条记录", "bStateSave": false, "oPaginate": { "sFirst": "首页", "sPrevious": "上一页", "sNext": "下一页", "sLast": "尾页" } }; var setting = {} ; setting.iDisplayLength = 10; setting.oLanguage = lan ; //语言设置 setting.bPaginate = true ; //是否分页。 setting.sPaginationType = "bootstrap" ; //全分页 setting.bJQueryUI = false ; //jQueryUI setting.bAutoWidth = true ; //自动计算Table宽度 setting.bProcessing = true ; //当datatable获取数据时候是否显示正在处理提示信息。 setting.sServerMethod = "POST"; setting.bServerSide = true ; setting.bFilter = false; setting.bStateSave = true ; //setting.sDom="<t<'span12 center'p>>"; setting.aLengthMenu = [[10, 25, 50,1], [10, 25, 50,1]] ; setting.callbackStack = { stack : [] , }; setting.callbackStack.stack.push( function(){ $.checkCasecade({ parent : "checkbox-checkall" , children : "item-checkbox" }); } ); setting.fnDrawCallback = function(){ for(var callback in setting.callbackStack.stack ){ setting.callbackStack.stack[callback]() ; } $("#datatable_tabletools tr:last-child").css("border-bottom","1px solid #CCCCCC"); $("body").removeAttr("style"); }; setting.fnInitComplete = function(setting){ $("#datatable_tabletools").css("width","100%"); //$("#datatable_tabletools th").css("width","auto"); //$("#datatable_tabletools tr:last-child").css("border-bottom","1px solid #CCCCCC"); }; setting.fnRowCallback = function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ //$('tr', nRow).css("border-bottom","1px solid #CCCCCC"); //$("#datatable_tabletools tr:last-child").css("border-bottom","1px solid #CCCCCC"); }; setting.fnServerData = function( sSource , aoData , fnCallback ){ util.parseDT(sSource , aoData , fnCallback ) ; $('.checkbox-checkall').prop("checked",false); }; var dataTable ; win.setting = setting ; win.dataTable = dataTable ; })(window) ; /** * Modal Message Alert */ //Alert Modal (function(win){ var mAlert = function (bMsg , title , btnMsg ){ var bodyMsg = typeof(bMsg) == "undefined" || bMsg == "" ? "" : bMsg; var titleMsg = typeof(title) == "undefined" || title == "" ? "提示!" : title; var buttonMsg = typeof(btnMsg) == "undefined" || btnMsg == "" ? "关闭" : btnMsg; $("#alertModelLabel").html( titleMsg ) ; $("#lertModelBody").html( bodyMsg ) ; $("#lertModelBtnClose").html( buttonMsg ) ; $("#alertModal").modal("show"); }; win.mAlert = mAlert ; })(window); (function(win){ var mConfirm = function ( bMsg , callBack , title , btnClose , btnActive ){ var bodyMsg = typeof(bMsg) == "undefined" || bMsg == "" ? "" : bMsg; var titleMsg = typeof(title) == "undefined" || title == "" ? "提示!" : title; var btnCloseMsg = typeof(btnClose) == "undefined" || btnClose == "" ? "取消" : btnClose; var btnActiveMsg = typeof(btnActive) == "undefined" || btnActive == "" ? "确定" : btnActive; $("#confirmModelLabel").html( titleMsg ) ; $("#confirmModelBody").html( bodyMsg ) ; $("#confirmModelBtnClose").html( btnCloseMsg ) ; $("#confirmModelBtnActive").html( btnActiveMsg ) ; if( typeof(callBack) == "function" ){ $("#confirmModelBtnActive").unbind("click"); $("#confirmModelBtnActive").click(callBack) ; } $("#confirmModal").modal("show"); }; win.mConfirm = mConfirm ; })(window); (function(win){ var timer = "" ; var task = function(){ $("#success-box").addClass("hidden") ; $("#warning-box").addClass("hidden") ; }; var msgBox = function( type , body , title ){ if( type == "fail" ){ typeof( body ) != "undefined" ? $("#warning-box-body").text(body) : $("#warning-box-body").text("") ; typeof( title ) != "undefined" ? $("#warning-box-title").text(title) : $("#warning-box-title").text("警告!") ; $("#warning-box").removeClass("hidden") ; }else{ typeof( body ) != "undefined" ? $("#success-box-body").text(body) : $("#success-box-body").text("") ; typeof( title ) != "undefined" ? $("#success-box-title").text(title) : $("#success-box-title").text("提示!") ; $("#success-box").removeClass("hidden") ; } timer = setTimeout(task , 5000 ) ; }; $("#warning-box .close").html(""); $("#success-box .close").html(""); win.msgBox = msgBox ; })(window) ; /** * Ajax Invoke */ (function(jqeury){ var ajaxInvoke = function ( args ) { var url = args.url ; var enumType = ["get","GET","post","POST"]; var type = typeof( args.type ) != "undefined" && enumType.indexOf(args.type)!= -1? args.type : "post" ; var data = typeof( args.data ) != "undefined" ? args.data : "" ; var sync = typeof( args.sync ) != "boolean" ? true : args.sync ; var success = function(data){} ; if( typeof(args.success) == "string" ){ success = function(data , state){ mAlert( args.success ) ; }; }else if( typeof(args.success) == "function" ){ success = args.success ; }else{ success = function( data , status ){ if( data.msgType == 1 ){ msgBox( data.state , data.msg ) ; }else if( data.msgType == 0 ){ mAlert( data.msg ) ; } } ; } var error = null ; if(typeof(args.error) == "string"){ error = function(){ mAlert( args.error ) ; }; }else if( typeof( args.error ) == "function" ){ error = args.error ; }else{ error = function (data , status ) { /** if( status == "error" ){ mAlert("请求失败!"); }else if( status == "parsererror"){ mAlert("对象转换失败!"); } */ } ; } var enumDataType = ["html" , "json" ] ; var dataType = typeof( args.dataType ) != "undefined" && enumDataType.indexOf(args.dataType) != -1 ? args.dataType :"json" ; var contentType = typeof( args.contentType ) != "undefined" ? args.contentType : "application/x-www-form-urlencoded" ; $.ajax({ url : url , type : type , async : sync , data : data , success : success, error : error, statusCode : { 401 : function(){ console.error("401:"+url) ; //location.href="/admin/login?statusCode=401&url="+url ; }, 404 : function(){ console.error("404:"+url) ; //location.href="/admin/login?statusCode=404&url="+url ; }, 408 : function(){ console.error("408:"+url) ; //location.href=G_CTX_ROOT+"/login?statusCode=408&url="+url ; }, 500 : function(){ console.error("500:"+url) ; //location.href="/admin/login?statusCode=500&url="+url ; }, }, dataType: dataType , cache : false, contentType : contentType , }); }; jqeury.ajaxInvoke = ajaxInvoke ; })($); /** * Validator */ function DataValidator(){ this.rule = {} ; this.isBlur = true ; var required = function(field , active , message){ if( active == "false" ) return true ; var msg = message + "不能为空!" ; var val = $("#"+field).val() ; var bRtn = val!=null && typeof(val) != "undefined" && val.replace(/(^\s*)|(\s*$)/g,"") != "" ; setMsg(field , msg , bRtn ) ; return bRtn; }; var gt = function( field , number , message ){ if($("#"+field).val()=="")return true ; var msg = message + "长度大于等于"+number+"!" ; var val = $("#"+field).val() ; var bRtn = val.length >= parseInt( number ) ; setMsg(field , msg , bRtn ) ; return bRtn; } ; var lt = function( field , number , message ){ if($("#"+field).val()=="")return true ; var msg = message + "长度小于等于"+number+"!" ; var val = $("#"+field).val() ; var bRtn = val.length <= parseInt( number ) ; setMsg(field , msg , bRtn ) ; return bRtn; }; var email = function( field , active , message ){ if($("#"+field).val()=="")return true ; if( active == "false")return true ; var msg = message + "email格式不正确"+"!" ; var pattern=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/; var val = $("#"+field).val() ; var bRtn =pattern.test(val); setMsg(field , msg , bRtn ) ; return bRtn; }; var phone = function( field , active , message ){ if($("#"+field).val()=="")return true ; if( active == "false")return true ; var msg = message + "格式不正确"; //var isMobile=/^1[3|4|5|8][0-9]\d{4,8}$/; var isMobile=/^[0-9]{11}$/; var bRtn = isMobile.test($("#"+field).val()) ; setMsg(field , msg , bRtn ) ; return bRtn ; }; var isNum = function( field , active , message ){ if($("#"+field).val()=="")return true ; if( active == "false" ) return true ; var msg = message + "不是数字类型" ; var bRtn = !isNaN( $("#"+field).val()) ; setMsg(field , msg , bRtn ) ; return bRtn ; }; var notNum = function( field , active , message ){ if($("#"+field).val()=="")return true ; if( active == "false" ) return true ; var msg = message + "不能全部是数字" ; var bRtn = isNaN( $("#"+field).val()) ; setMsg(field , msg , bRtn ) ; return bRtn ; }; var eq = function( field , val , message ){ if($("#field").val() == "" ) return true ; var msg = message + "不一致" ; var bRtn = ($("#"+field).val() == $("#"+val).val()) ; setMsg( field , msg , bRtn ) ; return bRtn ; }; var fixLen = function( field , val , message ){ var msg = message + "长度应为"+ val + "位" ; var bRtn = ($("#"+field).val().length == val) ; setMsg( field , msg , bRtn ) ; return bRtn ; }; var setMsg = function( field , msg , b){ if(b){ $("#"+field).prevAll().filter("span").html("") ; return ; } $("#"+field).prevAll().filter("span").html("<font color=red >" +msg+ "</font>") ; }; this.clearForm = function(){ for( var field in this.rule ){ if( this.rule[field].defaultValue != "undefined" ){ $("#"+field).val( this.rule[field].defaultValue ) ; }else{ $("#"+field).val("") ; } setMsg( field , "" ) ; } }; var Callback = function(){ var blurCallbackStack = []; var focusCallbackStack = [] ; this.setBlurCallback = function(bcs){ blurCallbackStack = bcs ; }; this.setFocusCallback = function(fcs){ focusCallbackStack = fcs ; }; this.blureCallback = function(){ if( blurCallbackStack.length == 0 ) return false ; for( var bc in blurCallbackStack ){ if( typeof( blurCallbackStack[bc] ) == "function" ){ if(!blurCallbackStack[bc]() ) break; }else if( typeof(blurCallbackStack[bc]) == "string"){ if(!eval(blurCallbackStack[bc]))break ; } } }; this.focusCallback = function(){ if(focusCallbackStack.length == 0 ) return false ; for(var fc in focusCallbackStack ){ if( typeof(focusCallbackStack[fc]) == "function"){ if(!focusCallbackStack[fc]()) break ; }else if(typeof(focusCallbackStack[fc]) == "string"){ if(!eval(focusCallbackStack[fc]))break ; } } }; }; this.init = function( rule ){ this.rule = rule ; for( var r in rule ){ var blurCallbackStack = [] ; var focusCallbackStack = [] ; if(! document.getElementById(r)){ } var field = r ; var name = rule[r].name ; var ms = rule[r].method ; for( var m in ms ){ var func = m + "('" + field + "','" + ms[m]+"','" + name +"')" ; blurCallbackStack.push(func) ; } if( typeof( rule[r].onBlur ) == "function" ){ blurCallbackStack.push( rule[r].onBlur ); } if( typeof( rule[r].onFocus ) == "function" ){ focusCallbackStack.push( rule[r].onFocus ); } var callBackObj = new Callback() ; callBackObj.setBlurCallback(blurCallbackStack) ; callBackObj.setFocusCallback(focusCallbackStack) ; if(document.getElementById(r)){ document.getElementById(r).onblur = callBackObj.blureCallback ; document.getElementById(r).onfocus = callBackObj.focusCallback ; } } }; this.validate = function(){ var success = true ; for( var field in this.rule ){ var fieldSuccess = true; var msg = this.rule[field].name ; var vs = this.rule[field].method ; for( var m in vs ){ var func = m+"('"+field+"' , '"+vs[m]+"' , '"+ msg +"' )" ; if( !eval( func) ){ success = false ; fieldSuccess = false; break ; } } if(fieldSuccess){ $("#"+field).nextAll().filter("span").html("") ; } } return success ; }; } (function(win){win.validator = new DataValidator() ;})(window) ; /** * 省市区级联操作 * 使用方法 * * 方法描述 * load( parentId ) 根据parentId加载选项 * init 初始化控件 使用参数依次为 标签ID、ajaxSource、下一结点对象、默认第一行显示文字【key为-1】 * 使用方法 * var selCasecade = new SelectCasecade() ; * var selCity = new SelectCasecade() ; * var selArea = new SelectCasecade() ; * selCasecade.init("provence" ,"${ctx}/sysArea/findProvinces" , selCity , "请选择省" ).load() ; * selCity.init("city" ,"${ctx}/sysArea/findCities" , selArea , "请选择市") ; * selArea.init("area" , "${ctx}/sysArea/findAreas" ,"" , "请选择区" ) ; */ function SelectCasecade(){ var field ; var ajaxSource ; var nextNode ; var key ; var fillValue = "" ; var header ; var dataAllFlag = false ; var selectedIndex = 0 ; this.load = function( parentId , callback,nodeid,value ){ var url = ajaxSource ; if( parentId == "" ){ parentId = "-2" ; } if( typeof( parentId ) != "undefined" && parentId != "-1"){ url += "/" + parentId ; } $.ajaxInvoke({ url : url , type : "post" , dtaType : "json" , cache : false, data : { dataAllFlag : dataAllFlag , }, success : function( data , status ){ if( data.state == "fail" ){ mAlert( data.msg ) ; }else{ initOption( data.data ) ; if( typeof(fillValue)!="undefined" && fillValue!="" ){ $("#"+field).val(fillValue) ; } if( selectedIndex != 0 && selectedIndex < $("#"+field).get(0).length ){ $("#"+field).get(0).selectedIndex = selectedIndex ; } if( $("#"+field).attr("preVal") && $("#"+field).attr("preVal")!= "" ){ $("#"+field).val($("#"+field).attr("preVal")) ; } selectedIndex = 0 ; if( typeof( nextNode ) == "object"){ childNodeLoad() ; } } }, sync : false }); if(typeof( callback ) == "function"){ callback(); } }; this.setValue = function ( value ){ fillValue = value ; }; this.setSelectedIndex = function( index ){ selectedIndex = index ; }; this.setDataScopeAll = function( flag ){ if( typeof( flag ) == "boolean" ){ dataAllFlag = flag ; } }; var initOption = function( data ){ $("#"+field).empty() ; if( data.length != 1 ){ if( typeof( header ) != "undefined" ){ $("#"+field).append("<option value=''>"+header+"</option>") ; } } data.sort(function(a,b){ if(a && b){ return a.name.localeCompare(b.name) };//汉字拼音排序方法 }); for( i = 0 ; i < data.length ; i ++ ){ $("#"+field).append("<option value='"+data[i].id+"'>" +data[i].name+"</option>") ; } if( data.length == 1 && typeof(nextNode) == "object" ){ nextNode.load($("#"+field+" option:first").val()); } }; var childNodeLoad = function(){ nextNode.load( $("#"+field).val() ) ; }; this. init = function( argField , argAjaxSource , argNextNode , argHeader , argValue ){ if( typeof($("#"+argField).val()) == "undefined" ){ return this; } field = argField ; ajaxSource = argAjaxSource ; nextNode = argNextNode ; header = argHeader ; fillValue = argValue ; if( typeof(argNextNode) == "object"){ nextNode = argNextNode ; document.getElementById(field).onchange=childNodeLoad ; } $("#"+field).empty() ; if( typeof( header ) != "undefined" ){ $("#"+field).append("<option value=''>"+header+"</option>") ; } return this ; }; this.clearOption = function(){ $("#"+field).empty() ; if( typeof( header ) != "undefined" ){ $("#"+field).append("<option value=''>"+header+"</option>") ; } }; this.val = function(value){ if(typeof( value ) != "undefined"){ if( typeof(argNextNode) == "object"){ childNodeLoad() ; } return $("#"+field).val(value) ; }else{ return $("#"+field).val() ; } }; }; /** * $.checkCasecade({ parent : "checkbox-checkall" , children : "item-checkbox" }); */ (function(jquery){ var checkCasecade = function (arg){ var parent = arg.parent ; var children = arg.children ; gloParent = parent ; gloChildren = children ; $("."+parent).unbind("change").bind("change",function(){ changeChild( children , $(this).is(":checked") ) ; }); }; var changeChild = function( name , status ){ $("."+name).prop("checked" , status ); }; var checkValues = function( arg ){ var className = "item-checkbox"; if(typeof( arg ) != "undefined" ){ className = arg ; } var values = [] ; $("."+className).each(function(){ if($(this).is(":checked")){ values.push($(this).val()) ; } }); return values ; }; jquery.checkCasecade = checkCasecade ; jquery.checkedValues = checkValues ; })($) ; (function(){ if(self.frameElement && self.frameElement.tagName == "IFRAME") { document.body.style.overflow = "scroll" ; } })() ; /** * combox */ (function ( jquery ){ var funBox = function( arg ){ var combox = { arg : { size : 10 , }, data : { }, init : function( arg ){ if( typeof(arg.url) == "string" && arg.url != "" ){ combox.arg.url = arg.url ; }else{ console.error("arg.url is undefined") ; return ; } if( typeof(arg.size) == "number" ){ combox.arg.size = arg.size ; } if( typeof( arg.key ) == "string" && arg.key != "" ){ combox.arg.key = arg.key ; }else{ console.error("arg.key is undefined") ; return ; } if( typeof( arg.value ) == "string" && arg.value != "" ){ combox.arg.value = arg.value ; }else{ console.error("arg.value is undefined") ; return ; } if( typeof( arg.field ) == "string" && arg.field != "" ){ combox.arg.field = arg.field ; }else{ console.error("arg.field is undefined") ; return ; } if( typeof(arg.callBack) == "function" ){ combox.callBack = arg.callBack ; } if( typeof( arg.callbackField ) == "string" && arg.key != "" ){ combox.arg.callbackField = arg.callbackField ; } if( typeof( arg.blurCallback ) == "function" ){ combox.arg.blurCallback = arg.blurCallback ; $("#"+combox.arg.field).blur(function(){ arg.blurCallback() ; }); } $("#"+combox.arg.field).keyup(combox.loadData) ; $("#"+combox.arg.field).click(function(){ $('#'+combox.arg.field).next("ul").toggle() ; if($('#'+combox.arg.field).css("display")!="none"){ combox.loadData() ; } }); $("#"+combox.arg.field).blur(function(){ setTimeout(function(){ $('#'+combox.arg.field).next("ul").hide() ; },300); }); $('#'+combox.arg.field).next("ul").css("width" , $('#'+combox.arg.field).css('width')); return combox ; }, loadData: function(){ var value = $("#"+combox.arg.field).val() ; if( value == combox.oldValue ){ return ; } combox.selectedValue.inputBody = value ; combox.selectedValue.value ="" ; combox.selectedValue.text = "" ; if( typeof(combox.callBack) == "function" ){ (combox.callBack)(combox.selectedValue.value, combox.arg.callbackField) ; } $('#'+combox.arg.field).next('ul').empty() ; if( typeof(value) == "undefined" ) return ; value = value.replace(/(^\s+)|(\s+$)/g,""); if( value == "" ){ $('#'+combox.arg.field).attr("val", value); //return ; } url = combox.arg.url ; $.ajaxInvoke({ url : url, data : { args : value , }, success : function( content , status ){ var data = content.data ; if(data == null){ $('#'+combox.arg.field).next('ul').hide() ; return ; } var count = 0 ; for( var d in data ){ var areaId = data[d]['areaId'] ; var cityId = data[d]['cityId'] ; var provinceId = data[d]['provinceId'] ; var text = data[d][combox.arg.value] + "-" + areaId ; $('#'+combox.arg.field).next('ul').append("<li><a title='"+(text+"-" + cityId +"-" + provinceId)+"' href=\"javascript:$."+combox.arg.field+".fixOpt('"+data[d][combox.arg.key]+"' , '"+data[d][combox.arg.value]+"')\">"+text+"</a></li>") ; if( ++ count >= combox.arg.size){ break ; } } $('#'+combox.arg.field).next('ul').show() ; } }); }, fixOpt : function(value , text){ if( typeof( value ) != "undefined" ){ combox.selectedValue.value = value ; $('#'+combox.arg.field).attr("val", value); if($('#'+combox.arg.field).next('ul').next('span')){ $('#'+combox.arg.field).next('ul').next('span').html(''); } } if( typeof( value ) != "undefined" ){ combox.selectedValue.text = text ; $('#'+combox.arg.field).val(text) ; combox.oldValue = text; } $('#'+combox.arg.field).next("ul").hide() ; if( typeof(combox.callBack) == "function" ){ (combox.callBack)(value, combox.arg.callbackField) ; } }, selectedValue : { value : "" , text : "" , inputBody : "" , }, val : function( key ){ return combox.selectedValue[key] ; } }; return combox.init( arg ); }; jquery.combox = funBox ; })( $ ) ; function dynamicSelect(){ $(".ajaxDynamicData").each(function(){ var src = $(this).attr("ajaxSource") ; var key = $(this).attr("key"); var text = $(this).attr("text") ; if( src == "" || key =="" || text == "" ) return ; var obj = $(this) ; $.ajaxInvoke({ url : src , success : function( content ){ if(content.data == null){ return ; } var data = content.data ; for( var row in data ){ obj.append("<option value='"+data[row][key]+"'>"+data[row][text]+"</option>") ; } }, }); }); } ; ``` OrderDao.java ```package com.lebao.modules.order.dao; import com.lebao.bean.OrderSearchParam; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.modules.BaseDao; import com.lebao.modules.order.entity.OrderEntity; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.sql.SQLException; /** * Created by Server on 2016/4/5. */ @Repository public class OrderDao extends BaseDao{ @Resource(name = "dbHelper") private DbHelper dbHelper; private int pageSize = 10; private int pages = 0; public int addOrder(OrderEntity oe) throws SQLException { /* String p_id = Sequence.nextId(); String p_user_id = oe.getP_user_id(); String p_product_id = oe.getP_product_id(); String p_account = oe.getP_account(); String p_password = oe.getP_password(); Float p_price = oe.getP_price(); Integer p_num = oe.getP_num(); Integer p_state = oe.getP_state(); Timestamp p_create_time = oe.getP_create_time(); //timestamp NULL创建时间 String sql = "INSERT INTO t_order(p_id,p_user_id,p_product_id,p_account,p_password,p_price,p_num,p_state,p_create_time) VALUES(?,?,?,?,?,?,?,?,?)"; return dbHelper.execute(sql, p_id, p_user_id, p_product_id, p_account, p_password, p_price, p_num, p_state, p_create_time); */ return 0; } public int deleteOrder(String p_id) throws SQLException { String sql = "update t_order set p_state = '-1' where p_id=?"; return dbHelper.execute(sql, p_id); } public int updateOrder(OrderEntity oe) throws SQLException { String p_id = oe.getP_id(); String p_state = oe.getP_status(); String p_update_time = oe.getP_update_time(); String sql = "update t_order set p_status=?,p_update_time=? where p_id=?"; return dbHelper.execute(sql, p_state, p_update_time, p_id); } public OrderEntity getOrderEntity(String p_id) throws SQLException { String sql = "select * from t_order where p_id=?"; return dbHelper.getBean(sql, OrderEntity.class, p_id); } /* SELECT t_user_base.p_user_name , t_order.* FROM t_order JOIN t_user_base ON t_user_base.p_id=t_order.p_user_id and t_user_base.p_user_name like '%z%' and t_order.p_order_id='1' */ public Page<OrderEntity> getOrderEntitys(OrderSearchParam s) throws SQLException { String sql = "SELECT t_order.* FROM t_order JOIN t_user_base ON t_user_base.p_id=t_order.p_user_id" ; if (StringUtils.isNotBlank(s.getUser_name())) { sql += " and t_user_base.p_user_name like '%" + s.getUser_name() + "%' "; } if (StringUtils.isNotBlank(s.getOrder_id())) { sql += " and t_order.p_id = '" + s.getOrder_id() + "' "; } if (StringUtils.isNotBlank(s.getUser_id())) { sql += " and t_order.p_user_id= '" + s.getUser_id() + "' "; } if (StringUtils.isNotBlank(s.getStatus())) { sql += " and t_order.p_status = '" + s.getStatus() + "' "; } // sql +=" order by t_order.p_create_time desc"; sql += " order by t_order." + s.getSortField() + " " + s.getSortType() + " "; return dbHelper.getPage(sql, OrderEntity.class, s.getCurPage(), s.getPageSize()); } } ``` user.js ```$(document) .ready( function () { setting.sAjaxSource = G_CTX_ROOT + "/user/query"; setting.aoColumns = [ { "sTitle": "<center>编号</center>", // 显示标题 "mData": "user_id", // 属性 "bSortable": true,// 排序 "sClass": "center", "sWidth": "2%" }, { "sTitle": "<center>姓名</center>", // 显示标题 "mData": "name", // 属性 "bSortable": false,// 排序 "sClass": "center", "sWidth": "2%" }, { "sTitle": "<center>电话</center>", // 显示标题 "mData": "phone", // 属性 "bSortable": false,// 排序 "sClass": "center", "sWidth": "2%" }, { "sTitle": "<center>操作</center>", // 显示标题 "bSortable": false,// 排序 "mData": "user_id", // 属性 "sClass": "center", "sWidth": "5%", "mRender": function (data, style, obj) { var xgDom = "<a class=\"btn btn-round btn-info btn-xs\" href=\"edit?module=user&action=update&id=" + obj.user_id + "\" >修改</a>"; var qrDom = "<button class=\"btn btn-round btn-primary btn-xs\" onclick=\"showQR('" + obj.qr + "')\" >二维码</button>"; var delDom = "<a class=\"btn btn-round btn-danger btn-xs\" onclick=\"preDel(" + obj.user_id + ")\" >删除</a>"; return qrDom + "&nbsp;" + xgDom + "&nbsp;" + delDom; } }]; setting.aaSorting = [[0, "desc"]]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); var rule = { m_phoneNumber: { name: "手机号码", method: { required: true, fixLen: 11, phone: true }, }, m_name: { name: "姓名", method: { required: true, lt: 10 } } }; validator.init(rule); }); function doSearch() { dataTable.fnDraw(); } /** * 展示二维码 * @param id */ function showQR(qr) { $("#qrModal").modal("show").css({ 'top': '60px' }); $("#qrTemp").html("<div style='border: 1px black'><a href='" + qr + "' target='_blank'><img src='" + qr + "' width='200' height='200'/></a></div>"); } function preDel(user_id) { $("#deleteModal").modal("show").css({ 'top': '60px' }); $("#deleteButton").attr("onClick", "del(" + user_id + ")"); } function del(user_id) { $.ajaxInvoke({ url: G_CTX_ROOT + "/user/delete/", type: "post", datatype: "json", data: { id: user_id }, success: function (data) { $("#deleteModal").modal("hide") msgBox(data.state, data.msg); dataTable.fnDraw(); }, }); } /** * Created by HQ on 2017/1/8. */ var p = ((function () { //返回当前 URL 的查询部分(问号 ? 之后的部分)。 var urlParameters = location.search; //声明并初始化接收请求参数的对象 var requestParameters = new Object(); //如果该求青中有请求的参数,则获取请求的参数,否则打印提示此请求没有请求的参数 if (urlParameters.indexOf('?') != -1) { //获取请求参数的字符串 var parameters = decodeURI(urlParameters.substr(1)); //将请求的参数以&分割中字符串数组 parameterArray = parameters.split('&'); //循环遍历,将请求的参数封装到请求参数的对象之中 for (var i = 0; i < parameterArray.length; i++) { requestParameters[parameterArray[i].split('=')[0]] = (parameterArray[i].split('=')[1]); } console.info('theRequest is =====', requestParameters); } else { console.info('There is no request parameters'); } return requestParameters; })()); console.log(p); function edit(action) { if (action === "save") { addUser(); console.log("save"); } else if (action === "update") { updateUser(); console.log("update"); } } function addUser() { var depart = []; $(".m_depart:checked").each(function () { depart.push(this.value); }); var user_image = $("#m_user_image").val(); var name = $("#m_name").val(); var sex = $("#m_sex").val(); var position = $("#m_position").val(); var edu = $("#m_edu").val(); var phoneNumber = $("#m_phoneNumber").val(); var remark = $("#m_remark").val(); if (!validator.validate()) return false; $.ajaxInvoke({ url: G_CTX_ROOT + "/user/save", type: "post", datatype: "json", data: { name: name, pic: user_image, sex: sex, eduLevel: edu, position: position, phone: phoneNumber, desc: remark, departmentIds: depart }, success: function (data) { $("#myModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } function updateUser() { var depart = []; $(".m_depart:checked").each(function () { depart.push(this.value); }); var id = $("#id").val(); var user_image = $("#m_user_image").val(); var name = $("#m_name").val(); var sex = $("#m_sex").val(); var position = $("#m_position").val(); var edu = $("#m_edu").val(); var phoneNumber = $("#m_phoneNumber").val(); var remark = $("#m_remark").val(); if (!validator.validate()) return false; $.ajaxInvoke({ url: G_CTX_ROOT + "/user/update", type: "post", datatype: "json", data: { id: id, name: name, pic: user_image, sex: sex, eduLevel: edu, position: position, phone: phoneNumber, desc: remark, departmentIds: depart }, success: function (data) { $("#myModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } ``` PositionService.java ```package com.lebao.service; import com.lebao.dao.user.PositionDao; import com.lebao.po.Department; import com.lebao.po.Position; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Author: zr * Date : 2016/12/6 18:13 */ @Service public class PositionService { @Autowired PositionDao positionDao; public Position findOne(Long id) { return positionDao.findOne(id); } public void save(Position position){ positionDao.save(position); } public List<Position> findAll(){ return positionDao.findAll(); } } ``` type.js ```$(document) .ready( function () { setting.sAjaxSource = G_CTX_ROOT + "/type/query"; setting.aoColumns = [ { "sTitle": "<center>类型编号</center>", //显示标题 "mData": "id", //属性 "bSortable": false,//排序 "sClass": "center", "sWidth": "3%" }, { "sTitle": "<center>类型名称</center>", //显示标题 "mData": "name", //属性 "bSortable": false,//排序 "sClass": "center", "sWidth": "3%" }, { "sTitle": "<center>状态</center>", //显示标题 "mData": "status", //属性 "bSortable": false,//排序 "sClass": "center", "sWidth": "1%" }, { "sTitle": "<center>操作</center>", // 显示标题 "bSortable": false,// 排序 "mData": "id", // 属性 "sClass": "center", "sWidth": "3%", "mRender": function (data, style, obj) { var xqDom = "<a class=\"btn btn-round btn-info btn-xs\" href=\"/type/preUpdate/" + obj.id + "\" >查看详情</a>"; var delDom = "<a class=\"btn btn-round btn-danger btn-xs\" onclick=\"preDel(" + obj.id + ")\" >下架</a>"; var reAddDom = "<a class=\"btn btn-round btn-danger btn-xs\" onclick=\"preReAdd(" + obj.id + ")\" >上架</a>"; return xqDom + "&nbsp;&nbsp;&nbsp;&nbsp;" + delDom + "&nbsp;&nbsp;&nbsp;&nbsp;"+ reAddDom; } }]; setting.aaSorting = [[3, "desc"]]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); var rule = { m_name: { name: "类型名称", method: { required: true } } }; validator.init(rule); }); function preReAdd(id) { $("#myModal2").modal("show").css({ 'top': '60px' }); $("#reAdd").attr("onClick", "reAdd(" + id + ")"); } function reAdd(id) { $.ajaxInvoke({ url: G_CTX_ROOT + "/type/reAdd/", type: "post", datatype: "json", data: { p_id: id }, success: function (data) { $("#myModal2").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } function doSearch() { dataTable.fnDraw(); } function addType() { var name = $("#m_name").val(); if (!validator.validate()) return false; $.ajaxInvoke({ url: G_CTX_ROOT + "/type/add", type: "post", datatype: "json", data: { p_name: name }, success: function (data) { msgBox(data.state, data.msg); } }); } function updType() { var id = $("#m_id").val(); var name = $("#m_name").val(); if (!validator.validate()) return false; $.ajaxInvoke({ url: G_CTX_ROOT + "/type/update", type: "post", datatype: "json", data: { p_id: id, p_name: name }, success: function (data) { msgBox(data.state, data.msg); } }); } function preDel(id) { $("#myModal").modal("show").css({ 'top': '60px' }); $("#del").attr("onClick", "del(" + id + ")"); } function del(id) { $.ajaxInvoke({ url: G_CTX_ROOT + "/type/delete/", type: "post", datatype: "json", data: { p_id: id }, success: function (data) { $("#myModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } ``` UserDepartmentRel.java ```package com.lebao.po; import javax.persistence.*; /** * Created by ZR on 2017/1/8. */ @Entity @Table(name="tb_user_department_rel") public class UserDepartmentRel { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private Long uid; private Long did; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUid() { return uid; } public void setUid(Long uid) { this.uid = uid; } public Long getDid() { return did; } public void setDid(Long did) { this.did = did; } public UserDepartmentRel(Long uid, Long did) { this.uid = uid; this.did = did; } public UserDepartmentRel() { } } ``` sysuser.js ```$(document) .ready( function () { setting.sAjaxSource = G_CTX_ROOT + "/sysUser/query"; setting.aoColumns = [ { "sTitle": "<center>编号</center>", // 显示标题 "mData": "user_id", // 属性 "bSortable": true,// 排序 "sClass": "center", "sWidth": "5%" }, { "sTitle": "<center>用户名</center>", // 显示标题 "mData": "name", // 属性 "bSortable": false,// 排序 "sClass": "center", "sWidth": "5%" }, { "sTitle": "<center>操作</center>", // 显示标题 "bSortable": false,// 排序 "mData": "user_id", // 属性 "sClass": "center", "sWidth": "2%", "mRender": function (data, style, obj) { // console.log(obj); var xqDom = "<a class=\"btn btn-round btn-info btn-xs\" onclick=\"preUpdate("+obj.user_id+")\" >修改</a>"; var delDom ="<a class=\"btn btn-round btn-danger btn-xs\" onclick=\"preDel("+obj.user_id+")\" >删除</a>"; return xqDom + "&nbsp;&nbsp;&nbsp;&nbsp;" + delDom; } }]; setting.aaSorting = [[0, "desc"]]; setting.bStateSave = false; dataTable = $('#datatable_tabletools').dataTable(setting); var rule = { m_name: { name: "用户名", method: { required: true, lt: 10 } }, m_password: { name: "密码", method: { required: true, gt: 8, lt: 18 } } }; validator.init(rule); }); /** * 查询 */ function doSearch() { dataTable.fnDraw(); } /** * 显示添加窗口 */ function preSave() { $("#m_name").val(""); $("#m_password").val(""); $("#saveModal").modal("show").css({ 'top': '60px' }); } /** * 发送添加请求 * @returns {boolean} */ function save() { var name = $("#m_name").val(); var password = $("#m_password").val(); if (!validator.validate()) return false; $.ajaxInvoke({ url: G_CTX_ROOT + "/sysUser/save", type: "post", datatype: "json", data: { name: name, password: password }, success: function (data) { $("#saveModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } /** * 显示更新窗口 * @param id */ function preUpdate(id) { var user_id=id; $.ajaxInvoke({ url: G_CTX_ROOT + "/sysUser/queryById", type: "post", datatype: "json", data: { id: id }, success: function (data) { var user=data; $("#m_name1").val(user.data.name); $("#m_password1").val(user.data.password); console.log(user); } }); $("#updateButton").replaceWith("<button type=\"button\" onclick=\"update("+user_id+")\" class=\"btn btn-info\" id=\"updateButton\">确认修改</button>"); $("#updateModal").modal("show").css({ 'top': '60px' }); } /** * 发送更新请求 * @param id */ function update(id) { var name = $("#m_name1").val(); var password = $("#m_password1").val(); console.log(id); $.ajaxInvoke({ url: G_CTX_ROOT + "/sysUser/update", type: "post", datatype: "json", data: { id:id, name: name, password: password }, success: function (data) { $("#updateModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); } /** * 显示删除窗口 */ function preDel(id) { $("#deleteButton").replaceWith("<button type=\"button\" onclick=\"del("+id+")\" class=\"btn btn-danger\" id=\"deleteButton\">确认删除</button>"); $("#deleteModal").modal("show").css({ 'top': '60px' }); } /** * 发送删除请求 * @param id */ function del(id) { $.ajaxInvoke({ url: G_CTX_ROOT + "/sysUser/delete", type: "post", datatype: "json", data: { id: id }, success: function (data) { $("#deleteModal").modal("hide"); msgBox(data.state, data.msg); dataTable.fnDraw(); } }); }``` NewsTypeDao.java ```package com.lebao.dao.newstype; import com.lebao.common.beans.SearchBean; import com.lebao.common.dbhelp.DbHelper; import com.lebao.common.dbhelp.page.Page; import com.lebao.po.NewsType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; @Repository public class NewsTypeDao { @Autowired NewsTypeRepo newsTypeRepo; @Autowired DbHelper dbHelper; public Page<NewsType> getPage(SearchBean searchBean) throws SQLException { String sql = " SELECT * from tb_newstype "; List<Object> list = new ArrayList<Object>(); Map<Object, Object> map = searchBean.getParamMap(); if (map.containsKey("name")) { sql += " and tb_newstype.name like ? "; list.add("%" + map.get("name") + "%"); } sql += " order by " + searchBean.getSortField() + " " + searchBean.getSortType() + " "; return dbHelper.getPage(sql, NewsType.class, searchBean.getCurrentPage(), searchBean.getPageSize(), list.toArray()); } public void save(NewsType newsType) { newsTypeRepo.save(newsType); } public void update(NewsType newsType) { newsTypeRepo.save(newsType); } public void delete(NewsType newsType) { newsTypeRepo.delete(newsType); } public NewsType findOne(Long id) { return newsTypeRepo.findOne(id); } public List<NewsType> findAll() throws SQLException{ String sql = " SELECT * from tb_newstype "; return dbHelper.getBeanList(sql,NewsType.class); } } ``` SearchParam.java ```package com.lebao.bean; public class SearchParam { private String name; private String id; private String phone; private String userName; private String account; private String time1; private String time2; private int pageSize = 15; private int pageNow = 0; private String sortField = "p_create_time"; private String sortType = "desc"; public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getPageNow() { return pageNow; } public void setPageNow(int pageNow) { this.pageNow = pageNow; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getSortField() { return sortField; } public void setSortField(String sortField) { this.sortField = sortField; } public String getSortType() { return sortType; } public void setSortType(String sortType) { this.sortType = sortType; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTime1() { return time1; } public void setTime1(String time1) { this.time1 = time1; } public String getTime2() { return time2; } public void setTime2(String time2) { this.time2 = time2; } } ``` ScoreRecordBean.java ```package com.lebao.bean; /** * Created by Server on 2016/7/5. */ public class ScoreRecordBean { private String p_id; private String p_user_id; private String p_user_name; private String p_order_user_name; private String p_order_user_id; private String p_point; private String p_point1; private String p_point2; private String p_create_time; private String p_order_id; private float p_order_price; public String getP_id() { return p_id; } public void setP_id(String p_id) { this.p_id = p_id; } public String getP_user_id() { return p_user_id; } public void setP_user_id(String p_user_id) { this.p_user_id = p_user_id; } public String getP_user_name() { return p_user_name; } public void setP_user_name(String p_user_name) { this.p_user_name = p_user_name; } public String getP_point() { return p_point; } public void setP_point(String p_point) { this.p_point = p_point; } public String getP_point1() { return p_point1; } public void setP_point1(String p_point1) { this.p_point1 = p_point1; } public String getP_point2() { return p_point2; } public void setP_point2(String p_point2) { this.p_point2 = p_point2; } public String getP_create_time() { return p_create_time; } public void setP_create_time(String p_create_time) { this.p_create_time = p_create_time; } public String getP_order_id() { return p_order_id; } public void setP_order_id(String p_order_id) { this.p_order_id = p_order_id; } public float getP_order_price() { return p_order_price; } public void setP_order_price(float p_order_price) { this.p_order_price = p_order_price; } public String getP_order_user_name() { return p_order_user_name; } public void setP_order_user_name(String p_order_user_name) { this.p_order_user_name = p_order_user_name; } public String getP_order_user_id() { return p_order_user_id; } public void setP_order_user_id(String p_order_user_id) { this.p_order_user_id = p_order_user_id; } @Override public String toString() { return "ScoreRecordBean{" + "p_id='" + p_id + '\'' + ", p_user_id='" + p_user_id + '\'' + ", p_user_name='" + p_user_name + '\'' + ", p_point='" + p_point + '\'' + ", p_point1='" + p_point1 + '\'' + ", p_point2='" + p_point2 + '\'' + ", p_create_time='" + p_create_time + '\'' + '}'; } } ``` UploadController.java ```package com.lebao.controller; import com.lebao.common.beans.UploadResult; import com.lebao.file.AppConfig; import com.lebao.file.UploadUtil; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.*; @Controller @RequestMapping(value = "/file") public class UploadController extends BaseController { @Autowired private AppConfig appConfig; @RequestMapping("/upload") @ResponseBody public String upload(MultipartFile uploadFile) { System.out.println("开始上传"); try { boolean result = false; //取得可上传的文件类型 // List<String> fileTypes = this.getAllowFiles(appConfig.IMAGE_ALLOW_TYPE); //获取文件名 String fileName = uploadFile.getOriginalFilename(); // 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名 String ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); // 对扩展名进行小写转换 ext = ext.toLowerCase(); /* //文件类型检查 if(!fileTypes.contains(ext)){ return UploadResult.fail("不是合法的格式"); } */ // 新的文件名 String newFileName = new SimpleDateFormat("yyyyMMddHHmmssms").format(new Date()) + (int) (Math.random() * 10000) + "." + ext; String imgFolderName = appConfig.NEWS_IMAGE_CONTENT; String floderName = new SimpleDateFormat("yyyyMMdd").format(new Date()); File file = this.creatFolder(imgFolderName, floderName, newFileName); String folderNameYear = floderName.substring(0, 4); String folderNameMonth = floderName.substring(4, 6); String folderNameDay = floderName.substring(6, 8); FileCopyUtils.copy(uploadFile.getInputStream(), new FileOutputStream(file)); String returnImgUrl = folderNameYear + "/" + folderNameMonth + "/" + folderNameDay + "/" + newFileName; returnImgUrl = returnImgUrl.replaceAll("\\\\", "/"); result = true; if (!result) { return UploadResult.fail("上传失败"); } return UploadResult.success(appConfig.ROOT+"/"+returnImgUrl); } catch (Exception e) { e.printStackTrace(); return UploadResult.fail("上传失败"); } } /** * 获取可以上传的文件类型 * @param allowFiles * @return */ public List<String> getAllowFiles(String allowFiles) { List<String> fileTypes = new ArrayList<String>(); String types[] = allowFiles.split(","); for (int i = 0; i < types.length; i++) { String type=types[i].toLowerCase(); fileTypes.add(type); } return fileTypes; } /** * 创建文件夹 * * @param imgFolderName * 图片存储路径 * @param folderName * 二级文件夹 * @param fileName * 文件名 * @return */ public File creatFolder(String imgFolderName, String folderName, String fileName) { File file = null; // imgFolderName = imgFolderName.replaceAll("/", ""); //去掉"/" imgFolderName = imgFolderName.replaceAll(" ", ""); // 替换半角空格 imgFolderName = imgFolderName.replaceAll(" ", ""); // 替换全角空格 // folderName = folderName.replaceAll("/", ""); //去掉"/" folderName = folderName.replaceAll(" ", ""); // 替换半角空格 folderName = folderName.replaceAll(" ", ""); // 替换全角空格 File firstFolder = new File(imgFolderName); // 一级文件夹 if (firstFolder.exists()) { // 如果一级文件夹存在,则检测二级文件夹 file = createSonFolder(firstFolder, folderName, fileName); } else { // 如果一级不存在,则创建一级文件夹 firstFolder.mkdir(); file = createSonFolder(firstFolder, folderName, fileName); } return file; } /** * 创建年月日三级文件夹 * * @param firstFolder * 根文件 * @param folderName * 年月日文件夹名 * @param fileName * 文件名 * @return */ public File createSonFolder(File firstFolder, String folderName, String fileName) { File file = null; String folderNameYear = folderName.substring(0, 4); String folderNameMonth = folderName.substring(4, 6); String folderNameDay = folderName.substring(6, 8); File yearFolder = new File(firstFolder, folderNameYear); if (yearFolder.exists()) { // 如果二级文件夹也存在,则创建文件 File monthFolder = new File(yearFolder, folderNameMonth); // 三级文件夹 if (monthFolder.exists()) { File dayFolder = new File(monthFolder, folderNameDay); // 四级文件夹 if (dayFolder.exists()) { file = new File(dayFolder, fileName); } else { dayFolder.mkdir(); file = new File(dayFolder, fileName); } } else { monthFolder.mkdir(); File dayFolder = new File(monthFolder, folderNameDay); if (dayFolder.exists()) { file = new File(dayFolder, fileName); } else { dayFolder.mkdir(); file = new File(dayFolder, fileName); } } } else { // 如果二级文件夹不存在,则创建二级文件夹 yearFolder.mkdir(); // 创建完二级文件夹后,再合建文件 File monthFolder = new File(yearFolder, folderNameMonth); if (monthFolder.exists()) { File dayFolder = new File(monthFolder, folderNameDay); if (dayFolder.exists()) { file = new File(dayFolder, fileName); } else { dayFolder.mkdir(); file = new File(dayFolder, fileName); } } else { monthFolder.mkdir(); File dayFolder = new File(monthFolder, folderNameDay); if (dayFolder.exists()) { file = new File(dayFolder, fileName); } else { dayFolder.mkdir(); file = new File(dayFolder, fileName); } } } return file; } } ```
zhongzishi/cohort-project
zhongzishi/cohort-project 03_face_recognition_w_google_texttospeech.py ```'''' Real Time Face Recogition ==> Each face stored on dataset/ dir, should have a unique numeric integer ID as 1, 2, 3, etc ==> LBPH computed model (trained faces) should be on trainer/ dir Based on original code by Anirban Kar: https://github.com/thecodacus/Face-Recognition Developed by Marcelo Rovai - MJRoBot.org @ 21Feb18 ''' import cv2 import os #from playsound import playsound from google.cloud import texttospeech import vlc os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/Users/zishi.zhong/Documents/json/tm-datastore-62ed021e8e3b.json" client = texttospeech.TextToSpeechClient() if not os.path.exists("mp3"): os.mkdir("mp3") recognizer = cv2.face.LBPHFaceRecognizer_create() recognizer.read('trainer/trainer.yml') cascadePath = "haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascadePath); font = cv2.FONT_HERSHEY_SIMPLEX #iniciate id counter id = 0 # names related to ids: example ==> Marcelo: id=1, etc names = ['None', 'Zishi', 'JP'] #mp3s = {"None":"sound0.mp3","Zishi":"sound1.mp3","Ali":"sound2.mp3"} speeches = {"None":"text0","Zishi":"Les quelque 1800 employés de soutien syndiqués de l'Université du Québec à Montréal (UQAM) mèneront mercredi une deuxième journée de grève d’affilée, en cette semaine de rentrée universitaire.","JP":"Un investissement de 107 millions de dollars pour développer le transport de marchandises à l’aéroport de Mirabel a été officiellement annoncé par le ministre fédéral des Transports, Marc Garneau, et par Aéroports de Montréal (ADM), mardi matin."} # Initialize and start realtime video capture cam = cv2.VideoCapture(0) cam.set(3, 640) # set video widht cam.set(4, 480) # set video height # Define min window size to be recognized as a face minW = 0.1*cam.get(3) minH = 0.1*cam.get(4) identification = None user_id = None while identification == None: ret, img =cam.read() #img = cv2.flip(img, -1) # Flip vertically gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor = 1.2, minNeighbors = 5, minSize = (int(minW), int(minH)), ) for(x,y,w,h) in faces: cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2) id, confidence = recognizer.predict(gray[y:y+h,x:x+w]) # Check if confidence is less them 100 ==> "0" is perfect match if (confidence < 100): id = names[id] confidence_display = " {0}%".format(round(100 - confidence)) else: id = "unknown" confidence_display = " {0}%".format(round(100 - confidence)) cv2.putText(img, str(id), (x+5,y-5), font, 1, (255,255,255), 2) cv2.putText(img, str(confidence_display), (x+5,y+h-5), font, 1, (255,255,0), 1) if round(100 - confidence) > 50 and confidence < 100: identification = True #playsound(mp3s.get(user_id)) synthesis_input = texttospeech.types.SynthesisInput(text=speeches.get(id)) voice = texttospeech.types.VoiceSelectionParams( language_code='fr-CA', ssml_gender=texttospeech.enums.SsmlVoiceGender.NEUTRAL) audio_config = texttospeech.types.AudioConfig( audio_encoding=texttospeech.enums.AudioEncoding.MP3) response = client.synthesize_speech(synthesis_input, voice, audio_config) mp3filepath = "mp3/"+id+".mp3" with open(mp3filepath, 'wb') as out: out.write(response.audio_content) vlc.MediaPlayer(mp3filepath).play() break cv2.imshow('camera',img) k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video if k == 27: break # Do a bit of cleanup print("\n [INFO] Exiting Program and cleanup stuff") cam.release() cv2.destroyAllWindows() ```
zhoudian64/what-to-eat
zhoudian64/what-to-eat README.MD ```# what-to-eat SHU 本科课程数据挖掘课程数据处理部分。 数据库使用PGSQL。``` db.sql ```create table if not exists "user" ( id serial not null constraint user_pk primary key, user_name text not null, average_rate double precision ); alter table "user" owner to postgres; create unique index if not exists user_id_uindex on "user" (id); create table if not exists item ( id serial not null constraint item_pk primary key, item_name text not null, average_rate double precision ); alter table item owner to postgres; create unique index if not exists item_id_uindex on item (id); create table if not exists bill ( id serial not null constraint bill_pk primary key, user_id integer not null constraint bill_user_id_fk references "user", item_id integer not null constraint bill_item_id_fk references item, rate double precision not null ); alter table bill owner to postgres; create unique index if not exists bill_id_uindex on bill (id); ``` data.py ```import asyncpg import asyncio from math import sqrt async def get_db(): """ 连接数据库 :return: 数据库对象 """ db = await asyncpg.connect("postgresql://postgres:123456@127.0.0.1:5432/homework") return db async def return_db(db: asyncpg.connection.Connection): await db.close() async def get_all_users(): db = await get_db() user_id_list = [] users_sql = "SELECT id FROM \"user\"" users = await db.fetch( users_sql ) for user in users: user_id_list.append(user['id']) print("get all users", user_id_list) await return_db(db) return user_id_list async def get_user_rate_sum(user_id): """ 获得用户评分和 :return: 评分和: number """ db = await get_db() sum_sql = "SELECT sum(rate) FROM bill WHERE user_id = " + str(user_id) sum_rate = await db.fetch( sum_sql ) await return_db(db) print("get user_id:", user_id, "rate sum:", sum_rate[0]['sum']) return sum_rate[0]['sum'] async def get_user_squared_rate_sum(user_id): """ 获得用户评分方和 :return: 评分方和: number """ db = await get_db() squared_rate_sql = "SELECT sum(rate * rate) FROM bill WHERE user_id = " + str(user_id) squared_rate_sum = await db.fetch( squared_rate_sql ) await return_db(db) print("get user_id:", user_id, "squared rate sum:", squared_rate_sum[0]['sum']) return squared_rate_sum[0]['sum'] async def get_both_rate_sum(user_1_id, user_2_id): rate_sum = 0 for item in await get_both_bought(user_1_id, user_2_id): rate_sum += await get_user_item_avg_rate(user_1_id, str(item)) + await get_user_item_avg_rate(user_2_id, str(item)) print("user_id:", user_1_id, "user_id:", user_2_id, "both rate sum:", rate_sum) return rate_sum async def get_user_item_avg_rate(user_id, item_id): """ 获得用户对某物体的平均分 :param user_id: string :param item_id: string :return: 平均分: number """ db = await get_db() avg_rate_sql = "SELECT avg(rate) FROM bill WHERE user_id = " + str(user_id) + " AND item_id = " + str(item_id) rate = await db.fetch( avg_rate_sql ) print(user_id, "rate items avg:", item_id, rate[0]['avg']) await return_db(db) return rate[0]['avg'] async def get_item_user_bought(user_id): """ 获得用户所有评价过的物体 :param user_id: string :return: 物体集合: set(item_id: number) """ db = await get_db() get_item_id = "SELECT DISTINCT item_id FROM bill WHERE user_id = " + str(user_id) item_set = set() items = await db.fetch( get_item_id ) for item in items: item_set.add(item['item_id']) print(user_id, "rated", item_set) await return_db(db) return item_set async def get_both_bought(user_1_id, user_2_id): """ 获得两个用户都买过的物体集合 :param user_1_id: :param user_2_id: :return: 物体集合: set(item_id: number) """ item_user_1_bought = await get_item_user_bought(user_1_id) item_user_2_bought = await get_item_user_bought(user_2_id) bought_set = item_user_1_bought & item_user_2_bought print(user_1_id, user_2_id, "both bought", bought_set) return bought_set async def user_similarity_score(user_1_id, user_2_id): """ 获得两个用户的相似度分数 :param user_1_id: string :param user_2_id: string :return: 用户相似度[0,1] """ both_bought = await get_both_bought(user_1_id, user_2_id) if both_bought == set(): print(user_1_id, user_2_id, "similarity score:", 0) return 0 euclid_distance_list = list() for item_id in both_bought: user_1_rate = await get_user_item_avg_rate(user_1_id, str(item_id)) user_2_rate = await get_user_item_avg_rate(user_2_id, str(item_id)) euclid_distance_list.append(euclid_distance(user_1_rate, user_2_rate)) sum_euclid_distance = sum(euclid_distance_list) score = 1 / (1 + sqrt(sum_euclid_distance)) print("user_1_id:", user_1_id, "&user_2_id", user_2_id, "similarity score:", score) return score async def user_correlation(user_1_id, user_2_id): """ 评价用户相关度 :param user_1_id: :param user_2_id: :return: 用户相关度: number """ both_bought_count = len(await get_both_bought(user_1_id, user_2_id)) if both_bought_count == 0: return 0 numerator = await get_both_rate_sum(user_1_id, user_2_id) - ( await get_user_rate_sum(user_1_id) * await get_user_rate_sum(user_2_id) / both_bought_count ) denominator = sqrt((await get_user_squared_rate_sum(user_1_id) - pow(await get_user_rate_sum(user_1_id), 2)) * (await get_user_squared_rate_sum(user_2_id) - pow(await get_user_rate_sum(user_2_id), 2))) if denominator == 0: return 0 else: return numerator / denominator async def get_similar_users(user_id): """ 获得最相似用户 :param user_id: :return: 最相似用户id: string """ all_users = await get_all_users() correlations = [(await user_correlation(user_id, user_id2), user_id2) for user_id2 in all_users if user_id2 != user_id] correlations.sort() correlations.reverse() return correlations[:] async def recommand(user_id): """ 给用户推荐最相似用户 首先推荐 用户 没 有的 相似用户 有 的,增加数据量和用户满意度 第二推荐 用户 没 有的 相似用户也 没有 的,增加数据量,防止用户过于相似(数据量够大时取消此操作) 第三推荐 用户 有的,增加用户满意度 :param user_id: :return: """ db = await get_db() item_bought = await get_item_user_bought(user_id) similar_users = await get_similar_users(user_id) items_similar_users_bought = {} for user in similar_users: item_similar_user_bought = await get_item_user_bought(user[1]) items_similar_users_bought[user] = item_similar_user_bought print(items_similar_users_bought) await return_db(db) def euclid_distance(value1, value2): """ 欧几里得距离 :param value1: :param value2: :return: """ return pow(value1 - value2, 2) async def get_all_bill(): db = await get_db() sql = "SELECT * FROM bill" form = await db.fetch(sql) await return_db(db) print(form) if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(get_item_user_bought('1')) asyncio.get_event_loop().run_until_complete(get_user_item_avg_rate('1', '1')) asyncio.get_event_loop().run_until_complete(get_all_bill()) asyncio.get_event_loop().run_until_complete(user_similarity_score('1', '4')) asyncio.get_event_loop().run_until_complete(recommand('6')) ```
zhoufanyi/-507F17_Final_Project
zhoufanyi/-507F17_Final_Project SI507F17_finalproject.py ```from bs4 import BeautifulSoup import requests import os from datetime import timedelta import psycopg2 import psycopg2.extras from psycopg2 import sql import sys from config import * from flask import Flask, request, render_template import matplotlib.pyplot as plt from io import BytesIO import base64 BASE_URL = 'https://sports.yahoo.com' PATH = os.getcwd() ##----------------------------------Caching System---------------------------## def get_html(title, html = None, directory = None,update = False): if directory: path = os.path.join(PATH,directory) else: path =PATH if not os.path.exists(path): os.makedirs(directory) if update and os.path.exists(os.path.join(path ,title+'.html')): os.remove(os.path.join(path ,title+'.html')) try: f = open(os.path.join(path ,title+'.html'),'r',encoding = 'utf-8') page = f.read() f.close() except: page = requests.get(html).text f = open(os.path.join(path ,title+'.html'),'w',encoding='utf-8') f.write(page) f.close() return page def team_html_generator(Base,directory,update = False): Base_Web_soup =BeautifulSoup(Base,'html.parser') for item in Base_Web_soup.find_all('li',{'class':"Lh(30px) Fz(14px)"}): information = item.find('a') link = BASE_URL+information['href'] team = information.find('span').text.strip() title = team.replace(' ','_') team_html = get_html(title,link,directory = directory,update = update) yield team, team_html def strip_multi_tag(all_soup,tag): for item in all_soup.find_all(tag): yield item.text.strip() def get_player_stat(html_page): players_list = [] stats_name = [] player_table_soup = BeautifulSoup(html_page,'html.parser').find('table',{'class':'table stats-table W(100%) Ta(start) Lh(2) Bdcl(c)'}) if player_table_soup: for item in player_table_soup.find_all('th',{'class':'P(0px) Cur(p)'}): if 'title' in item.find('div').attrs.keys(): stats_name.append(item.find('div')['title']) else: stats_name.append(item.find('div').text.strip()) for player in player_table_soup.find_all('tr',{'class':'Px(cell-padding-x) Py(cell-padding-y) Bdb(row-border) Va(m) Ta(start)'}): stat = list(strip_multi_tag(player,'td')) stats_dict = dict(zip(stats_name,stat)) players_list.append(stats_dict) return players_list def get_team_stat(html_page): team_list = [] stats_name = [] team_table_soup = BeautifulSoup(html_page,'html.parser').find('table',{'class':'table graph-table W(100%) Ta(start) Bdcl(c) Mb(20px) Ov(h)'}) if team_table_soup: for item in team_table_soup.find('thead').find_all('th'): stats_name.append(item['title']) for team in team_table_soup.find('tbody').find_all('tr'): stat = list(strip_multi_tag(team,'td')) stats_dict = dict(zip(stats_name,stat)) team_list.append(stats_dict) return team_list #---------------------------class player-----------------------------------# class Player: def __init__(self,player_dict,team): self.Player = player_dict['Player'] self.Team = team self.Games = int(player_dict['Games']) self.Minutes_Played = player_dict['Minutes Played'] self.Field_Goals_Attempted = float(player_dict['Field Goals Attempted']) self.Field_Goals_Made = float(player_dict['Field Goals Made']) self.Field_Goal_Percentage = float(player_dict['Field Goal Percentage']) self.Free_Throws_Attempted = float(player_dict['Free Throws Attempted']) self.Free_Throws_Made = float(player_dict['Free Throws Made']) self.Free_Throw_Percentage = float(player_dict['Free Throw Percentage']) self.Three_point_Shots_Attemped = float(player_dict['3-point Shots Attemped']) self.Three_point_Shots_Made = float(player_dict['3-point Shots Made']) self.Three_point_Percentage = float(player_dict['3-point Percentage']) self.Points_Scored = float(player_dict['Points Scored']) self.Offensive_Rebounds = float(player_dict['Offensive Rebounds']) self.Defensive_Rebounds = float(player_dict['Defensive Rebounds']) self.Total_Rebounds = float(player_dict['Total Rebounds']) self.Assists = float(player_dict['Assists']) self.Steals = float(player_dict['Steals']) self.Blocked_Shots = float(player_dict['Blocked Shots']) self.Turnovers = float(player_dict['Turnovers']) self.Personal_Fouls = float(player_dict['Personal Fouls']) def get_average_dict(self): avg_minutes = int(self.Minutes_Played.split(':')[0]) avg_seconds = int(self.Minutes_Played.split(':')[1]) total_time = (timedelta(minutes = avg_minutes, seconds = avg_seconds)).total_seconds() hours = 0 minutes = int(total_time/60) seconds = int(total_time-minutes*60) return {'Player': self.Player, 'Team': self.Team, 'Games':self.Games, 'Minutes Played':'{'+'{}h {}m {}s'.format(hours,minutes,seconds)+'}', 'Field Goals Attempted': self.Field_Goals_Attempted, 'Field Goals Made': self.Field_Goals_Made, 'Field Goal Percentage': self.Field_Goal_Percentage, 'Free Throws Attempted': self.Free_Throws_Attempted, 'Free Throws Made': self.Free_Throws_Made, 'Free Throw Percentage': self.Free_Throw_Percentage, '3PT Shots Attemped': self.Three_point_Shots_Attemped, '3PT Shots Made': self.Three_point_Shots_Made, '3PT Percentage': self.Three_point_Percentage, 'Points Scored': self.Points_Scored, 'Offensive Rebounds': self.Offensive_Rebounds, 'Defensive Rebounds': self.Defensive_Rebounds, 'Rebounds': self.Total_Rebounds, 'Assists': self.Assists, 'Steals': self.Steals, 'Blocked Shots': self.Blocked_Shots, 'Turnovers': self.Turnovers, 'Personal Fouls': self.Personal_Fouls } def get_total_dict(self): avg_minutes = int(self.Minutes_Played.split(':')[0]) avg_seconds = int(self.Minutes_Played.split(':')[1]) total_time = (timedelta(minutes = avg_minutes, seconds = avg_seconds)*self.Games).total_seconds() hours = int(total_time/3600) minutes = int((total_time-hours*3600)/60) seconds = int(total_time-hours*3600-minutes*60) return{'Player': self.Player, 'Team': self.Team, 'Games':self.Games, 'Minutes Played':'{'+'{}h {}m {}s'.format(hours,minutes,seconds)+'}', 'Field Goals Attempted':int(self.Field_Goals_Attempted*self.Games), 'Field Goals Made':int(self.Field_Goals_Made*self.Games), 'Free Throws Attempted':int(self.Free_Throws_Attempted*self.Games), 'Free Throws Made':int(self.Free_Throws_Made*self.Games), '3PT Shots Attemped':int(self.Three_point_Shots_Attemped*self.Games), '3PT Shots Made':int(self.Three_point_Shots_Made*self.Games), 'Points Scored':int(self.Points_Scored*self.Games), 'Offensive Rebounds':int(self.Offensive_Rebounds*self.Games), 'Defensive Rebounds':int(self.Defensive_Rebounds*self.Games), 'Rebounds':int(self.Total_Rebounds*self.Games), 'Assists':int(self.Assists*self.Games), 'Steals':int(self.Steals*self.Games), 'Blocked Shots':int(self.Blocked_Shots*self.Games), 'Turnovers':int(self.Turnovers*self.Games), 'Personal Fouls':int(self.Personal_Fouls*self.Games) } def __str__(self): return '{} plays {} games for {} this season with averge {} points, {} Rebounds and {} Assists.'.format(self.Player,self.Games,self.Team,self.Points_Scored, self.Total_Rebounds, self.Assists) def __contains__(self,minutes): time_minutes = timedelta(minutes = minutes) avg_minutes = int(self.Minutes_Played.split(':')[0]) avg_seconds = int(self.Minutes_Played.split(':')[1]) total_time = timedelta(minutes = avg_minutes, seconds = avg_seconds) return total_time > time_minutes ##------------------------class team------------------------------## class team: def __init__(self,stats_dict): self.team_stats = stats_dict def get_team_stat(self): return self.team_stats class team_defence(team): def __init__(self,stats_dict): super().__init__(stats_dict) @classmethod def process_dict(cls,defence_dict): stats_dict ={'Team': defence_dict['Team'], 'Field Goals Made': defence_dict['Field Goals Allowed Per Game'], 'Field Goal Attempts': defence_dict['Field Goal Attempts Allowed Per Game'], 'Field Goal Percentage': defence_dict['Field Goal Percentage Allowed'], '3PT Made': defence_dict['Three-Points Allowed Per Game'], '3PT Attempts': defence_dict['Three-Point Attempts Allowed Per Game'], '3PT Percentage': defence_dict['Three-Point Percentage Allowed'], 'Free Throws Made': defence_dict['Free Throws Allowed Per Game'], 'Free Throw Attempts': defence_dict['Free Throw Attempts Allowed Per Game'], 'Free Throw Percentage': defence_dict['Free Throw Percentage Allowed'], 'Offensive Rebounds': defence_dict['Offensive Rebounds Allowed Per Game'], 'Defensive Rebounds': defence_dict['Defensive Rebounds Allowed Per Game'], 'Total Rebounds': defence_dict['Total Rebounds Allowed Per Game'], 'Assists': defence_dict['Assists Allowed Per Game'], 'Turnover': defence_dict['Turnovers Forced Per Game'], 'Steal': defence_dict['Steals Forced Per Game'], 'Blocked Shots': defence_dict['Blocked Shots Allowed Per Game'], 'Personal Fous': defence_dict['Personal Fouls Drawn Per Game'], 'Points': defence_dict['Points Allowed Per Game'] } return cls(stats_dict) def __str__(self): return '{} lets opponent get {} points this season with {}% field goal percentage and {}% three-points percentage.'.format(self.team_stats['Team'],self.team_stats['Points'],self.team_stats['Field Goal Percentage'],self.team_stats['3PT Percentage']) def __contains__(self,point): return float(self.team_stats['Points']) < point class team_offence(team): def __init__(self,stats_dict): super().__init__(stats_dict) @classmethod def process_dict(cls,offence_dict): stats_dict ={'Team': offence_dict['Team'], 'Field Goals Made': offence_dict['Field Goals Made Per Game'], 'Field Goal Attempts': offence_dict['Field Goal Attempts Per Game'], 'Field Goal Percentage': offence_dict['Field Goal Percentage'], '3PT Made': offence_dict['Three-Points Made Per Game'], '3PT Attempts': offence_dict['Three-Point Attempts Per Game'], '3PT Percentage': offence_dict['Three-Point Percentage'], 'Free Throws Made': offence_dict['Free Throws Made Per Game'], 'Free Throw Attempts': offence_dict['Free Throw Attempts Per Game'], 'Free Throw Percentage': offence_dict['Free Throw Percentage'], 'Offensive Rebounds': offence_dict['Offensive Rebounds Per Game'], 'Defensive Rebounds': offence_dict['Defensive Rebounds Per Game'], 'Total Rebounds': offence_dict['Total Rebounds Per Game'], 'Assists': offence_dict['Assists Per Game'], 'Turnover': offence_dict['Turnovers Per Game'], 'Steal': offence_dict['Steals Per Game'], 'Blocked Shots': offence_dict['Blocked Shots Per Game'], 'Personal Fous': offence_dict['Personal Fouls Per Game'], 'Points': offence_dict['Points Per Game'] } return cls(stats_dict) def __str__(self): return '{} scores {} points this season with {}% field goal percentage and {}% three-points percentage.'.format(self.team_stats['Team'],self.team_stats['Points'],self.team_stats['Field Goal Percentage'],self.team_stats['3PT Percentage']) def __contains__(self,point): return float(self.team_stats['Points']) > point ##------------------------Database-----------------------------------------## def get_connection_and_cursor(): global db_connection, db_cursor try: if not db_connection: if db_password != "": db_connection = psycopg2.connect(dbname = db_name,user=db_user,password = db_password) print("Success connecting to database") else: db_connection = psycopg2.connect(dbname = db_name,user=db_user) except: print("Unable to connect the database. Check the server and credentials.") sys.exit(1) if not db_cursor: db_cursor = db_connection.cursor(cursor_factory = psycopg2.extras.RealDictCursor) return db_connection, db_cursor def setup_database(): db_cursor.execute(""" CREATE TABLE IF NOT EXISTS "Team Offence Stats"( "Team" VARCHAR(60) PRIMARY KEY, "Field Goal Attempts" REAL NOT NULL, "Field Goals Made" REAL NOT NULL, "Field Goal Percentage" REAL NOT NULL, "Free Throw Attempts" REAL NOT NULL, "Free Throws Made" REAL NOT NULL, "Free Throw Percentage" REAL NOT NULL, "3PT Attempts" REAL NOT NULL, "3PT Made" REAL NOT NULL, "3PT Percentage" REAL NOT NULL, "Offensive Rebounds" REAL NOT NULL, "Defensive Rebounds" REAL NOT NULL, "Total Rebounds" REAL NOT NULL, "Assists" REAL NOT NULL, "Turnover" REAL NOT NULL, "Steal" REAL NOT NULL, "Blocked Shots" REAL NOT NULL, "Personal Fous" REAL NOT NULL, "Points" REAL NOT NULL ) """) db_cursor.execute(""" CREATE TABLE IF NOT EXISTS "Team Defence Stats"( "Team" VARCHAR(60) PRIMARY KEY REFERENCES "Team Offence Stats"("Team"), "Field Goal Attempts" REAL NOT NULL, "Field Goals Made" REAL NOT NULL, "Field Goal Percentage" REAL NOT NULL, "Free Throw Attempts" REAL NOT NULL, "Free Throws Made" REAL NOT NULL, "Free Throw Percentage" REAL NOT NULL, "3PT Attempts" REAL NOT NULL, "3PT Made" REAL NOT NULL, "3PT Percentage" REAL NOT NULL, "Offensive Rebounds" REAL NOT NULL, "Defensive Rebounds" REAL NOT NULL, "Total Rebounds" REAL NOT NULL, "Assists" REAL NOT NULL, "Turnover" REAL NOT NULL, "Steal" REAL NOT NULL, "Blocked Shots" REAL NOT NULL, "Personal Fous" REAL NOT NULL, "Points" REAL NOT NULL ) """) db_cursor.execute("""CREATE TABLE IF NOT EXISTS "Player Stats Per Game"( "Player" VARCHAR(60), "Team" VARCHAR(60), "Games" INTEGER NOT NULL, "Minutes Played" INTERVAL MINUTE TO SECOND NOT NULL, "Field Goals Attempted" REAL NOT NULL, "Field Goals Made" REAL NOT NULL, "Field Goal Percentage" REAL NOT NULL, "Free Throws Attempted" REAL NOT NULL, "Free Throws Made" REAL NOT NULL, "Free Throw Percentage" REAL NOT NULL, "3PT Shots Attemped" REAL NOT NULL, "3PT Shots Made" REAL NOT NULL, "3PT Percentage" REAL NOT NULL, "Points Scored" REAL NOT NULL, "Offensive Rebounds" REAL NOT NULL, "Defensive Rebounds" REAL NOT NULL, "Rebounds" REAL NOT NULL, "Assists" REAL NOT NULL, "Steals" REAL NOT NULL, "Blocked Shots" REAL NOT NULL, "Turnovers" REAL NOT NULL, "Personal Fouls" REAL NOT NULL, PRIMARY KEY("Player","Team"))""") db_cursor.execute(""" CREATE TABLE IF NOT EXISTS "Player Stats Total"( "Player" VARCHAR(60), "Team" VARCHAR(60), "Games" INTEGER NOT NULL, "Minutes Played" INTERVAL MINUTE TO SECOND NOT NULL, "Field Goals Attempted" INTEGER NOT NULL, "Field Goals Made" INTEGER NOT NULL, "Free Throws Attempted" INTEGER NOT NULL, "Free Throws Made" INTEGER NOT NULL, "3PT Shots Attemped" INTEGER NOT NULL, "3PT Shots Made" INTEGER NOT NULL, "Points Scored" INTEGER NOT NULL, "Offensive Rebounds" INTEGER NOT NULL, "Defensive Rebounds" INTEGER NOT NULL, "Rebounds" INTEGER NOT NULL, "Assists" INTEGER NOT NULL, "Steals" INTEGER NOT NULL, "Blocked Shots" INTEGER NOT NULL, "Turnovers" INTEGER NOT NULL, "Personal Fouls" INTEGER NOT NULL, PRIMARY KEY("Player","Team")) """) db_connection.commit() def insert_player(conn,cur,table,data_dict): column_names = data_dict.keys() query = sql.SQL('INSERT INTO{0}({1}) VALUES({2}) ON CONFLICT("Team","Player") DO UPDATE SET({1}) = ({2})').format( sql.SQL(table), sql.SQL(', ').join(map(sql.Identifier, column_names)), sql.SQL(', ').join(map(sql.Placeholder, column_names)) ) cur.execute(query,data_dict) def insert_team(conn,cur,table,data_dict): column_names = data_dict.keys() query = sql.SQL('INSERT INTO{0}({1}) VALUES({2}) ON CONFLICT("Team") DO UPDATE SET({1}) = ({2})').format( sql.SQL(table), sql.SQL(', ').join(map(sql.Identifier, column_names)), sql.SQL(', ').join(map(sql.Placeholder, column_names)) ) query_string = query.as_string(conn) cur.execute(query_string,data_dict) def insert_update_team_table(conn,cur,update = False): Team_Stats = get_html('Team_Stats','https://sports.yahoo.com/nba/stats/team/?sortStatId=POINTS_PER_GAME&selectedTable=0',directory = 'Team_Stats',update = update) Opposing_Team_Stats =get_html('Opposing_Team_Stats','https://sports.yahoo.com/nba/stats/team/?sortStatId=POINTS_PER_GAME&selectedTable=1',directory = 'Team_Stats',update = update) offence_list = get_team_stat(Team_Stats) defence_list = get_team_stat(Opposing_Team_Stats) offence_table = '"Team Offence Stats"' defence_table = '"Team Defence Stats"' for stat in offence_list: insert_team(conn,cur,offence_table,team_offence.process_dict(stat).get_team_stat()) for stat in defence_list: team_defence.process_dict(stat).get_team_stat() insert_team(conn,cur,defence_table,team_defence.process_dict(stat).get_team_stat()) conn.commit() def insert_update_player_table(Base,directory,conn,cur,update =False): per_game_stat = '"Player Stats Per Game"' total_stat = '"Player Stats Total"' for item in team_html_generator(Base,directory,update = update): team, team_html = item player_list = get_player_stat(team_html) for player in player_list: player_obj = Player(player,team) insert_player(conn,cur,per_game_stat,player_obj.get_average_dict()) insert_player(conn,cur,total_stat,player_obj.get_total_dict()) conn.commit() def execute_and_return(query): db_cursor.execute(query) results = db_cursor.fetchall() if len(results) != 0: return results else: return False #----------------------------------------------------------------# def overall_stat(stat_list): overall_stat_dict = {} overall_stat_dict['Player'] = stat_list[0]['Player'] overall_stat_dict['Team'] = stat_list[0]['Team'] overall_stat_dict['Games'] = int(stat_list[0]['Games']) overall_stat_dict['Minutes Played'] = stat_list[0]['Minutes Played'] overall_stat_dict['Field Goals Attempted'] = float(stat_list[0]['Field Goals Attempted']) overall_stat_dict['Field Goals Made'] = float(stat_list[0]['Field Goals Made']) overall_stat_dict['Free Throws Attempted'] = float(stat_list[0]['Free Throws Attempted']) overall_stat_dict['Free Throws Made'] = float(stat_list[0]['Free Throws Made']) overall_stat_dict['3PT Shots Attemped'] = float(stat_list[0]['3PT Shots Attemped']) overall_stat_dict['3PT Shots Made'] = float(stat_list[0]['3PT Shots Made']) overall_stat_dict['Points Scored'] = float(stat_list[0]['Points Scored']) overall_stat_dict['Offensive Rebounds'] = float(stat_list[0]['Offensive Rebounds']) overall_stat_dict['Defensive Rebounds'] = float(stat_list[0]['Defensive Rebounds']) overall_stat_dict['Rebounds'] = float(stat_list[0]['Rebounds']) overall_stat_dict['Assists'] = float(stat_list[0]['Assists']) overall_stat_dict['Steals'] = float(stat_list[0]['Steals']) overall_stat_dict['Blocked Shots'] = float(stat_list[0]['Blocked Shots']) overall_stat_dict['Turnovers'] = float(stat_list[0]['Turnovers']) overall_stat_dict['Personal Fouls'] = float(stat_list[0]['Personal Fouls']) for item in stat_list[1:]: overall_stat_dict['Team'] += '/'+item['Team'] overall_stat_dict['Games'] += int(item['Games']) overall_stat_dict['Minutes Played'] += item['Minutes Played'] overall_stat_dict['Field Goals Attempted'] += float(item['Field Goals Attempted']) overall_stat_dict['Field Goals Made'] += float(item['Field Goals Made']) overall_stat_dict['Free Throws Attempted'] += float(item['Free Throws Attempted']) overall_stat_dict['Free Throws Made'] += float(item['Free Throws Made']) overall_stat_dict['3PT Shots Attemped'] += float(item['3PT Shots Attemped']) overall_stat_dict['3PT Shots Made'] += float(item['3PT Shots Made']) overall_stat_dict['Points Scored'] += float(item['Points Scored']) overall_stat_dict['Offensive Rebounds'] += float(item['Offensive Rebounds']) overall_stat_dict['Defensive Rebounds'] += float(item['Defensive Rebounds']) overall_stat_dict['Rebounds'] += float(item['Rebounds']) overall_stat_dict['Assists'] += float(item['Assists']) overall_stat_dict['Steals'] += float(item['Steals']) overall_stat_dict['Blocked Shots'] += float(item['Blocked Shots']) overall_stat_dict['Turnovers'] += float(item['Turnovers']) overall_stat_dict['Personal Fouls'] += float(item['Personal Fouls']) total_seconds = overall_stat_dict['Minutes Played'].total_seconds() minutes = str(int(total_seconds/60)) seconds = str(int(total_seconds%60)) overall_stat_dict['Minutes Played'] = '{} : {}'.format(minutes,seconds) return overall_stat_dict def overall_average_stat(stat_list): overall_average_stat_dict = {} overall_average_stat_dict['Player'] =stat_list[0]['Player'] overall_average_stat_dict['Team'] = stat_list[0]['Team'] overall_average_stat_dict['Games'] = int(stat_list[0]['Games']) overall_average_stat_dict['Minutes Played'] = stat_list[0]['Minutes Played']*float(stat_list[0]['Games']) overall_average_stat_dict['Field Goals Attempted'] = float(stat_list[0]['Field Goals Attempted'])*float(stat_list[0]['Games']) overall_average_stat_dict['Field Goals Made'] = float(stat_list[0]['Field Goals Made'])*float(stat_list[0]['Games']) overall_average_stat_dict['Field Goal Percentage'] = 0 overall_average_stat_dict['Free Throws Attempted'] = float(stat_list[0]['Free Throws Attempted'])*float(stat_list[0]['Games']) overall_average_stat_dict['Free Throws Made'] = float(stat_list[0]['Free Throws Made'])*float(stat_list[0]['Games']) overall_average_stat_dict['Free Throw Percentage'] = 0 overall_average_stat_dict['3PT Shots Attemped'] = float(stat_list[0]['3PT Shots Attemped'])*float(stat_list[0]['Games']) overall_average_stat_dict['3PT Shots Made'] = float(stat_list[0]['3PT Shots Made'])*float(stat_list[0]['Games']) overall_average_stat_dict['3PT Percentage'] = 0 overall_average_stat_dict['Points Scored'] = float(stat_list[0]['Points Scored'])*float(stat_list[0]['Games']) overall_average_stat_dict['Offensive Rebounds'] = float(stat_list[0]['Offensive Rebounds'])*float(stat_list[0]['Games']) overall_average_stat_dict['Defensive Rebounds'] = float(stat_list[0]['Defensive Rebounds'])*float(stat_list[0]['Games']) overall_average_stat_dict['Rebounds'] = float(stat_list[0]['Rebounds'])*float(stat_list[0]['Games']) overall_average_stat_dict['Assists'] = float(stat_list[0]['Assists'])*float(stat_list[0]['Games']) overall_average_stat_dict['Steals'] = float(stat_list[0]['Steals'])*float(stat_list[0]['Games']) overall_average_stat_dict['Blocked Shots'] = float(stat_list[0]['Blocked Shots'])*float(stat_list[0]['Games']) overall_average_stat_dict['Turnovers'] = float(stat_list[0]['Turnovers'])*float(stat_list[0]['Games']) overall_average_stat_dict['Personal Fouls'] = float(stat_list[0]['Personal Fouls'])*float(stat_list[0]['Games']) for item in stat_list[1:]: overall_average_stat_dict['Team'] += '/'+item['Team'] overall_average_stat_dict['Games'] += int(item['Games']) overall_average_stat_dict['Minutes Played'] += item['Minutes Played']*float(item['Games']) overall_average_stat_dict['Field Goals Attempted'] += float(item['Games'])*float(item['Field Goals Attempted']) overall_average_stat_dict['Field Goals Made'] += float(item['Games'])*float(item['Field Goals Made']) overall_average_stat_dict['Free Throws Attempted'] += float(item['Games'])*float(item['Free Throws Attempted']) overall_average_stat_dict['Free Throws Made'] += float(item['Games'])*float(item['Free Throws Made']) overall_average_stat_dict['3PT Shots Attemped'] += float(item['Games'])*float(item['3PT Shots Attemped']) overall_average_stat_dict['3PT Shots Made'] += float(item['Games'])*float(item['3PT Shots Made']) overall_average_stat_dict['Points Scored'] += float(item['Games'])*float(item['Points Scored']) overall_average_stat_dict['Offensive Rebounds'] += float(item['Games'])*float(item['Offensive Rebounds']) overall_average_stat_dict['Defensive Rebounds'] += float(item['Games'])*float(item['Defensive Rebounds']) overall_average_stat_dict['Rebounds'] += float(item['Games'])*float(item['Rebounds']) overall_average_stat_dict['Assists'] += float(item['Games'])*float(item['Assists']) overall_average_stat_dict['Steals'] += float(item['Games'])*float(item['Steals']) overall_average_stat_dict['Blocked Shots'] += float(item['Games'])*float(item['Blocked Shots']) overall_average_stat_dict['Turnovers'] += float(item['Games'])*float(item['Turnovers']) overall_average_stat_dict['Personal Fouls'] += float(item['Games'])*float(item['Personal Fouls']) overall_average_stat_dict['Field Goal Percentage'] =round(float(overall_average_stat_dict['Field Goals Made']/overall_average_stat_dict['Field Goals Attempted'] )* 100,1) overall_average_stat_dict['Free Throw Percentage'] = round(float(overall_average_stat_dict['Free Throws Made']/overall_average_stat_dict['Free Throws Attempted'] )* 100,1) overall_average_stat_dict['3PT Percentage'] =round(float(overall_average_stat_dict['3PT Shots Made']/overall_average_stat_dict['3PT Shots Attemped'] )* 100,1) overall_average_stat_dict['Minutes Played'] = overall_average_stat_dict['Minutes Played'] /float(overall_average_stat_dict['Games']) for k in overall_average_stat_dict.keys(): if k not in ['Player','Team','Games','Minutes Played','Field Goal Percentage','Free Throw Percentage','3PT Percentage']: overall_average_stat_dict[k] = overall_average_stat_dict[k]/overall_average_stat_dict['Games'] total_seconds = (overall_average_stat_dict['Minutes Played']).total_seconds() minutes = str(int(total_seconds/60)) seconds = str(int(total_seconds%60)) overall_average_stat_dict['Minutes Played'] = '{} : {}'.format(minutes,seconds) return overall_average_stat_dict def player_all_plot(result): query_result = execute_and_return("""SELECT "Points Scored","Assists", "Rebounds" FROM "Player Stats Per Game" """) Points = [item['Points Scored'] for item in query_result] Assists = [item['Assists'] for item in query_result] Rebounds = [item['Rebounds'] for item in query_result] plt.figure(figsize=(12,3)) plt.subplot(1,4,1) plt.hist(Points,bins = 100, density = True,color = 'red') plt.plot(result['Points Scored'],0,'o',color = 'black') plt.title('Points Scored') plt.subplot(1,4 ,2) plt.hist(Assists,bins = 100, density = True,color = 'green') plt.title('Assists') plt.plot(result['Assists'],0,'o',color = 'black') plt.subplot(1,4,3) plt.hist(Rebounds,bins = 100, density = True,color = 'yellow') plt.title('Rebounds') plt.plot(result['Rebounds'],0,'o',color = 'black') plt.subplot(1,4,4) label='Field Goal','3PT','Free Throw' size = (result['Field Goals Made']*2,result['3PT Shots Made']*3,result['Free Throws Made']) max_index = size.index(max(size)) explode = [0,0,0] explode[max_index] = 0.1 plt.pie(size,explode = explode, labels = label) plt.title('Points Distribution') figfile =BytesIO() plt.savefig(figfile,format = 'png') figfile.seek(0) figdata_png = base64.b64encode(figfile.getvalue()) return figdata_png def team_offence_plot(result): query_result = execute_and_return("""SELECT "Points","Assists", "Total Rebounds" FROM "Team Offence Stats" """) Points = [item['Points'] for item in query_result] Assists = [item['Assists'] for item in query_result] Rebounds = [item['Total Rebounds'] for item in query_result] plt.figure(figsize=(12,3)) plt.subplot(1,4,1) plt.hist(Points,bins = 10, density = True,color = 'red') plt.plot(result['Points'],0,'o',color = 'black') plt.title('Points Scored') plt.subplot(1,4 ,2) plt.hist(Assists,bins = 10, density = True,color = 'green') plt.title('Assists') plt.plot(result['Assists'],0,'o',color = 'black') plt.subplot(1,4,3) plt.hist(Rebounds,bins = 10, density = True,color = 'yellow') plt.title('Rebounds') plt.plot(result['Total Rebounds'],0,'o',color = 'black') plt.subplot(1,4,4) label='Field Goals','Free Throws','3PT' size = (result['Field Goals Made']*2,result['3PT Made']*3,result['Free Throws Made']) max_index = size.index(max(size)) explode = [0,0,0] explode[max_index] = 0.1 plt.pie(size,explode = explode, labels = label) plt.title('Points Distribution') figfile =BytesIO() plt.savefig(figfile,format = 'png') figfile.seek(0) figdata_png = base64.b64encode(figfile.getvalue()) return figdata_png def team_defence_plot(result): query_result = execute_and_return("""SELECT "Points","Assists", "Total Rebounds" FROM "Team Defence Stats" """) Points = [item['Points'] for item in query_result] Assists = [item['Assists'] for item in query_result] Rebounds = [item['Total Rebounds'] for item in query_result] plt.figure(figsize=(9,3)) plt.subplot(1,3,1) plt.hist(Points,bins = 10, density = True,color = 'red') plt.plot(result['Points'],0,'o',color = 'black') plt.title('Points Scored') plt.subplot(1,3,2) plt.hist(Assists,bins = 10, density = True,color = 'green') plt.title('Assists') plt.plot(result['Assists'],0,'o',color = 'black') plt.subplot(1,3,3) plt.hist(Rebounds,bins = 10, density = True,color = 'yellow') plt.title('Rebounds') plt.plot(result['Total Rebounds'],0,'o',color = 'black') figfile =BytesIO() plt.savefig(figfile,format = 'png') figfile.seek(0) figdata_png = base64.b64encode(figfile.getvalue()) return figdata_png ##----------------------------------## db_connection, db_cursor = None, None db_connection, db_cursor = get_connection_and_cursor() Base_Web = get_html('Base_Web',BASE_URL+'/nba/stats/') app =Flask(__name__) @app.route('/') def index(): update = request.args.get('update') if update: insert_update_team_table(db_connection, db_cursor,update = True) insert_update_player_table(Base_Web,directory='Player_By_Team',conn = db_connection,cur = db_cursor,update = True) result = True else: result = False return render_template('index.html',result = result) @app.route('/player') def player_site(): results1 = [] results2 = [] respones = {} search = request.args.get('name') if search: query1 = sql.SQL('SELECT * FROM "Player Stats Per Game" WHERE "Player" ILIKE {0} ').format(sql.SQL('\''+search+'\'')) query2 = sql.SQL('SELECT * FROM "Player Stats Total" WHERE "Player" ILIKE {0} ').format(sql.SQL('\''+search+'\'')) results1 = execute_and_return(query1) if not results1: results1 = False else: if len(results1) > 1: respones['results3'] = overall_average_stat(results1) respones['all_plot'] = player_all_plot(respones['results3']).decode('utf-8') else: respones['all_plot'] = player_all_plot(results1[0]).decode('utf-8') for item in results1: total_seconds = item['Minutes Played'].total_seconds() minutes = str(int(total_seconds/60)) seconds = str(int(total_seconds%60)) item['Minutes Played'] = '{} : {}'.format(minutes,seconds) results2 = execute_and_return(query2) if not results2: results2 = False else: if len(results2) > 1: respones['results4'] = overall_stat(results2) for item in results2: total_seconds = item['Minutes Played'].total_seconds() minutes = str(int(total_seconds/60)) seconds = str(int(total_seconds%60)) item['Minutes Played'] = '{} : {}'.format(minutes,seconds) return render_template('player.html',search = search, results1 = results1,results2 = results2,respones = respones) @app.route('/team') def team_site(): search = request.args.get('team') results1 = [] results2 = [] respones = {} if search: query1 = sql.SQL('SELECT * FROM "Team Offence Stats" WHERE "Team" ILIKE {0}').format(sql.SQL('\''+search+'\'')) query2 = sql.SQL('SELECT * FROM "Team Defence Stats" WHERE "Team" ILIKE {0}').format(sql.SQL('\''+search+'\'')) results1 = execute_and_return(query1) if not results1: results1 = False else: respones['offence_plot'] = team_offence_plot(results1[0]).decode('utf-8') results2 = execute_and_return(query2) if not results1: results2 = False else: respones['defence_plot'] = team_defence_plot(results2[0]).decode('utf-8') return render_template('team.html',search = search, results1 = results1,results2 = results2,respones = respones) if __name__ == '__main__': setup_database() insert_update_team_table(db_connection, db_cursor) insert_update_player_table(Base_Web,directory='Player_By_Team',conn = db_connection,cur = db_cursor) app.run(use_reloader=True, debug = True) ``` README.md ```# -507F17_Final_Project ### Before use 1. Make sure the python version is higher than 3.6 2. Create a virtual environment and install required modules described in **_requirement.txt_**. 3. Create a database and modify the database name, username and password in the **_config.py_** file. The **_config.py_** file shuold be put in the same directory where **_SI507F17_finalproject.py_** is. 4. The program starts up by **_python SI507F17_finalproject.py runserver_** in command line.Once you see **_Runnig on_** _http://127.0.0.1: localport/_ in the command line, open any web browser and go to that localhost. 5. Except for step 3, users are supposed to interact with the program through the web browser. 6. It takes a while before users are able to interact with the database via web browser at the first time. 7. A unittest program is provided. The test runs well after the database has been fully set up. ### Website Guide This website is designed to get latest NBA Player stats and Team stats. Before exploring the website, please read the following instructions. You can search player's stats in **_player_** website. The search words are not case sensitive, but be aware of typying the full name of the player you are looking for.For example, 'Lebron James', 'lebron james' and 'leBron jAMes' are eligible key words. But 'james','James' and 'jAMEs' do not work here. The search result contains two tables. One of them is the average stats this season, while the other is the total stats. Below the table, there are three histgrams about average points, average assists and average rebounds respectively. The black point in each histgram indicates where the player's stat locate. The is a pie chart decribing the player's distribution of points scored by three-point, field goals and free throw. ![](https://github.com/zhoufanyi/-507F17_Final_Project/blob/master/example1.png) The tables have mulitiple rows if the player plays for different team this season. In this case, the last row of the table is the overall stats. ![](https://github.com/zhoufanyi/-507F17_Final_Project/blob/master/example2.png) You can click **_Back_** button to go to the index website. The website **_team_** is desinged for getting the team stats this season. The keyword is the city where it locates, except for _'LA Clippers'_ and _'LA Lakers'_. In the result, You will see two tables of offense and diffence stats of each teams. Below the table, there are two groups of histgrams about average points, average assists and average rebounds respectively at both offence and defence end. The black point in each histgram indicates where the team's stat locate. The is a pie chart decribing the teams's distribution of points scored by three-point, field goals and free throws. ![](https://github.com/zhoufanyi/-507F17_Final_Project/blob/master/example3.png) You can click **_Back_** button to go to the index website. The database can be updated by clicking **_Update_** button. Because the data is scraped from website. It will take at most one minute. When you see **_The database has been updated_**, the update process is done. Please be patient and enjoy the database. ### Program Detail #### class Player This class is initialized with a string team name and a per game stat dictionary. Player class have two method which return a dictionary of player's per game stat and player's aggregate stat. All values in the returning dictionaries are modified to meet requirements of psql command. The str method returns a description of the player's average stat. ``` Player A plays 12 games for Team X this season with averge 10 points, 3.2 Rebounds and 4.2 Assists. ``` The contain method takes minutes as a float input and return True if the player plays more than the input miniutes in this team. Suppose Player A playes 9 minutes per game in Team A. ``` print(10 in Player A) False ``` #### class team, team_defence and team_offence The class team is initialized with a stat dictionary. The method get_team_stat returns self.team_stat which is a dictionary. Team_defence and team_offence are subclasses derived from team. These classes should be initialized through class method process_dict(). The str method of team_defence and team_offence gives a brief description of the team's stats. ``` print(str(team_defence)) Team A lets opponent get 100 points this season with 39% field goal percentage and 32% three-points percentage. print(str(team_offence)) Team A scores 100 points this season with 39% field goal percentage and 32% three-points percentage. ``` The contain method of both class takes _point_ as a float input. The contain methond of team defence returns whether the team let the opponets score more than the _point_ on average. The one of team offence returns whether the team scores more than the _point_ on average. ### Caching System The caching system consists of get_html(), team_html_generator(), strip_multi_tag(), get_player_stat() and get_team_stat(). The whole system caches the desires websites from internet, get NBA players' stat and teams' stat with the help of beautifulsoup and returns dictionaries which will be used in initializing class Player and class team. ### Database System The database system consits of get_connection_and_cursor(), setup_database(), insert_player(), insert_team(), insert_update_team_table(), insert_update_player_table() and execute_and_return(). This system helps connect to the database and create desired tables and colums. Then NBA stats dictionary will be insert into the database and updated to the latest version if needed with the help of psycopg2. The execute_and_return() gets the data from database for future use. ### Data Process System The data process system is designed for handling the returning list of execute_and_return() when the list contains more than one dictionary. This happens when a player plays for more than one team in a season due to transactions. It will return a dictionary of average stats and aggregate stats in entire season. ### Plot System The plot system contains player_all_plot(), team_offense_plot() and team_defense_plot(). These function takes dictionary input and draws histgram and pie chart with matplotlib. Then the figures are encoded in base64. The jinja template will decode them and regenerate figures in browser. ### Flask Part There are three routes, which lead to index page, player search page annd team search page. Basically, user only needs to go to the '/' route and access to team by clicking team and to player by clicking player in index page. ### Database Detail There are four databases connected to the program. "Team Offence Stats" - "Team" VARCHAR(60) PRIMARY KEY, - "Field Goal Attempts" REAL NOT NULL, - "Field Goals Made" REAL NOT NULL, - "Field Goal Percentage" REAL NOT NULL, - "Free Throw Attempts" REAL NOT NULL, - "Free Throws Made" REAL NOT NULL, - "Free Throw Percentage" REAL NOT NULL, - "3PT Attempts" REAL NOT NULL, - "3PT Made" REAL NOT NULL, - "3PT Percentage" REAL NOT NULL, - "Offensive Rebounds" REAL NOT NULL, - "Defensive Rebounds" REAL NOT NULL, - "Total Rebounds" REAL NOT NULL, - "Assists" REAL NOT NULL, - "Turnover" REAL NOT NULL, - "Steal" REAL NOT NULL, - "Blocked Shots" REAL NOT NULL, - "Personal Fous" REAL NOT NULL, - "Points" REAL NOT NULL "Team Defence Stats" - "Team" VARCHAR(60) PRIMARY KEY REFERENCES "Team Offence Stats"("Team"), - "Field Goal Attempts" REAL NOT NULL, - "Field Goals Made" REAL NOT NULL, - "Field Goal Percentage" REAL NOT NULL, - "Free Throw Attempts" REAL NOT NULL, - "Free Throws Made" REAL NOT NULL, - "Free Throw Percentage" REAL NOT NULL, - "3PT Attempts" REAL NOT NULL, - "3PT Made" REAL NOT NULL, - "3PT Percentage" REAL NOT NULL, - "Offensive Rebounds" REAL NOT NULL, - "Defensive Rebounds" REAL NOT NULL, - "Total Rebounds" REAL NOT NULL, - "Assists" REAL NOT NULL, - "Turnover" REAL NOT NULL, - "Steal" REAL NOT NULL, - "Blocked Shots" REAL NOT NULL, - "Personal Fous" REAL NOT NULL, - "Points" REAL NOT NULL "Player Stats Per Game" - "Player" VARCHAR(60), - "Team" VARCHAR(60), - "Games" INTEGER NOT NULL, - "Minutes Played" INTERVAL MINUTE TO SECOND NOT NULL, - "Field Goals Attempted" REAL NOT NULL, - "Field Goals Made" REAL NOT NULL, - "Field Goal Percentage" REAL NOT NULL, - "Free Throws Attempted" REAL NOT NULL, - "Free Throws Made" REAL NOT NULL, - "Free Throw Percentage" REAL NOT NULL, - "3PT Shots Attemped" REAL NOT NULL, - "3PT Shots Made" REAL NOT NULL, - "3PT Percentage" REAL NOT NULL, - "Points Scored" REAL NOT NULL, - "Offensive Rebounds" REAL NOT NULL, - "Defensive Rebounds" REAL NOT NULL, - "Rebounds" REAL NOT NULL, - "Assists" REAL NOT NULL, - "Steals" REAL NOT NULL, - "Blocked Shots" REAL NOT NULL, - "Turnovers" REAL NOT NULL, - "Personal Fouls" REAL NOT NULL, - PRIMARY KEY("Player","Team") "Player Stats Total" - "Player" VARCHAR(60), - "Team" VARCHAR(60), - "Games" INTEGER NOT NULL, - "Minutes Played" INTERVAL MINUTE TO SECOND NOT NULL, - "Field Goals Attempted" INTEGER NOT NULL, - "Field Goals Made" INTEGER NOT NULL, - "Free Throws Attempted" INTEGER NOT NULL, - "Free Throws Made" INTEGER NOT NULL, - "3PT Shots Attemped" INTEGER NOT NULL, - "3PT Shots Made" INTEGER NOT NULL, - "Points Scored" INTEGER NOT NULL, - "Offensive Rebounds" INTEGER NOT NULL, - "Defensive Rebounds" INTEGER NOT NULL, - "Rebounds" INTEGER NOT NULL, - "Assists" INTEGER NOT NULL, - "Steals" INTEGER NOT NULL, - "Blocked Shots" INTEGER NOT NULL, - "Turnovers" INTEGER NOT NULL, - "Personal Fouls" INTEGER NOT NULL, - PRIMARY KEY("Player","Team") ``` config.py ```db_name = 'final_project_507' db_user = 'zhoufan' db_password = '19920209' ``` SI507F17_finalproject_test.py ```import unittest from SI507F17_finalproject import * from bs4 import BeautifulSoup from datetime import timedelta import types TEST_PLAYER_DICT = {'Player':'A', 'Games':12,'Minutes Played':'25:30','Field Goals Attempted':15,'Field Goals Made':8,'Field Goal Percentage':53.3,'Free Throws Attempted':5,'Free Throws Made':3,'Free Throw Percentage':60,'3-point Shots Attemped':3,'3-point Shots Made':1,'3-point Percentage':33.3,'Points Scored':22,'Offensive Rebounds':2,'Defensive Rebounds':5,'Total Rebounds':7,'Assists':3,'Steals':3,'Blocked Shots':1,'Turnovers':5,'Personal Fouls':2} TEST_PLAYER_DICT_1 = {'Player':'A','Team':'Alpha', 'Games':12,'Minutes Played':timedelta(minutes=15,seconds=30),'Field Goals Attempted':9,'Field Goals Made':4.5,'Field Goal Percentage':50,'Free Throws Attempted':5,'Free Throws Made':3,'Free Throw Percentage':60,'3PT Shots Attemped':3,'3PT Shots Made':1,'3PT Percentage':33.3,'Points Scored':15,'Offensive Rebounds':2,'Defensive Rebounds':5,'Rebounds':7,'Assists':3,'Steals':3,'Blocked Shots':1,'Turnovers':5,'Personal Fouls':2} TEST_PLAYER_DICT_2 = {'Player':'A','Team':'Beta', 'Games':5,'Minutes Played':timedelta(minutes=20,seconds=10),'Field Goals Attempted':15,'Field Goals Made':8,'Field Goal Percentage':53.3,'Free Throws Attempted':5,'Free Throws Made':3,'Free Throw Percentage':60,'3PT Shots Attemped':3,'3PT Shots Made':1,'3PT Percentage':33.3,'Points Scored':22,'Offensive Rebounds':2,'Defensive Rebounds':5,'Rebounds':7,'Assists':3,'Steals':3,'Blocked Shots':1,'Turnovers':5,'Personal Fouls':2} TEST_PLAYER_LIST = [TEST_PLAYER_DICT_1,TEST_PLAYER_DICT_2] TEST_TEAM_OFFENCE_DICT = {'Team':'B','Field Goals Made Per Game':20,'Field Goal Attempts Per Game':50,'Field Goal Percentage':40,'Three-Points Made Per Game':8,'Three-Point Attempts Per Game':24,'Three-Point Percentage':33.3,'Free Throws Made Per Game':15,'Free Throw Attempts Per Game':20,'Free Throw Percentage':75,'Offensive Rebounds Per Game':9,'Defensive Rebounds Per Game':10,'Total Rebounds Per Game':19,'Assists Per Game':18,'Turnovers Per Game':12,'Steals Per Game':5,'Blocked Shots Per Game':7,'Personal Fouls Per Game':14,'Points Per Game':90} TEST_TEAM_DEFENCE_DICT = {'Team':'B','Field Goals Allowed Per Game':20,'Field Goal Attempts Allowed Per Game':50,'Field Goal Percentage Allowed':40,'Three-Points Allowed Per Game':8,'Three-Point Attempts Allowed Per Game':24,'Three-Point Percentage Allowed':33.3,'Free Throws Allowed Per Game':15,'Free Throw Attempts Allowed Per Game':20,'Free Throw Percentage Allowed':75,'Offensive Rebounds Allowed Per Game':9,'Defensive Rebounds Allowed Per Game':10,'Total Rebounds Allowed Per Game':19,'Assists Allowed Per Game':18,'Turnovers Forced Per Game':12,'Steals Forced Per Game':5,'Blocked Shots Allowed Per Game':7,'Personal Fouls Drawn Per Game':14,'Points Allowed Per Game':90} TEST_TEAM = 'B' class get_html_test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_return(self): A = get_html(title = 'Base_Web') self.assertIsInstance(A,str) class get_player_stat_test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_return(self): A = get_player_stat('Base_Web') self.assertIsInstance(A,list) class get_team_stat_test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_return(self): A = get_team_stat('Base_Web') self.assertIsInstance(A,list) class strip_multi_tag_test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test(self): A = get_html(title = 'Base_Web') self.assertIsInstance(strip_multi_tag(A,'td'),types.GeneratorType) class team_html_generator_test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test(self): self.assertIsInstance(team_html_generator('Base_Web',''),types.GeneratorType) class Player_test(unittest.TestCase): def setUp(self): self.test_player = Player(TEST_PLAYER_DICT,TEST_TEAM) def tearDown(self): self.test_player = None def test_Player_method(self): self.assertIsInstance(self.test_player.get_total_dict(),dict) self.assertIsInstance(self.test_player.get_average_dict(),dict) self.assertEqual(self.test_player.get_average_dict()['Points Scored'],22) self.assertEqual(self.test_player.get_total_dict()['Points Scored'],22*12) self.assertTrue(10 in self.test_player) class team_test(unittest.TestCase): def setUp(self): self.team_obj = team('A') def tearDown(self): self.team_obj = None def test_get_method(self): self.assertEqual(self.team_obj.get_team_stat(), 'A') class team_defence_test(unittest.TestCase): def setUp(self): self.team_defence_obj = team_defence.process_dict(TEST_TEAM_DEFENCE_DICT) def tearDown(self): self.team_defence = None def test_team_defence_method(self): self.assertIsInstance(self.team_defence_obj,team) self.assertIsInstance(self.team_defence_obj.team_stats, dict) self.assertEqual(self.team_defence_obj.team_stats['Field Goal Attempts'],50) self.assertTrue(100 in self.team_defence_obj ) class team_offence_test(unittest.TestCase): def setUp(self): self.team_offence_obj = team_offence.process_dict(TEST_TEAM_OFFENCE_DICT) def tearDown(self): self.team_offence = None def test_team_offence_method(self): self.assertIsInstance(self.team_offence_obj,team) self.assertIsInstance(self.team_offence_obj.team_stats, dict) self.assertEqual(self.team_offence_obj.team_stats['Field Goal Attempts'],50) self.assertFalse(100 in self.team_offence_obj) class execute_and_return_test(unittest.TestCase): def setUP(self): pass def tearDown(self): pass def test(self): result = execute_and_return("""SELECT "Points","Assists", "Total Rebounds" FROM "Team Offence Stats" """) self.assertIsInstance(result,list) class overall_stat_test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test(self): self.assertIsInstance(overall_stat(TEST_PLAYER_LIST),dict) self.assertEqual(overall_stat(TEST_PLAYER_LIST)['Team'],'Alpha/Beta') self.assertEqual(overall_stat(TEST_PLAYER_LIST)['Points Scored'],37 ) self.assertEqual(overall_stat(TEST_PLAYER_LIST)['Games'],17) class overal_average_stat_test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test(self): self.assertIsInstance(overall_average_stat(TEST_PLAYER_LIST),dict) self.assertEqual(overall_average_stat(TEST_PLAYER_LIST)['Team'],'Alpha/Beta') self.assertEqual(overall_average_stat(TEST_PLAYER_LIST)['Points Scored'],(15*12+22*5)/17) self.assertEqual(overall_average_stat(TEST_PLAYER_LIST)['Field Goal Percentage'],round((4.5*12+8*5)/(9*12+15*5)*100,1)) class player_all_plot_test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test(self): self.assertIsInstance(player_all_plot(TEST_PLAYER_DICT_1),bytes) class team_defence_plot_test(unittest.TestCase): def setUp(self): self.team_defence_obj = team_defence.process_dict(TEST_TEAM_DEFENCE_DICT) def tearDown(self): self.team_defence_obj = None def test(self): result = self.team_defence_obj.get_team_stat() self.assertIsInstance(team_defence_plot(result),bytes) class team_offence_plot_test(unittest.TestCase): def setUp(self): self.team_offence_obj = team_offence.process_dict(TEST_TEAM_OFFENCE_DICT) def tearDown(self): self.team_offence_obj = None def test(self): result = self.team_offence_obj.get_team_stat() self.assertIsInstance(team_offence_plot(result),bytes) if __name__ == '__main__': unittest.main(verbosity=2)```
zhougonglai/jss
zhougonglai/jss controllers.js ```angular.module('starter.controllers', ["homeCtrl","indentCtrl","accountCtrl","sign","store"]) .controller("tab",function ($scope,$state,$ionicModal,ionicMaterialInk) { var vm = this; vm.toggleMenu = true; $ionicModal.fromTemplateUrl('templates/component/setting.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modal = modal; }); $scope.openModel = function(){ $scope.modal.show(); }; $scope.closeModel = function(){ $scope.modal.hide(); }; $scope.$on("$ionicView.enter",function(e){ ionicMaterialInk.displayEffect(); }); }); ``` account.js ```angular.module("accountCtrl",[]) .controller('account', function($scope,ionicMaterialInk,$ionicNavBarDelegate,$state,$ionicSettings,$ionicPopup) { var vm = this; vm.title = "用户"; var settings = { language: { type: 'selection', values: ['英文','简体中文'], label: '语言设置', icon:"ion-android-globe", value: '简体中文' }, safety:{ type:"button", label:"账号与安全", icon:"ion-lock-combination", onClick:function(){ } }, quality:{ type:'selection', icon:"ion-images", values:['普通','高'], label:"非WIFI下图片质量", value:"普通" }, clear:{ type:"selection", icon:"ion-android-delete", values:['132M'], label:"清理缓存", value:"132M" }, checkUpdate:{ type:"button", icon:"ion-android-cloud-circle", label:"检查更新", onClick:function(){ } }, about:{ type:"button", label:"关于集食送", icon:"ion-android-alert", onClick:function(){ } }, pin: { type: 'pin', label: '安全锁', icon:"ion-android-lock", value:'', onValid: function() { $ionicPopup.alert({ title: '成功登入', template: '恭喜' }); }, onInvalid: function($event, wrongPinValue) { $ionicPopup.alert({ title: '失败', template: '输入值:' + wrongPinValue + '!错误.' }); } }, logout:{ type:"button", label:"退出当前账号", icon:"ion-log-out", onClick:function(){ } } }; $ionicSettings.init(settings); vm.openSetting = function(){ $scope.openModel(); }; $scope.closeSetting = function(){ $scope.closeModel(); }; $scope.$on($ionicSettings.changed, function($event, changedSetting) { console.log(changedSetting.key + ' -> ' + changedSetting.value); }); $scope.$on("$ionicView.enter",function(e){ $ionicSettings.init(settings); $ionicNavBarDelegate.showBar(false); ionicMaterialInk.displayEffect(); }); }); ``` sign.js ```angular.module("sign",[]) .controller("sign",function($scope){ var vm = this; vm.title="登录"; $scope.$on("$ionicView.enter",function(e){ }); }) .controller("signUp",function($scope){ var vm = this; vm.title="注册"; }) .controller("signIn",function($scope){ var vm = this; vm.title = "登录"; }) ; ``` indent.js ```angular.module("indentCtrl",[]) .controller('indent', function($scope,ionicMaterialInk) { var vm = this; vm.title="订单"; vm.index = 1; ionicMaterialInk.displayEffect(); }); ``` app.js ```// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'starter.services' is found in services.js // 'starter.controllers' is found in controllers.js angular.module('starter', [ 'ionic', 'starter.controllers', 'starter.services', "ngAnimate", "ngCookies", "ngFx", 'ionic-material', "ionicSettings", "ngResource", "ngCordova" ]) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); cordova.plugins.Keyboard.disableScroll(true); } if (window.StatusBar) { StatusBar.styleDefault(); } }); }) .config(function($stateProvider, $urlRouterProvider,$ionicConfigProvider,$httpProvider,$ionicSettingsConfigProvider) { $ionicConfigProvider.views.maxCache(5); $ionicConfigProvider.platform.ios.tabs.style('striped'); //$ionicConfigProvider.platform.ios.tabs.position('bottom'); //$ionicConfigProvider.platform.android.tabs.style('android'); $ionicConfigProvider.platform.android.tabs.position('bottom'); //$ionicConfigProvider.platform.ios.navBar.alignTitle('center'); //$ionicConfigProvider.platform.android.navBar.alignTitle('center'); $ionicConfigProvider.platform.ios.backButton.previousTitleText('').icon('ion-ios-arrow-thin-left'); $ionicConfigProvider.platform.android.backButton.previousTitleText('').icon('ion-android-arrow-back'); $ionicConfigProvider.platform.ios.views.transition('ios'); $ionicConfigProvider.platform.android.views.transition('android'); $stateProvider //root .state('tab', { url: '/tab', abstract: true, templateUrl: 'templates/tabs.html', controller:'tab', controllerAs:"vm" }) //主页 .state('tab.home', { url: '/home', views: { 'tab-home': { templateUrl: 'templates/tab-home.html', controller: 'home', controllerAs:'vm' } } }) //订单 .state('tab.indent', { url: '/indent', views: { 'tab-indent': { templateUrl: 'templates/tab-indent.html', controller: 'indent', controllerAs:"vm" } } }) //账户 .state('tab.account', { url: '/account', views: { 'tab-account': { templateUrl: 'templates/tab-account.html', controller: 'account', controllerAs:'vm' } } }) //登录注册 .state("sign",{ url:"/sign", abstract:true, templateUrl:"templates/component/sign.html", controller:"sign", controllerAs:"vm" }) //注册 .state("sign.up",{ url:"/up", templateUrl:"templates/component/sign-up.html", controller:"signUp", controllerAs:"vm" }) //登录 .state("sign.in",{ url:"/in", templateUrl:"templates/component/sign-in.html", controller:"signIn", controllerAs:"vm" }) //商店 .state("store",{ url:"/store", abstract:true, templateUrl:"templates/component/store.html", controller:"store", controllerAs:"vm" }) //商品 .state("store.wares",{ url:"/wares", templateUrl:"templates/component/store-wares.html", controller:"wares", controllerAs:"vm" }) //评价 .state("store.valuation",{ url:"/valuation", templateUrl:"templates/component/store-valuation.html", controller:"valuation", controllerAs:"vm" }) //商家 .state("store.business",{ url:"/business", templateUrl:"templates/component/store-business.html", controller:"business", controllerAs:"vm" }) //设置 //.state('setting',{ // url:'/setting', // //}) ; $ionicSettingsConfigProvider.setColor('assertive'); $urlRouterProvider.otherwise('/tab/home'); //$urlRouterProvider.otherwise('/sign/up'); $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8"; }); ``` store.js ```angular.module("store",[]) .controller("store",function($scope,$ionicScrollDelegate){ var vm = this; vm.title='商铺'; var header = document.getElementById("store-header"), storeBack = document.getElementById("store-back"), storeTitle = document.getElementById("store-title"), storeTools = document.getElementById("store-tools"), storeTool = storeTools.getElementsByTagName("button"); var storeHandle = $ionicScrollDelegate.$getByHandle("store-header"); header.style.backgroundColor = "RGBA(255,255,255,0)"; storeTitle.style.opacity = 0; storeBack.style.color = "RGBA(255,255,255,1)"; storeTool[0].style.color = "RGBA(255,255,255,1)"; storeTool[1].style.color = "RGBA(255,255,255,1)"; var changeNumber = 110; vm.onScroll = function(){ storeHandle.getScrollPosition().top<=0?(function(){ storeBack.style.color = "RGBA(255,255,255,1)"; storeTool[0].style.color = "RGBA(255,255,255,1)"; storeTool[1].style.color = "RGBA(255,255,255,1)"; header.style.backgroundColor = "RGBA(0,0,0,0)"; storeTitle.style.opacity = 0; })():(function(top){ ((top/changeNumber)<=1)?(function(level){ header.style.backgroundColor = "RGBA(255,255,255,"+level+")"; storeBack.style.color = "RGBA("+255*(1-level)+","+255*(1-level)+","+255*(1-level)+",1)"; storeTool[0].style.color = "RGBA("+255*(1-level)+","+255*(1-level)+","+255*(1-level)+",1)"; storeTool[1].style.color = "RGBA("+255*(1-level)+","+255*(1-level)+","+255*(1-level)+",1)"; storeTitle.style.opacity = level; $ionicScrollDelegate.freezeScroll(false); })(top/changeNumber):(function(){ header.style.backgroundColor = "RGBA(255,255,255,1)"; storeBack.style.color = "RGBA(0,0,0,1)"; storeTool[0].style.color = "RGBA(0,0,0,1)"; storeTool[1].style.color = "RGBA(0,0,0,1)"; storeTitle.style.opacity = 1; $ionicScrollDelegate.freezeScroll(true); })(); })(storeHandle.getScrollPosition().top) }; $scope.setStateView = function(view){ vm.stateView = ('store.wares' == view)?true:false; }; }) .controller("wares",function($scope,$state){ var vm = this; vm.title = "商品"; $scope.setStateView($state.$current.name); }) .controller("valuation",function($scope,$state){ var vm = this; vm.title = "评价"; $scope.setStateView($state.$current.name); }) .controller("business",function($scope,$state){ var vm = this; vm.title="商家"; $scope.setStateView($state.$current.name); }) ; ```
zhouhuafei/zhf.applications
zhouhuafei/zhf.applications index.min.js ```"use strict";var extend=require("zhf.extend");function Applications(){}Applications.prototype.extend=extend,Applications.prototype.cookie=require("zhf.cookie"),Applications.prototype.createElement=require("zhf.create-element"),Applications.prototype.AddSubtractInput=require("zhf.add-subtract-input"),Applications.prototype.getDomArray=require("zhf.get-dom-array"),Applications.prototype.getParent=require("zhf.get-parent"),Applications.prototype.htmlToDom=require("zhf.html-to-dom"),Applications.prototype.domRemove=require("zhf.dom-remove"),Applications.prototype.browserPlatform=require("zhf.browser-platform"),Applications.prototype.offset=require("zhf.offset"),Applications.prototype.scrollMoveTo=require("zhf.scroll-move-to"),Applications.prototype.SelectAll=require("zhf.select-all"),Applications.prototype.WhenScrollBottom=require("zhf.when-scroll-bottom"),Applications.prototype.whetherDisableScroll=require("zhf.whether-disable-scroll"),module.exports=new Applications;``` index.js ```'use strict'; var extend = require('zhf.extend'); // 应用方法集合 function Applications() {} Applications.prototype.extend = extend; // 对象的扩展 Applications.prototype.cookie = require('zhf.cookie'); // 操作cookie Applications.prototype.createElement = require('zhf.create-element'); // 创建元素节点 Applications.prototype.AddSubtractInput = require('zhf.add-subtract-input'); // 加减操作 Applications.prototype.getDomArray = require('zhf.get-dom-array'); // 获取原生的dom节点并转换成数组 Applications.prototype.getParent = require('zhf.get-parent'); // 获取指定父级 Applications.prototype.htmlToDom = require('zhf.html-to-dom'); // html转成DOM节点 Applications.prototype.domRemove = require('zhf.dom-remove'); // 移除dom Applications.prototype.browserPlatform = require('zhf.browser-platform'); // 浏览器平台检测 Applications.prototype.offset = require('zhf.offset'); // 获取元素距离文档的left和top Applications.prototype.scrollMoveTo = require('zhf.scroll-move-to'); // 滚动到指定位置 Applications.prototype.SelectAll = require('zhf.select-all'); // 全选,不选,反选 Applications.prototype.WhenScrollBottom = require('zhf.when-scroll-bottom'); // 当滚动到了浏览器的底部 Applications.prototype.whetherDisableScroll = require('zhf.whether-disable-scroll'); // 是否禁止浏览器滚动 module.exports = new Applications();``` index.test.js ```const applications = require('../dist/index.min'); test(`applications.offset(document.body); // {top: 0, left: 0}`, () => { expect(applications.offset(document.body)).toEqual({top: 0, left: 0}); }); ``` readme.md ```# 应用方法(此项目已无实际用途。已停止维护) * 此包不在维护,不建议使用此包。需要哪个包就引入哪个包即可。不应该像现在这样把其他包整合到这个包里,导致里面有任何包更新,我这个包都需要跟着更新一下,增加了维护成本 ``` const applications = require('zhf.applications'); applications.isPc(); // true false applications.scrollToY(100); // 滚动到浏览器y轴100的位置 其他方法请参阅源码0.0 ``` ```
zhoujintao1994/dy5
zhoujintao1994/dy5 HandlerMapping.java ```package com.dayuan.handler; import java.io.File; import java.io.FileFilter; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import com.dayuan.controller.BaseController; public class HandlerMapping { private static final Map<String, Object> objectMapp = new HashMap<String, Object>(); public static Object getController(String key) { return objectMapp.get(key); } public static void loadClassFile(String rootPath) throws ClassNotFoundException, InstantiationException, IllegalAccessException { String classPath = "/WEB-INF/classes/"; //TODO �������Ը��Ի� String packagePath = "com/dayuanit/atm/controller"; String filePath = rootPath + classPath + packagePath; File file = new File(filePath); File[] classFileArray = file.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.getName().endsWith("class")) { return true; } return false; } }); //com.dayuanit.atm.controller for (File f : classFileArray) { String fileName = f.getName();// �����ɴ˳���·������ʾ���ļ���Ŀ¼�����ơ� String packageName = packagePath.replace(File.separator, ".") + "."; packageName += fileName.substring(0, fileName.length() - 6); System.out.println(">>>" + packageName); Class clazz = Class.forName(packageName);//��������и����ַ����������ӿ�������� Class ���� if (Modifier.isInterface(clazz.getModifiers())) {//�ӿ� continue; } if (Modifier.isAbstract(clazz.getModifiers())) { continue; } Object controllerObject = clazz.newInstance();//���� Class ��������ʾ�����һ����ʵ���� String[] parray = clazz.getName().split("\\."); objectMapp.put(parray[parray.length - 1], controllerObject); } Iterator<String> iterator = objectMapp.keySet().iterator(); Set<Map.Entry<String, Object>> set = objectMapp.entrySet(); for (Map.Entry<String, Object> entry : set) { Object obj = objectMapp.get(iterator.next()); System.out.println(">>>>>>>>>>>>[" + entry.getKey() + "," + entry.getValue().getClass().getName() + "]"); } } public static void main(String[] args) { String packagePath = "com/dayuanit/atm/controller"; String packageName = packagePath.replace("/", "."); System.out.println(packageName); System.out.println(String.class.getName()); System.out.println(BaseController.class.getModifiers()); } } ``` WxLoginMapper.java ```package com.dayuan.mapper; import org.apache.ibatis.annotations.Param; import com.dayuan.domain.WxLogin; public interface WxLoginMapper { int add(WxLogin author); WxLogin getAuthor(String openid); int update(WxLogin wxLogin); } ``` BankCardService.java ```package com.dayuan.serviceimpl; import java.util.List; import com.dayuan.domain.BankCard; import com.dayuan.domain.Flow; import com.dayuan.domain.PageHolder; import com.dayuan.dto.FLowTenDTO; public interface BankCardService { PageHolder listBankCard(int userId, int currentPage); void deleteCard(int cardId); List<BankCard> listBankCard(int userId); List<FLowTenDTO> listFLow(int userId); } ``` AtmSessionListener.java ```package com.dayuan.listener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class AtmSessionListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent se) { System.out.println(">>>>>> session create:" + se.getSession().getId()); } @Override public void sessionDestroyed(HttpSessionEvent se) { System.out.println(">>>>>> session destroy:" + se.getSession().getId()); } } ``` AtmServiceImpl.java ```package com.dayuan.serviceimpl; import java.text.DecimalFormat; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.dayuan.controller.BankCardController; import com.dayuan.domain.BankCard; import com.dayuan.domain.Flow; import com.dayuan.domain.PageHolder; import com.dayuan.domain.Transfer; import com.dayuan.exception.BizException; import com.dayuan.handler.TransferMessageHandler2; import com.dayuan.mapper.BankCardMapper2; import com.dayuan.mapper.FlowMapper; import com.dayuan.mapper.TransferMapper; import com.dayuan.utill.CardUtils; import com.dayuan.utill.MoneyUtil; import com.dayuan.websocket.handler.ATMWebSocketHandler; @Component public class AtmServiceImpl implements AtmService { @Autowired private BankCardMapper2 bankCardMapper; @Autowired private FlowMapper flowMapper; @Autowired private TransferMapper thansferMapper; @Autowired private RedisService redisService; @Autowired private ATMWebSocketHandler atmWebSocketHandler; @Autowired private TransferMessageHandler2 transferMessageHandler2; private Logger log = LoggerFactory.getLogger(BankCardController.class); @Override public BankCard openAccount(String passWord, int userId) {// ���� System.out.println("111111111111111111111111111111111"); // TODO Auto-generated method stub BankCard bankCard = new BankCard(); bankCard.setSum("0.00"); bankCard.setVersion(0); System.out.println(bankCard.getSum()); String cardNumber = null; for (int i = 0; i < 3; i++) { String tempNum = CardUtils.createCardNum(); BankCard existBc = bankCardMapper.getBankCard(cardNumber); if (null != existBc) { System.out.println("第" + i + "机会"); continue; } cardNumber = tempNum; break; } if (null == cardNumber) { try { throw new BizException("卡号重复,请重新输入"); } catch (Exception e) { log.error(e.getMessage(), e); e.printStackTrace(); } } bankCard.setCardNumber(cardNumber); bankCard.setPassWord(passWord); bankCard.setUserId(userId); int rows = bankCardMapper.addCard(bankCard); if (1 != rows) { throw new BizException("开户失败"); } redisService.delBankCard(userId); return bankCard; } @Override @Transactional(rollbackFor = Exception.class) public void deposit(String sum, String cardNumber, String passWord) { // TODO Auto-generated method stub BankCard bankCard = bankCardMapper.getBankCard(cardNumber); System.out.println(bankCard); if (null == bankCard) {// 银行卡号不存在 throw new BizException("银行卡号不存在或密码不正确"); } if (!bankCard.getPassWord().equals(passWord)) {// ������� throw new BizException("银行卡号不存在或密码不正确"); } CardUtils.checkAmountAndFormat(sum); // CardUtill.checkAmount(sum); DecimalFormat df = new DecimalFormat("#0.00"); sum = df.format(Double.parseDouble(sum)); System.out.println("format=" + sum); bankCard.setSum(MoneyUtil.plus(bankCard.getSum(), sum)); int rows = bankCardMapper.modifyBalance(bankCard.getCardNumber(), bankCard.getSum(), bankCard.getVersion()); if (1 != rows) { throw new BizException("存款失败"); } Flow flow = new Flow(); flow.setAmount(sum); flow.setCardNum(cardNumber); flow.setDescript("存钱"); flow.setFlowType(1); rows = flowMapper.addFlow(flow); if (1 != rows) { throw new BizException("存款失败"); } redisService.delBankCard(bankCard.getUserId()); redisService.dellistFLow(bankCard.getUserId()); } @Override @Transactional(rollbackFor = Exception.class) public void draw(String sum, String cardNumber, String passWord) { // TODO Auto-generated method stub BankCard bankCard = bankCardMapper.getBankCard(cardNumber); if (null == bankCard) { throw new BizException("银行卡号不存在或密码不正确"); } if (!bankCard.getPassWord().equals(passWord)) { throw new BizException("银行卡号不存在或密码不正确"); } sum = CardUtils.checkAmountAndFormat(sum); System.out.println("format=" + sum); String newSum = MoneyUtil.sub(bankCard.getSum(), sum); if (Double.parseDouble(newSum) < 0) { throw new BizException("余额不足"); } bankCard.setSum(newSum); int rows = bankCardMapper.modifyBalance(bankCard.getCardNumber(), bankCard.getSum(), bankCard.getVersion()); if (1 != rows) { throw new BizException("取款失败"); } Flow flow = new Flow(); flow.setAmount(sum); flow.setCardNum(cardNumber); flow.setDescript("取款"); flow.setFlowType(2); rows = flowMapper.addFlow(flow); if (1 != rows) { throw new BizException("添加流水失败"); } redisService.delBankCard(bankCard.getUserId()); redisService.dellistFLow(bankCard.getUserId()); } @Override @Transactional(rollbackFor = Exception.class) public void transfer(String sum, String inCardNum, String outCardNum, String passWord) { // TODO Auto-generated method stub BankCard outCard = bankCardMapper.getBankCard(outCardNum); if (null == outCard) { throw new BizException("银行卡号不存在或密码不正确"); } if (!outCard.getPassWord().equals(passWord)) { throw new BizException("银行卡号不存在或密码不正确"); } sum = CardUtils.checkAmountAndFormat(sum); System.out.println("format=" + sum); String newSum = MoneyUtil.sub(outCard.getSum(), sum); if (Double.parseDouble(newSum) < 0) { throw new BizException("余额不足,无法转账"); } outCard.setSum(newSum); int rows = bankCardMapper.modifyBalance(outCard.getCardNumber(), outCard.getSum(), outCard.getVersion()); if (1 != rows) { throw new BizException("转账失败"); } Flow flow = new Flow(); flow.setAmount(sum); flow.setCardNum(outCardNum); flow.setDescript("转账支出"); flow.setFlowType(3); rows = flowMapper.addFlow(flow); if (1 != rows) { throw new BizException("添加流水失败"); } BankCard inCard = bankCardMapper.getBankCard(inCardNum); if (null == inCard) { throw new BizException("银行卡号不存在"); } String inSum = MoneyUtil.plus(inCard.getSum(), sum); inCard.setSum(inSum); rows = bankCardMapper.modifyBalance(inCard.getCardNumber(), inCard.getSum(), inCard.getVersion()); if (1 != rows) { throw new BizException("转账失败"); } flow = new Flow(); flow.setAmount(sum); flow.setCardNum(inCardNum); flow.setDescript("转账收入"); flow.setFlowType(4); rows = flowMapper.addFlow(flow); if (1 != rows) { throw new BizException("添加流水失败"); } } @Override public PageHolder queryFlow(String cardNumber, String passWord, int currentPage) { // TODO Auto-generated method stub BankCard bankCard = bankCardMapper.getBankCard(cardNumber); System.out.println(bankCard); if (null == bankCard) { throw new BizException("银行卡号不存在或密码不正确"); } if (!bankCard.getPassWord().equals(passWord)) { throw new BizException("银行卡号不存在或密码不正确"); } int totalElement = flowMapper.countFlow(cardNumber); PageHolder ph = new PageHolder(currentPage, totalElement); List<Flow> list = flowMapper.listFlow(cardNumber, ph.getOffset(), PageHolder.PRE_PAGE_NUM); System.out.println("getOffset1=" + ph.getOffset()); System.out.println("PRE_PAGE_NUM1=" + PageHolder.PRE_PAGE_NUM); ph.setObj(list); return ph; } @Override public BankCard getBankCard(String cardNumber) { // BankCard banKCard = bankCardMapper.getBankCard(cardNumber); // redisService.dellistFLow(banKCard.getUserId()); return bankCardMapper.getBankCard(cardNumber); } @Override public int countFlow(String cardNumber, String passWord) { return flowMapper.countFlow(cardNumber); } @Override @Transactional(rollbackFor=Exception.class) public void outTransfer(String sum, String inCardNum, String outCardNum, String passWord) { // TODO Auto-generated method stub BankCard outCard = bankCardMapper.getBankCard(outCardNum); if (null == outCard) { throw new BizException("银行卡号不存在或密码不正确"); } if (!outCard.getPassWord().equals(passWord)) { throw new BizException("银行卡号不存在或密码不正确"); } sum = CardUtils.checkAmountAndFormat(sum); String newSum = MoneyUtil.sub(outCard.getSum(), sum); if (Double.parseDouble(newSum) < 0) { throw new BizException("余额不足,无法转账"); } outCard.setSum(newSum); int rows = bankCardMapper.modifyBalance(outCard.getCardNumber(), outCard.getSum(), outCard.getVersion()); if (1 != rows) { throw new BizException("转账失败"); } Flow flow = new Flow(); flow.setAmount(sum); flow.setCardNum(outCardNum); flow.setDescript("转账支出"); flow.setFlowType(3); rows = flowMapper.addFlow(flow); if (1 != rows) { throw new BizException("添加流水失败"); } Transfer transfer = new Transfer(); transfer.setTfBankcard(outCardNum); transfer.setCfBankcard(inCardNum); transfer.setTfBlance(sum); transfer.setStatus(0); rows = thansferMapper.addTransf(transfer); if (1 != rows) { throw new BizException("增加转账记录失败"); } redisService.delBankCard(outCard.getUserId()); redisService.dellistFLow(outCard.getUserId()); } @Override @Transactional(rollbackFor=Exception.class) public void intTransfer(Transfer transfer) { // TODO Auto-generated method stub //获取那张筛选出来的转账表里转入卡 BankCard bankCard = bankCardMapper.getBankCard(transfer.getCfBankcard()); //原有金额和转入金额相加 String addSum = MoneyUtil.plus(bankCard.getSum(), transfer.getTfBlance()); //修改添加银行卡 int rows = bankCardMapper.modifyBalance(transfer.getCfBankcard(), addSum, bankCard.getVersion()); if(1 != rows) { throw new BizException("处理转账失败"); } Flow flow = new Flow(); flow = new Flow(); flow.setAmount(transfer.getTfBlance()); flow.setCardNum(transfer.getCfBankcard()); flow.setDescript("转账收入"); flow.setFlowType(4); rows = flowMapper.addFlow(flow); if (1 != rows) { throw new BizException("转账流水添加失败"); } thansferMapper.modifyStatus(1, transfer.getId()); //转账成功 修改状态为1 // 发消息给客户端 transferMessageHandler2.sendMessage( bankCard.getUserId(), "收到一笔转账" + transfer.getTfBlance() + "元"); redisService.delBankCard(bankCard.getUserId()); redisService.dellistFLow(bankCard.getUserId()); } @Override @Transactional(rollbackFor=Exception.class) public void rooBack(Transfer transfer) { // TODO Auto-generated method stub //获取那张筛选出来的转账表里转出卡 BankCard bankCard = bankCardMapper.getBankCard(transfer.getTfBankcard()); // 把钱回滚到那张转出卡中 String addSum = MoneyUtil.plus(bankCard.getSum(), transfer.getTfBlance()); int rows = bankCardMapper.modifyBalance(transfer.getTfBankcard(), addSum, bankCard.getVersion()); //把satatus状态改为3:取消转账 if(1 != rows) { throw new BizException("取消转账失败!!"); } Flow flow = new Flow(); flow = new Flow(); flow.setAmount(transfer.getTfBlance()); flow.setCardNum(transfer.getCfBankcard()); flow.setDescript("取消转账"); flow.setFlowType(5); rows = flowMapper.addFlow(flow); if (1 != rows) { throw new BizException("取消转账流水添加失败"); } thansferMapper.modifyStatus(3, transfer.getId()); redisService.delBankCard(bankCard.getUserId()); redisService.dellistFLow(bankCard.getUserId()); } } ``` RedisServiceImpl.java ```package com.dayuan.serviceimpl; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; import com.dayuan.domain.BankCard; import com.dayuan.dto.FLowTenDTO; @Service public class RedisServiceImpl implements RedisService{ @Autowired private RedisTemplate<String, String> template; @Resource(name="redisTemplate") private ValueOperations<String, List<BankCard>> cardTemplate; @Resource(name="redisTemplate") private ValueOperations<String, List<FLowTenDTO>> flowTemplate; @Override public List<BankCard> listBankCard(int userId) { String key = "atm:card:" + userId; return cardTemplate.get(key); } @Override public void saveBankCard(List<BankCard> cards, int userId) { String key = "atm:card:" + userId; cardTemplate.set(key, cards); } @Override public void delBankCard(int userId) { String key = "atm:card:" + userId; template.delete(key); } @Override public List<FLowTenDTO> listFLow(int userId) { String key = "atm:flow:" + userId; return flowTemplate.get(key); } @Override public void saveListFlow(int userId, List<FLowTenDTO> value) { String key = "atm:flow:" + userId; flowTemplate.set(key, value); } @Override public void dellistFLow(int userId) { String key = "atm:flow:" + userId; template.delete(key); System.out.println("key="+key); } @Override public boolean setNX(String key, long time) { //通过setIfAbsent(K key, V value)方法判断变量值key是否存在 // //如果key存在返回false;不存在,就存入reidis返回true boolean flag = template.opsForValue().setIfAbsent(key, ""); if (flag) { template.expire(key, time, TimeUnit.SECONDS);//过期时间 } return flag; } } ``` AtmServlet.java ```package com.dayuan.servlet; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Method; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSON; import com.dayuan.dto.AjaxDTO; import com.dayuan.handler.HandlerMapping2; //public class AtmServlet extends HttpServlet { // // // AtmService atm = new AtmServiceImpl(); // // UserService userService = new UserServiceImpl(); // // BankCardService bankCardService = new BankCardServiceImpl(); // private static final long serialVersionUID = -7137552077346522939L; // // @Override // protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // // TODO Auto-generated method stub // doPost(req, resp); // } // // public void init(ServletConfig config) throws ServletException { // //// try { //// System.out.println("=====================init begin========================="); //// //// HandlerMapping2.init(); //// //// System.out.println("=====================init end========================="); //// } catch (Exception e) { //// e.printStackTrace(); //// throw new ServletException(e.getMessage()); //// } // init(); // } // // // // public static void main(String[] args) { // String uri = "/user/toUsercenter.do"; // String[] uriArray = uri.split("\\/"); // String tailURI = uriArray[uriArray.length - 1]; // String clazzName = uriArray[uriArray.length - 2]; // tailURI = tailURI.substring(0, tailURI.length() - 3); // System.out.println(tailURI); // System.out.println(clazzName); // } // // protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // String uri = req.getRequestURI(); // String url = req.getRequestURL().toString(); // System.out.println("uri=" + uri); // System.out.println("url=" + url); // // String cp = req.getServletContext().getContextPath(); // System.out.println("cp=" + cp);// ��ȡ·�� // // String[] uriArray = uri.split("\\/"); // String tailURI = uriArray[uriArray.length - 1]; // String clazzName = uriArray[uriArray.length - 2]; // String action = tailURI.substring(0, tailURI.length() - 3); // // System.out.println("action=" + action); // // Object targetObj = HandlerMapping2.getController(clazzName); // System.out.println("targetObj="+targetObj); // if (null == targetObj) { // System.out.println(">>>>>>>>> URL erro"); // return; // } // try { // Method method = targetObj.getClass().getMethod(action, HttpServletRequest.class, HttpServletResponse.class); // Object result = method.invoke(targetObj, req, resp); // // if (null == result) { // return; // } // // if (result instanceof String) { // String pagename = "/WEB-INF/page/" + result.toString() + ".jsp"; // req.getRequestDispatcher(pagename).forward(req, resp); // } // // if (result instanceof AjaxDTO) { // resp.setContentType("text/html;charset=utf-8"); // resp.setCharacterEncoding("utf-8"); // try (OutputStream os = resp.getOutputStream()) { // os.write(JSON.toJSONString(result).getBytes("utf-8")); // os.flush(); // } // } // } catch (NoSuchMethodException e) { // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } // // } // //} // @Override // protected void doPost(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // // TODO Auto-generated method stub // String action = req.getParameter("action");// ���ò��� // System.out.println("action=" + action); // // if ("toPage".equals(action)) { // toPage(req, resp); // } // // if ("openAccount".equals(action)) { // openAccount(req, resp); // } // // if ("deposit".equals(action)) { // deposit(req, resp); // } // // if ("draw".equals(action)) { // draw(req, resp); // } // // if ("transfer".equals(action)) { // transfer(req, resp); // } // // if ("flow".equals(action)) { // flow(req, resp); // } // // if ("regist".equals(action)) { // regist(req, resp); // } // // if ("login".equals(action)) { // login(req, resp); // } // // if ("toFlow".equals(action)) { // toFlow(req, resp); // } // // if ("toDeposit".equals(action)) { // toDeposit(req, resp); // } // // if ("toDraw".equals(action)) { // toDraw(req, resp); // } // // if ("toTransfer".equals(action)) { // toTransfer(req, resp); // } // // if ("deleteCard".equals(action)) { // deleteCard(req, resp); // } // // if ("toUsercenter".equals(action)) { // toUserCenter(req, resp); // } // // if ("upload".equals(action)) { // upload(req, resp); // } // // if ("showPic".equals(action)) { // showPic(req, resp);// ��ʾͼƬ��action // } // // if ("downFlow".equals(action)) { // downFlow(req, resp); // } // // if ("loadBankCard".equals(action)) { // loadBankCard(req, resp); // } // } // // if ("regist".equals(action)) { // regist(req, resp); // } // // // // if ("login".equals(action)) { // login(req, resp); // } // // } // // private void toPage(HttpServletRequest req, HttpServletResponse resp) throws // ServletException, IOException { // HttpSession session = req.getSession(); // String pageName = req.getParameter("pageName"); // req.getRequestDispatcher("/WEB-INF/page/" + pageName + ".jsp").forward(req, // resp); // } // // private void toOpenAccount(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // // String openAccount = req.getParameter("openAccount");// ���ò��� // req.getRequestDispatcher("/WEB-INF/page/openAccount.jsp").forward(req, resp); // } // // private void openAccount(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // String passWord = req.getParameter("passWord"); // // HttpSession session = req.getSession(); // User user = (User) session.getAttribute("user"); // // BankCard bc = atm.openAccount(passWord, user.getId()); // req.setAttribute("bankCardAtm", bc); // // req.getRequestDispatcher("/WEB-INF/page/bankCardInfo.jsp").forward(req, // resp); // } // // private void toDeposit(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // String cardNumber = req.getParameter("cardNumber"); // req.setAttribute("cardNumber", cardNumber); // req.getRequestDispatcher("/WEB-INF/page/deposit.jsp").forward(req, resp); // // // String deposit = req.getParameter("deposit"); // // req.getRequestDispatcher("/WEB-INF/page/deposit.jsp").forward(req, resp); // } // // private void deposit(HttpServletRequest req, HttpServletResponse resp) throws // ServletException, IOException { // String cardNumber = req.getParameter("cardNumber"); // System.out.println(cardNumber); // String passWord = req.getParameter("passWord"); // String sum = req.getParameter("sum"); // atm.deposit(sum, cardNumber, passWord); // BankCard bankCard = atm.getBankCard(cardNumber); // req.setAttribute("bankCardAtm", bankCard); // req.getRequestDispatcher("/WEB-INF/page/bankCardInfo.jsp").forward(req, // resp); // // } // // private void toDraw(HttpServletRequest req, HttpServletResponse resp) throws // ServletException, IOException { // String cardNumber = req.getParameter("cardNumber"); // req.setAttribute("cardNumber", cardNumber); // req.getRequestDispatcher("/WEB-INF/page/draw.jsp").forward(req, resp); // // } // // private void draw(HttpServletRequest req, HttpServletResponse resp) throws // ServletException, IOException { // String cardNumber = req.getParameter("cardNumber"); // System.out.println(cardNumber); // String passWord = req.getParameter("passWord"); // String sum = req.getParameter("sum"); // atm.draw(sum, cardNumber, passWord); // BankCard bankCard = atm.getBankCard(cardNumber); // req.setAttribute("bankCardAtm", bankCard); // req.getRequestDispatcher("/WEB-INF/page/bankCardInfo.jsp").forward(req, // resp); // } // // private void toTransfer(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // String cardNumber = req.getParameter("cardNumber"); // req.setAttribute("cardNumber", cardNumber); // req.getRequestDispatcher("/WEB-INF/page/transfer.jsp").forward(req, resp); // } // // private void transfer(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // String outCardNum = req.getParameter("outCardNum"); // System.out.println(outCardNum); // String passWord = req.getParameter("passWord"); // String inCardNum = req.getParameter("inCardNum"); // String sum = req.getParameter("sum"); // atm.transfer(sum, inCardNum, outCardNum, passWord); // BankCard bankCard = atm.getBankCard(outCardNum); // req.setAttribute("bankCardAtm", bankCard); // req.getRequestDispatcher("/WEB-INF/page/bankCardInfo.jsp").forward(req, // resp); // } // // private void toFlow(HttpServletRequest req, HttpServletResponse resp) throws // ServletException, IOException { // // String cardNumber =req.getParameter("cardNumber"); // // String passWord = req.getParameter("passWord"); // // List<Flow> list = atm.queryFlow(cardNumber, passWord); // // req.setAttribute("flowInfo", list); // // req.setAttribute("cardNumber", cardNumber); // // req.setAttribute("passWord", passWord); // String cardNumber = req.getParameter("cardNumber"); // req.setAttribute("cardNumber", cardNumber); // req.getRequestDispatcher("/WEB-INF/page/flow.jsp").forward(req, resp); // // } // // private void flow(HttpServletRequest req, HttpServletResponse resp) throws // ServletException, IOException { // String cardNumber = req.getParameter("cardNumber"); // String passWord = req.getParameter("passWord"); // String currentPage = req.getParameter("currentPage"); // System.out.println("currentPage=" + currentPage); // // resp.setContentType("text/html;charset=utf-8"); // resp.setCharacterEncoding("utf-8"); // // OutputStream os = resp.getOutputStream(); // // try { // // PageHolder ph = atm.queryFlow(cardNumber, passWord, // Integer.parseInt(currentPage)); // os.write(AjaxDTO.success(ph).getBytes("utf-8")); // os.flush(); // } catch(Exception e) { // os.write(AjaxDTO.faild(e.getMessage()).getBytes("utf-8")); // os.flush(); // } // // } // // // private void toregist(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // // req.getRequestDispatcher("/WEB-INF/page/regist.jsp").forward(req, resp); // } // // private void regist(HttpServletRequest req, HttpServletResponse resp) throws // ServletException, IOException { // String username = req.getParameter("username"); // String passWord = req.getParameter("passWord"); // // OutputStream os = resp.getOutputStream();// ��ȡ����� // try { // User user = userService.regist(username, passWord); // os.write(AjaxDTO.success().getBytes("utf-8")); // // } catch (BizException be) { // os.write(AjaxDTO.faild(be.getMessage()).getBytes("utf-8")); // // } catch (Exception e) { // os.write(AjaxDTO.faild("ϵͳ�쳣������ϵ�ͷ�").getBytes("utf-8")); // // } // // } // // private void tologin(HttpServletRequest req, HttpServletResponse resp) throws // ServletException, IOException { // // req.getRequestDispatcher("/WEB-INF/page/login.jsp").forward(req, resp); // } // // private void login(HttpServletRequest req, HttpServletResponse resp) throws // ServletException, IOException { // String username = req.getParameter("username"); // String passWord = req.getParameter("passWord"); // // resp.setContentType("text/html;charset=utf-8");// ������������ // resp.setCharacterEncoding("utf-8");// �����ַ����� // // OutputStream os = resp.getOutputStream();// ��ȡ����� // try { // User user = userService.login(username, passWord);// ��¼���� // HttpSession session = req.getSession(); // session.setAttribute("user", user); // // os.write(AjaxDTO.success().getBytes("utf-8")); // os.flush(); // // } catch (BizException be) { // os.write(AjaxDTO.faild(be.getMessage()).getBytes("utf-8")); // os.flush(); // return; // } finally { // os.close(); // } // // } // // private void toUserCenter(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // // // req.getRequestDispatcher("/WEB-INF/page/usercenter.jsp").forward(req, resp); // } // // private void showPic(HttpServletRequest req, HttpServletResponse resp) throws // ServletException, IOException { // String rp = req.getServletContext().getRealPath("/");// �õ�����·�� // // HttpSession session = req.getSession();// ��ûỰ // User user = (User) session.getAttribute("user");// ������� // // try (FileInputStream fis = new FileInputStream(rp + "WEB-INF/upload/" + // user.getId()); // OutputStream os = resp.getOutputStream()) { // byte[] data = new byte[1024]; // int length = -1; // while (-1 != (length = fis.read(data))) { // os.write(data, 0, length); // os.flush(); // } // } // } // // private void deleteCard(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // String cardId = req.getParameter("cardId"); // bankCardService.deleteCard(Integer.parseInt(cardId)); // // toUserCenter(req, resp); // // } // // private void upload(HttpServletRequest req, HttpServletResponse resp) throws // ServletException, IOException { // DiskFileItemFactory factory = new DiskFileItemFactory(); // factory.setSizeThreshold(1024);// �ϴ�1024 // String rp = req.getServletContext().getRealPath("/"); // factory.setRepository(new File(rp + "WEB-INF/upload-tmp"));// ������ʱ����� // // ServletFileUpload upload = new ServletFileUpload(factory);// Servlet�ļ��ϴ� // upload.setSizeMax(1024 * 230);// ���óߴ���� // // try { // List<FileItem> items = upload.parseRequest(req); // Iterator<FileItem> iter = items.iterator(); // while (iter.hasNext()) { // FileItem item = iter.next(); // // if (item.isFormField()) { // String name = item.getFieldName(); // String value = item.getString(); // System.out.println("[" + name + "=" + value + "]"); // } else { // HttpSession session = req.getSession(); // User user = (User) session.getAttribute("user"); // // String fileName = "" + user.getId(); // String fileName = String.valueOf(user.getId());// ��ȡ�û���id // // File uploadedFile = new File(rp + "WEB-INF/upload/" + fileName);// �ϴ����ļ� // item.write(uploadedFile);// д�����ͼƬ // } // } // } catch (Exception e) { // e.printStackTrace(); // } // // toUserCenter(req, resp); // } // // private void downFlow(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // String cardNumber = req.getParameter("cardNumber"); // String passWord = req.getParameter("passWord"); // System.out.println("cardNumber=" + cardNumber); // System.out.println("passWord=" + passWord); // String filename = cardNumber + ".csv"; // // resp.setContentType("application/octet-stream"); // resp.setHeader("Content-Disposition", "attachment;filename=" + filename); // // try (BufferedWriter bw = new BufferedWriter(new // OutputStreamWriter(resp.getOutputStream()))) { // int currentPage = 1; // // String header = "ID,����,���,��ע"; // bw.write(header); // bw.newLine(); // bw.flush(); // System.out.println("w"); // while (true) { // PageHolder ph = atm.queryFlow(cardNumber, passWord, currentPage); // Object obj = ph.getObj(); // if (null == obj) { // break; // } // // List<Flow> flowList = (List<Flow>) obj; // if (flowList.isEmpty()) { // break; // } // // for (Flow flow : flowList) { // StringBuilder sx = new StringBuilder(); // sx.append(flow.getId()).append(",").append(flow.getCardNum()).append(",").append(flow.getAmount()) // .append(",").append(flow.getDescript()).append(","); // // bw.write(sx.toString()); // bw.newLine(); // bw.flush(); // // } // // currentPage++; // // } // } // // } // // public void loadBankCard(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // HttpSession session = req.getSession(); // User user = (User)session.getAttribute("user"); // // String currentPage = req.getParameter("currentPage"); // currentPage = currentPage == null ? "1" : currentPage; // // // ��ѯ���п� // PageHolder pageHolder = bankCardService.listBankCard(user.getId(), // Integer.parseInt(currentPage)); // // OutputStream os = resp.getOutputStream(); // os.write(AjaxDTO.success(pageHolder).getBytes()); // os.flush(); // } // } ``` BankCardMapper2.java ```package com.dayuan.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.dayuan.domain.BankCard; public interface BankCardMapper2 { // BankCard getBankCard6(@Param("cardNumber") String cardNum, @Param("id") int // id); BankCard getBankCard(String cardNumber); int addCard(BankCard bankCard); int modifyBalance(@Param("cardNumber") String cardNumber, @Param("sum") String sum, @Param("version") int version); List<BankCard> listBankCard(@Param("userId") int userId, @Param("offset") Integer offset,@Param("prePage") Integer prePage); int deleteCard(int id); int countBankCard(int userId); } ``` ControllerHandler.java ```package com.dayuan.handler; import java.util.HashMap; import java.util.Map; import com.dayuan.controller.BankCardController; import com.dayuan.controller.BaseController; import com.dayuan.controller.UserController; public class ControllerHandler { private static final Map<String, BaseController> conMap = new HashMap<String, BaseController>(); static { conMap.put("user", new UserController()); conMap.put("card", new BankCardController()); } public static BaseController getController(String key) { return conMap.get(key); } } ``` AjaxDTO.java ```package com.dayuan.dto; public class AjaxDTO { private boolean success;//是否成功 private String message;//信息 private Object data;//数据 private AjaxDTO(boolean success, String message) { this.success = success; this.message = message; } private AjaxDTO(boolean success, Object data) { this.success = success; this.data = data; } public static AjaxDTO success() { return new AjaxDTO(true, "");//? } public static AjaxDTO success(Object data) { return new AjaxDTO(true, data); } public static AjaxDTO faild(String message) { return new AjaxDTO(false, message); } public boolean isSuccess() { return success; } public String getMessage() { return message; } public Object getData() { return data; } } ``` WXAuthenDTO.java ```package com.dayuan.dto; public class WXAuthenDTO { // 第二部分中的参数 private String access_token;//接口调用凭证 private int expires_in;//access_token接口调用凭证超时时间,单位(秒) private String refresh_token;//用户刷新access_token private String openid;//授权用户唯一标识 private String scope;// 用户授权的作用域,使用逗号(,)分隔 private String unionid;//当且仅当该网站应用已获得该用户的userinfo授权时,才会出现该字段。 public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public int getExpires_in() { return expires_in; } public void setExpires_in(int expires_in) { this.expires_in = expires_in; } public String getRefresh_token() { return refresh_token; } public void setRefresh_token(String refresh_token) { this.refresh_token = refresh_token; } public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public String getUnionid() { return unionid; } public void setUnionid(String unionid) { this.unionid = unionid; } } ``` UserMapper.java ```package com.dayuan.mapper; import org.apache.ibatis.annotations.Param; import com.dayuan.domain.User; public interface UserMapper { int addUser(User user); User getUser(String username); int modifyPwd(@Param("username")String username,@Param("password")String password); User getUserById(Integer userId); } ``` CaptchaController.java ```package com.dayuan.controller; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.dayuan.captcha.Captcha; import com.dayuan.captcha.GifCaptcha; @Controller public class CaptchaController { @RequestMapping("/getCaptcha") public void getCaptcha(HttpServletResponse response, HttpSession session) { try {//配置 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/gif"); // gif格式动画验证码 宽,高,位数。 Captcha captcha = new GifCaptcha(146, 33, 6); //服务器返回一个输出流 captcha.out(response.getOutputStream()); //验证码以字符的格式并且小写 设置一个session session.setAttribute("capcode", captcha.text().toLowerCase()); } catch (Exception e) { } } } ``` MessageService.java ```package com.dayuan.serviceimpl; import com.dayuan.domain.PageHolder; import com.dayuan.dto.MessageDTO; public interface MessageService { MessageDTO setMessage(int userId); // MessageDTO modifyMessage(int userId); // MessageDTO flowMessage(int userId); PageHolder listMessage( int currentPage,int userId); void readMessage(int userId); } ``` FlowMapper.java ```package com.dayuan.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.dayuan.domain.Flow; public interface FlowMapper { int addFlow(Flow flow); List<Flow> listFlow(@Param("cardNumber") String cardNum, @Param("offset")int offset, @Param("prePage")int prePage); //偏移量 每页查询条数 int countFlow(String cardNumber);//统计条数 List<Flow> listFlowByUseId(@Param("userId") Integer userId, @Param("prePage") int prePage); } ``` TransferProcessTask.java ```package com.dayuan.task; import java.util.Calendar; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.dayuan.domain.Transfer; import com.dayuan.mapper.TransferMapper; import com.dayuan.serviceimpl.AtmService; @Component("transferProcessTask") public class TransferProcessTask { private static final Logger log = LoggerFactory.getLogger(TransferProcessTask.class); @Autowired private TransferMapper transferMapper; @Autowired private AtmService atmService; public void doTask() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, -20); List<Transfer> lists = transferMapper.list4TransferIn(0, cal.getTime()); log.info(">>>>>>>本次查询待转账记录:" + lists.size()); for(Transfer transfer : lists) { try { atmService.intTransfer(transfer); }catch(Exception e) { log.error("转账失败,回滚卡号:"+transfer.getTfBankcard(), e); transferMapper.modifyStatus(2, transfer.getId()); } } } } ``` ConcurrentTransferTest.java ```package com.dayuan.test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicInteger; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.dayuan.serviceimpl.AtmService; public class ConcurrentTransferTest { static AtmService atmService; static final int max_thread_num = 100; static CyclicBarrier cb = new CyclicBarrier(max_thread_num); static CountDownLatch cd = new CountDownLatch(max_thread_num); static AtomicInteger errorCount = new AtomicInteger(0);// static AtomicInteger successCount = new AtomicInteger(0); public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-config.xml"); atmService = context.getBean(AtmService.class); TransferRunnable runnable = new TransferRunnable(); for (int i = 0; i < max_thread_num; i++) { new Thread(runnable, "线程" + i).start(); } cd.await(); System.out.println("错误:" + errorCount.get()); System.out.println("成功:" + successCount.get()); } } class TransferRunnable implements Runnable { @Override public void run() { try { System.out.println(Thread.currentThread().getName() + "等待"); ConcurrentTransferTest.cb.await(); ConcurrentTransferTest.atmService.outTransfer("1", "2222", "7753", "123"); ConcurrentTransferTest.successCount.incrementAndGet(); } catch (Exception e) { ConcurrentTransferTest.errorCount.incrementAndGet(); } ConcurrentTransferTest.cd.countDown(); } } ``` RedisService.java ```package com.dayuan.serviceimpl; import java.util.List; import com.dayuan.domain.BankCard; import com.dayuan.dto.FLowTenDTO; public interface RedisService { List<BankCard> listBankCard(int userId); void saveBankCard(List<BankCard> cards, int userId); void delBankCard(int userId); List<FLowTenDTO> listFLow(int userId); void saveListFlow(int userId, List<FLowTenDTO> value); void dellistFLow(int userId); boolean setNX(String key, long time); } ``` UserMapperTest.java ```package com.dayuan.test; import static org.junit.Assert.assertEquals; 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 org.springframework.transaction.annotation.Transactional; import com.dayuan.mapper.UserMapper; @RunWith(SpringRunner.class) @ContextConfiguration({"/spring/spring.xml"}) @Transactional public class UserMapperTest { @Autowired private UserMapper userMapper; @Test public void testModifyPassword() { int rows = userMapper.modifyPwd("q1", "68"); assertEquals(1, rows); } } ``` UserInfoController.java ```package com.dayuan.controller; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.dayuan.domain.User; import com.dayuan.dto.AjaxDTO; import com.dayuan.exception.BizException; import com.dayuan.serviceimpl.UserService; @Controller @RequestMapping("/userInfo") public class UserInfoController extends BaseController { @Autowired private UserService userService; static Logger log = LoggerFactory.getLogger(UserInfoController.class); // public void setUserService(UserService userService) { // this.userService = userService; // } @RequestMapping("/toPage") public String toPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); String pageName = req.getParameter("pageName"); return req.getParameter("pageName"); } @RequestMapping("/toModifyPwd") public String toModifyPwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { return "modifyPwd"; } @RequestMapping("/modifyPwd") @ResponseBody public AjaxDTO modifyPwd(String oldPassword, String newPassword, String comfirmPassword, HttpSession session){ System.out.println(">>>>> UserInfoController.modifyPwd() >>>>>>>"); // String username = req.getParameter("username"); // String passWord = req.getParameter("passWord"); // OutputStream os = resp.getOutputStream(); try { userService.modifyPwd(oldPassword, newPassword, comfirmPassword, getUserName(session)); session.invalidate(); } catch (BizException be) { return AjaxDTO.faild(be.getMessage()); } catch(Exception e) { e.printStackTrace(); return AjaxDTO.faild("操作失败,请联系客服"); } return AjaxDTO.success(); } }``` BaseController.java ```package com.dayuan.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.dayuan.domain.User; import com.dayuan.dto.AjaxDTO; import com.dayuan.exception.BizException; @Controller public class BaseController { @RequestMapping("/toUserCenter") public String toUserCenter(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { return "usercenter"; } // @RequestMapping("/toPage") // public String toPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // return req.getParameter("pageName"); // } @ExceptionHandler(BizException.class) @ResponseBody public AjaxDTO handlerBizException(BizException be) { return AjaxDTO.faild(be.getMessage()); } @ExceptionHandler(Exception.class) @ResponseBody public AjaxDTO handlerException(Exception e) { e.printStackTrace(); return AjaxDTO.faild("操作失败,请联系客服"); } protected String getUserName(HttpSession session) { Object obj = session.getAttribute("user"); if (null == obj) { throw new BizException("用户不存在"); } User user = (User)obj; return user.getUsername(); } protected int getUserId(HttpSession session) { Object obj = session.getAttribute("user"); if (null == obj) { throw new BizException("用户不存在"); } User user = (User)obj; return user.getId(); } } ``` SpringContextListener.java ```package com.dayuan.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.dayuan.handler.HandlerMapping2; public class SpringContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("=============init begin=============="); HandlerMapping2.init(); System.out.println("=====================init end========================="); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println(">>>>>> context destroy"); } } ``` TestLogback.java ```package com.dayuan.utill; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestLogback { static Logger log = LoggerFactory.getLogger(TestLogback.class); public static void main(String[] args) { log.trace("hello,trace"); log.debug("hello,debug"); log.info("hello,info"); log.warn("hello,warn"); log.error("hello,error"); System.out.println("hello"); } } ``` WXAuthenHandler.java ```package com.dayuan.handler; import java.io.IOException; import java.util.Map; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSON; import com.dayuan.dto.WXAuthenDTO; import com.dayuan.dto.WXUserInfoDTO; import com.dayuan.exception.BizException; import com.dayuan.utill.ApiConnector; @Component public class WXAuthenHandler { private static final Logger log = LoggerFactory.getLogger(WXAuthenHandler.class); @Value("${wx_appId}") private String appId; @Value("${wx_redirectUrl}") private String redirectUri; @Value("${wx_secret}") private String secret; @Value("${wx_codeUrl}") private String codeUrl; @Value("${wx_accessTokenUrl}") private String accessTokenUrl; @Value("${wx_wxUserInfoUrl}") private String wxUserInfoUrl; public String getCodeUrl() { StringBuilder StringBuilder = new StringBuilder(); // 获取code请求地址 StringBuilder.append(codeUrl).append("?").append("appid=").append(appId) .append("&").append("redirect_uri=").append(redirectUri).append("&").append("response_type=code") .append("&").append("scope=snsapi_login"); return StringBuilder.toString(); } public WXAuthenDTO getAccessToken(String code) { log.info(">>>>>>>code:" + code); StringBuilder StringBuilder = new StringBuilder(); // 获取access_token的请求地址 StringBuilder.append(accessTokenUrl).append("?").append("appid=") .append(appId).append("&").append("redirect_uri=").append(redirectUri).append("&").append("code=") .append(code).append("&").append("authorization_code"); String result = ApiConnector.get(StringBuilder.toString(), null); log.info(">>>>>>>>>accessToken result:" + result); WXAuthenDTO authenDTO = JSON.parseObject(result, WXAuthenDTO.class); return authenDTO; } public WXUserInfoDTO getWxUserInfo(WXAuthenDTO authenDTO) { HttpGet userInfoGet = new HttpGet(wxUserInfoUrl+"?access_token=" + authenDTO.getAccess_token() + "&openid=" + authenDTO.getOpenid()); CloseableHttpClient httpclient = HttpClients.createDefault();// 创建http客户端 CloseableHttpResponse httpResponse; try { httpResponse = httpclient.execute(userInfoGet); String result = EntityUtils.toString(httpResponse.getEntity()); log.info(">>>>>>>>>用户微信信息:" + result); WXUserInfoDTO wxInfo = JSON.parseObject(result, WXUserInfoDTO.class); log.info(">>>>>>>>>>>nickname=" + wxInfo.getNickname()); return wxInfo; } catch (Exception e) { log.error(e.getMessage(), e); throw new BizException("获得用户信息失败"); } } } ``` BankCard.java ```package com.dayuan.domain; import java.io.Serializable; import java.sql.Date; public class BankCard implements Serializable{ private Integer id; private String cardNumber; private String passWord; private String sum; private Date grearTime; private Date mtime; private Integer version; private Integer userId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } public String getSum() { return sum; } public void setSum(String sum) { this.sum = sum; } public Date getGrearTime() { return grearTime; } public void setGrearTime(Date grearTime) { this.grearTime = grearTime; } public Date getMtime() { return mtime; } public void setMtime(Date mtime) { this.mtime = mtime; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } @Override public String toString() { return "BankCard [id=" + id + ", cardNumber=" + cardNumber + ", passWord=" + passWord + ", sum=" + sum + ", grearTime=" + grearTime + ", mtime=" + mtime + ", version=" + version + ", userId=" + userId + "]"; } } ``` BankCardServiceImpl.java ```package com.dayuan.serviceimpl; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.dayuan.domain.BankCard; import com.dayuan.domain.Flow; import com.dayuan.domain.PageHolder; import com.dayuan.dto.FLowTenDTO; import com.dayuan.exception.BizException; import com.dayuan.mapper.BankCardMapper2; import com.dayuan.mapper.FlowMapper; import com.dayuan.utill.DateUtils; @Component public class BankCardServiceImpl implements BankCardService { @Autowired private BankCardMapper2 bankCardMapper; @Autowired private FlowMapper flowMapper; @Autowired private RedisService redisService; @Override public PageHolder listBankCard(int userId, int currentPage) { int totalElement = bankCardMapper.countBankCard(userId); PageHolder ph = new PageHolder(currentPage, totalElement); List<BankCard> list = bankCardMapper.listBankCard(userId, ph.getOffset(), PageHolder.PRE_PAGE_NUM); System.out.println(list); ph.setObj(list); return ph; } @Override public void deleteCard(int cardId) { int rows = bankCardMapper.deleteCard(cardId); if (1 != rows) { throw new BizException("删除失败"); } } @Override public List<FLowTenDTO> listFLow(int userId) { // TODO Auto-generated method stub List<FLowTenDTO> saveListFlow = redisService.listFLow(userId); if(null != saveListFlow) { System.out.println("流水走缓存"); return saveListFlow; } List<Flow> list = flowMapper.listFlowByUseId(userId, 10); List<FLowTenDTO> listFLow = new ArrayList<>(list.size()); for (Flow flow : list) { FLowTenDTO dto = new FLowTenDTO(); listFLow.add(dto); dto.setAmount(flow.getAmount()); dto.setCardNum(flow.getCardNum()); dto.setCreateTime(DateUtils.dateToString(flow.getCreateTime())); dto.setDescript(flow.getDescript()); System.out.println(flow.getDescript()); dto.setFlowType(flow.getFlowType()); dto.setId(flow.getId()); } redisService.saveListFlow(userId, listFLow); return listFLow; } @Override public List<BankCard> listBankCard(int userId) { List<BankCard> list = redisService.listBankCard(userId); if (null != list) { System.out.println(">>>>>>>>走缓存"); return list; } System.out.println(">>>>>>>>没走缓存"); list = bankCardMapper.listBankCard(userId, null, null); // 保存到缓存 redisService.saveBankCard(list, userId); return list; } }``` TestMessageMapper.java ```package com.dayuan.test; import static org.junit.Assert.assertEquals; 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 org.springframework.transaction.annotation.Transactional; import com.dayuan.domain.Message; import com.dayuan.mapper.MessageMapper; import com.dayuan.mapper.UserMapper; @RunWith(SpringRunner.class) @ContextConfiguration({ "/spring.xml" }) @Transactional public class TestMessageMapper { @Autowired private MessageMapper messageMapper; private Message message; @Test public void countMessage() { Message message = new Message(); message.setId(1); message.setMsg("dsd"); message.setUserId(2); message.setStatus(0); int rows = messageMapper.countMessage(2); assertEquals(1, rows); } @Test public void updateStatus() { int rows = messageMapper.updateStatus(0, 2); assertEquals(1, rows); } } ``` HandlerMapping2.java ```package com.dayuan.handler; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class HandlerMapping2 { private static ApplicationContext context; public static void init() { context = new ClassPathXmlApplicationContext(new String[] {"/spring/spring.xml"}); } public static Object getController(String key) { return context.getBean(key); } } ``` WXAuthenController.java ```package com.dayuan.controller; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON; import com.dayuan.domain.User; import com.dayuan.domain.WxLogin; import com.dayuan.dto.AjaxDTO; import com.dayuan.dto.WXAuthenDTO; import com.dayuan.dto.WXUserInfoDTO; import com.dayuan.exception.BizException; import com.dayuan.handler.WXAuthenHandler; import com.dayuan.serviceimpl.ThirdAuthorService; import com.dayuan.serviceimpl.UserService; import com.dayuan.utill.AESUtils; @Controller @RequestMapping("/wxAuthen") public class WXAuthenController { // private String appId = "2018010817121159519"; // private String redirectUri = "http://127.0.0.1:8080/wxAuthen/wxLoginCallBack.do"; private static final Logger log = LoggerFactory.getLogger(WXAuthenHandler.class); @Autowired private ThirdAuthorService thirdAuthorService; @Autowired private UserService userService; @Autowired private WXAuthenHandler wXAuthenHandler; @RequestMapping("/toWxLogin") public String toWxLogin() {// 微信登录 获得二维码登录接口 // // 获取code请求地址 // StringBuilder.append("http://payhub.dayuanit.com/weixin/connect/qrconnect.do?").append("appid=").append(appId) // .append("&").append("redirect_uri=").append(redirectUri).append("&").append("response_type=code") // .append("&").append("scope=snsapi_login"); String codeUrl = wXAuthenHandler.getCodeUrl(); return "redirect:" + codeUrl; } @RequestMapping("/wxLoginCallBack") public String wxLoginCallBack(String code, HttpServletRequest request, HttpSession session) { // System.out.println(">>>>>>>code:" + code); // // StringBuilder StringBuilder = new StringBuilder(); // //获取access_token的请求地址 // StringBuilder.append("http://payhub.dayuanit.com/weixin/sns/oauth2/access_token.do?").append("appid=") // .append(appId).append("&").append("redirect_uri=").append(redirectUri).append("&").append("code=") // .append(code).append("&").append("authorization_code"); // // CloseableHttpClient httpclient = HttpClients.createDefault();// 创建http客户端 // HttpGet httpGet = new HttpGet(StringBuilder.toString());// 获得get请求的url地址 // try { // CloseableHttpResponse httpResponse = httpclient.execute(httpGet);//执行其中的请求 // String result = EntityUtils.toString(httpResponse.getEntity());//获取响应头里的信息转化为字符串的结果集 // System.out.println(">>>>>>>>>result:" + result); // // WXAuthenDTO authenDTO = JSON.parseObject(result, WXAuthenDTO.class);//将字符串转化为对象,便于操作 WXAuthenDTO authenDTO = wXAuthenHandler.getAccessToken(code); log.info(">>>>>>>>>accessToken:" + authenDTO.getAccess_token()); WxLogin wxLogin = thirdAuthorService.saveAuthor(authenDTO);//保存返回的参数到数据库 if (null != wxLogin.getUserId()) { User user = userService.getUserId(wxLogin.getUserId()); if (null == user) { throw new BizException("认证失败"); } session.setAttribute("user", user); return "redirect:/user/toUserCenter.do"; } // HttpGet userInfoGet = new HttpGet("http://payhub.dayuanit.com/weixin/sns/userinfo.do?access_token=" // + authenDTO.getAccess_token() + "&openid=" + authenDTO.getOpenid()); // CloseableHttpClient httpclient = HttpClients.createDefault();// 创建http客户端 // CloseableHttpResponse httpResponse; // httpResponse = httpclient.execute(userInfoGet); // String result = EntityUtils.toString(httpResponse.getEntity()); // log.info(">>>>>>>>>用户微信信息:" + result); // // Map<String, String> wxInfo = JSON.parseObject(result, Map.class); // log.info(">>>>>>>>>>>nickname=" + wxInfo.get("nickname")); WXUserInfoDTO wxInfo = wXAuthenHandler.getWxUserInfo(authenDTO); session.setAttribute("nickname", wxInfo.getNickname()); session.setAttribute("headimgurl", wxInfo.getHeadimgurl()); session.setAttribute("openid",wxInfo.getOpenid());//通过0penId来绑定 return "redirect:/wxAuthen/toBindLogin.do"; } @RequestMapping("/toBindLogin") public String toBindLogin() { return "bindLogin"; } @RequestMapping("/wxLogin") @ResponseBody public AjaxDTO wxLogin(String username, String passWord, String openid, HttpSession session) { User user = thirdAuthorService.bindUser(username, passWord, (String)session.getAttribute("openid") ); session.setAttribute("user", user); return AjaxDTO.success(); } } ``` TransferMessageHandler2.java ```package com.dayuan.handler; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.dayuan.websocket.handler.ATMWebSocketHandler; @Component public class TransferMessageHandler2 { // 单例执行调度程序 private static final ExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); @Autowired private ATMWebSocketHandler atmWebSocketHandler; public void sendMessage(int userId, String msg) { executorService.execute(new Runnable() { @Override public void run() { atmWebSocketHandler.sendMessage(userId, msg); } }); } } ``` TransferMapper.java ```package com.dayuan.mapper; import java.util.Date; import java.util.List; import org.apache.ibatis.annotations.Param; import com.dayuan.domain.Transfer; public interface TransferMapper { int addTransf(Transfer transfer); List<Transfer> list4TransferIn(@Param("status")Integer status, @Param("deadTime")Date deadTime); Transfer selectTransf(int id); int modifyStatus(@Param("newStatus") Integer newStatus, @Param("id") Integer id); List<Transfer> selectStatus(@Param("status")Integer status); } ``` TransferCancelTask.java ```package com.dayuan.task; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.dayuan.domain.Transfer; import com.dayuan.mapper.TransferMapper; import com.dayuan.serviceimpl.AtmService; @Component("transferCancelTask") public class TransferCancelTask { private static final Logger log = LoggerFactory.getLogger(TransferCancelTask.class); @Autowired private TransferMapper transferMapper; @Autowired private AtmService atmService; public void doTask() { List<Transfer> lists = transferMapper.selectStatus(2); log.info("转账失败卡数:"+lists.size()); for(Transfer transfer:lists) { try{ atmService.rooBack(transfer); log.info("转账取消回滚卡号:"+transfer.getTfBankcard()); }catch (Exception e) { log.error("转账取消回滚卡号失败:"+transfer.getTfBankcard(), e); } } } } ``` UserController.java ```package com.dayuan.controller; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Iterator; import java.util.List; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.util.WebUtils; import com.dayuan.domain.User; import com.dayuan.dto.AjaxDTO; import com.dayuan.exception.BizException; import com.dayuan.serviceimpl.RedisService; import com.dayuan.serviceimpl.UserService; @Controller @RequestMapping("/user") public class UserController extends BaseController { @Autowired private UserService userService; @Autowired private RedisService redisService; static Logger log = LoggerFactory.getLogger(UserController.class); // @RequestMapping("/showPic") // public void showPic(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // String rp = req.getServletContext().getRealPath("/");// 閿熺煫纰夋嫹閿熸枻鎷烽敓鏂ゆ嫹璺敓鏂ゆ嫹 // // HttpSession session = req.getSession();// 閿熸枻鎷锋病宄勶拷 // User user = (User) session.getAttribute("user");// 閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷烽敓锟� // // String filepath = rp + "\\WEB-INF\\upload\\" + user.getId(); // // System.out.println(">>>>>>>>>>filepath=" + filepath); // try (FileInputStream fis = new FileInputStream(filepath); OutputStream os = resp.getOutputStream()) { // byte[] data = new byte[1024]; // int length = -1; // while (-1 != (length = fis.read(data))) { // os.write(data, 0, length); // os.flush(); // } // } // } @RequestMapping("/showPic") public void showPic(HttpSession session, HttpServletResponse resp) throws ServletException, IOException { String filepath = WebUtils.getRealPath(session.getServletContext(), "/upload/" + getUserId(session)); try (FileInputStream fis = new FileInputStream(filepath); OutputStream os = resp.getOutputStream()) { byte[] data = new byte[1024]; int length = -1; while (-1 != (length = fis.read(data))) { os.write(data, 0, length); os.flush(); } } } @RequestMapping("/upload2") public String upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024);// 閿熻緝杈炬嫹1024 String rp = req.getServletContext().getRealPath("/"); System.out.println("rp=" + rp); factory.setRepository(new File(rp + "/WEB-INF/upload-tmp"));// 閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷锋椂閿熸枻鎷烽敓鏂ゆ嫹閿燂拷 ServletFileUpload upload = new ServletFileUpload(factory);// Servlet閿熶茎纭锋嫹閿熻緝杈炬嫹 upload.setSizeMax(4194304);// 閿熸枻鎷烽敓鐭昂杈炬嫹閿熸枻鎷烽敓锟� try { List<FileItem> items = upload.parseRequest(req); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); System.out.println("[" + name + "=" + value + "]"); } else { HttpSession session = req.getSession(); User user = (User) session.getAttribute("user"); // String fileName = "" + user.getId(); String fileName = String.valueOf(user.getId());// 閿熸枻鎷峰彇閿熺煫浼欐嫹閿熸枻鎷穒d File uploadedFile = new File(rp + "/WEB-INF/upload/" + fileName);// 閿熻緝杈炬嫹閿熸枻鎷烽敓渚ョ》鎷� item.write(uploadedFile);// 鍐欓敓鏂ゆ嫹閿熸枻鎷烽敓閰佃锟� } } } catch (Exception e) { e.printStackTrace(); } return toUserCenter(req, resp); } // 推荐 @RequestMapping("/upload") public void upload(MultipartFile upfile, HttpSession session, HttpServletResponse respon) { try { if (!upfile.isEmpty()) { String filePath = WebUtils.getRealPath(session.getServletContext(), "/upload/" + getUserId(session)); File uploadedFile = new File(filePath); upfile.transferTo(uploadedFile); OutputStream os = respon.getOutputStream(); os.write("<script type=\"text/javascript\">parent.loadAvatar();</script>".getBytes()); os.flush(); os.close(); } } catch (Exception e) { e.printStackTrace(); } } // public AjaxDTO login(HttpServletRequest req, HttpServletResponse resp) throws // ServletException, IOException { // String username = req.getParameter("username"); // String password = req.getParameter("password"); // // resp.setContentType("text/html;charset=utf-8"); // resp.setCharacterEncoding("utf-8"); // // try { // User user = userService.login(username, password); // HttpSession session = req.getSession(); // session.setAttribute("user", user); // // return AjaxDTO.success(); // } catch (BizException be) { // return AjaxDTO.faild(be.getMessage()); // } // // } @RequestMapping("/login") @ResponseBody public AjaxDTO login(String username, String passWord, String code, HttpServletRequest req) { //不能为"" 或null if (StringUtils.isBlank(code)) { return AjaxDTO.faild("验证码错误"); } code = code.trim();//忽略字符左右两边的空格 Object obj = req.getSession().getAttribute("capcode"); if (null == obj) { return AjaxDTO.faild("验证码错误"); } String realCode = (String)obj; //不区分大小写比较 if (!realCode.equalsIgnoreCase(code)) { return AjaxDTO.faild("验证码错误"); } User user = userService.login(username, passWord); HttpSession session = req.getSession(); session.setAttribute("user", user); return AjaxDTO.success(); } @RequestMapping("/toLoad") public String toLoad(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { return "load"; } @RequestMapping("/toLogin") public String toLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { return "login"; } @RequestMapping("/toOpenAccount") public String toOpenAccount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { return "openAccount"; } // @RequestMapping("/regist") // @ResponseBody // public AjaxDTO regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // String username = req.getParameter("username"); // String password = req.getParameter("passWord"); // // OutputStream os = resp.getOutputStream(); // // try { // User user = userService.regist(username, password); // return AjaxDTO.success(); // // } catch (BizException be) { // return AjaxDTO.faild(be.getMessage()); // } catch (Exception e) { // log.error(e.getMessage(), e); // return AjaxDTO.faild("注册失败,请联系客服"); // } // // } @RequestMapping("/toRegist") public String toRegist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String token = UUID.randomUUID().toString();//UUID是由一个十六位的数字组成,表现出来的形式的唯一码 req.getSession().setAttribute("registToken", token); return "regist"; } @RequestMapping("/regist") @ResponseBody public AjaxDTO regist(String username, String passWord, String registToken, HttpSession session) { if(StringUtils.isBlank(registToken)) { return AjaxDTO.faild("非法请求"); } Object obj = session.getAttribute("registToken"); if(null == obj) { return AjaxDTO.faild("请刷新页面,重新注册1"); } if(!registToken.equals(obj.toString()) ) { return AjaxDTO.faild("请刷新页面,重新注册"); } System.out.println(">>>>." + username); userService.regist(username, passWord); session.removeAttribute(registToken); return AjaxDTO.success(); } @RequestMapping("/regist2") @ResponseBody public AjaxDTO regist2(String username, String password, String registToken, HttpSession session) { String key = "regist:" + username;//获得key boolean flag = redisService.setNX(key, 1); if (!flag) { return AjaxDTO.faild("请求太频繁"); } userService.regist(username, password); return AjaxDTO.success(); } @RequestMapping("/logout") public String logout(HttpSession session) { session.invalidate();//废掉session return "redirect:/user/toLogin.do";//重定向 } } ``` pageHelper.java ```package com.dayuan.utill; public class pageHelper { /** * 总行数 */ private int totalCount; /** * 单页行数 */ private int pageNum = 5; /** * 当前页 */ private int currentPageIndex = 1; /** * 总页数 */ private int totalPages; /** * 开始索引 */ private int startIndex = 0; public pageHelper() { // TODO Auto-generated constructor stub } public pageHelper(Integer currentPageIndex, Integer totalCount) { this.currentPageIndex = currentPageIndex; this.totalCount = totalCount; /** * 计算总页数 */ if (totalCount % pageNum == 0) { totalPages = totalCount / pageNum; } else { totalPages = totalCount / pageNum + 1; } /** * 计算开始索引 */ startIndex = (currentPageIndex - 1) * pageNum; } public Integer getTotalCount() { return totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getCurrentPageIndex() { return currentPageIndex; } public void setCurrentPageIndex(int currentPageIndex) { this.currentPageIndex = currentPageIndex; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } public Integer getStartIndex() { return startIndex; } public void setStartIndex(Integer startIndex) { this.startIndex = startIndex; } } ``` TestJson.java ```//package com.dayuan.dto; // //import java.util.ArrayList; //import java.util.List; // //import com.alibaba.fastjson.JSON; // //public class TestJson { // // public static void main(String[] args) { // AjaxDTO dto = new AjaxDTO(true, "΄σΤ³IT"); // String jsonString = JSON.toJSONString(dto); // System.out.println(jsonString); // // String xxx = "{\"message\":\"΄σΤ³IT\",\"success\":true}"; // AjaxDTO dto2 = JSON.parseObject(xxx, AjaxDTO.class); // System.out.println(dto2.getMessage()); // // List<AjaxDTO> list = new ArrayList<>(); // list.add(new AjaxDTO(true, "΄σΤ³IT")); // list.add(new AjaxDTO(true, "΄σΤ³IT")); // // // System.out.println(JSON.toJSONString(list)); // // } //} ``` MessageMapper.java ```package com.dayuan.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.dayuan.domain.Message; public interface MessageMapper { int countMessage(Integer userId); List<Message> selectMessage(Integer userId); int add(Message message); int updateStatus(@Param("status")Integer status, @Param("userId")Integer userId); List<Message> listMessage(@Param("userId")Integer userId, @Param("offset")Integer offset, @Param("prePage")Integer prePage); int countAllMessage(Integer userId); } ``` RedistTest.java ```package com.dayuan.test; import java.io.Serializable; import com.alibaba.fastjson.JSON; import redis.clients.jedis.Jedis; public class RedistTest { public static void main(String[] args) { Jedis jedis = new Jedis("192.168.8.184", 6379); Person person = new Person(); person.setAge(10); person.setUsername("jim"); String personJson = JSON.toJSONString(person);//jeson½âÎöµÄ×Ö·û´® System.out.println(personJson); jedis.set("person:1002", personJson); System.out.println(jedis.get("person:1002")); String personString = jedis.get("person:1002"); Person person2 = JSON.parseObject(personString, Person.class); System.out.println(person2.getAge() + " " + person2.getUsername()); } } class Person implements Serializable{ private int age; private String username ; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } ``` PageHolder.java ```package com.dayuan.domain; public class PageHolder { public static final int PRE_PAGE_NUM = 3; private int currentPageNum = 1;//当前页 private int totalPageNum;//总页数 private Object obj; private int offset = 0;//偏移量 private int totalElementNum;//总条数 public PageHolder(int currentPageNum, int totalElementNum) { this.currentPageNum = currentPageNum; this.totalElementNum = totalElementNum; } public int getOffset() { return (currentPageNum - 1) * PRE_PAGE_NUM; } public int getTotalPageNum() {//获得总页数 return totalElementNum % PRE_PAGE_NUM == 0 ? totalElementNum / PRE_PAGE_NUM : totalElementNum / PRE_PAGE_NUM + 1; } public Object getObj() { return obj; } public void setObj(Object obj) { this.obj = obj; } public int getCurrentPageNum() { return currentPageNum; } } ``` ThirdAuthorService.java ```package com.dayuan.serviceimpl; import com.dayuan.domain.User; import com.dayuan.domain.WxLogin; import com.dayuan.dto.WXAuthenDTO; public interface ThirdAuthorService { WxLogin saveAuthor(WXAuthenDTO authenDTO); WxLogin queryAuthor(String openid); User bindUser(String username, String passWord, String openid); } ``` TestJob.java ```package com.dayuan.task; //public class TestJob { // // public void doTask() { // System.out.println("hello world"); // } // // public void doTask2() { // System.out.println("hello world 2"); // // try { // Thread.sleep(5000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // } // //} ``` BankCardController.java ```package com.dayuan.controller; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.dayuan.domain.BankCard; import com.dayuan.domain.Flow; import com.dayuan.domain.PageHolder; import com.dayuan.domain.User; import com.dayuan.dto.AjaxDTO; import com.dayuan.serviceimpl.AtmService; import com.dayuan.serviceimpl.BankCardService; import com.dayuan.utill.TestLogback; @Controller @RequestMapping("/card") public class BankCardController extends BaseController { @Autowired private AtmService atmService; @Autowired private BankCardService bankCardService; private Logger log = LoggerFactory.getLogger(BankCardController.class); // public void setAtmService(AtmService atmService) { // this.atmService = atmService; // } // // public void setBankCardService(BankCardService bankCardService) { // this.bankCardService = bankCardService; // } @RequestMapping("/openAccount") @ResponseBody public AjaxDTO openAccount(String passWord, HttpSession session) { if (StringUtils.isBlank(passWord)) { return AjaxDTO.faild("密码不能为空"); } BankCard bc = atmService.openAccount(passWord, getUserId(session)); return AjaxDTO.success(bc); } // @RequestMapping("/toPage") // public String toPage(HttpServletRequest req, HttpServletResponse resp) throws // ServletException, IOException { // HttpSession session = req.getSession(); // System.out.println(session); // String pageName = req.getParameter("pageName"); // return req.getParameter("pageName"); // } // @RequestMapping("/toDeposit") // public String toDeposit(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // String cardNumber = req.getParameter("cardNumber"); // req.setAttribute("cardNumber", cardNumber); // req.getRequestDispatcher("/WEB-INF/page/deposit.jsp").forward(req, resp); // // // String deposit = req.getParameter("deposit"); // // req.getRequestDispatcher("/WEB-INF/page/deposit.jsp").forward(req, resp); // return "deposit"; // } // @RequestMapping("/toDeposit") // public String toDeposit(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // String cardNumber = req.getParameter("cardNumber"); // req.setAttribute("cardNumber", cardNumber); // req.getRequestDispatcher("/WEB-INF/page/deposit.jsp").forward(req, resp); // // // String deposit = req.getParameter("deposit"); // // req.getRequestDispatcher("/WEB-INF/page/deposit.jsp").forward(req, resp); // return "deposit"; // } @RequestMapping("/deposit") @ResponseBody public AjaxDTO deposit(String sum, String cardNumber, String passWord) { System.out.println("111,1,1,"+sum+ cardNumber+passWord); atmService.deposit(sum, cardNumber, passWord); BankCard bankCard = atmService.getBankCard(cardNumber); return AjaxDTO.success(bankCard); } @RequestMapping("/toDeposit") public String toDeposit() { return "deposit"; } @RequestMapping("/toDraw") public String toDraw(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { return "draw"; } // @RequestMapping("/draw") // public String draw(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // String cardNumber = req.getParameter("cardNumber"); // String passWord = req.getParameter("passWord"); // String sum = req.getParameter("sum"); // atmService.draw(sum, cardNumber, passWord); // BankCard bankCard = atmService.getBankCard(cardNumber); // req.setAttribute("bankCardAtm", bankCard); // return "bankCardInfo"; // } @RequestMapping("/draw") @ResponseBody public AjaxDTO draw(String cardNumber, String passWord, String sum ){ atmService.draw(sum, cardNumber, passWord); BankCard bankCard = atmService.getBankCard(cardNumber); return AjaxDTO.success(bankCard); } @RequestMapping("/toTransfer") public String toTransfer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String cardNumber = req.getParameter("cardNumber"); req.setAttribute("cardNumber", cardNumber); return "transfer"; } // @RequestMapping("/transfer") // public String transfer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // String outCardNum = req.getParameter("outCardNum"); // System.out.println(outCardNum); // String passWord = req.getParameter("passWord"); // String inCardNum = req.getParameter("inCardNum"); // String sum = req.getParameter("sum"); // atmService.transfer(sum, inCardNum, outCardNum, passWord); // BankCard bankCard = atmService.getBankCard(outCardNum); // req.setAttribute("bankCardAtm", bankCard); // return "bankCardInfo"; // } @RequestMapping("/transfer") @ResponseBody public AjaxDTO transfer(String sum, String inCardNum, String outCardNum, String passWord) { BankCard bankCard = atmService.getBankCard(outCardNum); atmService.outTransfer(sum, inCardNum, outCardNum, passWord); return AjaxDTO.success(bankCard); } @RequestMapping("/toFlow") public String toFlow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // String cardNumber =req.getParameter("cardNumber"); // String passWord = req.getParameter("passWord"); // List<Flow> list = atm.queryFlow(cardNumber, passWord); // req.setAttribute("flowInfo", list); // req.setAttribute("cardNumber", cardNumber); // req.setAttribute("passWord", passWord); String cardNumber = req.getParameter("cardNumber"); req.setAttribute("cardNumber", cardNumber); return "flow"; } @RequestMapping("/flow") @ResponseBody public AjaxDTO flow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String currentPage = req.getParameter("currentPage"); String cardNumber = req.getParameter("cardNumber"); String passWord = req.getParameter("passWord"); System.out.println("currentPage=" + currentPage); try { System.out.println("11"); PageHolder ph = atmService.queryFlow(cardNumber, passWord, Integer.parseInt(currentPage)); return AjaxDTO.success(ph); } catch (Exception e) { log.error("11111111",e); return AjaxDTO.faild(e.getMessage()); } } @RequestMapping("/deleteCard") public String deleteCard(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String cardId = req.getParameter("cardId"); bankCardService.deleteCard(Integer.parseInt(cardId)); return toUserCenter(req, resp); } @RequestMapping("/downFlow") public void downFlow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String cardNumber = req.getParameter("cardNumber"); String passWord = req.getParameter("passWord"); System.out.println("cardNumber=" + cardNumber); System.out.println("passWord=" + passWord); String filename = cardNumber + ".csv"; resp.setContentType("application/octet-stream"); resp.setHeader("Content-Disposition", "attachment;filename=" + filename); try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(resp.getOutputStream()))) { int currentPage = 1; String header = "ID,卡号,金额,备注"; bw.write(header); bw.newLine(); bw.flush(); System.out.println("w"); while (true) { PageHolder ph = atmService.queryFlow(cardNumber, passWord, currentPage); Object obj = ph.getObj(); if (null == obj) { break; } List<Flow> flowList = (List<Flow>) obj; if (flowList.isEmpty()) { break; } for (Flow flow : flowList) { StringBuilder sx = new StringBuilder(); sx.append(flow.getId()).append(",").append(flow.getCardNum()).append(",").append(flow.getAmount()) .append(",").append(flow.getDescript()).append(","); bw.write(sx.toString()); bw.newLine(); bw.flush(); } currentPage++; } } } @RequestMapping("/loadBankCard") @ResponseBody public AjaxDTO loadBankCard(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); User user = (User) session.getAttribute("user"); String currentPage = req.getParameter("currentPage"); currentPage = currentPage == null ? "1" : currentPage; // ��ѯ���п� PageHolder pageHolder = bankCardService.listBankCard(user.getId(), Integer.parseInt(currentPage)); return AjaxDTO.success(pageHolder); } @RequestMapping("/loadBankCardNoPage") @ResponseBody public AjaxDTO loadBankCard(HttpSession session) { List<BankCard> bankCardList = bankCardService.listBankCard(getUserId(session)); return AjaxDTO.success(bankCardList); } @RequestMapping("/loadFLowTen") @ResponseBody public AjaxDTO loadFLowTen(HttpSession session) { try { return AjaxDTO.success(bankCardService.listFLow(getUserId(session))); } catch (Exception e) { log.error(e.getMessage(), e); return AjaxDTO.faild(e.getMessage()); } } } ``` MessageController.java ```package com.dayuan.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.dayuan.domain.PageHolder; import com.dayuan.dto.AjaxDTO; import com.dayuan.dto.MessageDTO; import com.dayuan.mapper.MessageMapper; import com.dayuan.serviceimpl.MessageService; import com.dayuan.serviceimpl.UserService; @Controller @RequestMapping("/message") public class MessageController extends BaseController { @Autowired private MessageService messageService; private Logger log = LoggerFactory.getLogger(BankCardController.class); @RequestMapping("/messageInfo") @ResponseBody public AjaxDTO messageInfo(HttpSession session) { MessageDTO msg = messageService.setMessage(getUserId(session)); return AjaxDTO.success(msg); // return AjaxDTO.success(messageService.setMessage(getUserId(session))); } // @RequestMapping("/modifymessage") // @ResponseBody // public AjaxDTO modifymessage(HttpSession session) { // // return AjaxDTO.success(messageService.modifyMessage(getUserId(session))); // // } @RequestMapping("/messageFlow") @ResponseBody public AjaxDTO messageFlow(int currentPageNum , HttpSession session) { PageHolder msg = messageService.listMessage(currentPageNum ,getUserId(session)); // messagemapper.updateStatus(1, getUserId(session)); return AjaxDTO.success(msg); } @RequestMapping("/toMessage") public String toMessage(HttpSession session) { messageService.readMessage(getUserId(session)); return "messageFlow"; } }``` Transfer.java ```package com.dayuan.domain; public class Transfer { private Integer id; private String tfBlance; private String tfBankcard; private String cfBankcard; private String createTime; private String modifyTime; private Integer status; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTfBlance() { return tfBlance; } public void setTfBlance(String tfBlance) { this.tfBlance = tfBlance; } public String getTfBankcard() { return tfBankcard; } public void setTfBankcard(String tfBankcard) { this.tfBankcard = tfBankcard; } public String getCfBankcard() { return cfBankcard; } public void setCfBankcard(String cfBankcard) { this.cfBankcard = cfBankcard; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getModifyTime() { return modifyTime; } public void setModifyTime(String modifyTime) { this.modifyTime = modifyTime; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } } ``` AtmService.java ```package com.dayuan.serviceimpl; import java.util.List; import com.dayuan.domain.BankCard; import com.dayuan.domain.PageHolder; import com.dayuan.domain.Transfer; public interface AtmService { BankCard openAccount(String passWord,int userId);// ���� void deposit(String sum, String cardNumber, String passWord);// ��Ǯ void draw(String sum, String cardNumber, String passWord);// ȡǮ void transfer(String sum, String inCardNum, String outCardNum, String passWord);// ת�� PageHolder queryFlow(String cardNumber, String passWord, int currentPage);//��ҳ��ѯ��ˮ int countFlow(String cardNumber, String passWord); BankCard getBankCard(String cardNumber); void outTransfer(String sum, String inCardNum, String outCardNum, String passWord); void intTransfer(Transfer transfer); void rooBack(Transfer transfer); } ``` ThirdAuthorServiceImpl.java ```package com.dayuan.serviceimpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dayuan.domain.User; import com.dayuan.domain.WxLogin; import com.dayuan.dto.WXAuthenDTO; import com.dayuan.exception.BizException; import com.dayuan.mapper.WxLoginMapper; import com.dayuan.utill.AESUtils; @Service public class ThirdAuthorServiceImpl implements ThirdAuthorService { @Autowired private WxLoginMapper wxLoginMapper; @Autowired private UserService userService; @Override public WxLogin saveAuthor(WXAuthenDTO authenDTO) { WxLogin wxLogin = wxLoginMapper.getAuthor(authenDTO.getOpenid()); if (null == wxLogin) { wxLogin = new WxLogin(); wxLogin.setExpiresIn(authenDTO.getExpires_in()); wxLogin.setOpenid(authenDTO.getOpenid()); wxLogin.setRefreshToken(authenDTO.getRefresh_token()); wxLogin.setAcceccToken(authenDTO.getAccess_token()); wxLogin.setUserId(null); int rows = wxLoginMapper.add(wxLogin); if (1 != rows) { throw new BizException("登录失败"); } } else { wxLogin.setAcceccToken(authenDTO.getAccess_token()); wxLogin.setExpiresIn(authenDTO.getExpires_in()); wxLogin.setOpenid(authenDTO.getOpenid()); wxLogin.setRefreshToken(authenDTO.getRefresh_token()); int rows = wxLoginMapper.update(wxLogin); if (1 != rows) { throw new BizException("登录失败"); } } return wxLogin; } @Override public WxLogin queryAuthor(String openid) { // TODO Auto-generated method stub WxLogin wxLogin = wxLoginMapper.getAuthor(openid); return wxLogin; } @Override public User bindUser(String username, String passWord, String openid) { // try { // openid =AESUtils.decodeMsg(openid.getBytes()); // System.out.println("<<<<<<<<解密后:"+openid); // }catch (Exception e) { // throw new BizException("揭秘失败"); } WxLogin wxLogin = wxLoginMapper.getAuthor(openid); if (null == wxLogin) { throw new BizException("认证失败"); } User user = userService.login(username, passWord); wxLogin.setUserId(user.getId()); int rows = wxLoginMapper.update(wxLogin); if (1 != rows) { throw new BizException("认证失败"); } return user; } } ``` MessageServiceImpl.java ```package com.dayuan.serviceimpl; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.dayuan.domain.Message; import com.dayuan.domain.PageHolder; import com.dayuan.dto.MessageDTO; import com.dayuan.dto.MessageDTO.Messageinfo; import com.dayuan.dto.MessageString; import com.dayuan.mapper.MessageMapper; import com.dayuan.utill.DateUtils; @Component public class MessageServiceImpl implements MessageService { @Autowired private MessageMapper messagemapper; // @Autowired // private MessageDTO messageDto ; @Override public MessageDTO setMessage(int userId) { // 统计未读消息数 int rows = messagemapper.countMessage(userId); // 获得想要查询的三条数据 List<Message> message3 = messagemapper.selectMessage(userId); // ArrayList<Messageinfo> messageList = new ArrayList<>(message3.size()); for (Message list : message3) { Messageinfo messageinfo = new Messageinfo(); // 装入ArrayList<Messageinfo> Messageinfo类型的 messageList.add(messageinfo); // Messageinfo集合里设置 获取值 messageinfo.setMsg(list.getMsg()); messageinfo.setStatus(list.getStatus()); messageinfo.setCreateTime(list.getCreateTime().getTime()); } MessageDTO messageDto = new MessageDTO(); messageDto.setCountMessage(rows); messageDto.setList(messageList); // messagemapper.updateStatus(1, userId); return messageDto; } @Override public PageHolder listMessage(int currentPageNum, int userId) { int totalElement = messagemapper.countAllMessage(userId); PageHolder ph = new PageHolder(currentPageNum, totalElement); List<Message> messageAll = messagemapper.listMessage(userId, ph.getOffset(), PageHolder.PRE_PAGE_NUM); ArrayList<MessageString> msg = new ArrayList<>(); for(Message list:messageAll) { MessageString messageString = new MessageString(); messageString.setCreateTime(DateUtils.dateToString(list.getCreateTime())); messageString.setId(list.getId()); messageString.setMsg(list.getMsg()); messageString.setUserId(list.getUserId()); messageString.setStatus(list.getStatus()); msg.add(messageString); } ph.setObj(msg); return ph; } @Override public void readMessage(int userId) { messagemapper.updateStatus(1, userId); } } //for (Message list: messageAll) { // MessageString stringMessage = new MessageString(); // stringMessage.setCreateTime(DateUtils.dateToString(list.getCreateTime())); // stringMessage.setId(list.getId()); // stringMessage.setMsg(list.getMsg()); // msg.add(stringMessage); //} ``` UserServiceImpl.java ```package com.dayuan.serviceimpl; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.dayuan.domain.User; import com.dayuan.exception.BizException; import com.dayuan.mapper.UserMapper; @Component public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User regist(String username, String passWord) { User selcetUser = userMapper.getUser(username); if (null != selcetUser) { throw new BizException("该用户已经存在"); } User user = new User(); if (StringUtils.isBlank(username)) { throw new BizException("账号不能为空"); } if (StringUtils.isBlank(passWord)) { throw new BizException("密码不能为空"); } user.setPassword(DigestUtils.md5Hex(passWord + username)); user.setUsername(username); int rows = userMapper.addUser(user); if (rows != 1) { throw new BizException("注册失败"); } return user; } @Override public User login(String username, String passWord) { User user = userMapper.getUser(username); if (null == user) { throw new BizException("用户名不存在"); } if (StringUtils.isBlank(username)) { throw new BizException("账号不能为空"); } if (StringUtils.isBlank(passWord)) { throw new BizException("账号不能为空"); } if (!user.getPassword().equals(DigestUtils.md5Hex(passWord + username))) { throw new BizException("密码错误"); } return user; } @Override public User modifyPwd(String oldPassword, String newPassword, String comfirmPassword, String username) { // TODO Auto-generated method stub User user = userMapper.getUser(username); System.out.println(user); if (null == user) { throw new BizException("用户名不存在"); } // //����̲� // if (null == newPassword || "".equals(newPassword)) { // throw new BizException("密码不能为空"); // } if (StringUtils.isBlank(newPassword)) { throw new BizException("新密码不能为空"); } if (StringUtils.isBlank(oldPassword)) { throw new BizException("旧密码不能为空"); } if (!newPassword.equals(comfirmPassword)) { throw new BizException("两次密码不相等"); } if (oldPassword.equals(newPassword)) { throw new BizException("新密码和老密码不能相同"); } if (!user.getPassword().equals(DigestUtils.md5Hex(oldPassword + username))) { throw new BizException("老密码错误"); } newPassword = DigestUtils.md5Hex(newPassword + username); // comfirmPassword = DigestUtils.md5Hex(newPassword + username); int rows = userMapper.modifyPwd(username, newPassword); if (1 != rows) { throw new BizException("修改失败"); } return user; } @Override public User getUserId(Integer userId) { User user = userMapper.getUserById(userId); return user; } } ``` AESUtils.java ```package com.dayuan.utill; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; public class AESUtils { private static final String private_key = "1234567812345678"; private static final String alg = "AES"; public static byte[] encode(byte[] data) { try { SecretKey secretKey = new SecretKeySpec(private_key.getBytes(), alg); Cipher cipher = Cipher.getInstance(alg + "/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return cipher.doFinal(data); } catch(Exception e) { e.printStackTrace(); } return null; } public static String encodeMsg(byte[] data) {// 加密 转换为字节 字节转换为Base64 字符串 try { SecretKey secretKey = new SecretKeySpec(private_key.getBytes(), alg); Cipher cipher = Cipher.getInstance(alg+ "/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] en = cipher.doFinal(data); return Base64.encodeBase64String(en); } catch(Exception e) { e.printStackTrace(); } return null; } public static byte[] decode(byte[] data) throws Exception { SecretKey secretKey = new SecretKeySpec(private_key.getBytes(), alg); Cipher cipher = Cipher.getInstance(alg + "/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] dataBase = Base64.decodeBase64(data); return cipher.doFinal(dataBase); } public static boolean check(String msg, String sign) throws Exception { byte[] deMsg = decode(msg.getBytes()); return sign.equals(new String(deMsg)); } public static String decodeMsg(byte[] data) throws Exception {//解码 SecretKey secretKey = new SecretKeySpec(private_key.getBytes(), alg); Cipher cipher = Cipher.getInstance(alg + "/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] dataBase = Base64.decodeBase64(data); return new String(cipher.doFinal(dataBase)); } public static void main(String args[]) throws Exception { String msg = "hello world"; byte[] encodeMsg = AESUtils.encode(msg.getBytes()); String miwen = Base64.encodeBase64String(encodeMsg); String noBase64Miwen = new String(encodeMsg); System.out.println("加密后:" + miwen); System.out.println("加密后>>:" + noBase64Miwen); String decodeMsg = AESUtils.decodeMsg(miwen.getBytes()); System.out.println("解密后:" + decodeMsg); } } ``` MessageDTO.java ```package com.dayuan.dto; import java.util.List; public class MessageDTO { private Integer countMessage; private List<Messageinfo> list; public Integer getCountMessage() { return countMessage; } public void setCountMessage(Integer countMessage) { this.countMessage = countMessage; } public List<Messageinfo> getList() { return list; } public void setList(List<Messageinfo> list) { this.list = list; } public static class Messageinfo { private Integer status; private String msg; private long createTime; public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } } } ``` UserService.java ```package com.dayuan.serviceimpl; import com.dayuan.domain.User; public interface UserService { User regist(String username, String passWord); User login(String username, String passWord); User modifyPwd(String oldPassword, String newPassword, String comfirmPassword, String username); User getUserId(Integer userId); } ``` ATMWebSocketHandler.java ```package com.dayuan.websocket.handler; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import com.dayuan.domain.Message; import com.dayuan.domain.User; import com.dayuan.mapper.MessageMapper; @Component("atmWebSocketHandler")//继承TextWebSocketHandler 这个类 并实现其中的方法 public class ATMWebSocketHandler extends TextWebSocketHandler { //线程安全的装键值对的map集合 private static final ConcurrentHashMap<Integer, WebSocketSession> map = new ConcurrentHashMap<>(); @Autowired private MessageMapper messageMapper; //发送信息要有对应的userid(人) 和信息 public void sendMessage(int userId, String message) { try { //持久化到数据库 Message addMessage = new Message(); addMessage.setMsg(message); addMessage.setStatus(0); addMessage.setUserId(userId); messageMapper.add(addMessage); //发送消息给客户端 WebSocketSession session = map.get(userId);//获得http协议里面的session里的userId if (null == session) { return; } //这个session里面发送一个(文本信息) session.sendMessage(new TextMessage(message)); } catch (IOException e) { map.remove(userId);//失败就忘掉这个session的userId } } @Override//建立连接的方法 public void afterConnectionEstablished(WebSocketSession session) throws Exception { Object obj = (Object) session.getAttributes().get("user");//获取登录时的设置的session的信息 if (null == obj) { System.out.println("没有session"); return; } User user = (User) obj; map.put(user.getId(), session);//在map里面放一个键值对 System.out.println("服务器端Websocket连接成功" + user.getUsername()); } @Override//处理文字信息 protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { System.out.println("客户端发送的消息:" + message.getPayload()); //服务端接到客户端信息,进行回应 session.sendMessage(new TextMessage("world")); //延迟五秒回复信息 new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); session.sendMessage(new TextMessage("thread world")); } catch (Exception e) { e.printStackTrace(); } } } ).start(); } @Override//连接关闭后 public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { Object obj = (Object) session.getAttributes().get("user"); if (null == obj) { System.out.println("没有session"); return; } User user = (User) obj; map.remove(user.getId());//关掉这个session } @Override//处理传输错误 public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { Object obj = (Object) session.getAttributes().get("user"); if (null == obj) { System.out.println("没有session"); return; } User user = (User) obj; map.remove(user.getId());//关掉这个session } }``` SpringTest.java ```package com.dayuan.test; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @ContextConfiguration({ "/spring.xml" }) public class SpringTest { @Autowired private RedisTemplate<String, String> template;// new一个spring.xml中的(RedisTemplate)连接工厂类来管理 @Resource(name = "redisTemplate") private ValueOperations<String, Person> personRedisTmp; @Resource(name = "redisTemplate") private HashOperations<String, String, Object> personRedisTmp1; @Resource(name = "redisTemplate") private ListOperations<String, Person> personRedisTmp2; @Test public void testSet() { //1 template.opsForValue().set("user:1005", "jim"); String user = template.opsForValue().get("user:1005"); System.out.println(user); //2 template.opsForHash().put("person:10025", "username", "p03"); template.opsForHash().put("person:10025", "age", "88"); //3 personRedisTmp2.leftPush("list:person", new Person()); } } ```
zhoujumbo/redis-config
zhoujumbo/redis-config 配置文件说明.md ```### Redis相关说明 #### 一、脚本/服务说明 > redis-server:Redis 服务器的daemon启动程序。 > redis-cli:Redis 命令行执行工具。当然,你也可以用telnet根据其纯文本协议来操作。 > redis-benchmark:Redis 性能检测工具,测试Redis在你的系统及你的配置下的读写性能。 > redis-stat:Redis 状态检测工具,可以检测 Redis 当前状态参数及延迟状况(高版本的Redis将没有这个脚本)。 > redis-check-dump:Redis dump 数据文件的修复工具。 > redis-check-aof:Redis aof 日志文件修复工具。 #### 二、配置详解 1. Redis默认不是以守护进程的方式运行,可以通过该配置项修改,使用yes启用守护进程 ​ **daemonize no** 2. 当Redis以守护进程方式运行时,Redis默认会把pid写入/var/run/redis.pid文件,可以通过pidfile指定 ​ **pidfile /var/run/redis.pid** 3. 指定Redis监听端口,默认端口为6379,作者在自己的一篇博文中解释了为什么选用6379作为默认端口,因为6379在手机按键上MERZ对应的号码,而MERZ取自意大利歌女Alessia Merz的名字 ​ **port 6379** 4. 绑定的主机地址 ​ **bind 127.0.0.1** 5.当 客户端闲置多长时间后关闭连接,如果指定为0,表示关闭该功能 ​ **timeout 300** 6. 指定日志记录级别,Redis总共支持四个级别:debug、verbose、notice、warning,默认为verbose ​ **loglevel verbose** 7. 日志记录方式,默认为标准输出,如果配置Redis为守护进程方式运行,而这里又配置为日志记录方式为标准输出,则日志将会发送给/dev/null ​ **logfile stdout** 8. 设置数据库的数量,默认数据库为0,可以使用SELECT <dbid>命令在连接上指定数据库id ​ **databases 16** 9. 指定在多长时间内,有多少次更新操作,就将数据同步到数据文件,可以多个条件配合 ​ **save <seconds> <changes>** ​ Redis默认配置文件中提供了三个条件: ​ **save 900 1** ​ **save 300 10** ​ **save 60 10000** ​ 分别表示900秒(15分钟)内有1个更改,300秒(5分钟)内有10个更改以及60秒内有10000个更改。 10. 指定存储至本地数据库时是否压缩数据,默认为yes,Redis采用LZF压缩,如果为了节省CPU时间,可以关闭该选项,但会导致数据库文件变的巨大 ​ **rdbcompression yes** 11. 指定本地数据库文件名,默认值为dump.rdb ​ **dbfilename dump.rdb** 12. 指定本地数据库存放目录 ​ **dir ./** 13. 设置当本机为slav服务时,设置master服务的IP地址及端口,在Redis启动时,它会自动从master进行数据同步 ​ **slaveof <masterip> <masterport>** 14. 当master服务设置了密码保护时,slav服务连接master的密码 ​ **masterauth <master-password>** 15. 设置Redis连接密码,如果配置了连接密码,客户端在连接Redis时需要通过AUTH <password>命令提供密码,默认关闭 ​ **requirepass foobared** 16. 设置同一时间最大客户端连接数,默认无限制,Redis可以同时打开的客户端连接数为Redis进程可以打开的最大文件描述符数,如果设置 maxclients 0,表示不作限制。当客户端连接数到达限制时,Redis会关闭新的连接并向客户端返回max number of clients reached错误信息 ​ **maxclients 128** 17. 指定Redis最大内存限制,Redis在启动时会把数据加载到内存中,达到最大内存后,Redis会先尝试清除已到期或即将到期的Key,当此方法处理 后,仍然到达最大内存设置,将无法再进行写入操作,但仍然可以进行读取操作。Redis新的vm机制,会把Key存放内存,Value会存放在swap区 ​ **maxmemory <bytes>** 18. 指定是否在每次更新操作后进行日志记录,Redis在默认情况下是异步的把数据写入磁盘,如果不开启,可能会在断电时导致一段时间内的数据丢失。因为 redis本身同步数据文件是按上面save条件来同步的,所以有的数据会在一段时间内只存在于内存中。默认为no ​ **appendonly no** 19. 指定更新日志文件名,默认为appendonly.aof ​ **appendfilename appendonly.aof** 20. 指定更新日志条件,共有3个可选值: **no**:表示等操作系统进行数据缓存同步到磁盘(快) **always**:表示每次更新操作后手动调用fsync()将数据写到磁盘(慢,安全) **everysec**:表示每秒同步一次(折衷,默认值) ​ **appendfsync everysec** 21. 指定是否启用虚拟内存机制,默认值为no,简单的介绍一下,VM机制将数据分页存放,由Redis将访问量较少的页即冷数据swap到磁盘上,访问多的页面由磁盘自动换出到内存中(在后面的文章我会仔细分析Redis的VM机制) ​ **vm-enabled no** 22. 虚拟内存文件路径,默认值为/tmp/redis.swap,不可多个Redis实例共享 ​ **vm-swap-file /tmp/redis.swap** 23. 将所有大于vm-max-memory的数据存入虚拟内存,无论vm-max-memory设置多小,所有索引数据都是内存存储的(Redis的索引数据 就是keys),也就是说,当vm-max-memory设置为0的时候,其实是所有value都存在于磁盘。默认值为0 ​ **vm-max-memory 0** 24. Redis swap文件分成了很多的page,一个对象可以保存在多个page上面,但一个page上不能被多个对象共享,vm-page-size是要根据存储的 数据大小来设定的,作者建议如果存储很多小对象,page大小最好设置为32或者64bytes;如果存储很大大对象,则可以使用更大的page,如果不 确定,就使用默认值 ​ **vm-page-size 32** 25. 设置swap文件中的page数量,由于页表(一种表示页面空闲或使用的bitmap)是在放在内存中的,,在磁盘上每8个pages将消耗1byte的内存。 ​ **vm-pages 134217728** 26. 设置访问swap文件的线程数,最好不要超过机器的核数,如果设置为0,那么所有对swap文件的操作都是串行的,可能会造成比较长时间的延迟。默认值为4 ​ **vm-max-threads 4** 27. 设置在向客户端应答时,是否把较小的包合并为一个包发送,默认为开启 ​ **glueoutputbuf yes** 28. 指定在超过一定的数量或者最大的元素超过某一临界值时,采用一种特殊的哈希算法 ​ **hash-max-zipmap-entries 64** ​ **hash-max-zipmap-value 512** 29. 指定是否激活重置哈希,默认为开启(后面在介绍Redis的哈希算法时具体介绍) ​ **activerehashing yes** 30. 指定包含其它的配置文件,可以在同一主机上多个Redis实例之间使用同一份配置文件,而同时各个实例又拥有自己的特定配置文件 ​ **include /path/to/local.conf** #### 三、其他 #### 基本配置 daemonize no 是否以后台进程启动 databases 16 创建database的数量(默认选中的是database 0) save 900 1 #刷新快照到硬盘中,必须满足两者要求才会触发,即900秒之后至少1个关键字发生变化。 save 300 10 #必须是300秒之后至少10个关键字发生变化。 save 60 10000 #必须是60秒之后至少10000个关键字发生变化。 stop-writes-on-bgsave-error yes #后台存储错误停止写。 rdbcompression yes #使用LZF压缩rdb文件。 rdbchecksum yes #存储和加载rdb文件时校验。 dbfilename dump.rdb #设置rdb文件名。 dir ./ #设置工作目录,rdb文件会写入该目录。 #### 主从配置 slaveof <masterip> <masterport> 设为某台机器的从服务器 masterauth <master-password> 连接主服务器的密码 slave-serve-stale-data yes # 当主从断开或正在复制中,从服务器是否应答 slave-read-only yes #从服务器只读 repl-ping-slave-period 10 #从ping主的时间间隔,秒为单位 repl-timeout 60 #主从超时时间(超时认为断线了),要比period大 slave-priority 100 #如果master不能再正常工作,那么会在多个slave中,选择优先值最小的一个slave提升为master,优先值为0表示不能提升为master。 repl-disable-tcp-nodelay no #主端是否合并数据,大块发送给slave slave-priority 100 从服务器的优先级,当主服挂了,会自动挑slave priority最小的为主服 #### 安全 requirepass foobared # 需要密码 rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52 #如果公共环境,可以重命名部分敏感命令 如config #### 限制 maxclients 10000 #最大连接数 maxmemory <bytes> #最大使用内存 maxmemory-policy volatile-lru #内存到极限后的处理 volatile-lru -> LRU算法删除过期key allkeys-lru -> LRU算法删除key(不区分过不过期) volatile-random -> 随机删除过期key allkeys-random -> 随机删除key(不区分过不过期) volatile-ttl -> 删除快过期的key noeviction -> 不删除,返回错误信息 ```makrdown 解释 LRU ttl都是近似算法,可以选N个,再比较最适宜T踢出的数据 maxmemory-samples 3 ``` #### 日志模式 appendonly no #是否仅要日志 appendfsync no # 系统缓冲,统一写,速度快 appendfsync always # 系统不缓冲,直接写,慢,丢失数据少 appendfsync everysec #折衷,每秒写1次 no-appendfsync-on-rewrite no #为yes,则其他线程的数据放内存里,合并写入(速度快,容易丢失的多) auto-AOF-rewrite-percentage 100 当前aof文件是上次重写是大N%时重写 auto-AOF-rewrite-min-size 64mb aof重写至少要达到的大小 #### 慢查询 slowlog-log-slower-than 10000 #记录响应时间大于10000微秒的慢查询 slowlog-max-len 128 # 最多记录128条 #### 服务端命令 time 返回时间戳+微秒 dbsize 返回key的数量 bgrewriteaof 重写aof bgsave 后台开启子进程dump数据 save 阻塞进程dump数据 lastsave slaveof host port 做host port的从服务器(数据清空,复制新主内容) slaveof no one 变成主服务器(原数据不丢失,一般用于主服失败后) flushdb 清空当前数据库的所有数据 flushall 清空所有数据库的所有数据(误用了怎么办?) shutdown [save/nosave] 关闭服务器,保存数据,修改AOF(如果设置) slowlog get 获取慢查询日志 slowlog len 获取慢查询日志条数 slowlog reset 清空慢查询 info [] config get 选项(支持*通配) config set 选项 值 config rewrite 把值写到配置文件 config restart 更新info命令的信息 debug object key #调试选项,看一个key的情况 debug segfault #模拟段错误,让服务器崩溃 object key (refcount|encoding|idletime) monitor #打开控制台,观察命令(调试用) client list #列出所有连接 client kill #杀死某个连接 CLIENT KILL 127.0.0.1:43501 client getname #获取连接的名称 默认nil client setname "名称" #设置连接名称,便于调试 #### 连接命令 auth 密码 #密码登陆(如果有密码) ping #测试服务器是否可用 echo "some content" #测试服务器是否正常交互 select 0/1/2... #选择数据库 quit #退出连接``` README.md ```### Redis-config ### windows版本 - 注册服务 1. 启动 运行 redis-server.exe redis.windows.conf 就启动了redis 2. 测试 另启一个cmd窗口,原来的cmd窗口不可关闭,不然Redis服务端就关闭了。 运行redis-cli.exe -h 127.0.0.1 -p 6379 设置键值对 set key1 123 取出键值对 get key2 得到123说明测试成功 3. 安装成Windows服务—开机自启 另启一个cmd窗口(管理员身份) 运行redis-server --service-install redis.windows.conf 4. 输入:redis-server --service-start ( 启动服务 ) 5. 输入:redis-server --service-stop (停止服务) 6. 启动指定的配置文件redis-server --service-start redis.windows-service.conf```
zhoulab/sclc-scripts
zhoulab/sclc-scripts run_all.sh ```#!/usr/bin/env bash # This script runs the pipeline for each of our desired gene lists. python -u run_pipeline.py -i ../data/4dataset_nonsilent.txt --mutsig_genes_file ../data/SigGenes_001.txt --result_dir ../results/GenePairs_SigGenes_001/ python -u run_pipeline.py -i ../data/4dataset_nonsilent.txt --mutsig_genes_file ../data/SigGenes_001.txt --result_dir ../results/GenePairs_SigGenes_005/ python -u run_pipeline.py -i ../data/4dataset_nonsilent.txt -p 2 --result_dir ../results/GenePairs_MoreThan2/ ``` README.md ```# oncotator files Full pipeline description: https://github.com/zhoulab/sclc-scripts/wiki/SCLC-mutation-analysis-pipeline ## `vcf_transform.py` ### `VCFFile` An extension of `pyvcf.Reader` that provides data access through `pandas.DataFrame`. ## `oncotator_maf_cross_check.py` Script to validate consistency between two oncotator MAF output files. ## `pandastsv.py` ### `get_tsv_df()` helper function used to load files in `oncotator_maf_cross_check.py`.``` oncotator_maf_cross_check.py ```""" Script to check if chr/start/end matches gene name for different MAF outputs of oncotator. *** MAY REQUIRE HIGH MEMORY USAGE *** FILE1 filepath of first file FILE2 filepath of second file KEY_COLS list of column names to use as unique key COL_TO_MATCH column name to cross check """ from pandastsv import get_tsv_df FILE1 = 'transformed_SCLC_onco.tsv' FILE2 = 'oncotator_muTect_122116VS.maf' KEY_COLS = ['Chromosome', 'Start_position', 'End_position'] COL_TO_MATCH = 'Entrez_Gene_Id' # get DataFrames df1 = get_tsv_df(FILE1, low_memory=False) df2 = get_tsv_df(FILE2, low_memory=False) # assert same number of rows assert len(df1) == len(df2), 'Number of rows are different.' # group by key columns df1_groups = df1.groupby(KEY_COLS) df2_groups = df2.groupby(KEY_COLS) for key, df1_group in df1_groups: df2_group = df2_groups.get_group(key) val1 = df1_group[COL_TO_MATCH].values[0] val2 = df2_group[COL_TO_MATCH].values[0] # assert on the specified column assert (val1 == val2), ', '.join(['{}={}'.format(x, eval(x)) for x in ['key', 'val1', 'val2']]) print 'These two files have identical information.' ``` README.md ```# sclc-scripts Scripts used in [Significantly mutated genes and regulatory pathways in SCLC—a meta-analysis](https://doi.org/10.1016/j.cancergen.2017.05.003). See folders for individual READMEs. ``` comutation_plot.py ```import argparse import csv import itertools import warnings import math import matplotlib matplotlib.use('PDF') import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import ListedColormap from collections import OrderedDict from itertools import islice # mutation type names for legend MUTATION_TYPE_MAP = OrderedDict([('3', 'C:G transitions'), ('4', 'C:G transversions'), ('5', 'A:T transitions'), ('6', 'A:T transversions'), ('7', 'null+indel mutations')]) def create_proxy(color): """Generate color proxy for use in plt.legend""" return matplotlib.lines.Line2D([0], [0], linestyle='none', mfc=color, mec='none', marker='s') def get_mutsig_gene_pvals(mutsig_genes_file, p_value=None): """Return dictionary for gene p-values from `mutsig_genes_file` Return ------ dict : { gene (str) : p-value (float) } """ with open(mutsig_genes_file, 'rU') as f: dialect = csv.Sniffer().sniff(f.read(1024)) f.seek(0) reader = csv.reader(f, delimiter='\t', dialect=dialect) col = reader.next().index('p') # find column index and ignore header if p_value: return {row[0]: float(row[col]) for row in reader if float(row[col]) <= p_value} return {row[0]: float(row[col]) for row in reader} def get_gene_info(args): """ Return sorted gene info If gene_list_file specified, sorted by the score column. Otherwise, sorted by p-value. NOTE: If there are multiple (gene,sample) pairs, the sample mutation for a gene shows only the final occurrence in the file. Return ------ genes_info (dict of dicts) OrderedDict( gene : { 'p' : p-value (float) 'score' : score (float) sample : mutation (str) } ) """ if args.gene_list_file: with open(args.gene_list_file) as f: genes_and_scores = OrderedDict([(line.split()[0], float(line.split()[1]) if len(line.split()) == 2 else None) for line in f]) else: all_genes_info = get_mutsig_gene_pvals(args.mutsig_genes_file, args.p_value) genes_info = OrderedDict() with open(args.mutation_tsv_file) as f: reader = csv.reader(f, delimiter='\t') for i, row in enumerate(reader): if not row: warnings.warn('Samples file: line {} is empty'.format(i + 1), stacklevel=2) elif ((args.gene_list_file and (row[0] in genes_and_scores)) or ((not args.gene_list_file) and (row[0] in all_genes_info))): # new gene if row[0] not in genes_info: genes_info[row[0]] = {} if args.gene_list_file: genes_info[row[0]]['score'] = genes_and_scores[row[0]] else: genes_info[row[0]]['p'] = all_genes_info[row[0]] if row[1] in genes_info[row[0]]: warnings.warn('Gene {} already has a mutation entry ({}) for sample {}.\n' 'Overwriting with value {}.'.format(row[0], genes_info[row[0]][row[1]], row[1], row[3]), stacklevel=2) genes_info[row[0]][row[1]] = row[3] if args.gene_list_file: sorted_genes = sorted(genes_and_scores, key=lambda g: genes_and_scores[g], reverse=True) else: sorted_genes = sorted(genes_info, key=lambda g: genes_info[g]['p']) genes_info = OrderedDict((gene, genes_info[gene]) for gene in sorted_genes) if args.num_genes: genes_info = OrderedDict(islice(genes_info.iteritems(), args.num_genes)) return genes_info def generate_mut_plot(args): """Generate PDF of mutation type plot. See ArgumentParser in __main__ for parameter info. """ genes_info = get_gene_info(args) print 'Displaying {} genes:'.format(len(genes_info)) for gene, info in genes_info.iteritems(): print '{}\t{}'.format(gene, info['p']) genes_list = genes_info.keys() samples = list(set(itertools.chain(*[genes_info[key].keys() for key in genes_info]) ) - {'p', 'score'}) for gene in list(reversed(genes_list)): samples = sorted(samples, key=lambda mut: mut not in genes_info[gene]) sample_nums = [(i + 1, s) for i, s in enumerate(samples)] if args.sample_id_output: with open(args.sample_id_output, 'w') as id_file: fwriter = csv.writer(id_file, delimiter='\t') for sample_info in sample_nums: fwriter.writerow(sample_info) ncols = len(genes_list) nrows = len(samples) image = np.zeros(nrows * ncols) image = image.reshape((ncols, nrows)) for r, gene in enumerate(genes_list): for c, sample in enumerate(samples): if sample in genes_info[gene]: image[r][c] = genes_info[gene][sample] if args.color_map else 1 else: image[r][c] = None plt.subplot(132) x = 20.0 if len(genes_info) > 25: y = len(genes_info) / 5 else: y = 5.0 plt.rcParams["figure.figsize"] = [x, y] fig, ax1 = plt.subplots() ax1.tick_params(length=0) comut_grid = ax1.imshow(image, aspect='auto', interpolation='nearest') if args.color_map: colors = ['#ad2a1a', '#da621e', '#d3b53d', '#829356', '#0d3d56'] color_map = ListedColormap(colors) proxies = [create_proxy(item) for item in colors] plt.legend(proxies, MUTATION_TYPE_MAP.values(), numpoints=1, loc='lower center', markerscale=2, fontsize=12, ncol=5, bbox_to_anchor=[0.5, 1.02]) comut_grid.set_cmap(color_map) ax1.xaxis.tick_top() ax1.xaxis.set_ticks(np.arange(-0.5, nrows - 0.5)) ax1.yaxis.tick_right() ax1.yaxis.set_ticks(np.arange(-0.5, ncols - 0.5)) ax1.yaxis.set_ticks(np.arange(0, ncols), minor=True) ax1.set_xticklabels([i for i, __ in sample_nums], rotation='vertical', fontsize=4, ha='left') ax1.set_yticklabels([]) ax1.set_yticklabels(genes_list, fontsize=13, va='center', minor=True) ax1.tick_params(axis='both', which='both', length=0) ax1.grid(linestyle='solid', color=((.3,) * 3)) box = ax1.get_position() ax1.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # -log(p) if args.show_p_values: ax2 = fig.add_subplot(133) y_pos = range(len(genes_list)) neg_log_p = [math.log(genes_info[gene]['p']) * -1 for gene in genes_info] ax2.barh(y_pos, sorted(neg_log_p), 1, align='edge', color='#737373', edgecolor='black', linewidth=1, log=True) ax2.set_yticklabels([]) ax2.set_xlabel('-log(p-value)') box = ax2.get_position() ax2.set_position([box.x0 + box.width * 0.71, box.y0, box.width * 0.2, box.height]) ax2.set_ylim([0, len(genes_list)]) # stacked bars if args.show_percent_graph and args.color_map: ax3 = fig.add_subplot(131) mut_summary = {} for gene in genes_list: for s, m in genes_info[gene].items(): if s != 'p': if gene not in mut_summary: mut_summary[gene] = {} for mut in MUTATION_TYPE_MAP: mut_summary[gene][mut] = 0 mut_summary[gene][m] += 1 totals = [sum([mut_summary[g][m] for m in MUTATION_TYPE_MAP]) for g in genes_list] bar_data = {} for mut in MUTATION_TYPE_MAP: bar_data[mut] = [(float(n) / total * 100) for n, total in zip([mut_summary[g][mut] for g in genes_list], totals)] bar_l = list(reversed([i for i in range(len(genes_list))])) bottom = [0] * len(genes_list) for m in MUTATION_TYPE_MAP.keys()[:MUTATION_TYPE_MAP.keys().index(mut)]: bottom = [base + last for base, last in zip(bottom, bar_data[m])] ax3.barh(bar_l, bar_data[mut], 1, left=bottom, color=colors[MUTATION_TYPE_MAP.keys().index(mut)], linewidth=0) ax3.set_xlim([0, 100]) ax3.set_ylim([0, len(genes_list)]) ax3.tick_params(left='off', labelleft='off') ax3.set_xlabel('%') ax3.set_xticklabels([0, 20, 40, 60, 80, 100], rotation='vertical') ax3.get_xaxis().set_tick_params(direction='out') plt.savefig(args.output, bbox_inches='tight', format='pdf') if __name__ == "__main__": parser = argparse.ArgumentParser(description='Generate comutation plots') parser.add_argument('--mutsig_genes_file', required=False, help='Filepath to MutSig genes output file') parser.add_argument('--mutation_tsv_file', required=True, help='Filepath to mutation TSV file {gene}\\t{patient}\\t{effect}\\t{categ}') parser.add_argument('-o', '--output', required=True, help='Filepath to output PDF') parser.add_argument('--sample_id_output', required=False, help='Filepath to save sample IDs ({id}\\t{name})') parser.add_argument('--show_p_values', action='store_true', help='Generate p-value graph [-log(p)]') parser.add_argument('--show_percent_graph', action='store_true', help='Generate stacked bar graph for mutation type distributions') parser.add_argument('-n', '--num_genes', type=int, required=False, help='Limit number of genes to display') parser.add_argument('--color_map', action='store_true', help='Generate plot with mutation type color map') # specify one of the following: parser.add_argument('-p', '--p_value', type=float, help='Sample gene mutation p-value significance cutoff') parser.add_argument('-g', '--gene_list_file', required=False, help='Filepath to gene list ({gene name}\\t{score})') args = parser.parse_args() generate_mut_plot(args) ``` README.md ```# Comutation Plot More information: `python genes_001.py --help` ## Data * `--mutsig_genes_file` * MutSig output file (TSV) containing information on significant genes * Used columns: `gene`, `p` * `--mutation_tsv_file` * TSV file containing gene mutation information * Columns: `gene`, `patient`, `effect`, `categ` ## Mutation type categories Definitions for 4th column in `--mutation_tsv_file` * `3`: C:G transitions * `4`: C:G transversions * `5`: A:T transitions * `6`: A:T transversions * `7`: null+indel mutations ## Filtering 1. `--p_value` and `--gene_list_file` are disjointly two primary filters and sort methods 2. `--num_genes` is applied as an additional cutoff ``` run_pipeline.py ```#!/usr/bin/env python import argparse import os import subprocess from gene_pairs import get_unique_samples, main as generate_gene_pair_files parser = argparse.ArgumentParser() parser.add_argument('-i', '--mutation_tsv_file', required=True, help='Mutation TSV file with columns gene/patient/effect/categ') parser.add_argument('--mutsig_genes_file', help='MutSig genes output file') parser.add_argument('-p', '--percent_threshold', type=int, help='threshold for patients count / total count') parser.add_argument('--filter_common', action='store_true', help='Filter common') parser.add_argument('--result_dir', required=True, help='Result directory') args = parser.parse_args() if bool(args.mutsig_genes_file) is bool(args.percent_threshold): raise Exception('Required: either a MutSig output file or percent threshold.') # create filepaths if not os.path.exists(args.result_dir): os.makedirs(args.result_dir) if args.mutsig_genes_file: suffix = os.path.basename(args.mutsig_genes_file) suffix = suffix[:suffix.rfind('.')] else: suffix = 'MoreThan{}'.format(args.percent_threshold) filepaths = { 'calc_file': 'GenePairs_{}.txt'.format(suffix), 'num_file': 'GenePairsNum_{}.txt'.format(suffix), 'patient_count_file': 'PatientCounts.txt', 'patient_count_dup_file': 'PatientCountsDuplicateGenes.txt', 'fisher_file': 'FisherGenePairs_{}.txt'.format(suffix), 'co_occurrence_plot': 'FrequencyPlot_{}.pdf'.format(suffix), 'co_occurrence_table': 'FrequencyTable_{}.txt'.format(suffix) } for f, filepath in filepaths.items(): filepaths[f] = os.path.join(args.result_dir, filepath) # generate gene pair files args.calc_out = filepaths['calc_file'] args.num_out = filepaths['num_file'] args.patient_count_out = filepaths['patient_count_file'] args.patient_count_dup_out = filepaths['patient_count_dup_file'] generate_gene_pair_files(args) # run Fisher analysis subprocess.call(['Rscript', 'gene_pairs_fisher.R', '-i', filepaths['num_file'], '-n', str(len(get_unique_samples(args.mutation_tsv_file))), '--out_all', filepaths['fisher_file']]) # genereate co-occurrence frequency plot and table subprocess.call(['Rscript', 'co-occurrence_freq_plot.R', '-i', filepaths['calc_file'], '-o', filepaths['co_occurrence_plot'], '--freq_table_out', filepaths['co_occurrence_table']]) ``` README.md ```# gene-pairs ## Quickstart $ ./run_all.sh ## Pipeline `run_pipeline.py` runs all sub-scripts collectively. * `-i` mutation TSV file with the following columns: (same as one of the input files used for MutSig) * `gene` * `patient` * `effect` * `categ` * `--mutsig_genes_file [GENE LIST]` **or** `-p [PERCENT THRESHOLD]` * `-f` filter out pairs with 0 common samples ### 1. `gene_pairs.py` #### Input data * mutation TSV file * either a percent threshold or MutSig genes output file defining the significant genes #### Output * GenePairsNum * GenePairs ### 2. `gene_pairs_fisher.R` #### Input Data * GenePairsNum file (from `gene_pairs.py`) #### Output * Fisher test results (FisherGenePairs) ### 3. `co-occurrence_freq_plot.R` #### Input Data * GenePairs file (from `gene_pairs.py`) #### Output * co-occurrence frequency plot ## Output File Specifics ### GenePairs * `GenePairs_{sig_gene_filter}.txt` Columns: * `Gene1` * `Gene1Freq` * `Gene2` * `Gene2Freq` * `PercofSamples` * `Co_Occurrence` (sorted descending) ### GenePairsNum * `GenePairsNum_{sig_gene_filter}.txt` * flat file from `gene_pairs.py` to `gene_pairs_fisher.R` Columns: * `Gene1` * `Gene1Samples` * `Gene2` * `Gene2Samples` * `Common` ### FisherGenePairs * `FisherGenePairs_{sig_gene_filter}.txt` Columns: * `Gene1` * `Gene1Samples` * `Gene2` * `Gene2Samples` * `Common` * `P_value` (sort ascending) * `Adjusted_p` #### Process For each gene pair, 4 values are computed: * `N1 = 228 - (N2 + N3 + N4)` * `N2 = Gene2Samples - CommonSamples` * `N3 = Gene1Samples - CommonSamples` * `N4 = CommonSamples` A two-sided Fisher's exact test is performed on the matrix: N1 N2 N3 N4 If the `-f` flag is applied, gene pairs are ignored from calculation and output if they share no common samples. ``` pandastsv.py ```#!/usr/bin/env python import pandas as pd def get_tsv_df(filename, **kwargs): """Return pandas.DataFrame of file. * skip lines starting with '##' * remove '#' from header line * contents should be tab-separated """ with open(filename) as f: # skip initial comment lines skip_count = 0 line = f.readline() while '\t' not in line: skip_count += 1 line = f.readline() header = line.rstrip().split('\t') # VCF header rows start with '#' if line[0] == '#': header[0] = header[0][1:] skip_count += 1 return pd.read_table(filename, header=None, names=header, skiprows=skip_count, **kwargs) ``` gene_sample_crosstab.py ```import pandas as pd mutations = pd.read_table('data/4dataset_nonsilent.txt', names=['gene', 'patient', 'effect', 'categ']) mat = pd.crosstab(mutations['patient'], mutations['gene']) mat = mat.apply(lambda x: x > 0) * 1 mat.to_csv('results/gene_sample_crosstab.tsv', sep='\t') # test patients = mutations['patient'].values genes = mutations['gene'].values for patient, gene in zip(patients, genes): assert mat.loc[patient, gene] != 0 ``` vcf_transform.py ```#!/usr/bin/env python import pandas as pd import numpy as np from collections import OrderedDict from argparse import ArgumentParser from vcf import Reader class VCFFile(Reader): """Extension of PyVCF's Reader with pandas.DataFrame. Additional attributes --------------------- see PyVCF documentation for Reader attributes. df : pandas.DataFrame is_nan_converted : specifies whether VCF empty values have been converted to NaN Also handles no-call format strings within the DataFrame. """ def __init__(self, filename, convert_empty=True, **kwargs): """Initialize VCFFile instance. Parameters ---------- filename : required for pandas.DataFrame loading convert_empty : specify whether to convert VCF file empty values to NaN """ Reader.__init__(self, filename=filename, **kwargs) self._init_df(filename) if convert_empty: self._convert_empty_to_nan() self.is_nan_converted = True else: self.is_nan_converted = False def _init_df(self, filename): """Initialize pandas.DataFrame of VCF file.""" self.df = pd.read_table(filename, header=None, names=(self._column_headers + self.samples), skiprows=(len(self._header_lines) + 1)) def _convert_empty_to_nan(self): """Replace VCF empty values with NaN values.""" self.df.replace('.', np.nan, inplace=True) for no_call_string in self._get_no_call_strings(): self.df.replace(no_call_string, np.nan, inplace=True) def get_maflite_df(self): """Return melted pandas.DataFrame of VCF with MAFLITE columns. Variables --------- maflite_columns : OrderedDict column definitions in the form { transformed column : intiial column } """ maflite_columns = OrderedDict([('chr', 'CHROM'), ('start', 'POS'), ('end', 'POS'), ('ref_allele', 'REF'), ('alt_allele', 'ALT'), ('sample', 'SAMPLE')]) maflite_df = pd.melt(self.df, id_vars=self._column_headers, var_name='SAMPLE', value_name='VARIANT') if not self.is_nan_converted: for no_call_string in self._get_no_call_strings(): maflite_df['VARIANT'].replace(no_call_string, np.nan, inplace=True) maflite_df = maflite_df.loc[maflite_df['VARIANT'].notnull(), maflite_columns.values()] maflite_df.columns = maflite_columns.keys() return maflite_df def _get_no_call_strings(self): """Return no-call string for each format string in the format cache.""" # generate the cache for x in self.next(): pass for format_string in self._format_cache: yield ':'.join([self._get_no_call_value(self.formats[x]) for x in format_string.split(':')]) def _get_no_call_value(self, format_namedtuple): """Return no-call string for a vcf.parser._Format namedtuple. default: . Specific formats ---------------- GT: ./. """ if format_namedtuple.id == 'GT': return './.' return '.' if __name__ == '__main__': parser = ArgumentParser(description='Generate MAFLITE file from VCF.') parser.add_argument('filename', help='input VCF file') parser.add_argument('output', help='output MAFLITE file') args = parser.parse_args() vcf_file = VCFFile(args.filename) maflite_df = vcf_file.get_maflite_df() maflite_df.to_csv(args.output, sep='\t', index=False) ``` subset_rb1_sig_gene_mutations.py ```import pandas as pd # read mutation dataset mutations = pd.read_table('data/4dataset_nonsilent.txt', names=['gene', 'patient', 'effect', 'categ']) # read set of significant genes genes_df = pd.read_table('data/SigGenes_005.txt', usecols=['gene']) genes = set(genes_df.gene.values) # subset mutation dataset for significant genes sig_gene_mutations = mutations[mutations['gene'].isin(genes)] # get rb1 samples rb1_sig_gene_mutations = sig_gene_mutations[sig_gene_mutations['gene'] == 'RB1'] rb1_samples = set(rb1_sig_gene_mutations['patient'].values) all_samples = set(sig_gene_mutations['patient'].values) print len(rb1_samples), 'out of', len(all_samples), 'samples have RB1 mutation' rb1_samples_sig_gene_mutations = sig_gene_mutations[sig_gene_mutations['patient'].isin(rb1_samples)] # write significant gene mutations from RB1 mutated samples rb1_samples_sig_gene_mutations.to_csv('results/SigGenes_005_RB1_samples_4dataset_nonsilent.tsv', sep='\t', index=False) # write significant gene mutations from non-RB1 mutated samples no_rb1_samples_sig_gene_mutations = sig_gene_mutations[~sig_gene_mutations['patient'].isin(rb1_samples)] no_rb1_samples_sig_gene_mutations.to_csv('results/SigGenes_005_not_RB1_samples_4dataset_nonsilent.tsv', sep='\t', index=False) ``` gene_pairs.py ```import argparse import logging import os import csv import sys import warnings import itertools from logging import StreamHandler, Formatter class GenePair(object): def __init__(self, gene1, gene2): self.Gene1 = gene1 self.Gene2 = gene2 def __getitem__(self, attr): return getattr(self, attr) def co_occurrence(self): pass class GenePairList(object): def __init__(self, pairs): self.pairs = list(pairs) if type(pairs) is not list else pairs def sort(self, attr, reverse=False): self.pairs = sorted(self.pairs, key=lambda (p): p[attr], reverse=reverse) def write(self, fpath, header, sort_attr=None, reverse=False, alpha=None): sorted_pairs = (sorted(self.pairs, key=lambda (p): p[sort_attr], reverse=reverse) if sort_attr else self.pairs) with open(fpath, 'w') as f: writer = csv.writer(f, delimiter='\t') writer.writerow(header) for pair in sorted_pairs: if not alpha or pair.P_value < alpha: writer.writerow(["{:.2E}".format(pair[col]) if col in ['P_value', 'Adjusted_p'] else pair[col] for col in header]) def get_mutsig_genes(mutsig_genes_file_file): """Return iterable of genes from MutSig genes output file""" with open(mutsig_genes_file_file) as f: reader = csv.reader(f, delimiter='\t') col = reader.next().index('gene') for row in reader: yield row[col] def get_unique_samples(mutation_tsv_file): """Return set of patient IDs from a TSV file. Assume column 2 to be the patient column. """ with open(mutation_tsv_file) as f: reader = csv.reader(f, delimiter='\t') patients = set([row[1] for row in reader]) return patients def get_common_samples(count_data, samples, gene1, gene2): """Return set of samples which contain both `gene1` and `gene2`""" for sample in samples: if count_data[gene1][sample] and count_data[gene2][sample]: yield sample def get_count_data(mutation_tsv_file, outer_value): """Return count data for a mutation TSV file Input file must have: * no header * gene ID under column 1 * patient ID under column 2 Parameters ---------- mutation_tsv_file : filepath outer_value : 'gene'/'patient' Return ------ genes : set of gene IDs patients : set of patient IDs count_data : example, when outer_value='gene': { gene : { patient : count } } """ if outer_value not in ('gene', 'patient'): raise ValueError('outer_value must be "gene" or "patient"') with open(mutation_tsv_file) as f: reader = list(csv.reader(f, delimiter='\t')) genes = set([row[0] for row in reader]) patients = set([row[1] for row in reader]) if outer_value == 'gene': count_data = {gene: {patient: 0 for patient in patients} for gene in genes} for row in reader: count_data[row[0]][row[1]] += 1 else: # outer_value='patient' count_data = {patient: {gene: 0 for gene in genes} for patient in patients} for row in reader: count_data[row[1]][row[0]] += 1 return genes, patients, count_data def get_pairs(mutation_tsv_file, sig_genes=None, percent_threshold=None, filter_common=False, log=None): """ Return GenePair objects with base attriutes: * Gene1Freq * Gene2Freq * Gene1Samples * Gene2Samples * Common * PercofSamples * Co_Occurrence Parameters ---------- filter_common : filter out common samples log : Logger object """ # get count data genes, patients, count_data = get_count_data(mutation_tsv_file, outer_value='gene') # create dictionaries gene_counts = {gene: sum([int(bool(count)) for patient, count in count_data[gene].items()]) for gene in genes} gene_percentages = {gene: (100.0 * count / len(patients)) for gene, count in gene_counts.items()} if sig_genes: sig_genes = set(sig_genes) for gene in sig_genes.copy(): if gene not in genes: warnings.warn('{} not in {}.'.format(gene, mutation_tsv_file)) warnings.warn('Continuing without the significant gene.') sig_genes.remove(gene) if not sig_genes: sig_genes = [gene for gene in genes if gene_percentages[gene] > percent_threshold] iter_pairs = list(itertools.combinations(sorted(sig_genes), 2)) num_pairs = len(list(iter_pairs)) log.info('analyzing %i pairs', num_pairs) log.info('\n{: <100}|'.format('PROGRESS:')) for i, (gene1, gene2) in enumerate(iter_pairs): if i % (num_pairs / 100) == 0: sys.stdout.write('#') pair = GenePair(gene1, gene2) pair.Gene1Freq = gene_percentages[gene1] pair.Gene2Freq = gene_percentages[gene2] pair.Gene1Samples = gene_counts[gene1] pair.Gene2Samples = gene_counts[gene2] pair.Common = 0 for patient in patients: if count_data[gene1][patient] and count_data[gene2][patient]: pair.Common += 1 if filter_common and pair.Common is 0: continue pair.PercofSamples = (100.0 * pair.Common / len(patients)) pair.Co_Occurrence = (100.0 * pair.PercofSamples / (pair.Gene1Freq * pair.Gene2Freq)) yield pair def write_patient_counts(mutation_tsv_file, filepath, ignore_duplicates=False): """Write patient count file to `filepath` Parameters ---------- mutation_tsv_file : filepath see get_count_data() ignore_duplicates : bool if True, do not count duplicate instances of (patient, gene) """ with open(filepath, 'w') as f: writer = csv.writer(f, delimiter='\t') genes, patients, count_data = get_count_data(mutation_tsv_file, outer_value='patient') writer.writerow(['patient', 'count']) for patient in patients: count = sum([int(bool(count)) if ignore_duplicates else count for gene, count in count_data[patient].items()]) writer.writerow([patient, count]) def main(args): log = logging.getLogger() handler = StreamHandler(stream=sys.stdout) formatter = Formatter(fmt='%(asctime)-15s %(levelname)-6s %(message)s') handler.setFormatter(formatter) log.addHandler(handler) log.setLevel(logging.DEBUG) if not args: parser = argparse.ArgumentParser() parser.add_argument('-i', '--mutation_tsv_file', required=True, help='Mutation TSV file with columns gene/patient/effect/categ') parser.add_argument('--mutsig_genes_file', help='MutSig genes output file') parser.add_argument('-p', '--percent_threshold', type=int, help='threshold for patients count / total count') parser.add_argument('--calc_out', required=True, help='Output filename') parser.add_argument('--num_out', required=True, help='Output filename') parser.add_argument('--patient_count_out', required=True, help='Patient count output filepath') parser.add_argument('--patient_count_dup_out', required=True, help='Patient count output with duplicate genes') parser.add_argument('--filter_common', action='store_true', help='Filter common') args = parser.parse_args() if args.mutsig_genes_file and args.percent_threshold: raise Exception('Cannot accept both a MutSig output file ' 'and percent threshold.') if not any([args.mutsig_genes_file, args.percent_threshold]): raise Exception('Required: either a MutSig output file ' 'or percent threshold.') elif args.mutsig_genes_file: log.info('Filtering for sig genes from %s...', args.mutsig_genes_file) sig_genes = get_mutsig_genes(args.mutsig_genes_file) pairs = get_pairs(args.mutation_tsv_file, sig_genes=sig_genes, log=log, filter_common=args.filter_common) elif args.percent_threshold: log.info('Filtering for sig genes using threshold=%i...', args.percent_threshold) pairs = get_pairs(args.mutation_tsv_file, percent_threshold=args.percent_threshold, log=log, filter_common=args.filter_common) log.debug('creating GenePairList') pairs_list = GenePairList(pairs) print if args.calc_out: log.debug('writing file %s', args.calc_out) pairs_list.write(args.calc_out, header=['Gene1', 'Gene1Freq', 'Gene2', 'Gene2Freq', 'PercofSamples', 'Co_Occurrence'], sort_attr='Co_Occurrence', reverse=True) if args.num_out: log.debug('writing file %s', args.num_out) pairs_list.write(args.num_out, header=['Gene1', 'Gene1Samples', 'Gene2', 'Gene2Samples', 'Common']) write_patient_counts(args.mutation_tsv_file, args.patient_count_out, ignore_duplicates=True) write_patient_counts(args.mutation_tsv_file, args.patient_count_dup_out, ignore_duplicates=False) if __name__ == '__main__': main() ```
zhouliufei/oa-server
zhouliufei/oa-server UserController.java ```package com.fanfan.controller; import com.fanfan.pojo.User; import com.fanfan.service.UserService; import org.springframework.beans.factory.annotation.Autowired; 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; @RestController public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/regist",method = RequestMethod.POST) public void regist(@RequestBody User user) { userService.register(user); } } ``` MyAuthenticationSuccessHandler.java ```package com.fanfan.auth; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static org.slf4j.LoggerFactory.getLogger; @Component("myAuthenticationSuccessHandler") public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { private Logger logger = getLogger(getClass()); @Autowired private ObjectMapper objectMapper; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { //这里可以根据实际情况,来确定是跳转到页面或者json格式。 //如果是返回json格式,那么我们这么写 logger.info("登录成功"); Map<String,String> map=new HashMap<>(); map.put("code", "200"); map.put("msg", "登录成功"); map.put("authentication", JSONObject.toJSONString(authentication)); response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(objectMapper.writeValueAsString(map)); } } ``` UserServiceImpl.java ```package com.fanfan.service.impl; import com.fanfan.mapper.UserMapper; import com.fanfan.pojo.User; import com.fanfan.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public void register(User user) { userMapper.insert(user); } } ``` RoleRouteDTO.java ```package com.fanfan.dto; import java.util.List; public class RoleRouteDTO { private Integer roleId; private List<String> uriList; public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public List<String> getUriList() { return uriList; } public void setUriList(List<String> uriList) { this.uriList = uriList; } } ``` StringUtil.java ```package com.fanfan.Util; public class StringUtil { /** * token前缀 */ public static final String TOKEN_PREFIX = "FANFAN_"; /** * 角色前缀 */ public static final String ROLE_PREFIX = "ROLE_"; /** * 请求的uri */ public static final String URI_PREFIX = "URI_"; /** * */ public static boolean isEmpty(String str) { if(str == null || str.trim().length() == 0) { return true; } return false; } } ``` JWTAuthenticationFilter.java ```package com.fanfan.filter; import com.fanfan.Util.RedisUtil; import com.fanfan.Util.SpringContextUtil; import com.fanfan.Util.StringUtil; import com.fanfan.pojo.UserInfo; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class JWTAuthenticationFilter extends BasicAuthenticationFilter { private RedisUtil redisUtil; public JWTAuthenticationFilter(AuthenticationManager authenticationManager) { super(authenticationManager); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException, ServletException { String token = request.getHeader("token"); //判断是否有token if (token == null || !token.startsWith(StringUtil.TOKEN_PREFIX)) { chain.doFilter(request, response); return; } UsernamePasswordAuthenticationToken authenticationToken = null; try { authenticationToken = getAuthentication(token,request); } catch (Exception e) { response.sendError(401,"用户信息失效,请重新登录"); return; } SecurityContextHolder.getContext().setAuthentication(authenticationToken); //放行 chain.doFilter(request, response); } /** * 解析token中的信息,并判断是否过期 */ private UsernamePasswordAuthenticationToken getAuthentication(String token,HttpServletRequest request) throws Exception { if(redisUtil == null) { redisUtil = SpringContextUtil.getBean(RedisUtil.class, request); } String username = redisUtil.get(token); if(username == null || username.trim().length() == 0) { throw new Exception("该账号已过期,请重新登陆"); } redisUtil.expireTime(token); //存储权限 UserInfo userInfo = new UserInfo(username,null,null,false,false,false,false); return new UsernamePasswordAuthenticationToken(userInfo, username, null); } } ``` MenuService.java ```package com.fanfan.service; import com.fanfan.pojo.Menu; import java.util.List; public interface MenuService { List<Menu> queryMenu(String roleCode); } ``` MenuController.java ```package com.fanfan.controller; import com.fanfan.Util.JsonResult; import com.fanfan.service.MenuService; import org.springframework.beans.factory.annotation.Autowired; 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; @RestController public class MenuController { @Autowired private MenuService menuService; @RequestMapping(value = "/queryMenu",method = RequestMethod.GET) public JsonResult queryMenu(@RequestParam("roleCode") String roleCode) { return new JsonResult(menuService.queryMenu(roleCode)); } } ``` SecurityConfig.java ```package com.fanfan; import com.fanfan.auth.MyAuthenticationFailHander; import com.fanfan.auth.MyAuthenticationProvider; import com.fanfan.auth.MyAuthenticationSuccessHandler; import com.fanfan.filter.JWTAuthenticationFilter; import com.fanfan.filter.JWTLoginFilter; import com.fanfan.service.UserInfoService; import com.sun.org.apache.xpath.internal.patterns.NodeTestFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import javax.sql.DataSource; import java.util.ArrayList; import java.util.List; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler; @Autowired private AuthenticationFailureHandler myAuthenticationFailHander; @Autowired private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { //禁用 csrf http.cors().and().csrf().disable() .authorizeRequests() //允许以下请求 .antMatchers("/regist").permitAll() .antMatchers("/test").permitAll() // 所有请求需要身份认证 .anyRequest().authenticated() .anyRequest().access("@rbacService.hasPermission(request,authentication)") .and() //验证登陆 .addFilter(jwtLoginFilter()) //验证token .addFilter(new JWTAuthenticationFilter(authenticationManager())); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //自定义provider,验证用户名和密码 auth.authenticationProvider(new MyAuthenticationProvider(userDetailsService)); } /** * 自定义登陆验证接口 */ public JWTLoginFilter jwtLoginFilter() throws Exception { JWTLoginFilter jwtLoginFilter = new JWTLoginFilter(authenticationManager()); //只有post请求才拦截 jwtLoginFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST")); jwtLoginFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler); jwtLoginFilter.setAuthenticationFailureHandler(myAuthenticationFailHander); return jwtLoginFilter; } } ``` MenuServiceImpl.java ```package com.fanfan.service.impl; import com.alibaba.fastjson.JSONObject; import com.fanfan.Util.RedisUtil; import com.fanfan.pojo.Menu; import com.fanfan.service.MenuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; @Service public class MenuServiceImpl implements MenuService { @Autowired private RedisUtil redisUtil; @Override public List<Menu> queryMenu(String roleCode) { Set<String> result = redisUtil.queryAllFromSet(roleCode); Iterator<String> iterator = result.iterator(); Map<String,Object> map=new HashMap<>(); List<Menu> menus = new ArrayList<>(); while (iterator.hasNext()) { String menuJson = iterator.next(); JSONObject jsonObject = JSONObject.parseObject(menuJson); Menu menu = JSONObject.toJavaObject(jsonObject,Menu.class); menus.add(menu); } return menus; } } ``` UserInfoDTO.java ```package com.fanfan.dto; public class UserInfoDTO { private Integer userId; private String roleName; private String roleCode; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleCode() { return roleCode; } public void setRoleCode(String roleCode) { this.roleCode = roleCode; } } ``` RoleMenuDTO.java ```package com.fanfan.dto; import com.fanfan.pojo.Menu; import com.fanfan.pojo.Role; import java.util.List; public class RoleMenuDTO extends Role { private List<Menu> menuList; public List<Menu> getMenuList() { return menuList; } public void setMenuList(List<Menu> menuList) { this.menuList = menuList; } } ``` JsonResult.java ```package com.fanfan.Util; /** * @Description: * 200:表示成功 * 500:表示错误,错误信息在msg字段中 * 501:bean验证错误,不管多少个错误都以map形式返回 * 502:拦截器拦截到用户token出错 * 555:异常抛出信息 */ public class JsonResult<T> { private String msg; private T data; private int status; private String ok; public static JsonResult ok() { return new JsonResult(null,null,200); } public static JsonResult errorMessage(String msg) { return new JsonResult(msg,null,500); } public static JsonResult errorTokenMsg(String msg) { return new JsonResult(msg,null,502); } public JsonResult() {} public JsonResult(T data) { setObject(data); } public JsonResult(String msg, T data, int status) { this.msg = msg; this.data = data; this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getObject() { return data; } public void setObject(T data) { this.data = data; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getOk() { return ok; } public void setOk(String ok) { this.ok = ok; } @Override public String toString() { return "JsonResult{" + "msg='" + msg + '\'' + ", data=" + data + ", status=" + status + ", ok='" + ok + '\'' + '}'; } } ``` RbacServiceImpl.java ```package com.fanfan.service.impl; import com.fanfan.Util.RedisUtil; import com.fanfan.Util.StringUtil; import com.fanfan.mapper.RoleMapper; import com.fanfan.mapper.UserMapper; import com.fanfan.service.RbacService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; import org.springframework.util.AntPathMatcher; import javax.servlet.http.HttpServletRequest; import java.util.HashSet; import java.util.Set; @Service("rbacService") public class RbacServiceImpl implements RbacService { @Autowired private RoleMapper roleMapper; @Autowired private RedisUtil redisUtil; private AntPathMatcher antPathMatcher = new AntPathMatcher(); @Override public boolean hasPermission(HttpServletRequest request, Authentication authentication) { Object principal = authentication.getPrincipal(); boolean hasPermission = false; if (principal instanceof UserDetails) { //首先判断先当前用户是否是我们UserDetails对象。 String userName = ((UserDetails) principal).getUsername(); //根据用户名读取用户的所有权限 Integer roleId = roleMapper.queryTallestLevel(userName); // 注意这里不能用equal来判断,因为有些URL是有参数的,所以要用AntPathMatcher来比较 if(redisUtil.sismember(StringUtil.URI_PREFIX + roleId,request.getRequestURI())) { hasPermission = true; } } return hasPermission; } } ``` MenuRoute.java ```package com.fanfan.pojo; public class MenuRoute { private Integer routeId; private Integer menuId; private String routeName; private String routeUrl; public MenuRoute(Integer routeId, Integer menuId, String routeName, String routeUrl) { this.routeId = routeId; this.menuId = menuId; this.routeName = routeName; this.routeUrl = routeUrl; } public MenuRoute() { super(); } public Integer getRouteId() { return routeId; } public void setRouteId(Integer routeId) { this.routeId = routeId; } public Integer getMenuId() { return menuId; } public void setMenuId(Integer menuId) { this.menuId = menuId; } public String getRouteName() { return routeName; } public void setRouteName(String routeName) { this.routeName = routeName == null ? null : routeName.trim(); } public String getRouteUrl() { return routeUrl; } public void setRouteUrl(String routeUrl) { this.routeUrl = routeUrl == null ? null : routeUrl.trim(); } }``` UserInfoService.java ```package com.fanfan.service; import com.fanfan.dto.UserInfoDTO; import com.fanfan.mapper.UserMapper; import com.fanfan.pojo.User; import com.fanfan.pojo.UserInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class UserInfoService implements UserDetailsService { @Autowired private UserMapper userMapper; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { if(username != null && username.length() > 0) { UserInfoDTO userInfoDto = userMapper.loadUserByUsername(username); if(userInfoDto == null) { return null; } User user = userMapper.selectByPrimaryKey((long)userInfoDto.getUserId()); if(user != null) { UserInfo userInfo = new UserInfo(user.getUsername(), user.getPassword(),userInfoDto.getRoleCode(), true,true, true, true); return userInfo; } } return null; } } ``` Springboot.java ```package com.fanfan; import com.fanfan.service.InitService; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * Hello world! * */ @SpringBootApplication @MapperScan("com.fanfan.mapper") public class Springboot implements CommandLineRunner { @Autowired private InitService initService; public static void main( String[] args ) { SpringApplication.run(Springboot.class,args); } @Override @Transactional(propagation = Propagation.REQUIRED) public void run(String... args) throws Exception { initService.init(); } } ``` UserMapper.java ```package com.fanfan.mapper; import com.fanfan.dto.UserInfoDTO; import com.fanfan.pojo.User; public interface UserMapper { int deleteByPrimaryKey(Long id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Long userId); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); UserInfoDTO loadUserByUsername(String username); String queryPasswordById(Integer userId); }``` LoginController.java ```package com.fanfan.controller; import com.fanfan.pojo.User; import com.fanfan.pojo.UserInfo; import org.springframework.stereotype.Controller; 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; @RestController public class LoginController { @RequestMapping(value = "/login",method = RequestMethod.POST) public String login(@RequestBody UserInfo userInfo) { return "hello word"; } @RequestMapping(value = "/login-error",method = RequestMethod.GET) public String loginError(){ return "/login-error"; } } ``` UserService.java ```package com.fanfan.service; import com.fanfan.pojo.User; public interface UserService { void register(User user); } ``` JWTLoginFilter.java ```package com.fanfan.filter; import com.alibaba.fastjson.JSONObject; import com.fanfan.Util.RedisUtil; import com.fanfan.Util.SpringContextUtil; import com.fanfan.Util.StringUtil; import com.fanfan.pojo.UserInfo; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.authority.GrantedAuthorityImpl; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*; public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter { private RedisUtil redisUtil; private AuthenticationManager authenticationManager; @Autowired private ObjectMapper objectMapper; public JWTLoginFilter(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } /** * 接收并解析用户登陆信息 /login, *为已验证的用户返回一个已填充的身份验证令牌,表示成功的身份验证 *返回null,表明身份验证过程仍在进行中。在返回之前,实现应该执行完成该过程所需的任何额外工作。 *如果身份验证过程失败,就抛出一个AuthenticationException * * * @param request 从中提取参数并执行身份验证 * @param response 如果实现必须作为多级身份验证过程的一部分(比如OpenID)进行重定向,则可能需要响应 * @return 身份验证的用户令牌,如果身份验证不完整,则为null。 * @throws AuthenticationException */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { //得到用户登陆信息,并封装到 Authentication 中,供自定义用户组件使用. String username = request.getParameter("username"); String password = request.getParameter("password"); if (username == null) { username = ""; } if (password == null) { password = ""; } username = username.trim(); ArrayList<GrantedAuthorityImpl> authorities = new ArrayList<>(); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password, authorities); //authenticate()接受一个token参数,返回一个完全经过身份验证的对象,包括证书. // 这里并没有对用户名密码进行验证,而是使用 AuthenticationProvider // 提供的 authenticate 方法返回一个完全经过身份验证的对象,包括证书. // Authentication authenticate = authenticationManager.authenticate(authenticationToken); //UsernamePasswordAuthenticationToken 是 Authentication 的实现类 setDetails(request, authenticationToken); Authentication authenticate = this.authenticationManager.authenticate(authenticationToken); return authenticate; } /** * 登陆成功后,此方法会被调用,因此我们可以在次方法中生成token,并返回给客户端 * 并返回用户的菜单列表 * @param request * @param response * @param chain * @param authResult */ @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { if(redisUtil == null) { redisUtil = SpringContextUtil.getBean(RedisUtil.class, request); } if(objectMapper == null) { objectMapper = SpringContextUtil.getBean(ObjectMapper.class,request); } String token = UUID.randomUUID().toString(); redisUtil.set(token,null,authResult.getName()); response.addHeader("token", StringUtil.TOKEN_PREFIX + token); logger.info("token生成成功"); UserInfo userInfo = (UserInfo) authResult.getPrincipal(); String roleCode = userInfo.getRole(); Map<String,Object> map=new HashMap<>(); map.put("code", "200"); map.put("msg", "登录成功"); map.put("role",roleCode); response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(objectMapper.writeValueAsString(map)); } } ``` UserRole.java ```package com.fanfan.pojo; public class UserRole { private Integer id; private Integer userId; private Integer roleId; private Integer roleLevel; public UserRole(Integer id, Integer userId, Integer roleId, Integer roleLevel) { this.id = id; this.userId = userId; this.roleId = roleId; this.roleLevel = roleLevel; } public UserRole() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public Integer getRoleLevel() { return roleLevel; } public void setRoleLevel(Integer roleLevel) { this.roleLevel = roleLevel; } }``` RedisUtil.java ```package com.fanfan.Util; import com.fanfan.RedisConfigration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import javax.annotation.PostConstruct; import java.util.Set; @Component public class RedisUtil { private static final Integer EXPIRE = 3600 * 24 * 7; @Autowired private RedisConfigration redisConfigration; private JedisPool jedisPool; private static Logger logger = LoggerFactory.getLogger(RedisUtil.class); @PostConstruct public void init() { jedisPool = redisConfigration.redisPoolFactory(); } //存数据 public void set(String key,Integer expire,String value) { Jedis jedis = null; try{ jedis = jedisPool.getResource(); if(expire == null) { jedis.setex(StringUtil.TOKEN_PREFIX + key,EXPIRE,value); } else { jedis.setex(StringUtil.TOKEN_PREFIX + key,expire,value); } }catch (Exception e) { logger.info("新增redis数据出错"); e.printStackTrace(); } finally { if(jedis != null) { jedis.close(); } } } //取数据 public String get(String key) { Jedis jedis = null; String value = null; try{ jedis = jedisPool.getResource(); value = jedis.get(key); } catch (Exception e) { logger.info("获取redis数据出错"); e.printStackTrace(); } finally { if(jedis != null) { jedis.close(); } } return value; } //删除数据 public void delete(String key) { Jedis jedis = null; try{ jedis = jedisPool.getResource(); jedis.del(key); } catch (Exception e) { logger.info("删除redis数据出错"); e.printStackTrace(); } finally { if(jedis != null) { jedis.close(); } } } public void expireTime(String key) { Jedis jedis = null; try{ jedis = jedisPool.getResource(); jedis.expire(key,EXPIRE); }catch (Exception e) { logger.info("更新redis数据出错"); e.printStackTrace(); }finally { if(jedis != null) { jedis.close(); } } } //jedis 加入数据到set中 public long addToSet(String key,String value) { Jedis jedis = null; Long num = null; try{ jedis = jedisPool.getResource(); num = jedis.sadd(key,value); }catch (Exception e) { logger.info("插入数据到set出错"); e.printStackTrace(); }finally { if(jedis != null) { jedis.close(); } return num.longValue(); } } //jedis查看数据是否在set中 public boolean sismember(String key,String value) { Jedis jedis = null; Boolean exist = null; try{ jedis = jedisPool.getResource(); exist = jedis.sismember(key,value); }catch (Exception e) { logger.info("查看数据是否在set中出错"); e.printStackTrace(); }finally { if(jedis != null) { jedis.close(); } return exist; } } //jedis 从set中移除数据 public long srem(String key,String value) { Jedis jedis = null; Long num = null; try{ jedis = jedisPool.getResource(); num = jedis.srem(key,value); }catch (Exception e) { logger.info("删除set数据出错"); e.printStackTrace(); }finally { if(jedis != null) { jedis.close(); } return num.longValue(); } } //jedis 取出set中所有数据 public Set<String> queryAllFromSet(String key) { Jedis jedis = null; Set<String> result = null; try{ jedis = jedisPool.getResource(); result = jedis.smembers(key); }catch (Exception e) { logger.info("获取redis数据出错"); e.printStackTrace(); }finally { if(jedis != null) { jedis.close(); } return result; } } } ``` MenuRouteMapper.java ```package com.fanfan.mapper; import com.fanfan.pojo.MenuRoute; public interface MenuRouteMapper { int deleteByPrimaryKey(Integer routeId); int insert(MenuRoute record); int insertSelective(MenuRoute record); MenuRoute selectByPrimaryKey(Integer routeId); int updateByPrimaryKeySelective(MenuRoute record); int updateByPrimaryKey(MenuRoute record); }``` TestController.java ```package com.fanfan.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @RequestMapping(value = "/test",method = RequestMethod.GET) public String test() { return "hello springboot"; } @RequestMapping(value = "/add",method = RequestMethod.GET) public String whoIm(){ return "访问add成功"; } @RequestMapping(value = "/search",method = RequestMethod.GET) public String whohename(){ return "访问search成功"; } } ``` InitServiceImpl.java ```package com.fanfan.service.impl; import com.alibaba.fastjson.JSONObject; import com.fanfan.Util.RedisUtil; import com.fanfan.Util.StringUtil; import com.fanfan.dto.RoleMenuDTO; import com.fanfan.dto.RoleRouteDTO; import com.fanfan.mapper.RoleMapper; import com.fanfan.service.InitService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class InitServiceImpl implements InitService { @Autowired private RoleMapper roleMapper; @Autowired private RedisUtil redisUtil; @Override public void init() { //存储每个角色的菜单到redis storeMenu(); //存储每个角色能访问的url到redis storeRequestUrl(); } private void storeRequestUrl() { List<RoleRouteDTO> list = roleMapper.queryAllRoleUri(); for(int i = 0; i < list.size();i++) { RoleRouteDTO roleRouteDTO = list.get(i); redisUtil.delete(StringUtil.URI_PREFIX + roleRouteDTO.getRoleId()); for(int j = 0; j < roleRouteDTO.getUriList().size();j++) { redisUtil.addToSet(StringUtil.URI_PREFIX + roleRouteDTO.getRoleId(),roleRouteDTO.getUriList().get(j)); } } } /** * 拿到每个角色对应的菜单列表 */ private void storeMenu() { List<RoleMenuDTO> list = roleMapper.queryAllRole(); for(int i = 0; i < list.size();i++) { RoleMenuDTO roleMenuDTO = list.get(i); redisUtil.delete(roleMenuDTO.getRoleCode()); for(int j = 0; j < roleMenuDTO.getMenuList().size();j++) { String value = JSONObject.toJSONString(roleMenuDTO.getMenuList().get(j)); redisUtil.addToSet(roleMenuDTO.getRoleCode(),value); } } } } ``` RoleMapper.java ```package com.fanfan.mapper; import com.fanfan.dto.RoleMenuDTO; import com.fanfan.dto.RoleRouteDTO; import com.fanfan.pojo.Role; import java.util.List; public interface RoleMapper { int deleteByPrimaryKey(Integer roleId); int insert(Role record); int insertSelective(Role record); Role selectByPrimaryKey(Integer roleId); int updateByPrimaryKeySelective(Role record); int updateByPrimaryKey(Role record); List<RoleMenuDTO> queryAllRole(); List<RoleRouteDTO> queryAllRoleUri(); Integer queryTallestLevel(String userName); }```
zhouqiuxing/pu
zhouqiuxing/pu dev.md ``` ### 45.63.50.67 ssh 端口 22312 yzhang aajjffkk ssh -l yzhang 45.63.50.67 -p22312 https://vsr.iirii.com/phpMyAdmin zhangyanxi yanxi312 test``` index.php ```<?php /** * Created by PhpStorm. * User: yafei * Date: 2017-04-02 * Time: 20:46 */ //echo __DIR__; require_once __DIR__ . "/bak/Test.php"; require_once __DIR__ . "/hhhh/Animal.php"; require_once __DIR__ . "/hhhh/Plant.php"; require_once __DIR__ . "/hhhh/Grass.php"; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// echo "[#######################################################][Plant]"; echo "<br />"; $tree = new Plant(); $tree->seHeight(33); $yyy = $tree->getHeight(); //$juh=$tree->type; $tree->hdhdhd(23,55555); $ooo = $tree->jjjj(); $tree->settype("tree"); $fff = $tree->gettype(); echo $fff; echo "<br />"; print_r($ooo); echo $ooo["0"]; //echo $yyy; echo "<br />"; $flower = new Plant(); $flower->settype("flower"); echo $flower->gettype(); $plant3 = new Plant(); echo "<br />"; $grass = new Grass(); $grass->settype("grass"); $grass_type = $grass->gettype(); $grass->setColor("blue"); $grass_ble = $grass->getColor(); echo $grass_ble; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// echo "<br />"; echo "[#######################################################][Animal]"; echo "<br />"; $animal = new Animal(); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// echo "<br />"; echo "[########################### ############################][Test]"; echo "<br />"; $test = new Test(); $test->say(); $test->setColor("bffflue"); $test->addIndex(); $test->addIndex(); $ddd = $test->getColor(); echo "<p style='color: #ac2925' >" . $ddd . "uuuuu</p>"; $inex = $test->getIndex(); $mutIn = $inex * 1000; echo $mutIn; $test->say(); echo $test->index; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //$mysqli = new mysqli("localhost", "zhangyanxi", "yanxi312", "test"); // ///* check connection */ //if (mysqli_connect_errno()) { // printf("Connect failed: %s\n", mysqli_connect_error()); // exit(); //} // //printf("Host information: %s\n", $mysqli->host_info); // ////获取当前字符集 //echo $mysqli->character_set_name() . "<br>"; ////获取客户端信息 //echo $mysqli->get_client_info() . "<br>"; ////获取mysql主机信息 //echo $mysqli->host_info . "<br>"; ////获取服务器信息 //echo $mysqli->server_info . "<br>"; ////获取服务器版本 //echo $mysqli->server_version . "<br>"; // // ////构造SQL语句 ////$query = "SELECT * FROM user order by Host LIMIT 4000"; //$query = "SELECT * FROM userqqq"; ////执行SQL语句 //$result = $mysqli->query($query); ////遍历结果 //while ($row = $result->fetch_array(MYSQLI_BOTH)) { // echo "Host:" . $row['Host'] . "|" . $row['User'] . "<br />"; //} // // // //$query = "SELECT * FROM Account_CustomerInfo"; ////执行SQL语句 //$result = $mysqli->query($query); ////遍历结果 //while ($row = $result->fetch_array(MYSQLI_BOTH)) { // echo "Account_CustomerInfoooo:<b style='color: #2e6da4;'>" . $row['aInfoName'] . '</b>|<b style="background-color:red;">'. $row['aInfoPhone'] . "</b><br />"; //} // // // ////释放结果集 //$result->free(); // // ////关闭数据库连接 //$mysqli->close(); //$link = mysqli_connect("localhost", "zhangyanxi", "yanxi312", "test"); // ///* check connection */ //if (!$link) { // printf("Connect failed: %s\n", mysqli_connect_error()); // exit(); //} // //printf("Host information: %s\n", mysqli_get_host_info($link)); // ///* close connection */ //mysqli_close($link); ?> ``` Grass.php ```<?php /** * Created by PhpStorm. * User: yafei * Date: 2017-12-26 * Time: 23:21 */ class Grass extends Plant { public $color;// 颜色 public function setColor($color) { $this->color = $color; } public function getColor() { echo $this->gettype(); return $this->color; } }``` sqr.php ```<?php /** * Created by PhpStorm. * User: yafei * Date: 2017-12-24 * Time: 23:01 */ //$email = $_POST['txtEmail']; //$password = $_POST['txtPassword']; //$sql = "SELECT * FROM tbluser WHERE email='$email' AND password='$password'"; //echo $sql; $hostname = "localhost"; $dbuser = "zhangyanxi"; $dbpass = "yanxi312"; //$dbname = "demo_cart_db"; $dbname = "Coam_Data"; $con = new mysqli($hostname, $dbuser, $dbpass, $dbname); if ($con->connect_error) { die ("Error connrrr55ect to db"); } //$email = "1071187704@qq.com"; //$password = "123456"; //$sql = "SELECT * FROM tbluser WHERE email='$email' AND password='$password'"; $sql = "SELECT * FROM Truck_Info;"; //$sql = "SELECT * FROM Truck_Info WHERE tid<>4;"; //$sql = "SELECT plateNo,tid FROM Truck_Info where tid>4 and tid<100;"; //$sql = "SELECT * FROM Truck_Info;"; //$sql = "DELETE FROM Truck_Info where tid=15;"; //$sql = "UPDATE Truck_Info SET plateNo= '赣G0000' whee tid=6"; //$sql="INSERT INTO Truck_Info(tid,plateNo) VALUES (100, '赣G0001')"; $result = $con->query($sql); if ($result->num_rows > 0) { //login success //$row = $result->fetch_assoc(); while ($row = $result->fetch_assoc()) { //printf("%s (%s)\n", $row["Name"], $row["CountryCode"]); print_r($row); echo "<br/>"; echo "<br/>"; } //$_SESSION["uid"] = $row['uid']; //set session // setcookie("uid", $row['uid'], time() + (86400 * 30), "/"); //set cookie //header("Location: ondex.php"); //print_r($row); echo "succesh"; } else { //login failed // setcookie("uid","yyyy", time() + (2 * 30), "/"); echo "Invali0d login<br/>"; } //SELECT * FROM tbluser WHERE email='1071187704@qq.com' AND password='hahaha'``` test.php ```<?php /** * Created by PhpStorm. * User: yafei * Date: 2017-12-26 * Time: 20:28 */ ini_set('display_errors', 1); if(false) { echo 6666; } else{ echo 555; } echo "kkkkkkkkkk kkkkkkkkkkkkkkkkkkkkkkkkk"; //echo time(); print_r($_GET); print_r($_POST); ariteMsg(); // function ariteMsg() { echo "Hello world!"; } //writeMsg(); // 调用函数 ?> <html> <head> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("div").ajaxSuccess(function(){ alert("AJAX 请求已成功完成"); }); $("button").click(function(){ // $("div.footer").load("http://zsr.iirii.com/aqq/index.html"); $("div").load("http://zsr.iirii.com/aqq/index.html"); }); }); </script> </head> <body> <div id="txt"><h2>通过 AJAX 改变文本</h2></div> <<button>改变内容</button> </body> </html> ``` sc.php ```<?php /** * Created by PhpStorm. * User: yafei * Date: 2018-01-05 * Time: 20:37 */ /** * 设置显示错误信息,为了方便调试 */ ini_set('display_errors', 1); session_start(); setcookie("uiykddddkk0000d", "oooooooo44444445555555ooooooooopppppppppppppppppppppoooo", time() + (86400 * 30), "/"); //set cookie echo "[$ _COOKIE]##################################"; echo "<br/>"; print_r($_COOKIE); echo "<br/>"; echo "[$ _SESSION]##################################"; echo "<br/>"; print_r($_SESSION); echo "<br/>"; echo "[$ _post]##################################"; echo "<br/>"; print_r($_POST); echo "<br/>"; echo "[$ _get]##################################"; echo "<br/>"; print_r($_GET); echo "<br/>"; echo "[$ _server]##################################"; echo "<br/>"; var_dump($_SERVER); echo "<br/>"; // 调用 error_log() 的另一种方式: error_log(print_r($_SERVER, true), 3, "logs/my-errors.log"); echo "[$ setcookie]##################################"; echo "<br/>"; //setcookie("uiyyyyyyd", "ooooooooooooooooooooooooooooo", time() + (86400 * 30), "/"); //set cookie //print_r($_Session_ID); $a = array('test' => 1, 'hello' => NULL, 'pie' => array('a' => 'apple', 'apple'=> array('k'=>4))); var_dump(isset($a['test'])); // TRUE var_dump(isset($a['pie']['apple']['k'])); // FALSE var_dump(isset($a['hello'])); // FALSE/$_SESSION["id"] = "11111111111111"; //$expected_array_got_string = "somestring"; $expected_array_got_string = "somestring"; var_dump(isset($expected_array_got_string['some_key'])); var_dump(isset($expected_array_got_string[0])); var_dump(isset($expected_array_got_string['0'])); var_dump(isset($expected_array_got_string[0.5])); var_dump(isset($expected_array_got_string['0.5'])); var_dump(isset($expected_array_got_string['0 Mostel'])); print_r($expected_array_got_string[0]); print_r($expected_array_got_string["1"]); print_r($expected_array_got_string[2]); print_r($expected_array_got_string[0.5]); ?> ``` Plant.php ```<?php /** * Created by PhpStorm. * User: yafei * Date: 2017-12-26 * Time: 21:12 */ class Plant { public $height;// 平均高度 public $season;// 开放季节 public $photosyntheticTime;// 每日光合时长 hour public $co2;// 每年吸收的二氧化碳量 g public $o2;// 每年转化的氧气 g public $type;//类型 public $hrt; public function __construct() { } public function seHeight($heigt) { $this->height = $heigt; } public function getHeight() { //$this->seHeight(55); echo $this->height; return $this->height; } public function settype($type) { $this->type = $type; } public function gettype() { //$this->setype("tree"); echo $this->type; return $this->type; } public function hdhdhd($co2, $o2) { // $lll = [$co2,$o2]; $this->co2 = $co2; $this->o2 = $o2; // $this->hrt=$lll; } public function jjjj() { $lll= [$this->co2,$this->o2]; // $hrt= ["co2","o2"]; // return $this->co2; // return $this->o2; // $this->hrt=$lll; return $lll; } }``` zq.php ```<?php /** * Created by PhpStorm. * User: yafei * Date: 2017-03-11 * Time: 22:47 */ echo "zhangqiang"; ``` Animal.php ```<?php /** * Created by PhpStorm. * User: yafei * Date: 2017-04-03 * Time: 20:05 */ class Animal { public $weight;// 体重 kg public $sex;//性别 public $bodyTemperature;// 体温 public function __construct() { $this->weight = 30; } public function setWeight($wet) { $this->weight = $wet; } public function geZhongLiang() { return $this->weight; } }``` Test.php ```<?php /** * Created by PhpStorm. * User: yafei * Date: 2017-04-03 * Time: 20:05 */ class Test { public $index; public $color; public function __construct() { $this->index = 0; $this->color = "red"; } public function say() { echo $this->index; echo $this->color; echo "<br />"; } public function setColor($col) { $this->color = $col; } public function getColor() { return $this->color; } public function addIndex() { $this->index += 1; } public function getIndex() { return $this->index; } } ?>```
zhouwentong1993/mybatis_test
zhouwentong1993/mybatis_test QueryVo.java ```package com.puhui.vo; /** * Created by zhouwentong1@gmail.com on 2016/2/13. * 复合查询 */ public class QueryVo { private User user; private UserCustom userCustom; @Override public String toString() { return "QueryVo{" + "user=" + user + ", userCustom=" + userCustom + '}'; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public UserCustom getUserCustom() { return userCustom; } public void setUserCustom(UserCustom userCustom) { this.userCustom = userCustom; } } ``` SecondTest.java ```package com.puhui.test; import java.io.InputStream; /** * Created by zhouwentong1@gmail.com on 2016/2/10. */ public class SecondTest { public static void main(String[] args) { InputStream resourceAsStream = SecondTest.class.getClass().getClassLoader().getResourceAsStream(""); System.out.println(resourceAsStream); } } ``` UserCustom.java ```package com.puhui.vo; /** * Created by zhouwentong1@gmail.com on 2016/2/13. * 用户自定义扩展类 */ public class UserCustom { } ``` UserDao.java ```package com.puhui.dao; import com.puhui.vo.User; import java.util.List; /** * Created by zhouwentong1@gmail.com on 2016/2/10. * UserDAO 接口 */ public interface UserDao { List<User> findAllUser(); User findUserById(int id); } ``` FirstTest.java ```package com.puhui.test; import com.puhui.vo.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * Created by zhouwentong1@gmail.com on 2016/2/9. * Test if the program can run */ public class FirstTest { //会话工厂 private SqlSessionFactory sqlSessionFactory; @Before public void createSqlSessionFactory() throws IOException { // 配置文件 String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); // 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); } // 根据 id查询用户信息 @Test public void testFindUserById() { // 数据库会话实例 SqlSession sqlSession = null; try { // 创建数据库会话实例sqlSession sqlSession = sqlSessionFactory.openSession(); // 查询单个记录,根据用户id查询用户信息 User user = sqlSession.selectOne("test.findAllUser"); List<Object> objects = sqlSession.selectList("test.findAllUser"); System.out.println(objects.size()); // 输出用户信息 System.out.println(user); } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } } // 根据用户名称模糊查询用户信息 @Test public void testFindUserByUsername() { // 数据库会话实例 SqlSession sqlSession = null; try { // 创建数据库会话实例sqlSession sqlSession = sqlSessionFactory.openSession(); // 查询单个记录,根据用户id查询用户信息 List<User> list = sqlSession.selectList("test.findUserByUsername", "张"); System.out.println(list.size()); } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } } // 添加用户信息 @Test public void testInsert() { // 数据库会话实例 SqlSession sqlSession = null; try { // 创建数据库会话实例sqlSession sqlSession = sqlSessionFactory.openSession(); // 添加用户信息 User user = new User(); user.setUsername("张小明21211"); user.setAddress("河南郑州"); user.setSex("1"); sqlSession.insert("test.insertUser1", user); //提交事务 sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } } @Test public void deleteUserById() { SqlSession sqlSession = null; try { sqlSession = sqlSessionFactory.openSession(); sqlSession.delete("test.deleteUserById", 31); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } } } ``` MapperTest.java ```package com.puhui.test; import com.puhui.mapper.UserMapper; import com.puhui.vo.OrderCustom; import com.puhui.vo.QueryVo; import com.puhui.vo.User; import junit.framework.TestCase; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.keygen.KeyGenerator; import org.apache.ibatis.io.Resources; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.InputStream; import java.lang.reflect.Field; import java.sql.Statement; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by zhouwentong1@gmail.com on 2016/2/10. * Mapper 文件测试 */ public class MapperTest extends TestCase { private SqlSessionFactory sqlSessionFactory; protected void setUp() throws Exception { //mybatis配置文件 String resource = "sqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); //使用SqlSessionFactoryBuilder创建sessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } public void testFindUserById() throws Exception { //获取session SqlSession session = sqlSessionFactory.openSession(); //获取mapper接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); //调用代理对象方法 User user = userMapper.findUserById(1); System.out.println(user); //关闭session session.close(); } @Test public void testFindUserByUsername() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.findUserByUsername("张"); System.out.println(user); } public void testInsertUser() throws Exception { //获取session SqlSession session = sqlSessionFactory.openSession(); //获取mapper接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); //要添加的数据 User user = new User(); user.setUsername("张三"); user.setBirthday(new Date()); user.setSex("1"); user.setAddress("北京市"); //通过mapper接口添加用户 userMapper.insertUser(user); //提交 session.commit(); //关闭session session.close(); } public void testParameterByMap() throws Exception { //获取session SqlSession session = sqlSessionFactory.openSession(); //获取mapper接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); HashMap<String, Object> userMap = new HashMap<String,Object>(); //要添加的数据 // User user = new User(); // user.setUsername("张三"); // user.setBirthday(new Date()); // user.setSex("1"); // user.setAddress("北京市"); userMap.put("id", 31); userMap.put("username", "张三"); userMap.put("sex", "1"); userMap.put("address", "北京市"); //通过mapper接口添加用户 // userMapper.insertUser(user); User user = userMapper.findUserByHashMap(userMap); System.out.println(user); //提交 // session.commit(); //关闭session session.close(); } /** * 测试复合查询参数问题 * @throws Exception */ public void testQueryVo() throws Exception { //获取session SqlSession session = sqlSessionFactory.openSession(); //获取mapper接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); // HashMap<String, Object> userMap = new HashMap<String,Object>(); //要添加的数据 // User user = new User(); // user.setUsername("张三"); // user.setBirthday(new Date()); // user.setSex("1"); // user.setAddress("北京市"); // userMap.put("id", 31); // userMap.put("username", "张三"); // userMap.put("sex", "1"); // userMap.put("address", "北京市"); // //通过mapper接口添加用户 //// userMapper.insertUser(user); // User user = userMapper.findUserByHashMap(userMap); // System.out.println(user); //提交 // session.commit(); //关闭session QueryVo queryVo = new QueryVo(); User user = new User(); user.setUsername("王五"); user.setId(1); queryVo.setUser(user); User queryUser = userMapper.findUserByQueryVo(queryVo); System.out.println(queryUser); session.close(); } public void testQueryCount() throws Exception { //获取session SqlSession session = sqlSessionFactory.openSession(); //获取mapper接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); // User user = new User(); int userCount = userMapper.getAllUser(new User()); System.out.println(userCount); session.close(); } public void testManyCondition() throws Exception { //获取session SqlSession session = sqlSessionFactory.openSession(); //获取mapper接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); User user = userMapper.queryUserByManyCondition(1, "王五", "北京市"); System.out.println(user); session.close(); } public void testQueryUserListByArray() throws Exception { //获取session SqlSession session = sqlSessionFactory.openSession(); //获取mapper接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); User user = new User(); user.setId(1); User user1 = new User(); user1.setId(2); Object[] arr = new Object[2]; arr[0] = user; arr[1] = user1; List<User> users = userMapper.queryUserListByArray(arr); System.out.println(users.size()); session.close(); } public void testQueryUserListByStringArray() throws Exception { //获取session SqlSession session = sqlSessionFactory.openSession(); //获取mapper接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); String[] idList = {"1","2","1212"}; List<User> userList = userMapper.queryUserListByStringArray(idList); System.out.println(userList.size()); session.close(); } public void testQueryOrderList() throws Exception { //获取session SqlSession session = sqlSessionFactory.openSession(); //获取mapper接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); List<OrderCustom> orderCustomList = userMapper.queryOrderList(); orderCustomList.forEach(System.out::println); session.close(); } /** * * @throws Exception */ public void testQueryMap() throws Exception { //获取session SqlSession session = sqlSessionFactory.openSession(); //获取mapper接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); Map<String, Object> userMap = userMapper.getMapByQueryAllUser(); Class<User> clazz = User.class; Field[] fields = clazz.getDeclaredFields(); Map<String, Object> requiredMap = new HashMap<>(fields.length); if (fields.length > 0) { for (Field field : fields) { requiredMap.put(field.getName(), null); } } System.out.println(requiredMap.size()); Map<String, Object> copyOfUserMap = new HashMap<>(userMap); Map<String, Object> copyOfRequiredMap = new HashMap<>(requiredMap); System.out.println(copyOfUserMap.size()); for (Map.Entry entry1 : requiredMap.entrySet()) { for (Map.Entry entry2 : userMap.entrySet()) { if (!entry1.getKey().equals(entry2)) { copyOfUserMap.put(entry1.getKey().toString(), null); } else { break; } } } System.out.println(copyOfUserMap.size()); // for (int i = 0; i < requiredMap.size(); i++) { // for (int j = 0; j < userMap.size(); j++) { // if (requiredMap.containsKey()) // } // } for (Map.Entry entry : copyOfUserMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } System.out.println("============="); for (Map.Entry entry : userMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } System.out.println("============="); System.out.println(userMap.size()); session.close(); } }``` UserDaoImpl.java ```package com.puhui.dao.impl; import com.puhui.dao.UserDao; import com.puhui.vo.User; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import java.util.Collections; import java.util.List; /** * Created by zhouwentong1@gmail.com on 2016/2/10. */ public class UserDaoImpl implements UserDao { private SqlSessionFactory sqlSessionFactory; public UserDaoImpl(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } @Override public List<User> findAllUser() { SqlSession sqlSession = this.sqlSessionFactory.openSession(); List<User> userList = null; try { userList = sqlSession.selectList("test.findAllUser"); } finally { sqlSession.close(); } return userList == null ? Collections.<User>emptyList() : userList; } @Override public User findUserById(int id) { SqlSession sqlSession = this.sqlSessionFactory.openSession(); User user = null; try { user = sqlSession.selectOne("test.findUserById", id); } finally { sqlSession.close(); } return user; } } ``` UserMapper.java ```package com.puhui.mapper; import com.puhui.vo.OrderCustom; import com.puhui.vo.QueryVo; import com.puhui.vo.User; import org.apache.ibatis.annotations.Param; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by zhouwentong1@gmail.com on 2016/2/10. * UserMapper 用来替代 DAO */ public interface UserMapper { User findUserById(int id); User findUserByUsername(String username); void insertUser(@Param("user") User user); User findUserByHashMap(HashMap<String, Object> userMap); User findUserByQueryVo(QueryVo queryVo); int getAllUser(User user); User queryUserByManyCondition(@Param("id") int id, @Param("username") String username, @Param("address") String address); Map<String, Object> getMapByQueryAllUser(); List<User> queryUserListByArray(Object[] userList); List<User> queryUserListByStringArray(String[] idList); List<OrderCustom> queryOrderList(); } ```
zhouyikai129/SYTSPublic
zhouyikai129/SYTSPublic README.md ```# SYTSPublic 项目经常用的时间和字符串的封装 ```
zhouzgang/css-demo
zhouzgang/css-demo README.md ```##### 选择器练习```
zhozhoba1204/PayServis
zhozhoba1204/PayServis BruteForcePrevent.java ```package ru.blinov.payservis.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ru.blinov.payservis.dao.UserRepository; import ru.blinov.payservis.exception.CustomException; import ru.blinov.payservis.model.User; import java.util.Date; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Service public class BruteForcePrevent { private final static long BLOCKEDUNTIL = 300000; private final static long MAXATTEMPT = 2; private Map<User,Integer> map = new ConcurrentHashMap<>(); @Autowired private UserRepository userRepository; public void failAttempt(User user) { if (map.get(user)==null||map.get(user)<MAXATTEMPT) { map.putIfAbsent(user,0); map.put(user,map.get(user)+1); }else { user.setBlockedUntil(new Date(System.currentTimeMillis() + BLOCKEDUNTIL)); map.put(user,0); user.setBlocked(true); userRepository.save(user); throw new CustomException("user is blocked"); } } public void successAttempt(User user) { user.setBlocked(false); user.setBlockedUntil(new Date(0)); map.put(user,0); userRepository.save(user); } public boolean check(User user){ return user.getBlockedUntil().getTime()>new Date(System.currentTimeMillis()).getTime(); } } ``` PayservisApplication.java ```package ru.blinov.payservis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class PayservisApplication { public static void main(String[] args) { SpringApplication.run(PayservisApplication.class, args); } } ``` PaymentService.java ```package ru.blinov.payservis.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import ru.blinov.payservis.dao.TokenRepository; import ru.blinov.payservis.dao.UserRepository; import ru.blinov.payservis.dto.LoginRequestDto; import ru.blinov.payservis.exception.CustomException; import ru.blinov.payservis.model.Token; import ru.blinov.payservis.model.Transaction; import ru.blinov.payservis.model.User; import ru.blinov.payservis.security.BruteForcePrevent; import javax.servlet.http.HttpServletRequest; import java.math.BigDecimal; import java.util.List; import java.util.Set; import java.util.UUID; @Service public class PaymentService { private UserRepository userRepository; private TokenRepository tokenRepository; private BCryptPasswordEncoder bCryptPasswordEncoder; private AuthenticationManager authenticationManager; private UserDetailsService userDetailsService; private BruteForcePrevent bruteForcePrevent; @Autowired public PaymentService(UserRepository userRepository, TokenRepository tokenRepository, BCryptPasswordEncoder bCryptPasswordEncoder, AuthenticationManager authenticationManager, UserDetailsService userDetailsService, BruteForcePrevent bruteForcePrevent) { this.userRepository = userRepository; this.tokenRepository = tokenRepository; this.bCryptPasswordEncoder = bCryptPasswordEncoder; this.authenticationManager = authenticationManager; this.userDetailsService = userDetailsService; this.bruteForcePrevent = bruteForcePrevent; } public String login(LoginRequestDto loginRequestDto, HttpServletRequest request) { User user = null; user = userRepository.findByUserName(loginRequestDto.getName()); // System.out.println(user.getPassword()); if (user != null && bruteForcePrevent.check(user) && bCryptPasswordEncoder.matches(loginRequestDto.getPassword(), user.getPassword())) { throw new CustomException("user is blocked"); } else if (user != null && !bCryptPasswordEncoder.matches(loginRequestDto.getPassword(), user.getPassword())) { bruteForcePrevent.failAttempt(user); throw new CustomException("invalid username or password"); } if (user == null) { user = new User(); user.setUserName(loginRequestDto.getName()); user.setPassword(bCryptPasswordEncoder.encode(loginRequestDto.getPassword())); user.setTotalBalance(new BigDecimal("8")); } bruteForcePrevent.successAttempt(user); user.setSessionId(request.getSession().getId()); userRepository.save(user); UserDetails userDetails = userDetailsService.loadUserByUsername(loginRequestDto.getName()); Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginRequestDto.getName(), loginRequestDto.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); Token token = new Token(); token.setUser(user); token.setGenerateToken(UUID.randomUUID().toString()); token.setSessionId(request.getSession().getId()); tokenRepository.save(token); return "user is authenticated"; } public String payment() { String username = SecurityContextHolder.getContext().getAuthentication().getName(); User user = userRepository.findByUserName(username); BigDecimal totalBalance = user.getTotalBalance(); if (totalBalance.compareTo(new BigDecimal("1.1")) < 0) { throw new CustomException("no money"); } else { List<Transaction> set = user.getSetOfTransactions(); totalBalance = totalBalance.subtract(new BigDecimal("1.1")); Transaction transaction = new Transaction(totalBalance, new BigDecimal("1.1")); set.add(transaction); user.setTotalBalance(totalBalance); userRepository.save(user); return "payment is passed"; } } }``` PaymentController.java ```package ru.blinov.payservis.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import ru.blinov.payservis.dto.LoginRequestDto; import ru.blinov.payservis.service.PaymentService; import javax.servlet.http.HttpServletRequest; @RestController public class PaymentController { private PaymentService paymentService; @Autowired public PaymentController(PaymentService paymentService) { this.paymentService = paymentService; } @PostMapping("/login") public ResponseEntity<String> login(@RequestBody LoginRequestDto loginRequestDto, HttpServletRequest request){ String response = paymentService.login(loginRequestDto, request); return new ResponseEntity(response, HttpStatus.OK); } @PostMapping("/payment") @Transactional(isolation = Isolation.REPEATABLE_READ) public ResponseEntity<String> payment(){ String response = paymentService.payment(); return new ResponseEntity(response, HttpStatus.OK); } } ``` TokenRepository.java ```package ru.blinov.payservis.dao; import org.springframework.data.jpa.repository.JpaRepository; import ru.blinov.payservis.model.Token; public interface TokenRepository extends JpaRepository<Token, Long> { Token findByUserId(Long id); Token findBySessionId(String id); } ``` CustomLogoutHandler.java ```package ru.blinov.payservis.security; import ru.blinov.payservis.dao.TokenRepository; import ru.blinov.payservis.dao.UserRepository; import ru.blinov.payservis.model.Token; import ru.blinov.payservis.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Service public class CustomLogoutHandler implements LogoutHandler { @Autowired UserRepository userRepository; @Autowired TokenRepository tokenRepository; @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { User user = userRepository.findByUserName(authentication.getName()); String sessionId = user.getSessionId(); Token token = tokenRepository.findBySessionId(sessionId); tokenRepository.deleteById(token.getId()); SecurityContextHolder.clearContext(); System.out.println("token is deleted"); } } ``` UserDetailsServiceImplementation.java ```package ru.blinov.payservis.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import ru.blinov.payservis.dao.UserRepository; import ru.blinov.payservis.model.User; @Service public class UserDetailsServiceImplementation implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUserName(username); if (user == null) { throw new UsernameNotFoundException("unable to find user " + username); } UserDetails authorisedUser = org.springframework.security.core.userdetails.User.withUsername( user.getUserName()).password(user.getPassword()).authorities("USER").build(); return authorisedUser; } } ``` Token.java ```package ru.blinov.payservis.model; import javax.persistence.*; @Entity @Table(name = "Tokens") public class Token { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String sessionId; @OneToOne @JoinColumn(name = "USER_ID") private User user; private String generateToken; public Token() { } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public Long getId() { return id; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getGenerateToken() { return generateToken; } public void setGenerateToken(String generateToken) { this.generateToken = generateToken; } } ``` User.java ```package ru.blinov.payservis.model; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.Set; @Entity @Table(name = "Users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "USER_ID") private Long id; private String userName; private String password; private BigDecimal totalBalance; private String sessionId; private Date blockedUntil = new Date(0); private Boolean blocked; @ElementCollection(fetch = FetchType.LAZY) @CollectionTable(name = "USER_TRANSACTIONS", joinColumns = @JoinColumn(name = "USER_ID")) @Cascade(org.hibernate.annotations.CascadeType.ALL) List<Transaction> setOfTransactions; public User(){ } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public void setBlocked(Boolean blocked) { this.blocked = blocked; } public Date getBlockedUntil() { return blockedUntil; } public void setBlockedUntil(Date blockedUntil) { this.blockedUntil = blockedUntil; } public Long getId() { return id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public BigDecimal getTotalBalance() { return totalBalance; } public void setTotalBalance(BigDecimal totalBalance) { this.totalBalance = totalBalance; } public List<Transaction> getSetOfTransactions() { return setOfTransactions; } public void setSetOfTransactions(List<Transaction> setOfTransactions) { this.setOfTransactions = setOfTransactions; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return Objects.equals(userName, user.userName) && Objects.equals(password, user.password); } @Override public int hashCode() { return Objects.hash(userName, password); } } ``` Transaction.java ```package ru.blinov.payservis.model; import javax.persistence.Embeddable; import java.math.BigDecimal; @Embeddable public class Transaction { private BigDecimal remainBalance; private BigDecimal amountOfPayment; public Transaction(){ } public Transaction(BigDecimal remainBalance, BigDecimal amountOfPayment) { this.remainBalance = remainBalance; this.amountOfPayment = amountOfPayment; } public BigDecimal getRemainBalance() { return remainBalance; } public void setRemainBalance(BigDecimal remainBalance) { this.remainBalance = remainBalance; } public BigDecimal getAmountOfPayment() { return amountOfPayment; } public void setAmountOfPayment(BigDecimal amountOfPayment) { this.amountOfPayment = amountOfPayment; } } ```
zhssmy/zhssmy.github.io
zhssmy/zhssmy.github.io README.md ```# zhssmy.github.io 海上生明月 > public文件 ```
zht1990/kafka-demo
zht1990/kafka-demo README.md ```# kafka-demo kafka 生产者消费者例子 - SingleThreadProducer.java 单线程生产者 - SingleThreadConsumer.java 单线程消费者 - MultipleThreadConsumer.java 多线程消费者 kafka 技术交流群:733847341 ```
zhuanke/Hello-World
zhuanke/Hello-World README.md ```# Hello-World First Test Hello GitHuber, I am the newbird in GitHub, now I am learning how to use it. it's my first lesson! Good! ```
zhubinsheng/KeyPairJava
zhubinsheng/KeyPairJava EsptouchGenerator.java ```package com.company.touch; import java.net.InetAddress; public class EsptouchGenerator { /** * Constructor of EsptouchGenerator, it will cost some time(maybe a bit * much) * * @param apSsid the Ap's ssid * @param apBssid the Ap's bssid * @param apPassword the Ap's password * @param inetAddress the phone's or pad's local ip address allocated by Ap */ public EsptouchGenerator(byte[] apSsid, byte[] apBssid, byte[] apPassword, InetAddress inetAddress, ITouchEncryptor encryptor) { // generate data code DatumCode dc = new DatumCode(apSsid, apBssid, apPassword, inetAddress, encryptor); char[] dcU81 = dc.getU8s(); mDcBytes2 = new byte[dcU81.length][]; for (int i = 0; i < mDcBytes2.length; i++) { mDcBytes2[i] = ByteUtil.genSpecBytes(dcU81[i]); } } /** * Constructor of DatumCode * * @param apSsid the Ap's ssid * @param apBssid the Ap's bssid * @param apPassword the Ap's password * @param ipAddress the ip address of the phone or pad * @param encryptor null use origin data, not null use encrypted data */ private DatumCode(byte[] apSsid, byte[] apBssid, byte[] apPassword, InetAddress ipAddress, ITouchEncryptor encryptor) { // Data = total len(1 byte) + apPwd len(1 byte) + SSID CRC(1 byte) + // BSSID CRC(1 byte) + TOTAL XOR(1 byte)+ ipAddress(4 byte) + apPwd + apSsid apPwdLen <= // 105 at the moment // total xor char totalXor = 0; char apPwdLen = (char) apPassword.length; CRC8 crc = new CRC8(); crc.update(apSsid); update(apSsid, 0, apSsid.length); char apSsidCrc = (char) crc.getValue(); crc.reset(); crc.update(apBssid); char apBssidCrc = (char) crc.getValue(); char apSsidLen = (char) apSsid.length; byte[] ipBytes = ipAddress.getAddress(); int ipLen = ipBytes.length; char totalLen = (char) (EXTRA_HEAD_LEN + ipLen + apPwdLen + apSsidLen); // ^= 异或就是两个数的二进制形式,按位对比,相同取0,不同取一 // build data codes mDataCodes = new LinkedList<>(); mDataCodes.add(new DataCode(totalLen, 0)); totalXor ^= totalLen; mDataCodes.add(new DataCode(apPwdLen, 1)); totalXor ^= apPwdLen; mDataCodes.add(new DataCode(apSsidCrc, 2)); totalXor ^= apSsidCrc; mDataCodes.add(new DataCode(apBssidCrc, 3)); totalXor ^= apBssidCrc; // ESPDataCode 4 is null for (int i = 0; i < ipLen; ++i) { char c = ByteUtil.convertByte2Uint8(ipBytes[i]); totalXor ^= c; mDataCodes.add(new DataCode(c, i + EXTRA_HEAD_LEN)); } for (int i = 0; i < apPassword.length; i++) { char c = ByteUtil.convertByte2Uint8(apPassword[i]); totalXor ^= c; mDataCodes.add(new DataCode(c, i + EXTRA_HEAD_LEN + ipLen)); } // totalXor will xor apSsidChars no matter whether the ssid is hidden for (int i = 0; i < apSsid.length; i++) { char c = ByteUtil.convertByte2Uint8(apSsid[i]); totalXor ^= c; mDataCodes.add(new DataCode(c, i + EXTRA_HEAD_LEN + ipLen + apPwdLen)); } // add total xor last mDataCodes.add(4, new DataCode(totalXor, 4)); // add bssid int bssidInsertIndex = EXTRA_HEAD_LEN; for (int i = 0; i < apBssid.length; i++) { int index = totalLen + i; char c = ByteUtil.convertByte2Uint8(apBssid[i]); DataCode dc = new DataCode(c, index); if (bssidInsertIndex >= mDataCodes.size()) { mDataCodes.add(dc); } else { mDataCodes.add(bssidInsertIndex, dc); } bssidInsertIndex += 4; } } // ^运算符跟 | 类似,但有一点不同的是 如果两个操作位都为1的话,结果产生0 private void update(byte[] buffer, int offset, int len) { for (int i = 0; i < len; i++) { int data = buffer[offset + i] ^ value; value = (short) (crcTable[data & 0xff] ^ (value << 8)); } } } ``` ECCEnum.java ```package com.company; public enum ECCEnum { ALGORITHM("EC"), PROVIDER("BC"), PUBLIC_KEY("PUBLIC_KEY"), PRIVATE_KEY("PRIVATE_KEY"); private String value; ECCEnum(String value) { this.value = value; } public String value() { return this.value; } }``` ECCUtil.java ```//package com.company; // //import com.ktnw.utils.encrypt.BASE64Decoder; // //import javax.crypto.Cipher; //import javax.crypto.NullCipher; //import java.io.Serializable; //import java.security.KeyFactory; //import java.security.interfaces.ECPrivateKey; //import java.security.interfaces.ECPublicKey; //import java.security.spec.PKCS8EncodedKeySpec; //import java.security.spec.X509EncodedKeySpec; // ///** // * ecc 加密/解密 // */ //public class ECCUtil implements Serializable { // // // /** // * 加密 // * @param data // * @param publicKey // * @return // * @throws Exception // */ // public static byte[] encrypt(byte[] data, String publicKey) // throws Exception { // byte[] keyBytes = BASE64Decoder.decodeBuffer(publicKey); // // X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); // KeyFactory keyFactory = KeyFactory.getInstance(ECCEnum.ALGORITHM.value()); // // ECPublicKey pubKey = (ECPublicKey) keyFactory // .generatePublic(x509KeySpec); // // Cipher cipher = new NullCipher(); // cipher.init(Cipher.ENCRYPT_MODE, pubKey); // return cipher.doFinal(data); // } // // // /** // * 解密 // * @param data // * @param privateKey // * @return // * @throws Exception // */ // public static byte[] decrypt(byte[] data, String privateKey) throws Exception { // byte[] keyBytes = BASE64Decoder.decodeBuffer(privateKey); // // PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); // KeyFactory keyFactory = KeyFactory.getInstance(ECCEnum.ALGORITHM.value()); // // ECPrivateKey priKey = (ECPrivateKey) keyFactory // .generatePrivate(pkcs8KeySpec); // // Cipher cipher = new NullCipher(); // cipher.init(Cipher.DECRYPT_MODE, priKey); // // return cipher.doFinal(data); // } //}``` EncryptOrDecryptUtil.java ```package com.company; import java.io.UnsupportedEncodingException; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import java.util.Map; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; public class EncryptOrDecryptUtil { private static MessageDigest md5Digest; static { try { md5Digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } public static void main(String[] args) { Map<String, String> initKeys = generatorKey(); Map<String, String> tempKeys = generatorKey(); System.out.println("*******************************************************"); String serPubKey = initKeys.get("serPubKey"); System.out.println("【服务端初始化公钥serPubKey】" + serPubKey); String serPriKey = initKeys.get("serPriKey"); System.out.println("【服务端初始化私钥serPriKey】" + serPriKey); String cliPubKey = initKeys.get("cliPubKey"); System.out.println("【客户端初始化公钥cliPubKey】" + cliPubKey); String cliPriKey = initKeys.get("cliPriKey"); System.out.println("【客户端初始化私钥cliPriKey】" + cliPriKey); String tempSerPubKey = tempKeys.get("serPubKey"); System.out.println("【服务端临时公钥tempSerPubKey】" + tempSerPubKey); String tempSerPriKey = tempKeys.get("serPriKey"); System.out.println("【服务端临时私钥tempSerPriKey】" + tempSerPriKey); String tempCliPubKey = tempKeys.get("cliPubKey"); System.out.println("【客户端临时公钥tempCliPubKey】" + tempCliPubKey); String tempCliPriKey = tempKeys.get("cliPriKey"); System.out.println("【客户端临时公钥tempCliPriKey】" + tempCliPriKey); System.out.println("*******************************************************"); String request = "{\"serviceHeader\":{\"serviceId\":\"1010\",\"responseCode\":\"000000\",\"requestMsg\":\"请求成功\"},\"serviceBody\":{\"sessionId\":\"bf2d5af85239439aa56db5a149ddaaac\",\"userId\":null,\"deviceId\":\"990009263463476\",\"lastAccessTime\":\"2018-06-11 14:30:21\"}}"; String response = "{\"serviceId\":\"1010\",\"responseCode\":\"000000\",\"responseMsg\":\"请求成功\"}"; //客户端加密 System.out.println("start-------"); Map<String, String> clientRequest = clientEncryption(request, tempCliPriKey, cliPriKey, serPubKey); System.out.println("end-------client encrypt result: 【secretContent】" + clientRequest.get("secretContent") + " 【signData】" + clientRequest.get("signData")); //服务端解密 System.out.println("start-------"); Map<String, String> serverResult = serverDecryption(clientRequest.get("secretContent"), clientRequest.get("signData"), tempCliPubKey, serPriKey, cliPubKey); System.out.println("end-------server decrypt result: " + serverResult); //服务端加密 System.out.println("start-------"); Map<String, String> serverResponse = serverEncryption(response, tempSerPriKey, cliPubKey, serPriKey); System.out.println("end-------server encrypt result: " + serverResponse); //客户端解密 System.out.println("start-------"); Map<String, String> clientResult = clientDecryption(serverResponse.get("secretContent"), serverResponse.get("signData"), tempSerPubKey, cliPriKey, serPubKey); System.out.println("end-------client encrypt result: " + clientResult); } /** * 生成密钥公共方法 * @return */ public static Map<String, String> generatorKey(){ Map<String, String> keys = Maps.newHashMap(); Provider provider = new BouncyCastleProvider(); KeyPairGenerator keyPairGeneratorServer = null; KeyPairGenerator keyPairGeneratorClient = null; try { //1.服务端初始化密钥 keyPairGeneratorServer = KeyPairGenerator.getInstance("ECDH", provider); keyPairGeneratorServer.initialize(256); KeyPair keyPairSer = keyPairGeneratorServer.generateKeyPair(); //生成服务端密钥 String serpubKey = Base64.getMimeEncoder().encodeToString(keyPairSer.getPublic().getEncoded()); String serPriKey = Base64.getMimeEncoder().encodeToString(keyPairSer.getPrivate().getEncoded()); //2.客户端初始化密钥 keyPairGeneratorClient = KeyPairGenerator.getInstance("ECDH", provider); keyPairGeneratorClient.initialize(256); KeyPair keyPairCli = keyPairGeneratorClient.generateKeyPair(); //生成客户端密钥 String cliPubKey = Base64.getMimeEncoder().encodeToString(keyPairCli.getPublic().getEncoded()); String cliPriKey = Base64.getMimeEncoder().encodeToString(keyPairCli.getPrivate().getEncoded()); keys.put("serPubKey", serpubKey); keys.put("serPriKey", serPriKey); keys.put("cliPubKey", cliPubKey); keys.put("cliPriKey", cliPriKey); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return keys; } public static byte[] signData(String algorithm, byte[] data, PrivateKey key) throws Exception { Signature signer = Signature.getInstance(algorithm); signer.initSign(key); signer.update(data); return (signer.sign()); } /** * Client加密 * @param content 要加密的数据 * @param temCliPriKey 客户临时端私钥 * @param cliPriKey 客户端初始化公钥 * @param serPubKey 服务端初始化公钥 * @return */ public static Map<String, String> clientEncryption(String content, String temCliPriKey, String cliPriKey, String serPubKey){ System.out.println("开始数据加密........"); Map<String, String> result = Maps.newHashMap(); //生成签名数据 String signData = sign(content, cliPriKey); System.out.println("签名:" + "【" + signData + "】"); //密钥磋商 String key = ecdhKey(temCliPriKey, serPubKey); System.out.println("加锁钥匙:ecdhKey【" + key + "】"); String secretContent = doAES(content, key, Cipher.ENCRYPT_MODE); result.put("secretContent", secretContent); result.put("signData", signData); return result; } /** * Client解密 * @param secretContent 加密数据 * @param signData 数据签名 * @param tmpSerPubKey 服务端临时公钥 * @param cliPriKey 客户端初始化私钥 * @param serPubKey 服务端初始化公钥 * @return */ public static Map<String, String> clientDecryption(String secretContent, String signData, String tmpSerPubKey, String cliPriKey, String serPubKey){ System.out.println("开始客户端解密......"); Map<String, String> result = Maps.newHashMap(); String key = ecdhKey(cliPriKey, tmpSerPubKey); System.out.println("开锁钥匙:ecdhKey【" + key + "】"); String textContent = doAES(secretContent, key, Cipher.DECRYPT_MODE); System.out.println("解密后内容:" + textContent); //验签 boolean res = verify(textContent, serPubKey, signData); if(!res){ System.err.println("验签失败!"); return null; } result.put("textContent", textContent); result.put("res", res+""); return result; } /** * Server加密 * @param content 明文请求 * @param temSerPriKey 服务端临时私钥 * @param cliPubKey 客户端初始化公钥 * @param serPriKey 服务端初始化私钥 * @return */ public static Map<String, String> serverEncryption(String content, String temSerPriKey, String cliPubKey, String serPriKey){ System.out.println("开始服务端解密......"); Map<String, String> result = Maps.newHashMap(); String signData = sign(content, serPriKey); System.out.println("加签【" + signData + "】"); //密钥磋商 String key = ecdhKey(temSerPriKey, cliPubKey); System.out.println("加密钥匙:ecdhKey【" + key + "】"); String secretContent = doAES(content, key, Cipher.ENCRYPT_MODE); result.put("secretContent", secretContent); result.put("signData", signData); return result; } /** * Server解密 * @param secrtContent 加密数据 * @param signData 数据签名 * @param tmpCliPubKey 客户端临时公钥 * @param serPriKey 服务端初始化私钥 * @param cliPubKey 客户端初始化公钥 * @return */ public static Map<String, String> serverDecryption(String secrtContent, String signData, String tmpCliPubKey, String serPriKey, String cliPubKey){ Map<String, String> result = Maps.newHashMap(); String key = ecdhKey(serPriKey, tmpCliPubKey); System.out.println("开锁钥匙【" + key + "】"); String textContent = doAES(secrtContent, key, Cipher.DECRYPT_MODE); System.out.println("解密后内容:" + textContent); //验签 boolean res = verify(textContent, cliPubKey, signData); result.put("textContent", textContent); result.put("res", res+""); return result; } /** * 生成签名数据 * @param content 加密数据 * @param priKey 私钥 * @return */ private static String sign(String content, String priKey) { try { byte[] keyBytes = Base64.getMimeDecoder().decode(priKey.getBytes("utf-8")); byte[] contentBytes = Base64.getMimeDecoder().decode(content.getBytes("utf-8")); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("EC"); PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); byte[] sign1 = signData("SHA256withECDSA", "content".getBytes(), privateKey); Signature signature = Signature.getInstance("SHA1withECDSA"); // Provider provider = new BouncyCastleProvider(); // Signature signature = Signature.getInstance("SHA256withECDSA",provider); signature.initSign(privateKey); signature.update(contentBytes); return Base64.getMimeEncoder().encodeToString(signature.sign()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 密钥磋商 * @param priKey 私钥 * @param pubKey 公钥 * @return */ private static String ecdhKey(String priKey, String pubKey) { //使用ECDH-BC方法添加进环境信息内 Security.addProvider(new BouncyCastleProvider()); KeyAgreement akeyAgree = null; try { //初始化ECDH,KeyFactory KeyFactory keyFactory = KeyFactory.getInstance("ECDH", "BC"); //处理私钥 byte[] priKeybytes = Base64.getMimeDecoder().decode(priKey.getBytes("utf-8")); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(priKeybytes); PrivateKey ecPriKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); //处理公钥 byte[] pubKeyBytes = Base64.getMimeDecoder().decode(pubKey.getBytes("utf-8")); X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubKeyBytes); PublicKey ecPubKey = keyFactory.generatePublic(pubX509); //密钥磋商生成新的密钥Byte数组 akeyAgree = KeyAgreement.getInstance("ECDH", "BC"); akeyAgree.init(ecPriKey); akeyAgree.doPhase(ecPubKey, true); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } return Base64.getMimeEncoder().encodeToString(akeyAgree.generateSecret()); } /** * AES加密数据 * @param data * @param key * @param mode * @return */ private static String doAES(String data, String key, int mode) { try { if (StringUtils.isBlank(data) || StringUtils.isBlank(key)) { return null; } boolean encrypt = mode == Cipher.ENCRYPT_MODE; byte[] content; //true 加密内容 false 解密内容 if (encrypt) { content = data.getBytes("UTF-8"); } else { content = parseHexStr2Byte(data); } SecretKeySpec keySpec = new SecretKeySpec(md5Digest.digest(key.getBytes("UTF-8")), "AES");//构造一个密钥 Cipher cipher = Cipher.getInstance("AES");// 创建密码器 cipher.init(mode, keySpec);// 初始化 byte[] result = cipher.doFinal(content);//加密或解密 if (encrypt) { return parseByte2HexStr(result); } else { return new String(result, "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 将二进制转化成十六进制 * @param result * @return */ private static String parseByte2HexStr(byte[] result) { StringBuffer buffer = new StringBuffer(); for(int i=0;i < result.length;i++){ String hex = Integer.toHexString(result[i] & 0xFF); if(hex.length() == 1){ hex = '0' + hex; } buffer.append(hex.toUpperCase()); } return buffer.toString(); } /** * 十六进制转换成二进制 * @param content * @return */ private static byte[] parseHexStr2Byte(String content) { if(content.length() < 1){ return null; } int hexStr = content.length() / 2; byte[] result = new byte[hexStr]; for(int i=0; i < hexStr; i++){ int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } /** * 验签方法 * @param textContent 解密明文 * @param pubKey 公钥 * @param signData 签名 * @return */ private static boolean verify(String textContent, String pubKey, String signData) { try { byte[] keyBytes = Base64.getMimeDecoder().decode(pubKey.getBytes("utf-8")); byte[] contentBytes = Base64.getMimeDecoder().decode(textContent.getBytes("utf-8")); byte[] signBytes = Base64.getMimeDecoder().decode(signData.getBytes("utf-8")); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("EC"); PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); Signature signature = Signature.getInstance("SHA1withECDSA"); signature.initVerify(publicKey); signature.update(contentBytes); return signature.verify(signBytes); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } return Boolean.parseBoolean(null); } } ``` Main.java ```//package com.company; // //import sun.security.util.KeyUtil; // //import java.security.KeyPair; //import java.security.PrivateKey; //import java.security.PublicKey; //import java.security.Signature; // //public class Main { // // public static void main(String[] args) { // // write your code here // } // // // public static byte[] signData(String algorithm, byte[] data, PrivateKey key) throws Exception { // Signature signer = Signature.getInstance(algorithm); // signer.initSign(key); // signer.update(data); // return (signer.sign()); // } // // public static boolean verifySign(String algorithm, byte[] data, PublicKey key, byte[] sig) throws Exception { // Signature signer = Signature.getInstance(algorithm); // signer.initVerify(key); // signer.update(data); // return (signer.verify(sig)); // } // // @Test // public void testSignVerify() throws Exception { // // 需要签名的数据 // byte[] data = new byte[1000]; // for (int i=0; i<data.length; i++) // data[i] = 0xa; // // // 生成秘钥,在实际业务中,应该加载秘钥 // KeyPair keyPair = KeyUtil.createKeyPairGenerator("secp256k1"); // PublicKey publicKey1 = keyPair.getPublic(); // PrivateKey privateKey1 = keyPair.getPrivate(); // // // 生成第二对秘钥,用于测试 // keyPair = KeyUtil.createKeyPairGenerator("secp256k1"); // PublicKey publicKey2 = keyPair.getPublic(); // PrivateKey privateKey2 = keyPair.getPrivate(); // // // 计算签名 // byte[] sign1 = signData("SHA256withECDSA", data, privateKey1); // byte[] sign2 = signData("SHA256withECDSA", data, privateKey1); // // // sign1和sign2的内容不同,因为ECDSA在计算的时候,加入了随机数k,因此每次的值不一样 // // 随机数k需要保密,并且每次不同 // // // // 用对应的公钥验证签名,必须返回true // Assert.assertTrue(verifySign("SHA256withECDSA", data, publicKey1, sign1)); // // 数据被篡改,返回false // data[1] = 0xb; // Assert.assertFalse(verifySign("SHA256withECDSA", data, publicKey1, sign1)); // data[1] = 0xa; // // Assert.assertTrue(verifySign("SHA256withECDSA", data, publicKey1, sign1)); // // 签名被篡改,返回false // // 签名为DER格式,前三个字节是标识和数据长度,如果修改了这三个会抛出异常,无效签名格式 // sign1[20] = (byte)~sign1[20]; // Assert.assertFalse(verifySign("SHA256withECDSA", data, publicKey1, sign1)); // // // 使用其他公钥验证,返回false // Assert.assertFalse(verifySign("SHA256withECDSA", data, publicKey2, sign1)); // } // // public static boolean verifySign(String _data, String _key, String _sign) { // // try { // java.security.spec.X509EncodedKeySpec bobPubKeySpec = new java.security.spec.X509EncodedKeySpec( // new BASE64Decoder().decodeBuffer(_key)); // KeyFactory keyf = KeyFactory.getInstance("EC"); //ECC 可根据需求更改 // PublicKey publicKey = keyf.generatePublic(bobPubKeySpec); // // byte[] data = hexStringToBytes(_data); // byte[] sig = hexStringToBytes(_sign); // // Signature signer = Signature.getInstance("SHA256withECDSA"); // signer.initVerify(publicKey); // signer.update(data); // return (signer.verify(sig)); // } // catch(Exception ex) // { // System.out.println(ex.getMessage()); // return false; // } //} ```
zhucong/Warlock
zhucong/Warlock README.md ```Warlock ======= A 3D game running on unity engine running game like temple run ```
zhucongx/finial_proj
zhucongx/finial_proj finial_project.py ```from bs4 import BeautifulSoup import requests import json import re import secrets # file that contains your API key import sqlite3 import textwrap import plotly.figure_factory as ff import plotly.graph_objects as go CACHE_FILE_NAME = 'cache.json' CACHE_DICT = {} DATA_BASE_NAME = 'database.sqlite' HEADERS = {'Authorization': 'Bearer ' + secrets.API_KEY} def save_cache(cache): """ Saves cache to disk Parameters ---------- cache: dict The dictionary to save Returns ------- None """ cache_handler = open(CACHE_FILE_NAME, 'w') cache_handler.write(json.dumps(cache)) cache_handler.close() def load_cache(): """ Opens the cache file from disk. If the cache file doesn't exist, creates a empty dict Parameters ---------- None Returns ------- Cache: dict """ try: cache_handler = open(CACHE_FILE_NAME, 'r') content = cache_handler.read() cache = json.loads(content) cache_handler.close() except: cache = {} return cache def make_request_api(baseurl, params): """Make a request to the Web API using the baseurl and params Parameters ---------- baseurl: string The URL for the API endpoint params: dictionary A dictionary of param:value pairs Returns ------- dict the data returned from making the request in the form of a dictionary """ return requests.get(baseurl, params, headers=HEADERS).json() def construct_unique_key(baseurl, params): """ constructs a key that is guaranteed to uniquely and repeatably identify an API request by its baseurl and params AUTOGRADER NOTES: To correctly test this using the autograder, use an underscore ("_") to join your baseurl with the params and all the key-value pairs from params E.g., baseurl_key1_value1 Parameters ---------- baseurl: string The URL for the API endpoint params: dict A dictionary of param:value pairs Returns ------- string the unique key as a string """ param_strings = [] connector = '_' for k in params.keys(): param_strings.append(f'{k}_{params[k]}') param_strings.sort() unique_key = baseurl + connector + connector.join(param_strings) return unique_key def make_request_api_after_check_cache(baseurl, params): """Check the cache for a saved result for this baseurl+params:values combo. If the result is found, return it. Otherwise send a new request, save it, then return it. Parameters ---------- baseurl: string The URL for the API endpoint params: dict The params to search for Returns ------- dict the results of the query as a dictionary loaded from cache JSON """ unique_key = construct_unique_key(baseurl, params) if unique_key in CACHE_DICT.keys(): print("Using Cache") else: print("Fetching") CACHE_DICT[unique_key] = make_request_api(baseurl, params) save_cache(CACHE_DICT) return CACHE_DICT[unique_key] def make_url_after_check_cache(url, cache): """Check the cache for the url. If there is cache, returns it, otherwise make a new request Parameters ---------- url: string The URL for the html cache: dict The cache with saved data Returns ------- str the results of the query as a dictionary loaded from cache """ if url in (cache.keys()): print("Using cache") else: print("Fetching") response = requests.get(url) cache[url] = response.text save_cache(cache) return cache[url] class City(object): def __init__(self, rank, name, state, description): """ Parameters ---------- rank: string The rank of the city on the website name: string City name state: The states of the city description: string A short introduction """ self.rank = int(rank) self.name = name self.state = state self.description = description def get_variables_tuple(self): """Gets a tuple with info for database Returns ------- tuple A tuple with info for database """ return self.rank, self.name, self.state, self.description def get_print_str(self): """Gets a base info str of the city Returns ------- str Base info str of the city """ return_str = f'{self.rank}. {self.name}, {self.state}' return return_str def get_city_info_str(self): """Gets the introduction str of the city Returns ------- str Introduction str of the city """ info_list = textwrap.wrap(self.description) return ' ' + '\n '.join(info_list) def build_city_list(): """Builds a list of city class Returns ------- list The city list """ city_rank_url = 'https://www.businessinsider.com/us-news-best-places-to-live-in-america-2016-3' response_text = make_url_after_check_cache(city_rank_url, CACHE_DICT) soup = BeautifulSoup(response_text, 'html.parser') found_list = soup.find_all(class_="slide-layout clearfix") in_city_list = [] for city_result in found_list: title = city_result.find("h2", class_="slide-title-text").text first_split = title.split('.') second_split = ''.join(first_split[1:]).split(',') city = City(first_split[0].strip(), second_split[0].strip(), second_split[-1].strip(), city_result.find('p').text) in_city_list.append(city) return in_city_list def save_to_cities_table(in_city_list): """Saves the city list to the local database Parameters ---------- in_city_list Returns ------- """ try: conn = sqlite3.connect(DATA_BASE_NAME) cur = conn.cursor() cur.execute(''' CREATE TABLE IF NOT EXISTS "Cities" ( "Rank" INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, "City" TEXT NOT NULL, "State" TEXT NOT NULL, "Info" TEXT NOT NULL ); ''') add_city = "INSERT INTO Cities VALUES (?, ?, ?, ?)" for city in in_city_list: cur.execute(add_city, city.get_variables_tuple()) conn.commit() except: return None def display_city_list(in_city_list): """Displays the cities information Parameters ---------- in_city_list Returns ------- """ for city in in_city_list: print(city.get_print_str()) print('-' * 80) class Location(object): def __init__(self, name=None, city=None, address=None, categories=None, rating=None, price=None, phone=None): """A class to describe a location Parameters ---------- name city address categories rating price phone """ self.name = name self.city = city self.address = address self.categories = categories self.rating = rating self.price = price self.phone = phone def get_variables_tuple(self, city_id): """Gets a tuple for saving to database Parameters ---------- city_id Returns ------- tuple """ return self.name, self.city, city_id, self.address, self.categories, self.rating, self.price, self.phone def get_print_str(self): """Gets a string for information showing Returns ------- str """ return f'{self.name} | Rating: {self.rating} | Price: {self.price} | Address: {self.address}' def save_to_locations_table(location_list): """Saves the location list to the local database Parameters ---------- location_list Returns ------- """ for loc in location_list: try: conn = sqlite3.connect(DATA_BASE_NAME) cur = conn.cursor() query = f'SELECT Rank FROM Cities WHERE Cities.City= "{loc.city}"' result = cur.execute(query).fetchall() conn.close() city_id = result[0][0] conn.close() conn = sqlite3.connect(DATA_BASE_NAME) cur = conn.cursor() cur.execute(''' CREATE TABLE IF NOT EXISTS "Locations" ( "Id" INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, "Name" TEXT NOT NULL, "City" TEXT NOT NULL, "CityId" INTEGER NOT NULL, "Address" TEXT NOT NULL, "Categories" TEXT NOT NULL, "Rating" REAL, "Price" TEXT NOT NULL, "Phone" TEXT NOT NULL, FOREIGN KEY (CityId) REFERENCES Cities (Id) ); ''') add_business = "INSERT INTO Locations VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)" cur.execute(add_business, loc.get_variables_tuple(city_id)) conn.commit() except: return None def get_location_dict_list_from_api(city_name, term='food'): """Generates a location list from api with cache checking Parameters ---------- city_name term Returns ------- dict: API raw dict """ yelp_url = 'https://api.yelp.com/v3/businesses/search' yelp_dict = make_request_api_after_check_cache(yelp_url, { 'location': city_name, 'term': term, 'limit': 50 }) return yelp_dict def try_to_get_str_from_dict(dic, key): """ if dic has key, return dic[key], else return "". Parameters ---------- dic: dict key: Any Returns ------- Any value of key in the dict """ try: return dic[key] except: return '' def build_location_list_from_api_result(yelp_dict, city, cat): """Builds a list of location class Parameters ---------- yelp_dict: dict city: string cat: string Returns ------- list """ location_list = [] for loc in yelp_dict["businesses"]: name = loc['name'] rating = float(try_to_get_str_from_dict(loc, 'rating')) price = try_to_get_str_from_dict(loc, 'price') phone = try_to_get_str_from_dict(loc, 'phone') address = '' if try_to_get_str_from_dict(loc, 'location') != '': address = try_to_get_str_from_dict(loc['location'], 'address1') if price == '': price = 'no price info' if rating == '': rating = 'no rating info' location_list.append(Location(name, city, address, cat, rating, price, phone)) return location_list def get_info_from_dataset(props, params=None): """Return information from the dataset Parameters ---------- props:list Information asking for params:dict Information constrained Returns ------- list A list of asked props """ conn = sqlite3.connect(DATA_BASE_NAME) cur = conn.cursor() real_props = "" for i in range(len(props)): real_props += f"b.{props[i]}, " real_props = real_props[:-2] command = f'SELECT {real_props} FROM Locations as b' if params is not None: keys = list(params.keys()) for key in keys: if keys.index(key) == 0: command += f' WHERE {key}="{params[key]}"' else: command += f' AND {key}="{params[key]}"' command += ";" result = cur.execute(command).fetchall() conn.close() return result def get_unique_database_type_set(): """Checks the database for existing recording Returns ------- set """ try: res = set() info = get_info_from_dataset(['city', 'categories']) for item in info: res.add(item[0] + item[1]) return res except: return set() def display_loc_list(in_loc_list): """Displays the locations Parameters ---------- in_loc_list Returns ------- """ for i, loc in enumerate(in_loc_list): print(f'{i + 1}.', loc.get_print_str()) print('-' * 80) def input_user_cities_choice_index(upper_range): """Asks user for city choice Parameters ---------- upper_range Returns ------- int """ possible_choice = [str(i) for i in range(1, upper_range + 1)] while True: cities_choice = input(f'Please enter a city number from 1 to {upper_range} or "exit": ').lower() print('-' * 80) if cities_choice == "exit": exit() if cities_choice in possible_choice: return int(cities_choice) - 1 else: print('[Error] Wrong command. Try again') def input_user_categories_choice(): """Asks user for category choice Parameters ---------- upper_range Returns ------- str """ categories_list = ['American', 'British', 'Chinese', 'Indian'] while True: categories_choice = input(f'Please choose from the following categories {", ".join(categories_list)} ' 'or "back" to choose another city: ').lower() print('-' * 80) if categories_choice == 'back': return categories_choice if categories_choice in [cate.lower() for cate in categories_list]: return categories_choice else: print('[Error] Wrong command. Try again') def input_user_display_choice(): """Asks user for display method choice Parameters ---------- upper_range Returns ------- int """ possible_choice = [str(i) for i in range(1, 5)] while True: print('Data visualization') print('1. The highest 3 rating restaurant') print('2. Average rating of these restaurants') print('3. Rating distribution plot') print('4. Price pie chart') display_choice = input(f'Please enter a choice number from 1 to 4 or "back" to chose a new category: ').lower() print('-' * 80) if display_choice == "back": return display_choice if display_choice in possible_choice: return display_choice else: print('[Error] Wrong command. Try again') def print_highest_three_rating_restaurants(params): """Display method one showing the first three highest rating restaurants Parameters ---------- params Returns ------- """ info_list = get_info_from_dataset(['name', 'rating', 'price', 'address'], params) info_list.sort(key=lambda sort_loc: float(sort_loc[1]), reverse=True) print("The highest 3 rating restaurant in this category:") for rest in info_list[:3]: print(f'{rest[0]} | Rating: {rest[1]} | Price: {rest[2]} | Address: {rest[3]}') print('-' * 80) def print_average_rating(params): """Display method two showing the average rating Parameters ---------- params Returns ------- """ info_list = get_info_from_dataset(['rating'], params) average = sum(float(loc[0]) for loc in info_list) / len(info_list) print(f'The average rating is {average}') print('-' * 80) def plot_rating_distribution(params): """Display method three plotting the rating distribution Parameters ---------- params Returns ------- """ info_list = get_info_from_dataset(['rating'], params) rating_list = [float(loc[0]) for loc in info_list] fig = ff.create_distplot([rating_list], ['Rating'], bin_size=0.5) print("Plotting") print('-' * 80) fig.show() def plot_price_pie_chart(params): """Display method three plotting the price pie chart Parameters ---------- params Returns ------- """ info_list = get_info_from_dataset(['price'], params) price_dict = {} for loc in info_list: price_dict[loc[0]] = price_dict.get(loc[0], 0) + 1 labels = [] values = [] for key, value in price_dict.items(): if key[0] == '$': key = 'pricing level ' + str(len(key)) labels.append(key) values.append(value) print("Plotting") print('-' * 80) fig = go.Figure(data=[go.Pie(labels=labels, values=values)]) fig.show() if __name__ == "__main__": CACHE_DICT = load_cache() city_list = build_city_list() # sort by rank city_list.sort(key=lambda city: city.rank) save_to_cities_table(city_list) city_category_set = get_unique_database_type_set() while True: display_city_list(city_list) city_index = input_user_cities_choice_index(len(city_list)) query_city = city_list[city_index] print(query_city.get_print_str()) print(query_city.get_city_info_str()) while True: category = input_user_categories_choice() if category == 'back': break loc_list = build_location_list_from_api_result(get_location_dict_list_from_api(query_city.name, category), query_city.name, category) if (query_city.name + category) in city_category_set: print("Using data from dataset") else: print("Saving new data") save_to_locations_table(loc_list) city_category_set.add(query_city.name + category) display_loc_list(loc_list) parms = {'city': query_city.name, 'categories': category} while True: display = input_user_display_choice() if display == 'back': break if display == '1': print_highest_three_rating_restaurants(parms) elif display == '2': print_average_rating(parms) elif display == '3': plot_rating_distribution(parms) elif display == '4': plot_price_pie_chart(parms) ``` README.md ```# SI507 Final Project This the final project of the course SI 507 at the University of Michigan ## Description This application will provide users a list of the best cities to live according to the U.S. News. Based on this list, the application will provide users restaurant information of user-selected city. The user can specify the type of restaurant (e.g. fast food, American, Chinese, Indian, Mediterranean). The application can present and recommend user restaurants based on user’s selection and Yelp’ rating. ## Data Source ### News Website The 50 best places to live in America, ranked https://www.businessinsider.com/us-news-best-places-to-live-in-america-2016-3. ### Yelp Fusion API Get Started: https://www.yelp.com/fusion Documentation Link: https://www.yelp.com/developers/documentation/v3 API URL: https://api.yelp.com/v3/businesses/search ## User Guide ### Required packages ```shell pip install bs4 requests plotly scipy ``` ### Run ```shell python finial_project.py ``` ```
zhudaihao/EditTextView
zhudaihao/EditTextView MainActivity.java ```package cn.zdh.edittextview; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ScrollView; import com.ziyeyouhu.library.KeyboardTouchListener; import com.ziyeyouhu.library.KeyboardUtil; import cn.zdh.edittextview.view.ClearEditText; public class MainActivity extends AppCompatActivity { private KeyboardUtil keyboardUtil; private LinearLayout ll_layout; private ScrollView scroll_view; private EditText editText, et_2; private ClearEditText et_3; /** * 注意ScrollView布局 * android:layout_width="match_parent" * android:layout_height="0dp" * android:layout_weight="1" * * 如果想 刚进activity不显示键盘 在manifest的activity设置下面几个属性 * * android:screenOrientation="portrait" * android:windowSoftInputMode="stateHidden|adjustPan" * android:launchMode="singleTask" */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ll_layout = findViewById(R.id.ll_layout); scroll_view = findViewById(R.id.scrollView); editText = findViewById(R.id.et_1); et_2 = findViewById(R.id.et_2); et_3 = findViewById(R.id.et_3); keyboardUtil = new KeyboardUtil(this, ll_layout, scroll_view); keyboardUtil.setOtherEdittext(editText); keyboardUtil.setOtherEdittext(et_2); keyboardUtil.setOtherEdittext(et_3); editText.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_ABC, -1)); // et_2.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_ABC, -1)); et_3.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_NUM, -1)); //键盘监听 keyboardUtil.setInputOverListener(new KeyboardUtil.InputFinishListener() { @Override public void inputHasOver(int onclickType, EditText editText) { } }); } // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // if (keyboardUtil.isShow) { // keyboardUtil.hideSystemKeyBoard(); // keyboardUtil.hideAllKeyBoard(); // keyboardUtil.hideKeyboardLayout(); // } else { // return super.onKeyDown(keyCode, event); // } // // return false; // } else // return super.onKeyDown(keyCode, event); // } } ``` SIZE.java ```package com.ziyeyouhu.library; public class SIZE { public final static float KEY_BOAR_H = 0.391f; public final static float KEY_BOAR_T_H = 0.053f; } ```
zhued/twitter_stereotypes
zhued/twitter_stereotypes server.js ```var express = require('express'); var path = require('path'); var logger = require('morgan'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var fs = require('fs'); Array.prototype.contains = function(q) { var ans = false; this.forEach(function(e) { if(e == q) { ans = true; return; }}); return ans; } var conf = JSON.parse(fs.readFileSync('resources.json')); mongoose.connect(conf.mongo.connect); var categories = JSON.parse(fs.readFileSync('keywords.json')); var totals = {}; var percentages = {}; for(var category in categories) { totals[category] = 0; percentages[category] = 0 }; var Tweet = mongoose.model('Tweet', { tweet: String }); var Stats = mongoose.model('Stats', { numbers: String }); var Located = mongoose.model('Located', { data: String }); var Coords = mongoose.model('Coords', { coordinates: String, word: String }); var app = express(); var http = require('http').Server(app); app.get('/', function(req, res) { res.render('index'); }); app.get('/stats', function(req, res) { var totals = {}; var percentages = {}; for(var category in categories) { totals[category] = 0; percentages[category] = 0 }; Stats.find({}, function(error, stats) { if(error) { res.send(error); } else { try { var nums = JSON.parse(stats[0].numbers); var keys = Object.keys(nums); var all = 0; keys.forEach(function(key) { for(var category in categories) { if(categories[category].contains(key)){ totals[category] += nums[key]; all += nums[key] } } }); Object.keys(totals).forEach(function(category) { percentages[category] = totals[category]/all; }); res.send(JSON.stringify({totals: totals, percentages: percentages})); } catch(e) { res.send(e); } } }); }); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(express.static(path.join(__dirname, 'public'))); http.listen(8080, function() { console.log('listening on 8080'); }); ``` process.js ```var fs = require('fs'); var net = require('net'); var mongoose = require('mongoose'); var conf = JSON.parse(fs.readFileSync('resources.json')); mongoose.connect(conf.mongo.connect); var Tweet = mongoose.model('Tweet', { tweet: String }); var Stats = mongoose.model('Stats', { numbers: String }); var Located = mongoose.model('Located', { data: String }); var Coords = mongoose.model('Coords', { coordinates: String, word: String }); var categories = JSON.parse(fs.readFileSync('keywords.json')); var stats = {}; Stats.find({}, function(error, stat) { if(stat[0] && stat[0].numbers != null) { stats = JSON.parse(stat[0].numbers); console.log('loaded stats'); } else { for(var category in categories) { categories[category].forEach(function(word) { stats[word] = 0; }); } } }); var num = 0; var processTweets = function() { var stream = Tweet.find().stream(); stream.on('data', function(data) { num++; try { var tweet = JSON.parse(data.tweet); if(tweet.coordinates) { var keeper = new Located({ data: JSON.stringify(tweet) }); keeper.save(function(error) {}); var locatedWord = ''; for(var word in stats) { if(tweet.text.indexOf(word) >= 0) { locatedWord = word; } } condensed = new Coords({ coordinates: tweet.coordinates.coordinates.toString(), word: locatedWord }); console.log(condensed); condensed.save(function(error) {}); } for(var word in stats) { if(tweet.text.indexOf(word) >= 0) { stats[word]++; } } } catch(e) { console.log(e); } }); stream.on('error', function(error) { console.log('DB READ ERROR'); setTimeout(processTweet, 1000); }); stream.on('close', function() { Tweet.remove({}, function() {}); Stats.remove({}, function() {}); var write = new Stats({ numbers: JSON.stringify(stats) }); write.save(function(error) {}); setTimeout(processTweets, 5000); }); } var clean = function() { console.log('processed: '+num+'\t time: '+new Date()); Located.find({}, function(error, tweets) { if(tweets.length > 300) { var gone = tweets.slice(280, tweets.length); gone.forEach(function(e) { Located.remove({ _id: e._id }, function() {}); }); } }); } processTweets(); setInterval(clean, 30000); ``` consume.js ```var fs = require('fs'); var mongoose = require('mongoose'); var Twitter = require('twitter'); var conf = JSON.parse(fs.readFileSync('resources.json')); mongoose.connect(conf.mongo.connect); var categories = JSON.parse(fs.readFileSync('keywords.json')); var keywords = []; for(var category in categories) { categories[category].forEach(function(word) { keywords.push(word); }); } var usa = '-125.4,27.5,-58.9,50.3'; var Tweet = mongoose.model('Tweet', { tweet: String }); var client = new Twitter(JSON.parse(fs.readFileSync('auth.json'))); var num = 0; client.stream('statuses/filter', { track: keywords.toString(), location: usa }, function(stream) { stream.on('data', function(data) { var tweet = new Tweet({ tweet: JSON.stringify(data) }); tweet.save(function(error) { if(error) { console.log(error); } else { num++; } }); }); stream.on('error', function(error) { console.log(error); }); }); setInterval(function() { console.log('tweets: '+num+'\t'+'time: '+new Date()); }, 30000); ``` client.js ```(function () { var app = angular.module('hateUI', []); app.controller('graphics', ['$http', function($http) { var ui = this; ui.title = 'Categorical Statistics'; ui.stats = {}; ui.categories = []; var map = L.map('usa-map').setView([40.010098, -105.268359], 13); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); var update = function() { $http.get('/stats').success(function(data) { if(data) { ui.stats = angular.fromJson(data); var max = 0; for(var num in ui.stats.totals) { ui.categories.push(num); if(ui.stats.totals[num] > max) { max = ui.stats.totals[num]; } } graph.maxValue = max+200; } }); }; update(); function createCanvas(divName) { var div = document.getElementById(divName); var canvas = document.createElement('canvas'); div.appendChild(canvas); if (typeof G_vmlCanvasManager != 'undefined') { canvas = G_vmlCanvasManager.initElement(canvas); } var ctx = canvas.getContext("2d"); return ctx; } var ctx = createCanvas("graphDiv1"); var graph = new BarGraph(ctx); graph.margin = 2; graph.colors = ["#49a0d8", "#d353a0", "#ffc527", "#df4c27"]; graph.xAxisLabelArr = ui.categories; setInterval(function () { update(); var nums = []; for(n in ui.stats.totals) { nums.push(ui.stats.totals[n]); } graph.update(nums); }, 7000); var live = createCanvas("graphDiv2"); var g2 = new BarGraph(live); g2.maxValue = 50; g2.margin = 2; g2.colors = ["#49a0d8", "#d353a0", "#ffc527", "#df4c27"]; g2.xAxisLabelArr = ui.categories; setInterval(function () { update(); g2.update([Math.random()*50, Math.random()*50, Math.random()*50]); }, 1000); }]); }()); ```
zhufangda/MyNote
zhufangda/MyNote metric.md ```# Confusion matrix |True Positive(TP)|False Positive(FP)| |------------|---------| |False Negative(FN)|True Negative(TN)| # Accuracy Accuracy is the fraction of predictions our model got right. Formally, accuracy has the following definition: $$\text{Accuracy} = \frac{TP + TN}{TP + TN + FP + FN}$$ # Precision Precision mesures the percentage of sentences flagged as positive that were corretly classified $$\text{Precision} = \frac{TP}{TP + FP} = \frac{\text{Example identified as positive correctly}}{\text{Example identified}}$$ # Recall Recall mesures the percentage of actual positive sentence that were correctly classified. $\text{Recall} = \frac{TP}{TP + FN} = \frac{TP}{\text{Actual positive}}$ # F1 Score $$\text{F1} = 2\times \frac{precision \times recall}{precision + recall}$$ A good F1 score means that we have low flase positives and low false negatives.``` # VS2017 OpenGL 配置方法.md ```# VS2017 OpenGL 配置方法 1. 添加Include目录在<code>VC++目录-包含目录</code> 2. 添加lib目录在<code>VC++目录-库目录</code>> 3. 在 <code>链接器-附加依赖项</code>中添加 - opengl32.lib - glew32s.lib - glew32.lib ``` 二叉搜索树.md ```<!-- * @description: * @author: ZHU Fangda * @Date: 2019-11-24 14:00:44 * @LastEditors: ZHU Fangda * @LastEditTime: 2019-11-26 14:44:45 --> # 二叉搜索树(Binary Search Tree) - [二叉搜索树(Binary Search Tree)](#%e4%ba%8c%e5%8f%89%e6%90%9c%e7%b4%a2%e6%a0%91binary-search-tree) - [相关概念](#%e7%9b%b8%e5%85%b3%e6%a6%82%e5%bf%b5) - [查询二叉树](#%e6%9f%a5%e8%af%a2%e4%ba%8c%e5%8f%89%e6%a0%91) - [查找(Search)](#%e6%9f%a5%e6%89%besearch) - [最大关键字元素何最小关键字元素](#%e6%9c%80%e5%a4%a7%e5%85%b3%e9%94%ae%e5%ad%97%e5%85%83%e7%b4%a0%e4%bd%95%e6%9c%80%e5%b0%8f%e5%85%b3%e9%94%ae%e5%ad%97%e5%85%83%e7%b4%a0) - [后继和前驱](#%e5%90%8e%e7%bb%a7%e5%92%8c%e5%89%8d%e9%a9%b1) - [插入和删除](#%e6%8f%92%e5%85%a5%e5%92%8c%e5%88%a0%e9%99%a4) - [插入](#%e6%8f%92%e5%85%a5) - [删除](#%e5%88%a0%e9%99%a4) - [随机构建二叉树](#%e9%9a%8f%e6%9c%ba%e6%9e%84%e5%bb%ba%e4%ba%8c%e5%8f%89%e6%a0%91) - [二叉树遍历](#%e4%ba%8c%e5%8f%89%e6%a0%91%e9%81%8d%e5%8e%86) - [前序遍历](#%e5%89%8d%e5%ba%8f%e9%81%8d%e5%8e%86) - [中序遍历](#%e4%b8%ad%e5%ba%8f%e9%81%8d%e5%8e%86) - [后续遍历](#%e5%90%8e%e7%bb%ad%e9%81%8d%e5%8e%86) ## 相关概念 **定义** 二叉搜索树是一颗组织数据的**二叉树**。 对于每一个节点, 其左子树的元素都小于该节点元素, 其右子树的元素都大于该节点元素。 **二叉树的性质** 设$x$是二叉搜索树中的一个结点.如果**y**是**x**左子树的一个结点, 那么$y.key \leq x.key$.如果$y$是$x$右子树的一个结点, 那么$y.key \geq x.key$. **二叉树结构** 二叉树可由链表数据来表示: ```java class BinarySearchTree<T>{ T tree; TreeNode left; TreeNode right; TreeNode parent; } ``` **二叉搜索树的操作** 二叉搜索书的常见操作有: - SEARCH - MINIUM - MAXIUM - PREDECESSOR - SUCCESSOR - INSERT - DELETE 二叉搜索树上的基本操作所花费的时间与这棵树的高度成正比 **二叉树的遍历** 二叉树的遍历分为: - 深度优先(Depth-first search of binary tree) - 前序遍历(preorder tree walk) - 中序遍历(Inorder tree walk) - 后序遍历(postorder tree walk) - 广度优先(readth-first search) - 层次遍历(level order tree walk) 对于深度遍历其前序,中序与后序取决于根节点的位置. **前序遍历**先输出根节点关键字, 再前序遍历左右子树. **中遍遍历**先中序遍历左子树, 然后输出根节点关键字, 最后中序遍历右子树. **后续遍历**先后续遍历左右子树, 最后输出根节点关键字. >**定理 12.1** 如果$x$是一个由n个结点子树的根, 那么调用INORDER-TREE-WALK需要$\Theta(n)$时间. ## 查询二叉树 常见的查找二叉树操作有: - SEARCH - MINIMUM - MAWXIMUM - SUCCESSOR - PREDECESSOR 上述操作都可在$O(h)$时间内完成。 ### 查找(Search) ```JAVA public boolean search(T value) { if (value == null) { return false; } BinaryTreePosition<T> curr = root; while (curr != null) { if (value.equals(curr.getElem())) { return true; } else if (value.compareTo(curr.getElem()) < 0) { curr = curr.getLeftChild(); } else { curr = curr.getRightChild(); } } return false; } ``` ### 最大关键字元素何最小关键字元素 ```Java public T mininum() { BinaryTreePosition<T> curr = root; if(curr==null){ return null; } while (curr.getLeftChild() != null) { curr = curr.getLeftChild(); } return curr.getElem(); } ``` ```java public T maximun() { BinaryTreePosition<T> curr = root; if(curr==null){ return null; } while (curr.getRightChild() != null) { curr = curr.getRightChild(); } return curr.getElem(); } ``` 上述操作在高度为h的树上均能$O(h)$时间内执行完, 因为与TREE-SEARCH一样, 他们所遇到的结点均形成一条从树根向下的简单路径。 需要注意的是, 最小元素未必位于子叶位置。它可以拥有一个右儿子。 同理, 最大元素未必位于子叶位置。它可以拥有一个左儿子。 ### 后继和前驱 所谓后继与前驱,指的是在中序遍历中指定元素的前一个元素与后一个元素。 ```java public BinaryTreePosition<T> successor(BinaryTreePosition<T> node) { if (node == null) { return null; } if (node.hasRightChild()) { return mininum(node.getRightChild()); } BinaryTreePosition<T> curr = node; BinaryTreePosition<T> parent = node.getParent(); while (parent != null && parent.getRightChild() == curr) { curr = curr.getParent(); parent = curr.getParent(); } return parent; } ``` 对于寻找当前结点x的后继, 有两种情况: 1. 当前结点$x$¥的右子树不为空, 那么应当返回当前结点右子树最左边的子叶结点,也就是右子树最小的结点。 2. 如果当前点$x$的右子树为空, 那么又可以分为两种情况: 1. 当前结点$x$为父节点$y$左子树,则返回父节点。 2. 当前结点$x$为父结点$y$右子树,那么应该寻找一个祖先,该祖先的的左子树也是该结点的祖先。 我们可以吧这两种情况合并。即沿着该结点向上寻找。curr代表当前结点, y代表父节点,如果当前节点是父节点的左儿子, 则返回父节点。反之,当前结点必为父节点的右儿子, 那么当前结点curr变为父节点,y变为curr的父节点,继续寻找。如果发现父节点也为空, 那么代表已经到达根结点, 这种情况下后继不存为。 ```java public BinaryTreePosition<T> predecessor(BinaryTreePosition<T> node) { if (node == null) { return null; } if (node.hasLeftChild()) { return maximun(node.getLeftChild()); } BinaryTreePosition<T> curr = node; BinaryTreePosition<T> parent = node.getParent(); while(parent !=null && parent.getLeftChild()==curr){ curr = parent; parent = curr.getParent(); } return parent; } ``` 对于寻找当前结点x的前驱, 有两种情况: 1. 当前结点$x$的左子树不为空, 那么应当返回当前结点左子树最右边的子叶结点,也就死左子树最小的结点。 2. 如果当前点$x$的左子树为空, 那么又可以分为两种情况: 1. 当前结点$x$为父节点$y$右子树,则返回父节点。 2. 当前结点$x$为父结点$y$左子树,那么应该寻找一个祖先,该祖先的的右子树也是该结点的祖先。 我们可以吧这两种情况合并。即沿着该结点向上寻找。curr代表当前结点, y代表父节点,如果当前节点是父节点的右儿子, 则返回父节点。反之,当前结点必为父节点的左儿子, 那么当前结点curr变为父节点,y变为curr的父节点,继续寻找。如果发现父节点也为空, 那么代表已经到达根结点, 这种情况下后继不存在。 对于上述算法, 在运行过程中或者以当前结点沿着一条简单路径向下, 或者沿着一条简单路径向上, 孤儿最坏情况是$\Theta(max(h_{root}, h_{root}-h_{node}))$。 所以其运行时间也是$\Theta(h)$. **定理 12.2** 在一棵高为h的二叉搜索树上, 动态集合上的操作SEARCH, MINUMUM, MAXIMUM, SUCCESSOR和PREDECESSOR可以在$\Theta(h)$时间内完成。 ## 插入和删除 ### 插入 ```java public void insert(T t) { BinaryTreePosition<T> node = new BinaryTreeNode<>(t); BinaryTreePosition<T> curr = root; BinaryTreePosition<T> parent = root; while (curr != null) { parent = curr; if (t.compareTo(curr.getElem()) <= 0) { curr = curr.getLeftChild(); } else { curr = curr.getRightChild(); } } if (t.compareTo(parent.getElem()) <= 0) { parent.attachLeft(node); } else { parent.attachRight(node); } } ``` 插曲算法相对简单, 每次插入的其实都是数的子叶结点, 所以其寻找路径是一条从更结点出发到子叶结点的简单路径, 所以其算法复杂度是$O(h)$。因此该算法首先寻找到插入位置的父节点, 然后插入该节点。因为在寻找过程中, 并没有存储相应信息来获知插入结点为父节点的左孩子还是右孩子。 所以插入前还需要再判断一次插入位置。 ### 删除 从一棵二叉树中删除一个结点$z$可以分为三种情况: 1. 如果$z$没有孩子结点, 那么简单的将它删除. 2. 如果$z$只有一个孩子, 只需要用这个孩子代替被删除的结点即可。 ![z只有右子树](img/Binary_tree_delete_1.png) ![z只有左子树](img/Binary_tree_delete_2.png) 3. 如果$z$有两个孩子, 那我们寻找$z$的后继,用$z$的后继来替代$z$。因为$z$有两个孩子,所以其后继必然在右子树且其后继$y$的左子树必然为0,且他的key必然大于$z$的左子树的所有元素。所以可以用$y$来替代$z$的位置, 将$z$的左子树作为$y$的左子树,$y$的右子树替代$y$本来的位置。 ![z有两个子树, 且其后继为右子树树根](img/Binary_tree_delete_3.png) ![z有两个子树, 且其后继部位右子树树根](img/Binary_tree_delete_4.png) 为了在二叉搜索树内移动子树, 定义一个子过程$TRANSPLANT$, 它是用一棵子树替换另外一棵子树并成为双亲孩子的结点。该过程包含两个参数, u跟v, 他的作用是用v替代u。 ```python def TRANSPLANT(T, u, v): # 如果u为根结点,直接替换 if u.p == NIL: T.root = u # 如果u为父节点的左孩子, v替换u父节点的左孩子 elif u==u.p.left: u.p.left = v # 如果u为父节点的右孩子, v替换u父节点的右孩子 else u.p.right = v # 更改v父节点的指向 if v!= NIL: v.p = u.p ``` ```java public void removeNode(BinaryTreePosition<T> node) { if (node.hasLeftChild() && node.hasRightChild()) { BinaryTreePosition<T> suc = successor(node); suc.attachLeft(node.getLeftChild()); if (node.getLeftChild() != suc) { transplant(suc, suc.getRightChild()); suc.attachLeft(node.getLeftChild()); } transplant(node, suc); } else if (node.hasLeftChild()) { transplant(node, node.getLeftChild()); } else { transplant(node, node.getRightChild()); } } ``` 除了寻找后继的复杂度为$O(h)$, 其他步骤均为常数。 所以我们有 **定理 12.3** 在一棵高度为$h$的二叉搜索树上, 实现动态集合操作 *INSERT* 与 *DELETE* 的运行时间均为 $O(h)$. ## 随机构建二叉树 **定理 12.4** 一颗有$n$个不同关键字的随机构建二叉搜索树的期望高度是$lg(n)$. ## 二叉树遍历 我们主要讨论使用迭代器方法实现二叉树的遍历。 实现迭代器需要实现两个方法**hasNext**与**next**.我们使用curr来存储当前的节点,那么next得作用就是寻找curr节点在该遍历方法中的后继。 ### 前序遍历 对于当前节点, 有以下三种情况 1. 当前节点有左儿子, 则后继为当前节点左儿子 2. 当前结点有右儿子, 则后继为当前结点右儿子。 3. 如果当前结点为父节点的左儿子且父节点右儿子存在, 则后继为父节点右儿子 4. 剩下的情况, 当前节点为子叶结点,且没有兄弟。那么我们要在从这个结点到根节点寻找三个结点 $x$,$y$,$z$. 其中$x$为$y$的左儿子, $y$为$x$根结点, 且$y$的右儿子存在,记为$z$. 如果找到则返回$z$. ### 中序遍历 对于当前结点, 有以下几种情况: 1. 如果有右儿子, 返回右儿子中最小元素 2. 从当前节点到根节点中寻找两个结点,$x$与$y$使得$y$是$x$的父节点且$x$是$y$的左儿子。 ### 后续遍历 将当前节点初始化为树的左下角。 后续遍历的顺序为先左节点,再兄弟结点,最后输出中间结点。 对于任意结点我们有: 1. 如果树为双亲的左儿子且双亲右儿子存在,则返回双亲右儿子的最边缘结点。 2. 否则返回父节点``` README.md ```# MyNote THis is a readme ``` AlertDialog.md ```# Alert Dialog 用法 ## 构建提醒对话框 对话框一般都通过<code> AlertDialog </code> 类构建各种对话框设计,并且该类通常是您需要的唯一对话框类。<code>AlertDialog</code>有三个区域: ![对话框布局](AlertDialog/dialogs_regions.png) 1. 标题 这是可选项,只应在内容区域被详细消息、列表或自定义布局占据时使用。 如需陈述的是一条简单消息或问题(如图 1 中的对话框),则不需要标题。 2. 内容区域 它可以显示消息、列表或其他自定义布局。 3. 操作按钮 对话框中的操作按钮不应超过三个。 <code>AlertDialog.Builder</code> 类似一个工厂类, 提供API用来设计对话框规格(布局,按钮,功能等),然后通过<code>AlertDialog.Builder.create()</code> 来创建新的对话框. 构建<code>AlertDialog.Builder</code> 代码如下 ```java // 1. 初始化 AlertDialog.Builder, 参数为所依附的Activity AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // 2. 通过一系列的set函数设计对话框内容 builder.setMessage(R.string.dialog_message) // 内容区域显示的文字 .setTitle(R.string.dialog_title); //对话框标题 // 3. 获得对话框实例 AlertDialog dialog = builder.create(); ``` ## 添加按钮 通过 set...Button()` 方法添加按钮. 该方法需要两个参数,一个按钮标题(由[字符串资源](https://developer.android.com/guide/topics/resources/string-resource.html?hl=zh-cn)提供)和一个 `DialogInterface.OnClickListener`监听器,后者用于定义用户按下该按钮时执行的操作。 您可以添加三种不同的操作按钮: | ``The identifier for the negative button. | | | ---------------------------------------- | -------------------------------------- | | `int` | The identifier for the neutral button. | | `int | | - `BUTTON_POSITIVE`肯定 您应该使用此按钮来接受并继续执行操作(“确定”操作)。 - `BUTTON_NEGATIVE`否定 您应该使用此按钮来取消操作。 - `BUTTON_NEUTRAL`中性 您应该在用户可能不想继续执行操作,但也不一定想要取消操作时使用此按钮。 它出现在肯定按钮和否定按钮之间。 例如,实际操作可能是“稍后提醒我”。 对于每种按钮类型,您只能为 `AlertDialog` 添加一个该类型的按钮。也就是说,您不能添加多个“肯定”按钮。 使用代码如下 ```Java AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // 添加按钮 builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // 确认按钮动作 } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // 否定按钮动作 } }); // Set other dialog properties ... // Create the AlertDialog AlertDialog dialog = builder.create(); ``` ## 添加列表 可通过 `AlertDialog` API 提供三种列表: - 传统单选列表 - 永久性单选列表(单选按钮) - 永久性多选列表(复选框) > 注意:使用列表时,不可以使用 `setMessage()`, 否则message会把items覆盖. ### 添加传统单选列表 要想创建下图所示的单选列表,请使用 `setItems()` 方法: ```java AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.pick_color) .setItems(R.array.colors_array, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // The 'which' argument contains the index position // of the selected item } }); return builder.create(); ``` ![包含标题和列表的对话框](AlertDialog/dialog_list.png) 由于列表出现在对话框的内容区域,因此对话框无法同时显示消息和列表,您应该通过 `setTitle()` 为对话框设置标题。要想指定列表项,请调用`setItems()` 来传递一个数组。或者,您也可以使用 `setAdapter()` 指定一个列表。 这样一来,您就可以使用 `ListAdapter` 以动态数据(如来自数据库的数据)支持列表。使用上述方式,触摸列表项对话框会消失,除非您使用的是下列其中一种永久性选择列表。 ### 添加永久性多选列表或单选列表 要想添加多选项(复选框)或单选项(单选按钮)列表,请分别使用 `setMultiChoiceItems()`或 `setSingleChoiceItems()` 方法。 例如,以下示例展示了如何创建下图 所示的多选列表,将选定项保存在一个 `ArrayList` 中: ![img](AlertDialog/dialog_checkboxes.png) ```java @Override public Dialog onCreateDialog(Bundle savedInstanceState) { mSelectedItems = new ArrayList(); // Where we track the selected items AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Set the dialog title builder.setTitle(R.string.pick_toppings) // Specify the list array, the items to be selected by default (null for none), // and the listener through which to receive callbacks when items are selected .setMultiChoiceItems(R.array.toppings, null, new DialogInterface.OnMultiChoiceClickListener() { @Override /** * @param id 代表按下的按钮 * @param dialog 代表对话框 */ public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (isChecked) { // If the user checked the item, add it to the selected item mSelectedItems.add(which); } else if (mSelectedItems.contains(which)) { // Else, if the item is already in the array, remove it mSelectedItems.remove(Integer.valueOf(which)); } } }) // Set the action buttons .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // User clicked OK, so save the mSelectedItems results somewhere // or return them to the component that opened the dialog ... } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { ... } }); return builder.create(); } ``` 尽管传统列表和具有单选按钮的列表都能提供“单选”操作,但如果您想持久保存用户的选择,则应使用 `setSingleChoiceItems()`。也就是说,如果稍后再次打开对话框时系统应指示用户的当前选择,那么您就需要创建一个具有单选按钮的列表 ## 创建自定义布局 如果您想让对话框具有自定义布局,请创建一个布局,然后通过调用 `AlertDialog.Builder` 对象上的 `setView()` 将其添加到 `AlertDialog`。默认情况下,自定义布局会填充对话框窗口,但您仍然可以使用 `AlertDialog.Builder` 方法来添加按钮和标题。setView()既可以添加自定义布局,也可以仅仅创建一个'view'实例, 比如`NumberPicker`或者 `TimePicker`, 添加的view将入填满内容区域. 默认情况下,自定义布局会填充对话框窗口,但您仍然可以使用 `AlertDialog.Builder` 方法来添加按钮和标题。 ```java @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout builder.setView(inflater.inflate(R.layout.dialog_signin, null)) // Add action buttons .setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // sign in the user ... } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { LoginDialogFragment.this.getDialog().cancel(); } }); return builder.create(); } ``` ![img](AlertDialog/dialog_custom.png) ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:src="@drawable/header_logo" android:layout_width="match_parent" android:layout_height="64dp" android:scaleType="center" android:background="#FFFFBB33" android:contentDescription="@string/app_name" /> <EditText android:id="@+id/username" android:inputType="textEmailAddress" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginLeft="4dp" android:layout_marginRight="4dp" android:layout_marginBottom="4dp" android:hint="@string/username" /> <EditText android:id="@+id/password" android:inputType="textPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="4dp" android:layout_marginLeft="4dp" android:layout_marginRight="4dp" android:layout_marginBottom="16dp" android:fontFamily="sans-serif" android:hint="@string/password"/> </LinearLayout> ``` 要扩展 `DialogFragment` 中的布局,请通过 `getLayoutInflater()` 获取一个 `LayoutInflater` 并调用 `inflate()`,其中第一个参数是布局资源 ID,第二个参数是布局的父视图。然后,您可以调用 `setView()` 将布局放入对话框。 ```java @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout builder.setView(inflater.inflate(R.layout.dialog_signin, null)) // Add action buttons .setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // sign in the user ... } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { LoginDialogFragment.this.getDialog().cancel(); } }); return builder.create(); } ``` > 提示:**如果您想要自定义对话框,可以改用对话框的形式显示 `Activity`,而不是使用 `Dialog` API。 只需创建一个 Activity,并在 [``](https://developer.android.com/guide/topics/manifest/activity-element.html?hl=zh-cn) 清单文件元素中将其主题设置为 `Theme.Holo.Dialog`: > > ``` <activity android:theme="@android:style/Theme.Holo.Dialog" > ``` > 就这么简单。Activity 现在会显示在一个对话框窗口中,而非全屏显示 ## 将事件传递回对话框的宿主 ## Reference: https://developer.android.com/guide/topics/ui/dialogs.html?hl=zh-cn ``` NumberPicker.md ```# NumberPicker 使用方法 ## 基本用法 ### 显示数字 如果想有滚动效果,必须设置最大最小值 ``` mNumberPicker.setMaxValue(10); //设置最大值 mNumberPicker.setMinValue(0); //设置最小值 mNumberPicker.setValue(5); //设置当前值 int value = mNumberPicker.getValue(); //获取当前值 ``` 有一点需要注意的数值不能用负数 ![基本用法](NumberPicker/basefunction.png) ### 显示文字 我们只需要使用一个方法就可以了 ```java public void setDisplayedValues(String[] displayedValues) ``` 具体代码如下 ```java String[] datas = new String[]{"北京","上海","广州","深圳"}; mNumberPicker.setDisplayedValues(datas); //设置文字 mNumberPicker.setMaxValue(datas.length - 1); //设置最大 ``` 效果如下 ![显示文字](NumberPicker/show_text.png) ### 设置监听 NumberPicker有三个监听分别是OnValueChangeListener、OnScrollListener、Formatter #### OnValueChangeListener值改变监听 代码如下 ```java mNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() { /** * 每当选择的值改变时都会调用一次 * @param oldVal 改变前的值 * @param newVal 改变后的值 */ @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { //做想做的事 } }); ``` #### OnScrollListener滑动事件 每当选择的值改变都会调用一次这个方法,选择的值改变也就是显示在中间的那个值改变 OnScrollListener滑动事件 实例代码如下 ```java mNumberPicker.setOnScrollListener(new NumberPicker.OnScrollListener() { @Override public void onScrollStateChange(NumberPicker view, int scrollState) { switch (scrollState){ case SCROLL_STATE_FLING: //手离开之后还在滑动 break; case SCROLL_STATE_IDLE: //停止滑动 break; case SCROLL_STATE_TOUCH_SCROLL: //正在滑动 break; } } }); ``` 滑动事件就是监听控件滑动时的状态 滑动事件有三个状态 * `SCROLL_STATE_FLING` ——>手离开之后还在滑动 * `SCROLL_STATE_IDLE` ——>停止滑动 * `SCROLL_STATE_TOUCH_SCROLL` ——>正在滑动 #### Formatter监听 用于格式化当前数值 ```java mNumberPicker.setFormatter(new NumberPicker.Formatter() { @Override public String format(int value) { //做一些格式转换 return "返回转换后要显示的内容"; } }); ``` 这个监听是用于做一些格式转换的,比如把10以下的数前面加个0显示(01、02、03…..),也能理解为转换器,下面我会为大家介绍如何利用Formatter监听设置10以下的数前面加0显示。 我们需要注意一下不能返回空 ## 常见问题 ### 设置小于10的数前面显示0 设置小于10的数前面显示0 实现这个效果我们只需要设置Formatter监听,让小于10的数前面加个0再输出 ```java mNumberPicker.setMaxValue(20); mNumberPicker.setMinValue(0); mNumberPicker.setValue(0); mNumberPicker.setFormatter(new NumberPicker.Formatter() { @Override public String format(int value) { String data; if (value < 10) { data = "0" + value;//让小于10的数前面加个0再输出 } else { data = String.valueOf(value); //大于10的数就不变 } return data; } }); ``` ### 循环滚动 要设置是否循环滚动只需要使用一个方法就可以了 ```java mNumberPicker.setWrapSelectorWheel(true); //设置循环滚动 ``` 设置false代表不循环滚动,true代表循环滚动 > 注意 > > * 一定要设置好最大值才有效果 > * 最大值必须大于等于3 ### 禁止编辑 当我们用手指点一下显示的数值会发现竟然可以输入,有些时候我们需要禁止输入,该怎么办呢?我介绍两种常用的方法一种是用在代码里设置,一种是在xml里面设置。 可以编辑的NumberPicker #### java代码中设置 只需要使用一个方法就可以了 ```java mNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); //禁止输入 ``` #### xml中设置 设置NumberPicker的属性 ```xml android:focusable="true" android:focusableInTouchMode="true" ``` 这样就可以禁止输入了 ### 改变字体颜色、字体大小,改变分割线颜色和隐藏分割线 很遗憾NumberPicker没有提供修改字体颜色和字体大小的方法,不过我们可以继承NumberPicker实现需求,代码并不复杂,只是多写了几行代码,其他代码复制粘贴就好了。 修改分割线需要通过反射获得相应的类,然后进行就修改 package com.my.numberpickertest; import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.NumberPicker; public class MyNumberPicker extends NumberPicker { public MyNumberPicker(Context context) { super(context); } public MyNumberPicker(Context context, AttributeSet attrs) { super(context, attrs); } public MyNumberPicker(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } ```java @Override public void addView(View child) { super.addView(child); updateView(child); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { super.addView(child, index, params); updateView(child); } @Override public void addView(View child, ViewGroup.LayoutParams params) { super.addView(child, params); updateView(child); } /** * 修改字的大小和颜色 */ private void updateView(View view){ if( view instanceof EditText){ EditText editText = (EditText) view; editText.setTextColor(Color.parseColor("#00ff00")); //修改字的颜色 editText.setTextSize(30);//修改字的大小 } } } ``` ## Reference http://blog.csdn.net/qq1137830424/article/details/52597371``` Cours 2 .md ```# RMSprop 这个方法确保,点将会向梯度比较小的方向快速滑动, 梯度大的方向缓慢滑动, 就如同一个球,永远向梯度较小的方向滑动``` Structing Machine Learning Projets.md ```# Structing Machine Learning Projets ## Orthogonalization It is necessary to tune the hypermeters systematically. It means we have to know which parameters to tune in ordre to achieve one effect. This process we call orthogonalization. When we tune the parameters, it is well to assure that each parametres we tune just change the performence in one single aspects. For example, firstly, we should find the best parameters will just have a influence in the training set.(Optimiser, for example) And then we considre the model performence in dev set and test set. We don't recommend to use early stop in the first step, because it will have effect in both training set and test set. ## Setting up your goal ### Single number evaluation metric A single number evaluation will speed up the iterative process of imporving our machine learning alogrithm. If we have several numbers evaluation for metrics, we need to merge these numbers into a single number for picking a model more easily. ### Satisficing and Optimizing metric If there are multiple things you care about, you can set one of them as the optimizing metric that you want to do as well as possible on and one or more as satisficing metrics were you'ill be satisfice. ### Train/dev/test distributions The dev set and test set have to come from the same distribution. **This video just give the guideline, but don't give any approche to do it** We can take this randomly shuffled data into the dev and test set. ### Size of the dev and test sets If the dataset is small, we can apply the rule of thumbe of taking all the data you have and using a 70/30 split into a train and test set. If the dataset is big enough, it might be quite reasonable to set up your data so that you have 98% in the training set, and 1% dev set, and 1% test set. The test set is not necessary. But we don't recommand not having a test set when buinding a system. Because with test set, we reassuring to get an unbiased estimate. But if we have a dev set big enough, we can igonre the test set. ### When to change dev/test sets and metrics Firstly we need to set the metric and dev set for driving the speed of our team iterating. If we find out the metric or the dev set are not good enough, we can change them at that time. ## Comparing to human-level performance Raison: - Because of advances in deep learning, machine learning algorithms are suddenly working much better and so ti has become competitive with human-level performance - It turns out that the workflow of designing andbuilding a machine learning system, the workflow is much more efficient when you're trying to do something that humans can also do. So in thoses settings, it becomes natural to take about comparing, or trying to mimic human-level performance. Humans are quite good at a lot of tasks. So long as ML is worse than humansn you can: - Get labeled data from humans - Gain insight from manual error analysis: Why did a person get this right? - Better analysis of bias/variance ``` Machine Learning.md ```# Improving Deep Neural Networks: Hyperparameter tuning, Regularization and Optimiztion When we create our model, we have to decide the hyperparameters in order to improve the performence of our model, the possible hypermaters could be: - Number of layers - Number of hidden units - Learning rate - activation functions ![ML iterative process](images/ml_iterative_process.png) It is very difficult to guess the best choic of hyperparameters ## How to splite data into Train/dev/test We often splite the data into train/dev/test set. The test set. Train set used to train the model. Dev set(hold-out cross validation set) used to test the model's performence and compare different algorithms. Test set used to test the model and get unbiased estimate. - Small dataset : 60%/20%/20% or 70%/30% - Big dataset : 98%/1%/1% The test set and dev set should come from the same distribution. In some times, the test set is not necessary. ## Bias-Variance trade-off High Bias estimator means the model can not fit well the training set. So the model is underfitting the data. High variance means the model is over fitting. This estimator is complexe enough to fit the train data but it don't work well in test set. A estimator could be high bias and high variance at the same time. In this condition, the estimator is complexe enough but it still don'tt work well in the train set. ## Basic Recipe for Machine Learning ### High Bias Estimator doesn't work well in the train set. Measure: - User more hidden units - Add more hidden layers - Train longer - Try another architecture of neuro network ### High variance Estimator doesn't work well for the test set. Mesure: - Use more data to train our model - Regularization - Find new neuro networl architecture Firstly, you have to get rid of high bias problem by fitting or overfitting train data, and then we try to resolve the high variance problem. We can find we use different approche to resolve the two problems. So we can increase one without hurt another one. # Regularization ## L2 regularization Regularization could prevent the overfitting. If the parameters W very small, so the Z will become relatively small. So the Z will take on a very small range of values. So the activation function **tanh** will be relatively linear. So the neural network will be computing something not too far from linear function. If we add regularization, the cost function $J$ will decrease monotonically on very single elevation. Otherwise, not. It is very useful for debug.(But in tensorflow palyground, this phenomenon is not very evident.) What you should remember -- the implications of L2-regularization on: - The cost computation: - A regularization term is added to the cost - The backpropagation function: - There are extra terms in the gradients with respect to weight matrices - Weights end up smaller ("weight decay"): - Weights are pushed to smaller values ### Observation - The value of $λ$ is a hyperparameter that you can tune using a dev set. - L2 regularization makes your decision boundary smoother. If $λ$ is too large, it is also possible to "oversmooth", resulting in a model with high bias. - Although we increase the numbre of iteration, the boundary also keeps slippy and the forme of boundary doesn't change. What is L2-regularization actually doing?: L2-regularization relies on the assumption that a model with small weights is simpler than a model with large weights. Thus, by penalizing the square values of the weights in the cost function you drive all the weights to smaller values. It becomes too costly for the cost to have large weights! This leads to a smoother model in which the output changes more slowly as the input changes. What you should remember -- the implications of L2-regularization on: The cost computation: A regularization term is added to the cost The backpropagation function: There are extra terms in the gradients with respect to weight matrices Weights end up smaller ("weight decay"): Weights are pushed to smaller values. ## Dropout regularization We set some probability of eliminationg a node in neural network for each sample.So we train our sample with deminished network. So the network become more simple and prevent the overfitting. Don't not use dropout at test time. ### Note: A common mistake when using dropout is to use it both in training and testing. You should use dropout (randomly eliminate nodes) only in training. Deep learning frameworks like tensorflow, PaddlePaddle, keras or caffe come with a dropout layer implementation. Don't stress - you will soon learn some of these frameworks. ### What you should remember about dropout - Dropout is a regularization technique. - You only use dropout during training. Don't use dropout (randomly eliminate nodes) during test time. - Apply dropout both during forward and backward propagation. - During training time, divide each dropout layer by keep_prob to keep the same expected value for the activations. For example, if keep_prob is 0.5, then we will on average shut down half the nodes, so the output will be scaled by 0.5 since only the remaining half are contributing to the solution. Dividing by 0.5 is equivalent to multiplying by 2. - Hence, the output now has the same expected value. You can check that this works even when keep_prob is other values than 0.5. ### Other regularization methodes - Data augmentation. - **Early stopping** When the network start to overfit the dataset, wo stop to train our model. It didn't recommanded. It could be used to save time.So we just ust it when we try to find best hyperparameters. ### What we want you to remember from this notebook: - Regularization will help you reduce overfitting. - Regularization will drive your weights to lower values. - L2 regularization and Dropout are two very effective regularization techniques. # Normalizing inputs Normalizing input features could speed up training. ## Initialization for Deep Nerworks - General $$W^{[l]} = np.random.randn(shape) * \sqrt{\frac{2}{n^{[l-1]}}}$$ - For **tanh** activation function - Xavier initialization $$\sqrt{\frac{1}{n^{[l-1]}}} $$ - $$\sqrt{\frac{2}{n^{[l-1]}+n^{[l]}}}$$ - The weights W[l]W[l] should be initialized randomly to break symmetry. - It is however okay to initialize the biases b[l]b[l] to zeros. Symmetry is still broken so long as W[l]W[l] is initialized randomly. - Initializing weights to very large random values does not work well. - Hopefully intializing with small random values does better. The important question is: how small should be these random values be? Lets find out in the next part! - Different initializations lead to different results - Random initialization is used to break symmetry and make sure different hidden units can learn different things - Don't intialize to values that are too large - He initialization works well for networks with ReLU activations. # Graduent Checking Backpropagation computes the gradients $\frac{\partial J}{\partial \theta}$, where $\theta$ denotes the parameters of the model. $J$ is computed using forward propagation and your loss function. Because forward propagation is relatively easy to implement, you're confident you got that right, and so you're almost 100% sure that you're computing the cost $J$ correctly. Thus, you can use your code for computing $J$ to verify the code for computing $\frac{\partial J}{\partial \theta}$. Let's look back at the definition of a derivative (or gradient): $$ \frac{\partial J}{\partial \theta} = \lim_{\varepsilon \to 0} \frac{J(\theta + \varepsilon) - J(\theta - \varepsilon)}{2 \varepsilon} \tag{1}$$ If you're not familiar with the "$\displaystyle \lim_{\varepsilon \to 0}$" notation, it's just a way of saying "when $\varepsilon$ is really really small." We know the following: - $\frac{\partial J}{\partial \theta}$ is what you want to make sure you're computing correctly. - You can compute $J(\theta + \varepsilon)$ and $J(\theta - \varepsilon)$ (in the case that $\theta$ is a real number), since you're confident your implementation for $J$ is correct. Lets use equation (1) and a small value for $\varepsilon$ to convince your CEO that your code for computing $\frac{\partial J}{\partial \theta}$ is correct! ## 2) 1-dimensional gradient checking Consider a 1D linear function $J(\theta) = \theta x$. The model contains only a single real-valued parameter $\theta$, and takes $x$ as input. You will implement code to compute $J(.)$ and its derivative $\frac{\partial J}{\partial \theta}$. You will then use gradient checking to make sure your derivative computation for $J$ is correct. <img src="images/1Dgrad_kiank.png" style="width:600px;height:250px;"> <caption><center> <u> **Figure 1** </u>: **1D linear model**<br> </center></caption> The diagram above shows the key computation steps: First start with $x$, then evaluate the function $J(x)$ ("forward propagation"). Then compute the derivative $\frac{\partial J}{\partial \theta}$ ("backward propagation"). **Exercise**: implement "forward propagation" and "backward propagation" for this simple function. I.e., compute both $J(.)$ ("forward propagation") and its derivative with respect to $\theta$ ("backward propagation"), in two separate functions. ``` SmartGit.md ```stage: 将工作区的文件保存至暂存区(staging area) git -add commit:将暂存区的文件提交到仓库中 git -commit "Message" Add branch:增加新的分支 Check-out:将选择分支设置为当前分支 .gitignore:记录要忽略的文件 merge:将选择分支与当前分支合并 先将文件推送到暂存器,再将文件推送到仓库。之后修改新文件,我们将能看到工作区与暂存区文件的对比。 单击log,能看到仓库文件的版本库。当在主窗选择根文件,log则显示整个文件的版本,标题栏显示为"Log for.",其中.代表根文件夹。由绿色三角指示的分支的当前分支。 ``` 红黑树.md ```<!-- * @description: * @author: ZHU Fangda * @Date: 2019-11-21 16:06:47 * @LastEditors: ZHU Fangda * @LastEditTime: 2019-11-28 00:26:19 --> # 红黑树 - [红黑树](#%e7%ba%a2%e9%bb%91%e6%a0%91) - [定义](#%e5%ae%9a%e4%b9%89) - [红黑树的性质:](#%e7%ba%a2%e9%bb%91%e6%a0%91%e7%9a%84%e6%80%a7%e8%b4%a8) - [概念:](#%e6%a6%82%e5%bf%b5) - [树旋转](#%e6%a0%91%e6%97%8b%e8%bd%ac) - [插入](#%e6%8f%92%e5%85%a5) ## 定义 红黑树是一颗二叉搜索树,它在每个节点上增加一个存储位来表示节点的颜色, 可以是RED或者BLACK。 通过对任何一条从根到叶子的简单路径上各个节点的颜色进行约束, 红黑树确保没有一条路径比其他路径长出两倍, 因而是近似于平衡的。 **二叉搜索树**: ## 红黑树的性质: 1. 每个节点或是红色的, 或者是黑色的 2. 根节点是黑色的 3. 每个叶节点都是NIL且是黑色的 4. 如果一个结点是红色的, 则他的两个子节点都是黑色的 5. 对于每个节点, 从该节点到其所有后代叶节点的简单路径上, 均包含相同数目的黑色节点。 ## 概念: **内部节点(internal node)** 至少拥有一个孩子的节点称为内部节点。 **子叶** 没有孩子的节点称为子叶 >**黑高(black-height)** 从节点x(不包含该节点)出发,到达任意一个叶节点的任意一条简单路径上的黑色节点个数称为该节点的黑高。子叶节点的黑高为0. 性质5保证黑高的存在 **定理:** > 引理0: 任一节点$x$为根的子树, 则至少含有$2^{bh(x)}-1$个内部节点 > 引理1: 一颗有n个内部节点的红黑树的高度至多为$2\lg(n+1)$ ## 树旋转 通过旋转操作,二叉搜索树的性质保持不变, 所以旋转不会改变中序遍历的结果, 只会改变当前的节点的高度。 LEAF-ROTATE与RIGHT-ROTATE只会与当前节点的左儿子或者右儿子交换位置, 并改变当前结点的深度。 向右旋转,会用左儿子代替当前节点的位置,并让当前节点称为左儿子的右儿子, 右二子的左儿子称为当前节点的左儿子 ![](img/red_black_tree_rotation.png) ```java public void rightRotation(BinaryTreePosition<T> node) throws IllegalArgumentException { if (node.getLeftChild() == null) { throw new IllegalArgumentException("Illegal Exception. Can not do lefr roation"); } BinaryTreePosition<T> parent = node.getParent(); BinaryTreePosition<T> y = node.getRightChild(); // 将y结点与node的父节点相连 if (node.isLeftChild()) { parent.attachLeft(y); } else { parent.attachRight(y); } node.attachRight(y.getLeftChild()); y.attachLeft(node); } ``` ```java public void leftRotation(BinaryTreePosition<T> node) throws IllegalArgumentException{ if (node.getRightChild() == null) { throw new IllegalArgumentException("Illegal Exception. Can not do left roation"); } BinaryTreePosition<T> parent = node.getParent(); BinaryTreePosition<T> y = node.getRightChild(); // 将y结点与node的父节点相连 if (node.isLeftChild()) { parent.attachLeft(y); } else { parent.attachRight(y); } node.attachRight(y.getLeftChild()); y.attachLeft(node); } ``` ## 插入 我们可以在$O(\lg n)$时间内完成向一棵含$n$个结点的红黑树中插入一个新节点。 微课做到这一点, 利用**TREE-INSERT**过程的一个略作修改的版本来讲结点$z$插入树$T$内。 就好像$T$是一颗普通的二叉搜索树一样,然后将$z$着色为红色。 为了保证红黑性质能继续保持, 我们调用一个辅助程序**RB-INSERT-FIXUP**来对结点重新着色并旋转。调用**BR-INSERT(T,z)**在红黑树T内插入结点$z$。 ```python def RB_INSERT(T, z): y = T.nil x = T.root while x!=T.nil: y = x if z.key < x.key: x = x.left else x = x.right z.p = y if y == T.nil: T.root = z else if z.key<y.key: y.left = z else: y.right = z z.left = T.nil z.right = T.nil z.color = RED BR_INSERT_FIXUP(T, z) ``` 过程``TREE-INSERT``和``BR-INSERT``之间有四处不同。第一,``TREE-INSERT``内所有``NIL``都被``T.nil``代替。 第二, ``BR-INSERT``第14-15行置z.left与z.right为T.nil,以保持合理的树结构. 第三, 在第16行将z着为红色可能违反其中一条红黑树性质, 所以BR-iINSER的第17行中调用BR-INSERT-FIXUP(T, z)来保持红黑性质。 ```python def BR-INSERT-FIXUP(T, z): 1 while z.color == RED 2 if z.p==z.p.p.left: 3 y = z.p.p.right 4 if y.color = RED: 5 z.p.color = BLACK 6 y.color = BLACK 7 z.p.p.color = RED 8 z = z.p.p 9 else 10 if z=z.p.right: 11 z = z.p 12 LEFT_ROTATION(T,z) 13 z.p.color = BLACK 14 z.p.p.color = RED 15 RIGHT-ROTATE(T, z.p.p) 16 else(case as then lause with "right" and "left" exchanged) T.root.color = BLACK ``` 为了理解BR-INSERT-FIXUP过程如何工作, 把代码分为三个主要步骤。首先, 要确定当结点z被插入并着色为红色后, 红黑性质有哪些不能继续保持。 其次, 应分析第1-15行中,while循环的总目标。最后,要分析while循环中的三种情况, 看看他们是如何完成目标的。 在调用BR-INSERT-FIXUP操作时, 有哪些性质会被破坏呢?性质1根性质3不会发生改变, 因为新插入的红色结点的哨兵T.nil。 性质5, 即从一个指定结点开始的每条简单路径上的黑色结点的个数都是相等的, 也会成立, 因为增加结点z并没有引入新的黑色结点。 仅仅有可能被破坏的就是性质2和性质4, 及根节点必须为黑色结点,以及一个红的结点的子节点必须是黑色的。 第1-15行中的while循环在每次迭代的开头保持下列三部分的不变式: a. 结点z是红色的 b. 如果z.p是根节点, 则z.p是黑结点 c. 如果有任何红黑性质被破坏,则至多只有一条被破坏,或者性质2或者性质4。 如果性质2被破坏,其原因是z是根节点且是红色结点。 如性质4被破坏,其原因为z和z.p都是红色结点。 需要证明在循环的第一次迭代之前循环不变式为真, 每次迭代都保持这个循环不变式成立, 并且在循环终止时, 这个循环不变式给出一个有用的性质。 **初始化**: 在循环的第一次迭代之前, 从一棵正常的红黑树开始, 并新增加一个红色结点z。a. 在调用BR-INSERT-FIXUP时, z是新增的红色几点。 b.如果z.p是根, 那么z.p开始是黑色, 且在调用BR-INSERT-FIXUP之前保持不变。 c.注意到调用RB-INSERT-FIXUP时, 性质1,性质3和性质5成立。 如果违反性质2, 则红色根结点一定是新增结点 z, 它是树中的唯一内部结点。因为因为z的父节点根哨兵结点都是黑色结点,所以没有破坏性质4。 这样对性质2的违反是整棵树中唯一违反红黑性质的地方。 如果违反了性质4, 因为结点z的哨兵结点是黑色的,且在z加入之前没有违反其他性质被违反,则z根z.parent必然是红色的。其他性质没有被违反。 **终止**: 循环终止时, 我们有p的父节点是黑色的。因此这棵树没有违反性质4。 根据循环不变式, 唯一可能违反的性质是性质2。 第16行恢复这个性质, 所以当RB-INSERT终止时, 所有红黑树的性质成立。 **保持**: 实际需要考虑while循环中的6中情况;其中三种与另外三种是对称的。这取决于第2行中z的父节点z.p是z祖先结点的左儿子还是右儿子。结点z.p.p肯定存在, 因为根据循环不变式, z.p如果是根节点, 它必然是黑色, 而进入循环不变式的条件是z.p是红色结点,我们知道z.p不可能是根节点。所以z.p.p存在。 我们根据z父节点的兄弟, 分成三种情况讨论。 y指向z的叔叔结点。第一种情况, y结点是红色的。 在所有的情形中, z的父节点是黑色的, 如果父节点z.p是红色, 则对性质4的违反只出现在z.p跟z之间。 **情形1 叔叔结点是黑色的** 第一种情况出现当y根z.p都是红色的。因为z.p.p是黑色的, 我们可以将z.p跟y染黑,将z.p.p染黑以保持性质5。同事z的祖先结点z.p.p成为新的z结点。 在此情况下, z向上移动两层。 现在证明在下次循环之前, 上述操作维持了循环不变式。 a.因为本次迭代, z.p.p被着色为红色, 且颜色没有再改变过。如果该节点是根节点, b. 此次迭代之前z.p.p.p如果是根节点, 在此之前他就是黑色的, 且没有被改变过, 所以在本次迭代开始前依旧是黑色的。 c. 情形1没有改变黑高, 所以性质5保持不变。 只有性质4可能被破坏。 如果z`在下次循环开始的时候是根节点, 则性质1被修正,因为没有父节点了。 性质2变成了唯一被破坏的性质。 如果$z'$不是根节点, 情形1不会破坏性质2。 性质4成为唯一可能被破坏的性质。 如果z'.p是黑色的,性质4并没有被违背。 如果是红色的, 性质4的违背也只限于z'与z'.p之间。 **情形 2: z叔叔结点是黑色的且z是右儿子** 在情况2中z.p是z.p.p的左节点, z是z.p的右儿子。 所以从z.p.p到z会形成一条折线,我们通过左旋z.p使得z成为z.p的父节点, 且z, z.p, z.p.p在同一条直线上.由于z与z.p都是红色的, 所以它不改变z.p与z子树上所有结点的黑高, 所以任然只有性质4被破坏。由于我们将z向上移动一层, 做左旋操作使得z下降一层, 所以z.p.p没有发生改变,操作前后指向相同的结点。 **情形 3: z叔叔结点是黑色的且z是左儿子** 情形3中, 我们将z.p.p右旋, 并把颜色改为黑色, z.p改为红色。因为没有对C的右子树做改动, B的黑高与C的相同, 所以操作前后没有改变C的黑高。 B的黑高也没发生改变。 由于我们把C染红,所以B的黑高没发生改变。 由于B替换了C的位置,变为黑色,对于B的祖先结点来说,黑高也没有发生改变µ。所以性质5保持。 由于B变为黑色, 性质4也保持不变。 现在来证明情形4跟情形5保持循环不变式。 a.情形2使得z指向z.p,依旧是红色的。 情形三的操作使得循环结束。 b.两种情形中z.p的位置保持不变,所以z.p不可能是根节点。 c.同上 综上所述, BR-INSERT-FIXUP不会引起红黑树性质的概念。 ```
zhugq819905749/GitDemo
zhugq819905749/GitDemo README.md ```# GitDemo http://github.com/GitDemo ```
zhuguangxiang/LeetCode
zhuguangxiang/LeetCode Longest Substring Without Repeating Characters.py ```class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ maxlen = 0 prev_pos_dict = {} start = end = 0 for i,v in enumerate(s): if v in prev_pos_dict: start = max(start,prev_pos_dict[v]+1) maxlen = max(maxlen, end-start+1) prev_pos_dict[v] = i end += 1 return maxlen``` README.md ```# LeetCode Please see Wiki page for this repo for more ideas and code solutions for various algorithm problems. [Click Here](https://github.com/gigglegrig/LeetCode/wiki) ``` add-two-number.py ```''' 2. Add Two Numbers https://www.jianshu.com/p/5d8f13225adf You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. ''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode [2,4,3] :type l2: ListNode [5,0,6] :rtype: ListNode """ def to_int(l): if l is None: return 0 else: return l.val + 10 * to_int(l.next) def to_linkedlist(num): l = ListNode(num % 10) num = num // 10 if num != 0: l.next = to_linkedlist(num) return l l1_num = to_int(l1) l2_num = to_int(l2) return to_linkedlist(l1_num + l2_num) if __name__ == '__main__': l1 = ListNode(2) l1.next = ListNode(4) l1.next.next = ListNode(3) l2 = ListNode(5) l2.next = ListNode(0) l2.next.next = ListNode(6) sol = Solution().addTwoNumbers(l1,l2) while sol: print(sol.val) sol = sol.next``` median-2-sorted-arrary.py ```class Solution: def findMedianSortedArrays(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: float """ if (len(A) == 0 or A is None) and (len(B) == 0 or B is None): return -1 length = len(A) + len(B) if (length % 2 == 0): return (Solution.findKth(A, 0, B, 0, length // 2) + Solution.findKth(A, 0, B, 0, length // 2 + 1)) / 2; else: return Solution.findKth(A, 0, B, 0, length // 2 + 1) @staticmethod def findKth(A, idx_A, B, idx_B, k): if idx_A > (len(A) - 1): return B[idx_B + k - 1] if idx_B > (len(B) - 1): return A[idx_A + k - 1] if k == 1: return min(A[idx_A], B[idx_B]) # try to get the median of A and B i = j = 2 ** 64 if (idx_A + k // 2 - 1) < len(A): i = A[idx_A + k // 2 - 1] if (idx_B + k // 2 - 1) < len(B): j = B[idx_B + k // 2 - 1] if (i > j): return Solution.findKth(A, idx_A, B, idx_B + k // 2, k - k // 2) else: return Solution.findKth(A, idx_A + k // 2, B, idx_B, k - k // 2)``` Topological Sort.py ```def topological_sort(unsorted_graph): ''' idea from http://blog.jupo.org/2012/04/06/topological-sorting-acyclic-directed-graphs/ deal with a node only if all it's children are sorted, in other words, start from the latest appeared nodes, build from there. A cycle is defined when in any iteration, none of the node can be solved, i.e 2 nodes point to each other :param unsorted_graph: list[tuple(node, list[children])] :return: sorted graph ''' sorted_nodes = [] while graph_unsorted: acyclic = False for idx, (node, children_list) in enumerate(unsorted_graph): for children in children_list: if children not in sorted_nodes: # do not deal with the node who has unsorted child break else: # if all children been sorted, move this node to sorted list acyclic = True sorted_nodes.append(node) unsorted_graph.remove(unsorted_graph[idx]) if acyclic is False: raise RuntimeError("Cycle formed in the graph") return sorted_nodes[::-1] if __name__=="__main__": graph_unsorted = [(2, []), (5, [11]), (11, [2, 9, 10]), (7, [11, 8]), (9, []), (10, []), (8, [9]), (3, [10, 8])] sorted_list = topological_sort(graph_unsorted) print(sorted_list) ```
zhuhai/myweixin
zhuhai/myweixin user.js ```var scripts = [null,'/static/js/common.js','/static/js/bootstrap-multiselect.js','/static/js/sha1.js','/static/js/bootbox.min.js',null]; ace.load_ajax_scripts(scripts,function(){ var grid_selector = "#grid-table"; var pager_selector = "#grid-pager"; //resize to fit page size $(window).on('resize.jqGrid', function () { $(grid_selector).jqGrid( 'setGridWidth', $(".page-content").width() ); }); //resize on sidebar collapse/expand var parent_column = $(grid_selector).closest('[class*="col-"]'); $(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() ); }, 0); } }); $(grid_selector).jqGrid({ url:"/user/list", datatype: "json", mtype:"GET", height: '300', colNames:['编号','用户名','部门','角色','是否锁定','创建时间'], colModel:[ { key:true, name:'id', index:'id', width:40 }, { name:'userName', width:90, sortable:false }, { name:'organization', width:90, sortable:false }, { name:'roleName', width:90, sortable:false }, { name:'locked', width:90, sortable:false, formatter: function (cellvalue,options,rowObject) { var screenValue = ''; switch (cellvalue) { case false: screenValue = '正常'; break; case true: screenValue = '<span style="color:red">锁定</span>'; break; default : screenValue = '正常'; } return screenValue; } }, { name:'createTime', index:'create_time', width:90, sortable:true } ], viewrecords : true, rowNum:10, rowList:[10,20,30], pager : pager_selector, altRows: true, //第一个参数表示是否显示排序图标,第二个参数表示图标排序方式,vertical:垂直,horizontal:水平 //第三个参数指单击功 能,true:单击列可排序,false:单击图标排序。 viewsortcols:[true,'vertical',true], multiselect: true, multiselectWidth:30, //multikey: "ctrlKey", multiboxonly: true, loadComplete : function() { var table = this; setTimeout(function(){ styleCheckbox(table); updateActionIcons(table); updatePagerIcons(table); enableTooltips(table); }, 0); }, autowidth: true }); //trigger window resize to make the grid get the correct size $(window).triggerHandler('resize.jqGrid'); $(".multiselect").multiselect({ enableFiltering: true, buttonClass: 'btn btn-white btn-primary', buttonWidth:'100%', templates: { button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>', ul: '<ul class="multiselect-container dropdown-menu"></ul>', filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="fa fa-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>', filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default btn-white btn-grey multiselect-clear-filter" type="button"><i class="fa fa-times-circle red2"></i></button></span>', li: '<li><a href="javascript:void(0);"><label></label></a></li>', divider: '<li class="multiselect-item divider"></li>', liGroup: '<li class="multiselect-item group"><label class="multiselect-group"></label></li>' } }); //添加用户 $("#submitAddButton").click(function(){ $("#createForm").submit(); }); $("#createForm").validate({ errorElement:'div', errorClass:'help-block', //使多选框验证生效 //ignore:':hidden:not(".multiselect")', rules:{ userName:{ required:true }, password:{ required:true, rangelength:[6,18] }, organizationId:{ required:true }, roleIds:{ required:true } }, messages:{ userName:{ required:'请输入用户名' }, password:{ required:'请输入密码', rangelength:'密码长度为6~18位' }, organizationId:{ required:'请选择部门' }, roleIds:{ required:'请选择角色' } }, highlight:function(e){ $(e).closest(".form-group").addClass("has-error"); }, success:function(e){ $(e).closest(".form-group").removeClass("has-error"); $(e).remove(); }, errorPlacement:function(error,element){ if(element.is('input[type=checkbox]') || element.is('input[type=radio]')) { var controls = element.closest('div[class*="col-"]'); if(controls.find(':checkbox,:radio').length > 1) controls.append(error); else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0)); } else if(element.is('.select2')) { error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)')); } else if(element.is('.chosen-select')) { error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)')); } else { error.insertAfter(element.parent()); } }, submitHandler:function(form){ var userName = $("#userName").val(); var password = CryptoJS.SHA1($("#password").val())+""; var organizationId = $("#organizationId").val(); var roleIds = $("#roleIds").val(); if(!roleIds) { alertErrorNotice("请选择角色!"); return; } $.ajax({ url:'/user/create', type:'post', data:{userName:userName,password:password,organizationId:organizationId,roleIds:roleIds.toString()}, dataType:'json', success:function(result) { if (result && result.success) { $("#create-user-modal").modal('hide'); $(grid_selector).jqGrid().trigger("reloadGrid"); } else { alertErrorNotice(result.msg) } }, error:function() { alertErrorNotice("系统异常,添加失败!"); } }); } }); //模态框关闭,清空表单内容 $("#create-user-modal").on('hidden.bs.modal',function(){ $("#createForm")[0].reset(); $("#roleIds").multiselect('refresh'); }); //修改用户 $("#editButton").click(function(){ $("#role").multiselect('deselectAll',false); $("#role").multiselect('updateButtonText'); //var id = $(grid_selector).jqGrid('getGridParam','selrow'); var userIds = $(grid_selector).jqGrid('getGridParam','selarrrow'); if(userIds.length != 1){ alertErrorNotice("请选择需要修改的一条数据!"); }else{ var rowData = $(grid_selector).jqGrid('getRowData',userIds); var organization = rowData.organization; var roleNames = rowData.roleName.split(","); $("#name").val(rowData.userName); $("#userId").val(rowData.id); $("#organization option").each(function(){ if ($(this).text() == organization) { $(this).attr('selected', true); } }); for(var i=0;i<roleNames.length;i++){ $("#role option").each(function(){ if($(this).text() == roleNames[i]) { $("#role").multiselect('select',$(this).val()); } }); } $("#edit-user-modal").modal('toggle'); } //var name = $(grid_selector).jqGrid('getCell',id,'userName'); }); $("#updateBtn").click(function(){ $("#updateForm").submit(); }); $("#updateForm").validate({ errorElement:'div', errorClass:'help-block', rules:{ userName:{ required:true }, organizationId:{ required:true }, roleIds:{ required:true } }, messages:{ userName:{ required:'请输入用户名' }, organizationId:{ required:'请选择部门' }, roleIds:{ required:'请选择角色' } }, highlight:function(e){ $(e).closest(".form-group").addClass("has-error"); }, success:function(e){ $(e).closest(".form-group").removeClass("has-error"); $(e).remove(); }, errorPlacement:function(error,element){ if(element.is('input[type=checkbox]') || element.is('input[type=radio]')) { var controls = element.closest('div[class*="col-"]'); if(controls.find(':checkbox,:radio').length > 1) controls.append(error); else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0)); } else if(element.is('.select2')) { error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)')); } else if(element.is('.chosen-select')) { error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)')); } else { error.insertAfter(element.parent()); } }, submitHandler:function(form){ var userId = $("#userId").val(); var userName = $("#name").val(); var organizationId = $("#organization").val(); var roleIds = $("#role").val(); if(!roleIds){ alertErrorNotice("请选择角色!"); return; } $.ajax({ url:'/user/'+userId+'/update', type:'post', dataType:'json', data:{userName:userName,organizationId:organizationId,roleIds:roleIds.toString()}, success:function(result){ if(result && result.success){ $("#edit-user-modal").modal('hide'); $(grid_selector).jqGrid().trigger('reloadGrid'); }else { alertErrorNotice(result.msg); } }, error:function(){ alertErrorNotice("系统异常,修改失败!") } }); } }); /** * 锁定用户 */ $("#lockButton").click(function(){ var ids = $(grid_selector).jqGrid('getGridParam','selarrrow'); if(ids.length == 0) { alertErrorNotice("请至少选择一条数据!"); } else { bootbox.setLocale("zh_CN"); bootbox.confirm('确定要锁定吗?',function(result){ if (result) { $.ajax({ url:'/user/lock', type:'POST', dataType:'json', data:{ids:ids,lock:true}, success:function(result){ if (result && result.success) { alertSuccessNotice(result.msg,1000); $(grid_selector).jqGrid().trigger('reloadGrid'); }else{ alertErrorNotice(result.msg); } }, error:function(){ alertErrorNotice("系统异常,锁定失败!") } }); } }); } }); /** * 解锁用户 */ $("#unLockButton").click(function(){ var ids = $(grid_selector).jqGrid('getGridParam','selarrrow'); if(ids.length == 0) { alertErrorNotice("请至少选择一条数据!"); } else { $.ajax({ url:'/user/lock', type:'POST', dataType:'json', data:{ids:ids,lock:false}, success:function(result){ if (result && result.success) { alertSuccessNotice(result.msg,1000); $(grid_selector).jqGrid().trigger('reloadGrid'); }else{ alertErrorNotice(result.msg); } }, error:function(){ alertErrorNotice("系统异常,解锁失败!") } }); } }); }); ``` README.md ```# myweixin this is my first git project ``` ResultJson.java ```package com.zhuhai.dto; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/7/5 * Time: 18:08 */ //@JsonInclude(JsonInclude.Include.NON_NULL) public class ResultJson<T> { private boolean success; private T data; private String msg; public ResultJson(boolean success, T data) { this.success = success; this.data = data; } public ResultJson(boolean success, String msg) { this.success = success; this.msg = msg; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public T getData() { return data; } public void setData(T data) { this.data = data; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } ``` ResourcesMapper.java ```package com.zhuhai.mapper; import com.zhuhai.entity.Resources; import java.util.List; import java.util.Set; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/20 * Time: 11:19 */ public interface ResourcesMapper { public void createResource(Resources resources); public void updateResource(Resources resources); public void deleteResource(long id); public Resources findById(long id); public List<Resources> findAll(); public Set<String> findPermissionsByIds(Long[] ids); } ``` OrganizationMapper.java ```package com.zhuhai.mapper; import com.zhuhai.entity.Organization; import java.util.List; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/6/19 * Time: 12:44 */ public interface OrganizationMapper { public void createOrganization(Organization organization); public void updateOrganization(Organization organization); public void deleteOrganization(long id); public Organization findById(long id); public List<Organization> findAll(); public List<Organization> findByParentId(long pid); } ``` DateUtil.java ```package com.zhuhai.utils; import java.text.SimpleDateFormat; import java.util.Date; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/6/28 * Time: 21:22 */ public class DateUtil { private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss"; public static String date2String(Date date,String pattern) { SimpleDateFormat sdf = new SimpleDateFormat(pattern); return sdf.format(date); } public static String date2String(Date date) { return date2String(date,DEFAULT_PATTERN); } } ``` OrganizationServiceImpl.java ```package com.zhuhai.service.impl; import com.zhuhai.entity.Organization; import com.zhuhai.mapper.OrganizationMapper; import com.zhuhai.service.OrganizationService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/22 * Time: 17:34 */ @Service public class OrganizationServiceImpl implements OrganizationService { @Resource private OrganizationMapper organizationMapper; @Override public void createOrganization(Organization organization) { organizationMapper.createOrganization(organization); } @Override public void updateOrganization(Organization organization) { organizationMapper.updateOrganization(organization); } @Override public void deleteOrganization(long id) { organizationMapper.deleteOrganization(id); } @Override public Organization findById(long id) { return organizationMapper.findById(id); } @Override public List<Organization> findAll() { return organizationMapper.findAll(); } @Override public List<Organization> findChildOrganizations(long pid) { return organizationMapper.findByParentId(pid); } } ``` ResourceController.java ```package com.zhuhai.controller; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/6/30 * Time: 21:57 */ @Controller @RequestMapping("/resource") public class ResourceController { @RequiresPermissions("resource:view") @RequestMapping(method = RequestMethod.GET) public String getResourceList() { return "resource/resourceList"; } } ``` UserDTO.java ```package com.zhuhai.dto; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/6/28 * Time: 20:31 */ public class UserDTO { private Long id; private String userName; private String roleName; private String organization; private Boolean locked; private String createTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } public Boolean getLocked() { return locked; } public void setLocked(Boolean locked) { this.locked = locked; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } } ``` HomeController.java ```package com.zhuhai.controller; import com.zhuhai.entity.Resources; import com.zhuhai.entity.User; import com.zhuhai.service.ResourcesService; import com.zhuhai.service.UserService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AccountException; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.ExcessiveAttemptsException; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.annotation.Resource; import java.util.List; import java.util.Set; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/6/17 * Time: 21:46 */ @Controller @RequestMapping("/") public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @Resource private UserService userService; @Resource private ResourcesService resourcesService; @RequestMapping(method = RequestMethod.GET) public String home(Model model) { User user = (User) SecurityUtils.getSubject().getPrincipal(); Set<String> permissions = userService.findPermissionsByUserName(user.getUserName()); List<Resources> menus = resourcesService.findMenus(permissions); model.addAttribute("menus",menus); model.addAttribute("user",user); return "home"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String loginForm() { return "login"; } @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(User user, boolean rememberMe,RedirectAttributes redirectAttributes) { try { logger.info("登录用户名:{}",user.getUserName()); logger.info("登录密码:{}",user.getPassword()); logger.info("记住我:{}",rememberMe); UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getPassword(),rememberMe); SecurityUtils.getSubject().login(token); return "redirect:/"; } catch (UnknownAccountException e) { redirectAttributes.addFlashAttribute("message","用户名或密码错误"); } catch (LockedAccountException e) { redirectAttributes.addFlashAttribute("message","用户被锁定"); } catch (ExcessiveAttemptsException e) { redirectAttributes.addFlashAttribute("message","失败次数过多,账号被锁定,请10分钟后再试!"); } catch (IncorrectCredentialsException e){ redirectAttributes.addFlashAttribute("message","用户名或密码错误"); } catch (AccountException e) { redirectAttributes.addFlashAttribute("message", "用户名或密码错误"); } catch (AuthenticationException e) { redirectAttributes.addFlashAttribute("message","系统异常"); } return "redirect:login"; } @RequestMapping(value = "/logout",method = RequestMethod.GET) public String logout(){ SecurityUtils.getSubject().logout(); return "redirect:login"; } } ``` TreeDTO.java ```package com.zhuhai.dto; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/7/5 * Time: 14:01 */ public class TreeDTO { private long id; private long pId; private String name; private boolean isParent; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getpId() { return pId; } public void setpId(long pId) { this.pId = pId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean getIsParent() { return isParent; } public void setIsParent(boolean isParent) { this.isParent = isParent; } } ``` weixin.sql ```/* SQLyog Ultimate v11.11 (64 bit) MySQL - 5.6.11 : Database - weixin ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`weixin` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `weixin`; /*Table structure for table `sys_organization` */ DROP TABLE IF EXISTS `sys_organization`; CREATE TABLE `sys_organization` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(100) DEFAULT NULL COMMENT '组织机构名称', `parent_id` bigint(20) DEFAULT NULL COMMENT '父组织编号', `parent_ids` varchar(100) DEFAULT NULL COMMENT '父组织编号列表', `avaliable` tinyint(1) DEFAULT '0', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `create_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `idx_sys_orginzation_parent_id` (`parent_id`), KEY `idx_sys_orginzation_parent_ids` (`parent_ids`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; /*Data for the table `sys_organization` */ insert into `sys_organization`(`id`,`name`,`parent_id`,`parent_ids`,`avaliable`,`update_time`,`create_time`) values (1,'总公司',0,'0/',1,'2016-06-20 10:18:26','2016-06-20 10:18:26'),(2,'分公司1',1,'0/1/',1,'2016-06-20 10:18:26','2016-06-20 10:18:26'),(3,'分公司2',1,'0/1/',1,'2016-06-20 10:18:26','2016-06-20 10:18:26'),(4,'分公司11',2,'0/1/2/',1,'2016-06-20 10:18:26','2016-06-20 10:18:26'),(5,'分公司3',1,'0/',1,'2016-06-20 10:18:26','2016-06-20 10:18:26'),(6,'分公司4',1,'0/1/',1,'2016-06-20 10:18:26','2016-06-20 10:18:26'),(7,'分公司5',1,'0/1/',1,'2016-06-20 10:18:26','2016-06-20 10:18:26'),(8,'分公司12',2,'0/1/2/',1,'2016-06-20 10:18:26','2016-06-20 10:18:26'); /*Table structure for table `sys_resource` */ DROP TABLE IF EXISTS `sys_resource`; CREATE TABLE `sys_resource` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(100) DEFAULT NULL COMMENT '资源名称', `type` varchar(50) DEFAULT NULL COMMENT '资源类型', `url` varchar(200) DEFAULT NULL COMMENT '资源路径', `parent_id` bigint(20) DEFAULT NULL, `parent_ids` varchar(100) DEFAULT NULL, `permission` varchar(100) DEFAULT NULL, `avaliable` tinyint(1) DEFAULT '0', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `create_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `icon` varchar(20) DEFAULT NULL, PRIMARY KEY (`id`), KEY `idx_sys_resource_parent_id` (`parent_id`), KEY `idx_sys_resource_parent_ids` (`parent_ids`) ) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8; /*Data for the table `sys_resource` */ insert into `sys_resource`(`id`,`name`,`type`,`url`,`parent_id`,`parent_ids`,`permission`,`avaliable`,`update_time`,`create_time`,`icon`) values (1,'资源','menu','',0,'0/',NULL,1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(2,'组织机构管理','menu','/organization',1,'0/1/','organization:*',1,'2016-06-28 14:27:24','2016-06-20 10:18:26','fa-folder-open'),(3,'组织机构添加','button','',2,'0/1/2/','organization:create',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(4,'组织机构修改','button','',2,'0/1/2/','organization:update',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(5,'组织机构删除','button','',2,'0/1/2/','organization:delete',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(6,'组织机构查看','button','',2,'0/1/2/','organization:view',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(7,'用户管理','menu','/user',1,'0/1/','user:*',1,'2016-06-28 14:27:28','2016-06-20 10:18:26','fa-group'),(8,'用户新增','button','',7,'0/1/7/','user:create',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(9,'用户修改','button','',7,'0/1/7/','user:update',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(10,'用户删除','button','',7,'0/1/7/','user:delete',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(11,'用户查看','button','',7,'0/1/7/','user:view',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(12,'资源管理','menu','/resource',1,'0/1/','resource:*',1,'2016-06-28 14:27:31','2016-06-20 10:18:26','fa-briefcase'),(13,'资源新增','button','',12,'0/1/12/','resource:create',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(14,'资源修改','button','',12,'0/1/12/','resource:update',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(15,'资源删除','button','',12,'0/1/12/','resource:delete',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(16,'资源查看','button','',12,'0/1/12/','resource:view',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(17,'角色管理','menu','/role',1,'0/1/','role:*',1,'2016-06-28 15:27:40','2016-06-20 10:18:26','fa-thumbs-up'),(18,'角色新增','button','',17,'0/1/17/','role:create',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(19,'角色修改','button','',17,'0/1/17/','role:update',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(20,'角色删除','button','',17,'0/1/17/','role:delete',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL),(21,'角色查看','button','',17,'0/1/17/','role:view',1,'2016-06-20 10:18:26','2016-06-20 10:18:26',NULL); /*Table structure for table `sys_role` */ DROP TABLE IF EXISTS `sys_role`; CREATE TABLE `sys_role` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `role` varchar(100) DEFAULT NULL COMMENT '角色标识', `description` varchar(100) DEFAULT NULL COMMENT '角色描述', `resource_ids` varchar(100) DEFAULT NULL COMMENT '资源编号列表', `avaliable` tinyint(1) DEFAULT '0', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `create_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `idx_sys_role_resource_ids` (`resource_ids`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; /*Data for the table `sys_role` */ insert into `sys_role`(`id`,`role`,`description`,`resource_ids`,`avaliable`,`update_time`,`create_time`) values (1,'admin','超级管理员','2,7,12,17',1,'2016-06-20 10:18:26','2016-06-20 10:18:26'),(2,'root','管理员','2',1,'2016-06-20 17:57:36','2016-06-20 14:34:05'); /*Table structure for table `sys_user` */ DROP TABLE IF EXISTS `sys_user`; CREATE TABLE `sys_user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `username` varchar(100) DEFAULT NULL COMMENT '用户名', `password` varchar(100) DEFAULT NULL COMMENT '密码', `organization_id` bigint(20) DEFAULT NULL COMMENT '组织机构id', `role_ids` varchar(100) DEFAULT NULL COMMENT '角色id', `locked` tinyint(1) DEFAULT '0' COMMENT '是否锁定', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `create_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), UNIQUE KEY `idx_sys_user_username` (`username`), KEY `idx_sys_user_organization_id` (`organization_id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; /*Data for the table `sys_user` */ insert into `sys_user`(`id`,`username`,`password`,`organization_id`,`role_ids`,`locked`,`update_time`,`create_time`) values (1,'admin','c37d8a8f79139bd5749f54b6a5b47cc19f417d22',1,'1',0,'2016-06-27 17:59:06','2016-06-20 10:18:26'),(2,'root','c37d8a8f79139bd5749f54b6a5b47cc19f417d22',1,'2',0,'2016-06-27 17:59:08','2016-06-20 15:38:37'),(3,'tom','c37d8a8f79139bd5749f54b6a5b47cc19f417d22',1,'2',0,'2016-06-27 17:59:09','2016-06-22 17:18:08'),(4,'tom2','c37d8a8f79139bd5749f54b6a5b47cc19f417d22',7,'2',0,'2016-06-27 17:59:12','2016-06-22 17:41:56'); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; ``` UserServiceImpl.java ```package com.zhuhai.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.zhuhai.entity.User; import com.zhuhai.mapper.ResourcesMapper; import com.zhuhai.mapper.RoleMapper; import com.zhuhai.mapper.UserMapper; import com.zhuhai.service.UserService; import com.zhuhai.utils.CommonUtil; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/16 * Time: 15:16 */ @Service public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Resource private RoleMapper roleMapper; @Resource private ResourcesMapper resourcesMapper; @Override public void saveUser(User user) { userMapper.createUser(user); } @Override public void updateUser(User user) { userMapper.updateUser(user); } @Override public void deleteUser(Long userId) { userMapper.deleteUser(userId); } @Override public User findUserById(Long userId) { return userMapper.findById(userId); } @Override public PageInfo<User> findAllByPage(String sidx, String sord, Integer pageNo, Integer pageSize) { PageHelper.startPage(pageNo, pageSize); PageHelper.orderBy(sidx + " " + sord); List<User> userList = userMapper.findAll(); return new PageInfo<User>(userList); } @Override public User findUserByUserName(String userName) { return userMapper.findByUserName(userName); } /** * 根据用户名获取角色id * * @param userName * @return */ @Override public Set<String> findRolesByUserName(String userName) { User user = userMapper.findByUserName(userName); if (user == null) { return Collections.EMPTY_SET; } String[] roleIds = user.getRoleIds().split(","); return roleMapper.findRolesByIds(CommonUtil.stringArray2LongArray(roleIds)); } /** * 根据用户获取权限名称列表 * * @param userName * @return */ @Override public Set<String> findPermissionsByUserName(String userName) { User user = userMapper.findByUserName(userName); if (user == null) { return Collections.EMPTY_SET; } String[] roleIds = user.getRoleIds().split(","); Set<String> resources = roleMapper.findResourceIdsByIds(CommonUtil.stringArray2LongArray(roleIds)); Set<Long> resourceIdSet = new HashSet<Long>(); for (String resource : resources) { String[] resourceIds = resource.split(","); for (String resourceId : resourceIds) { resourceIdSet.add(Long.valueOf(resourceId)); } } return resourcesMapper.findPermissionsByIds(resourceIdSet.toArray(new Long[resourceIdSet.size()])); } @Override public void lockOrUnLockUser(Long[] ids, boolean lock) { userMapper.lockOrUnLockUser(ids,lock); } } ``` sql-schema.sql ```create table sys_user( id bigint auto_increment, username varchar(100) comment '用户名', password varchar(100) comment '密码', organization_id bigint comment '组织机构id', role_ids varchar(100) comment '角色id', locked boolean default false comment '是否锁定', update_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, create_time timestamp NOT NULL DEFAULT now(), constraint pk_sys_user primary key(id), unique index idx_sys_user_username(username), index idx_sys_user_organization_id(orgainzation_id) )charset=utf8 ENGINE=InnoDB; create table sys_organization( id bigint auto_increment, name varchar(100) comment '组织机构名称', parent_id bigint comment '父组织编号', parent_ids varchar(100) comment '父组织编号列表', avaliable boolean default false, update_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, create_time timestamp NOT NULL DEFAULT now(), constraint pk_sys_orginzation primary key(id), index idx_sys_orginzation_parent_id(parent_id), index idx_sys_orginzation_parent_ids(parent_ids) )charset=utf8 ENGINE=InnoDB; create table sys_role( id bigint auto_increment, role varchar(100) comment '角色标识', description varchar(100) comment '角色描述', resource_ids varchar(100) comment '资源编号列表', avaliable boolean default false, update_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, create_time timestamp NOT NULL DEFAULT now(), constraint pk_sys_role primary key(id), index idx_sys_role_resource_ids(resource_ids) )charset=utf8 ENGINE=InnoDB; create table sys_resource( id bigint auto_increment, name varchar(100) comment '资源名称', type varchar(50) comment '资源类型', url varchar(200) comment '资源路径', parent_id bigint, parent_ids varchar(100), permission varchar(100), avaliable boolean default false, update_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, create_time timestamp NOT NULL DEFAULT now(), constraint pk_sys_resource primary key(id), index idx_sys_resource_parent_id(parent_id), index idx_sys_resource_parent_ids(parent_ids) )charset=utf8 ENGINE=InnoDB; ``` OrganizationService.java ```package com.zhuhai.service; import com.zhuhai.entity.Organization; import java.util.List; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/22 * Time: 17:33 */ public interface OrganizationService { public void createOrganization(Organization organization); public void updateOrganization(Organization organization); public void deleteOrganization(long id); public Organization findById(long id); public List<Organization> findAll(); public List<Organization> findChildOrganizations(long pid); } ``` MyRealm.java ```package com.zhuhai.shiro.realm; import com.zhuhai.entity.User; import com.zhuhai.service.UserService; import com.zhuhai.utils.Constant; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import javax.annotation.Resource; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/20 * Time: 15:56 */ public class MyRealm extends AuthorizingRealm { @Resource private UserService userService; /** * 授权 * @param principalCollection * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { User user = (User) principalCollection.fromRealm(getName()).iterator().next(); //User user = userService.findUserByUserName(loginName); if (user != null) { SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.setRoles(userService.findRolesByUserName(user.getUserName())); authorizationInfo.setStringPermissions(userService.findPermissionsByUserName(user.getUserName())); return authorizationInfo; } return null; } /** * 认证 * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; User user = userService.findUserByUserName(token.getUsername()); if (user == null) { throw new UnknownAccountException(); } if (user.getLocked()) { throw new LockedAccountException(); } /*if (!String.valueOf(token.getPassword()).equals(user.getPassword())) { throw new AccountException(); }*/ SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(),ByteSource.Util.bytes(Constant.SALT),getName()); return authenticationInfo; } } ``` UserController.java ```package com.zhuhai.controller; import com.github.pagehelper.PageInfo; import com.zhuhai.dto.JqGridView; import com.zhuhai.dto.ResultJson; import com.zhuhai.dto.UserDTO; import com.zhuhai.entity.Organization; import com.zhuhai.entity.Role; import com.zhuhai.entity.User; import com.zhuhai.service.OrganizationService; import com.zhuhai.service.RoleService; import com.zhuhai.service.UserService; import com.zhuhai.utils.Constant; import com.zhuhai.utils.DateUtil; import org.apache.commons.codec.digest.DigestUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; 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.ResponseBody; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/17 * Time: 14:53 */ @Controller @RequestMapping("/user") public class UserController { private static final Logger logger = LoggerFactory.getLogger(UserController.class); @Resource private UserService userService; @Resource private OrganizationService organizationService; @Resource private RoleService roleService; @RequiresPermissions("user:view") @RequestMapping(method = RequestMethod.GET) public String getUserList(Model model) { List<Organization> organizationList = organizationService.findAll(); List<Role> roleList = roleService.findAll(); model.addAttribute("organizationList", organizationList); model.addAttribute("roleList",roleList); return "user/userList"; } @RequiresPermissions("user:view") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public JqGridView<UserDTO> userList(@RequestParam(value = "sidx",required = false,defaultValue = "create_time") String sidx, @RequestParam(value = "sord",required = false,defaultValue = "asc") String sord, @RequestParam(value = "rows",required = false,defaultValue = "10") Integer pageSize, @RequestParam(value = "page",required = false,defaultValue = "1") Integer pageNo) { JqGridView<UserDTO> jqGridView = new JqGridView<UserDTO>(); try { PageInfo<User> pageInfo = userService.findAllByPage(sidx, sord, pageNo, pageSize); List<UserDTO> userDTOList = new ArrayList<UserDTO>(); for (User user : pageInfo.getList()) { UserDTO userDTO = new UserDTO(); userDTO.setId(user.getId()); userDTO.setUserName(user.getUserName()); Organization organization = organizationService.findById(user.getOrganizationId()); if (organization != null) { userDTO.setOrganization(organization.getName()); } String[] roleIds = user.getRoleIds().split(","); StringBuilder roleNames = new StringBuilder(); for (int i = 0; i < roleIds.length; i++) { Role role = roleService.findById(Long.valueOf(roleIds[i])); roleNames.append(role.getDescription()); if (i < roleIds.length - 1) { roleNames.append(","); } } userDTO.setRoleName(roleNames.toString()); userDTO.setLocked(user.getLocked()); userDTO.setCreateTime(DateUtil.date2String(user.getCreateTime())); userDTOList.add(userDTO); jqGridView.setPage(pageInfo.getPageNum()); jqGridView.setTotal(pageInfo.getPages()); jqGridView.setRecords(pageInfo.getTotal()); jqGridView.setRows(userDTOList); } } catch (Exception e) { e.printStackTrace(); } return jqGridView; } @RequiresPermissions("user:view") @RequestMapping(value = "/findByName", method = RequestMethod.GET) @ResponseBody public ResultJson<User> findByName(String userName) { try { User user = userService.findUserByUserName(userName); if (user == null) { return new ResultJson<User>(true,"用户名不存在"); }else { return new ResultJson<User>(false,"用户名已存在"); } } catch (Exception e) { e.printStackTrace(); return new ResultJson<User>(false,Constant.SYSTEM_ERROR); } } @RequiresPermissions("user:create") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public ResultJson<User> createUser(User user) { try { User checkUser = userService.findUserByUserName(user.getUserName()); if (checkUser == null) { user.setPassword(DigestUtils.sha1Hex(Constant.SALT + user.getPassword())); user.setLocked(false); userService.saveUser(user); return new ResultJson<User>(true,Constant.ADD_SUCCESS); }else { return new ResultJson<User>(false,Constant.ERROR_USERNAME_EXISTS); } } catch (Exception e) { e.printStackTrace(); return new ResultJson<User>(false,Constant.SYSTEM_ERROR); } } @RequiresPermissions("user:update") @RequestMapping(value = "/{id:\\d+}/update", method = RequestMethod.POST) @ResponseBody public ResultJson<User> updateUserForm(@PathVariable long id, String userName,Long organizationId,String roleIds) { try { User user = userService.findUserById(id); User checkUser = userService.findUserByUserName(userName); if(checkUser !=null && !checkUser.getId().equals(user.getId())) { return new ResultJson<User>(false,Constant.ERROR_USERNAME_EXISTS); } user.setUserName(userName); user.setOrganizationId(organizationId); user.setRoleIds(roleIds); userService.updateUser(user); return new ResultJson<User>(true,Constant.UPDATE_SUCCESS); } catch (Exception e) { e.printStackTrace(); return new ResultJson<User>(false,Constant.SYSTEM_ERROR); } } /** * 锁定或解锁用户 * @param ids * @param lock * @return */ @RequiresPermissions("user:update") @RequestMapping(value = "/lock",method = RequestMethod.POST) @ResponseBody public ResultJson<User> lockOrUnLockUser(@RequestParam("ids[]") Long[] ids,@RequestParam("lock") Boolean lock) { try { userService.lockOrUnLockUser(ids, lock); if (lock) { return new ResultJson<User>(true,Constant.LOCK_SUCCESS); }else { return new ResultJson<User>(true,Constant.UNLOCK_SUCCESS); } } catch (Exception e) { e.printStackTrace(); return new ResultJson<User>(false,Constant.SYSTEM_ERROR); } } } ``` OrganizationMapperTest.java ```package com.zhuhai.dao; import com.zhuhai.entity.Organization; import com.zhuhai.mapper.OrganizationMapper; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/6/19 * Time: 12:41 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class OrganizationMapperTest { @Resource private OrganizationMapper organizationMapper; @Test public void testFindById() { long id = 2; Organization organization = organizationMapper.findById(id); System.out.println(organization.getId()); System.out.println(organization.getName()); System.out.println(organization.getAvaliable()); System.out.println(organization.isRootNode()); Assert.assertNotNull(organization); } @Test public void testSaveOrganization(){ Organization organization = new Organization(); organization.setName("分公司12"); organization.setParentId(2l); organization.setParentIds("0/1/"); organization.setParentIds(organization.makeSelfAsParentIds()); organization.setAvaliable(true); organizationMapper.createOrganization(organization); } } ``` Resources.java ```package com.zhuhai.entity; import java.io.Serializable; import java.util.Date; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/6/18 * Time: 23:43 */ public class Resources implements Serializable{ private static final long serialVersionUID = -8451827913855903760L; private Long id; private String name; private ResourceType type; private String url; private String icon; private Long parentId; private String parentIds; private String permission; private Boolean avaliable; private Date updateTime; private Date createTime = new Date(); public static enum ResourceType{ menu("菜单"), button("按钮"); private final String info; ResourceType(String info) { this.info = info; } public String getInfo() { return info; } } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ResourceType getType() { return type; } public void setType(ResourceType type) { this.type = type; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getParentIds() { return parentIds; } public void setParentIds(String parentIds) { this.parentIds = parentIds; } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } public Boolean getAvaliable() { return avaliable; } public void setAvaliable(Boolean avaliable) { this.avaliable = avaliable; } public boolean isRootNode() { return parentId == 0; } public String makeSelfAsParentIds() { return getParentIds() + getParentId() +"/"; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } } ``` UserServiceTest.java ```package com.zhuhai.service; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.util.Set; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/20 * Time: 15:19 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class UserServiceTest { @Resource private UserService userService; @Test public void testFindRolesByUserName(){ String userName = "admin"; Set<String> roles = userService.findRolesByUserName(userName); for (String role : roles) { System.out.println(role); } } @Test public void testFindPermissionByUserName() { String userName = "root"; Set<String> permissions = userService.findPermissionsByUserName(userName); for (String permission : permissions) { System.out.println(permission); } } } ``` UserMapper.java ```package com.zhuhai.mapper; import com.zhuhai.entity.User; import org.apache.ibatis.annotations.Param; import java.util.List; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/16 * Time: 15:18 */ public interface UserMapper { public void createUser(User user); public void updateUser(User user); public void deleteUser(long userId); public User findById(long userId); public List<User> findAll(); public User findByUserName(String userName); public void lockOrUnLockUser(@Param("ids") Long[] ids,@Param("lock") boolean lock); } ``` CommonUtil.java ```package com.zhuhai.utils; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/20 * Time: 14:44 */ public class CommonUtil { public static Long[] stringArray2LongArray(String[] strs){ if (strs == null) { return null; } Long[] longs = new Long[strs.length]; for (int i = 0; i <strs.length ; i++) { longs[i] = Long.valueOf(strs[i]); } return longs; } } ``` UserService.java ```package com.zhuhai.service; import com.github.pagehelper.PageInfo; import com.zhuhai.entity.User; import java.util.Set; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/16 * Time: 15:15 */ public interface UserService { public void saveUser(User user); public void updateUser(User user); public void deleteUser(Long userId); public User findUserById(Long userId); public PageInfo<User> findAllByPage(String sidx, String sord, Integer pageNo, Integer pageSize); public User findUserByUserName(String userName); public Set<String> findRolesByUserName(String userName); public Set<String> findPermissionsByUserName(String userName); public void lockOrUnLockUser(Long[] ids,boolean lock); } ``` Organization.java ```package com.zhuhai.entity; import java.io.Serializable; import java.util.Date; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/6/18 * Time: 23:58 */ public class Organization implements Serializable{ private static final long serialVersionUID = -152896645170865479L; private Long id; private String name; private Long parentId; private String parentIds; private Boolean avaliable; private Date updateTime; private Date createTime = new Date(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getParentIds() { return parentIds; } public void setParentIds(String parentIds) { this.parentIds = parentIds; } public Boolean getAvaliable() { return avaliable; } public void setAvaliable(Boolean avaliable) { this.avaliable = avaliable; } public boolean isRootNode() { return parentId == 0; } public String makeSelfAsParentIds() { return getParentIds() + getParentId() + "/"; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } } ``` ResourcesService.java ```package com.zhuhai.service; import com.zhuhai.entity.Resources; import java.util.List; import java.util.Set; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/20 * Time: 15:04 */ public interface ResourcesService { public void createResource(Resources resources); public void updateResource(Resources resources); public void deleteResource(long id); public Resources findById(long id); public List<Resources> findAll(); public List<Resources> findMenus(Set<String> permissions); } ``` ResourcesMapperTest.java ```package com.zhuhai.dao; import com.zhuhai.entity.Resources; import com.zhuhai.mapper.ResourcesMapper; import 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.SpringJUnit4ClassRunner; import java.util.List; import java.util.Set; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/20 * Time: 13:33 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class ResourcesMapperTest { @Autowired private ResourcesMapper resourcesMapper; @Test public void testFindAll() { List<Resources> list = resourcesMapper.findAll(); for (Resources resources : list) { System.out.println(resources.getId()); System.out.println(resources.getName()); System.out.println(resources.getParentId()); } Assert.assertNotNull(list); } @Test public void testFindByIds(){ Set<String> sets = resourcesMapper.findPermissionsByIds(new Long[]{2l,3l,4l,5l,6l}); for (String set : sets) { System.out.println(set); } } } ``` OrganizationController.java ```package com.zhuhai.controller; import com.zhuhai.dto.ResultJson; import com.zhuhai.dto.TreeDTO; import com.zhuhai.entity.Organization; import com.zhuhai.service.OrganizationService; import com.zhuhai.utils.Constant; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.CollectionUtils; 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.ResponseBody; import javax.annotation.Resource; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/7/5 * Time: 11:05 */ @Controller @RequestMapping("/organization") public class OrganizationController { private static final Logger logger = LoggerFactory.getLogger(OrganizationController.class); @Resource private OrganizationService organizationService; /** * 一次性加载树 * @param model * @return */ @RequiresPermissions("organization:view") @RequestMapping(method = RequestMethod.GET) public String getOrganizationList(Model model) { List<Organization> organizationList = organizationService.findAll(); model.addAttribute("organizationList", organizationList); return "organization/organizationList"; } /** * 异步加载树 * @param id * @return */ @RequiresPermissions("organization:view") @RequestMapping(value = "/load/list", method = RequestMethod.GET) @ResponseBody public List<TreeDTO> loadOrganizations(@RequestParam(value = "id", required = false, defaultValue = "0") long id) { List<TreeDTO> treeDTOList = null; try { List<Organization> organizationList = organizationService.findChildOrganizations(id); treeDTOList = new ArrayList<TreeDTO>(); for (Organization organization : organizationList) { TreeDTO tree = new TreeDTO(); tree.setId(organization.getId()); tree.setpId(organization.getParentId()); tree.setName(organization.getName()); if (!CollectionUtils.isEmpty(organizationService.findChildOrganizations(organization.getId()))) { tree.setIsParent(true); } treeDTOList.add(tree); } } catch (Exception e) { e.printStackTrace(); } return treeDTOList; } /** * 修改organization * @param id * @param name * @return * @throws IOException */ @RequestMapping(value = "/update", method = RequestMethod.POST) @ResponseBody public ResultJson<Organization> updateOrganization(long id, String name) throws IOException { ResultJson<Organization> result; try { Organization organization = organizationService.findById(id); if (organization != null) { organization.setName(name); organizationService.updateOrganization(organization); result = new ResultJson<Organization>(true, Constant.UPDATE_SUCCESS); } else { result = new ResultJson<Organization>(false, Constant.DATA_ERROR); } } catch (Exception e) { logger.error("update organization error", e); result = new ResultJson<Organization>(false, Constant.SYSTEM_ERROR); } return result; } } ``` JqGridView.java ```package com.zhuhai.dto; import java.io.Serializable; import java.util.List; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/7/3 * Time: 23:39 */ public class JqGridView<T> implements Serializable { private static final long serialVersionUID = -5671925815510482631L; //total page private long total; //current page private long page; //total records private long records; // data list private List<T> rows; public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } public long getPage() { return page; } public void setPage(long page) { this.page = page; } public long getRecords() { return records; } public void setRecords(long records) { this.records = records; } public List<T> getRows() { return rows; } public void setRows(List<T> rows) { this.rows = rows; } } ``` RoleMapperTest.java ```package com.zhuhai.dao; import com.zhuhai.entity.Role; import com.zhuhai.mapper.RoleMapper; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.util.Set; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/6/19 * Time: 18:29 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class RoleMapperTest { @Resource private RoleMapper roleMapper; @Test public void testFindById(){ long roleId = 1; Role role = roleMapper.findById(roleId); System.out.println(role.getRole()); Assert.assertNotNull(role); } } ``` DefaultExceptionHandler.java ```package com.zhuhai.exception; import org.springframework.web.bind.annotation.ControllerAdvice; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/6/20 * Time: 22:06 */ @ControllerAdvice public class DefaultExceptionHandler { /** * 无权限异常处理 * @param e * @return */ /* @ExceptionHandler(UnauthorizedException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) public String processsUnAuthorizedException(UnauthorizedException e) { return "redirect:/403"; }*/ /** * 全局异常处理 * @param e * @return */ /*@ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public String processException(Exception e) { if (e instanceof NullPointerException) { return "error/500"; } else if (e instanceof NoHandlerFoundException) { return "error/404"; } else if(e instanceof UnauthorizedException) { return "redirect:/403"; } else { return "error/500"; } }*/ } ``` RoleMapper.java ```package com.zhuhai.mapper; import com.zhuhai.entity.Role; import java.util.List; import java.util.Set; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/6/19 * Time: 0:34 */ public interface RoleMapper { public void createRole(Role role); public void updateRole(Role role); public void deleteRole(long id); public Role findById(long id); public List<Role> findAll(); public Set<String> findResourceIdsByIds(Long[] ids); public Set<String> findRolesByIds(Long[] ids); } ``` Role.java ```package com.zhuhai.entity; import java.io.Serializable; import java.util.Date; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/6/18 * Time: 23:55 */ public class Role implements Serializable{ private static final long serialVersionUID = 6103625113611842274L; private Long id; private String role; private String description; private String resourceIds; private Boolean avaliable; private Date updateTime; private Date createTime = new Date(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getResourceIds() { return resourceIds; } public void setResourceIds(String resourceIds) { this.resourceIds = resourceIds; } public Boolean getAvaliable() { return avaliable; } public void setAvaliable(Boolean avaliable) { this.avaliable = avaliable; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } } ``` Constant.java ```package com.zhuhai.utils; import java.math.BigDecimal; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/22 * Time: 13:36 */ public class Constant { public static final String SALT = "xajf@#afs$@2wefsjf#@ljs2#$@34jf**&8$%#2jisjfe"; public static final String UPDATE_SUCCESS = "修改成功!"; public static final String SYSTEM_ERROR = "系统异常!"; public static final String DATA_ERROR = "数据异常!"; public static final String ADD_SUCCESS = "添加成功!"; public static final String ERROR_USERNAME_EXISTS = "用户名已存在!"; public static final String LOCK_SUCCESS = "用户锁定成功!"; public static final String UNLOCK_SUCCESS = "用户解锁成功!"; public static void main(String[] args) { BigDecimal b1 = new BigDecimal(0); BigDecimal b2 = new BigDecimal(1.0); System.out.println(b1.compareTo(b2)); } } ``` RoleServiceImpl.java ```package com.zhuhai.service.impl; import com.zhuhai.entity.Role; import com.zhuhai.mapper.RoleMapper; import com.zhuhai.service.RoleService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/23 * Time: 14:17 */ @Service public class RoleServiceImpl implements RoleService { @Resource private RoleMapper roleMapper; @Override public void createRole(Role role) { roleMapper.createRole(role); } @Override public void updateRole(Role role) { roleMapper.updateRole(role); } @Override public void deleteRole(long id) { roleMapper.deleteRole(id); } @Override public Role findById(long id) { return roleMapper.findById(id); } @Override public List<Role> findAll() { return roleMapper.findAll(); } } ``` RoleService.java ```package com.zhuhai.service; import com.zhuhai.entity.Role; import java.util.List; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/20 * Time: 15:04 */ public interface RoleService { public void createRole(Role role); public void updateRole(Role role); public void deleteRole(long id); public Role findById(long id); public List<Role> findAll(); } ``` AuthorizationException.java ```package com.zhuhai.exception; /** * Created with IntelliJ IDEA * User: hai * Date: 2016/6/20 * Time: 21:30 */ public class AuthorizationException extends RuntimeException { private static final long serialVersionUID = 952758738954757857L; } ``` ResourcesServiceImpl.java ```package com.zhuhai.service.impl; import com.zhuhai.entity.Resources; import com.zhuhai.mapper.ResourcesMapper; import com.zhuhai.service.ResourcesService; import org.apache.shiro.authz.permission.WildcardPermission; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/23 * Time: 10:55 */ @Service public class ResourcesServiceImpl implements ResourcesService { @Resource private ResourcesMapper resourcesMapper; @Override public void createResource(Resources resources) { resourcesMapper.createResource(resources); } @Override public void updateResource(Resources resources) { resourcesMapper.updateResource(resources); } @Override public void deleteResource(long id) { resourcesMapper.deleteResource(id); } @Override public Resources findById(long id) { return resourcesMapper.findById(id); } @Override public List<Resources> findAll() { return resourcesMapper.findAll(); } @Override public List<Resources> findMenus(Set<String> permissions) { List<Resources> allResources = findAll(); List<Resources> menus = new ArrayList<Resources>(); for (Resources resource : allResources) { if (resource.isRootNode()) { continue; } if (Resources.ResourceType.menu != (resource.getType())) { continue; } if (!hasPermission(permissions,resource)) { continue; } menus.add(resource); } return menus; } private boolean hasPermission(Set<String> permissions,Resources resources) { if (StringUtils.isEmpty(resources.getPermission())) { return true; } for (String permission : permissions) { WildcardPermission p1 = new WildcardPermission(permission); WildcardPermission p2 = new WildcardPermission(resources.getPermission()); if (p1.implies(p2) || p2.implies(p1)) { return true; } } return false; } } ``` UserMapperTest.java ```package com.zhuhai.dao; import com.zhuhai.entity.User; import com.zhuhai.mapper.UserMapper; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; /** * Created with IntelliJ IDEA. * User: zhuhai * Date: 2016/6/20 * Time: 13:32 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class UserMapperTest { @Resource private UserMapper userMapper; @Test public void testFindBy() { String userName = "admin"; User user = userMapper.findByUserName(userName); System.out.println(user.getId()); System.out.println(user.getUserName()); System.out.println(user.getUpdateTime()); Assert.assertNotNull(user); } } ```
zhujun123/TeatApp
zhujun123/TeatApp README.md ```# TeatApp 测试使用的仓库 ```
zhujunwei1994/WWTVideoPlay
zhujunwei1994/WWTVideoPlay VideoPlay.java ```package com.cvim.v.play1; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.LinearLayout; import android.widget.MediaController; import android.widget.TextView; import android.widget.VideoView; import com.cvim.v.play.R; import com.cvim.v.play.ReadVideoFile; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class VideoPlay extends AppCompatActivity { private VideoView mPlayVideo; private LinearLayout mWelcome_tv; private LinearLayout mVideo_area; //解析出来的所有需要播放的视频文件 private ArrayList<File> playVideoList = new ArrayList<>(); public void setPlayVideoList(ArrayList<File> playVideoList) { this.playVideoList = playVideoList; } private int videoIndex = 0; private LinearLayout otherArea; private LinearLayout videoArea; ArrayList<File> tempFiles; int UPDATE_VIDEO_LIST = 8; int ClEAN_ALL_VIDEO_FILE_DATA = 9; int keyDownCount = 0; public Handler mHanlderUpdateVideoList = new Handler() { @Override public void handleMessage(Message msg) { int msgWhat = msg.what; videoIndex = 0; Log.i("play", "视频数据已经更新同步 请同步..... msgWhat = "+msgWhat); if (msgWhat == ClEAN_ALL_VIDEO_FILE_DATA) { mPlayVideo.pause(); playVideoList.clear(); mVideo_area.setVisibility(View.GONE); mWelcome_tv.setVisibility(View.VISIBLE); }else if (msgWhat == UPDATE_VIDEO_LIST) { if (null!=ReadVideoFiles.getmVideoMP4File()&&ReadVideoFiles.getmVideoMP4File().size()>0) { setPlayVideoList(ReadVideoFiles.getmVideoMP4File()); // Collections.sort(playVideoList); updateVideoList(); } } } }; void updateVideoList(){ Log.i("play", "数据已经更新同步 即将播放.....playVideoList = "+playVideoList.size()); if (playVideoList.size()==0) { Log.i("play", "01 -视频数据为空 .....playVideoList = "+playVideoList.size()); mPlayVideo.pause(); mVideo_area.setVisibility(View.GONE); mWelcome_tv.setVisibility(View.VISIBLE); return; }else { Log.i("play", "02 - 视频数据更新已同步 播放.....playVideoList = "+playVideoList.size()); mVideo_area.setVisibility(View.VISIBLE); mWelcome_tv.setVisibility(View.GONE); mPlayVideo.setVideoURI(Uri.parse(playVideoList.get(0).getPath())); mPlayVideo.start(); // for (File f:playVideoList) // { // Log.i("play", "mHanlderUpdateVideoList f.name = " + f.getName() + " f.path = " + f.getPath()); // } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_play); Log.i("play","VideoPlay onCreate"); initView(); initData(); } void initData() { int index = getIntent().getIntExtra("index",0); Log.i("play","oncreate index = "+index); ReadVideoFiles.setmVideoPlay(this); ReadManager.init(this,index); } void initView(){ mPlayVideo = (VideoView)findViewById(R.id.vv_play); mWelcome_tv = (LinearLayout)findViewById(R.id.welcome_tv); mVideo_area = (LinearLayout)findViewById(R.id.video_area); mWelcome_tv.setVisibility(View.GONE); MediaController mc = new MediaController(this); mc.setVisibility(View.GONE); mPlayVideo.setMediaController(mc); mPlayVideo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { playNext(true); } }); mPlayVideo.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { playNext(true); return true; } }); } @Override public boolean dispatchKeyEvent(KeyEvent event) { // Log.i("play","getDownTime = "+event.getDownTime()+" getEventTime = "+event.getEventTime()+" continueTime = "+(event.getEventTime()-event.getDownTime())+" event.getScanCode() = "+ event.getScanCode()); if (playVideoList.size()==0) { mPlayVideo.pause(); mVideo_area.setVisibility(View.GONE); mWelcome_tv.setVisibility(View.VISIBLE); }else { mVideo_area.setVisibility(View.VISIBLE); mWelcome_tv.setVisibility(View.GONE); } if (event.getAction() == KeyEvent.ACTION_DOWN) { Log.i("play","keycode = "+event.getKeyCode()+" event.getAction = "+event.getAction()+" event.getRepeatCount = "+event.getRepeatCount()); if ( event.getRepeatCount() == 11 &&event.getKeyCode() == KeyEvent.KEYCODE_BACK) { finish(); return true; } if (event.getRepeatCount() == 11 && event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT ) { playNext(false); return true; } if (event.getRepeatCount() ==11 && event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) { playNext(true); return true; } } if (handlerKeys(event)) return true; // 组合键 处理方式 return super.dispatchKeyEvent(event); } void playNext(Boolean direction) { Log.i("play","*********************************************************************************"); if (playVideoList.size()==0) return; videoIndex = videoIndex+( direction?1:-1); if (videoIndex >= playVideoList.size())videoIndex = 0; else if (videoIndex == -1) videoIndex = playVideoList.size()-1; Log.i("play"," playVideoFiles.size = "+playVideoList.size()+" direction = "+direction); Log.i("play","*************************************************************************************************************"); for (File f:playVideoList) { Log.i("play", "videoPlay playNext f.name = " + f.getName() + " f.path = " + f.getPath()); } Log.i("play","**************************************************************************************************************"); Log.i("play","playNext videoIndex = "+videoIndex+" getName = "+playVideoList.get(videoIndex).getName()+" playVideoList.get(videoIndex).getPath() ="+playVideoList.get(videoIndex).getPath()); mPlayVideo.setVideoURI( Uri.parse(playVideoList.get(videoIndex).getPath())); mPlayVideo.start(); } /** * 0:a : 左右上 1: b : 左右下 * 2: b : 上下左 3: c : 上下右 4: d : 左左右右 * public static final int KEYCODE_DPAD_UP = 19; * public static final int KEYCODE_DPAD_DOWN = 20; * public static final int KEYCODE_DPAD_LEFT = 21; * public static final int KEYCODE_DPAD_RIGHT = 22; */ long[] mHits = new long[3]; int[] mkeys = new int[3]; int[] keys = {KeyEvent.KEYCODE_DPAD_UP , KeyEvent.KEYCODE_DPAD_DOWN , KeyEvent.KEYCODE_DPAD_LEFT}; int[] keysUP = {KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_UP}; int[] keysDown = {KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_DOWN}; int[] keysLeft = {KeyEvent.KEYCODE_DPAD_UP , KeyEvent.KEYCODE_DPAD_DOWN , KeyEvent.KEYCODE_DPAD_LEFT}; int[] keysRight = {KeyEvent.KEYCODE_DPAD_UP , KeyEvent.KEYCODE_DPAD_DOWN , KeyEvent.KEYCODE_DPAD_RIGHT}; int[] keysA = {KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_UP}; int[] keysB = {KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_DOWN}; int[] keysC = {KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_LEFT}; int[] keysD = {KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_RIGHT}; int[] keysABC = {KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_CENTER}; int[] keysABC1 = {KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT}; int[] keysMoreFounction = {KeyEvent.KEYCODE_DPAD_LEFT , KeyEvent.KEYCODE_DPAD_UP , KeyEvent.KEYCODE_DPAD_RIGHT}; boolean handlerKeys(KeyEvent event) { int keyCode = event.getKeyCode(); if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_LEFT||keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)) { System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1); System.arraycopy(mkeys, 1, mkeys, 0, mkeys.length - 1); mkeys[mkeys.length - 1] = event.getKeyCode(); mHits[mHits.length - 1] = SystemClock.uptimeMillis(); if (mHits[0] >= (SystemClock.uptimeMillis() - 10000)) { if (Arrays.equals(mkeys, keysA)) { // left right up 0->A ReadVideoFiles.mHandler.sendEmptyMessage(0); return true; }else if (Arrays.equals(mkeys,keysB )) { // left right down B->1 ReadVideoFiles.mHandler.sendEmptyMessage(1); return true; }else if (Arrays.equals(mkeys, keysC)) { // up down left c-> 2 ReadVideoFiles.mHandler.sendEmptyMessage(2); return true; } else if (Arrays.equals(mkeys, keysD)) { //up down right d->3 ReadVideoFiles.mHandler.sendEmptyMessage(3); return true; } else if (Arrays.equals(mkeys, keysABC1)) { // left up right 4 ReadVideoFiles.mHandler.sendEmptyMessage(4); return true; } } } return super.dispatchKeyEvent(event); } boolean mutliKeys(KeyEvent event) { if (Arrays.equals(mkeys, keysUP)) { // left right up 0 ReadVideoFiles.mHandler.sendEmptyMessage(0); return true; }else if (Arrays.equals(mkeys,keysDown )) { // left right down 1 ReadVideoFiles.mHandler.sendEmptyMessage(1); return true; }else if (Arrays.equals(mkeys, keysLeft)) { // up down left 2 ReadVideoFiles.mHandler.sendEmptyMessage(2); return true; } else if (Arrays.equals(mkeys, keysRight)) { //up down right 3 ReadVideoFiles.mHandler.sendEmptyMessage(3); return true; } else if (Arrays.equals(mkeys, keysMoreFounction)) { // left up right 4 ReadVideoFiles.mHandler.sendEmptyMessage(4); return true; } return super.dispatchKeyEvent(event); } boolean longPressKey(KeyEvent event) { if ((event.getRepeatCount() == 10 ||event.getRepeatCount() == 11)&& event.getAction() == KeyEvent.ACTION_DOWN &&event.getKeyCode()==KeyEvent.KEYCODE_DPAD_LEFT) { Log.i("play","你已经长按了 返回键----12 KEYCODE_DPAD_LEFT event.getRepeatCount() = "+ event.getRepeatCount()); ReadVideoFiles.mHandler.sendEmptyMessage(0); return true; } if ((event.getRepeatCount() == 10 ||event.getRepeatCount() == 11)&& event.getAction() == KeyEvent.ACTION_DOWN &&event.getKeyCode()==KeyEvent.KEYCODE_DPAD_UP) { Log.i("play","你已经长按了 返回键----12 KEYCODE_DPAD_UP event.getRepeatCount() = "+ event.getRepeatCount()); ReadVideoFiles.mHandler.sendEmptyMessage(1); return true; } if ((event.getRepeatCount() == 10 ||event.getRepeatCount() == 11)&& event.getAction() == KeyEvent.ACTION_DOWN &&event.getKeyCode()==KeyEvent.KEYCODE_DPAD_RIGHT) { Log.i("play","你已经长按了 返回键----12 KEYCODE_DPAD_RIGHT event.getRepeatCount() = "+ event.getRepeatCount()); ReadVideoFiles.mHandler.sendEmptyMessage(2); return true; } if ((event.getRepeatCount() == 10 ||event.getRepeatCount() == 11)&& event.getAction() == KeyEvent.ACTION_DOWN &&event.getKeyCode()==KeyEvent.KEYCODE_DPAD_DOWN) { Log.i("play","你已经长按了 返回键----12 KEYCODE_DPAD_DOWN event.getRepeatCount() = "+ event.getRepeatCount()); ReadVideoFiles.mHandler.sendEmptyMessage(3); return true; } return super.dispatchKeyEvent(event); } @Override protected void onStart() { Log.i("play","VideoPlay onStart"); super.onStart(); } @Override protected void onResume() { Log.i("play","VideoPlay onResume"); ReadManager.initRegisterUSB(); super.onResume(); } @Override protected void onPause() { Log.i("play","VideoPlay onPause"); ReadManager.unRegisterReceiver(); super.onPause(); } @Override protected void onDestroy() { Log.i("play","VideoPlay onDestroy"); // ReadManager.unRegisterReceiver(); super.onDestroy(); } } ``` CompareName.java ```package com.cvim.v.play1; import java.io.File; import java.util.Comparator; public class CompareName implements Comparator<File> { @Override public int compare(File file1, File file2) { int flag = file1.getName().compareTo(file2.getName()); // if (flag == 1) // { // flag = -1; // } return flag; } } ``` BootComplementReceiver.java ```package com.cvim.v.play.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import com.cvim.v.play1.VideoPlay; public class BootComplementReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i("main","--BootComplementReceiver-----intent.getAction = "+intent.getAction()); if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { Intent intent1 = new Intent(context, VideoPlay.class); // context.startActivity(intent1); } } } ``` ReceiverHelper.java ```package com.cvim.v.play.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; public class ReceiverHelper { private Context mContext; private IntentFilter mFilter; private MyReceiver mMyReceiver; class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i("main","--MyReceiver-----intent.getAction = "+intent.getAction()); if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { // Intent intent1 = new Intent(mContext, VideoPlay.class); //mContext.startActivity(intent1); } } } public ReceiverHelper(Context mConttext) { this.mContext = mConttext; } public void register() { mMyReceiver = new MyReceiver(); mFilter = new IntentFilter(); mFilter.addAction(Intent.ACTION_BOOT_COMPLETED); mContext.registerReceiver(mMyReceiver,mFilter); } public void unRegister() { mContext.unregisterReceiver(mMyReceiver); } } ``` MainActivity.java ```package com.cvim.v.play; import android.content.Intent; import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private TextView mVideoPath; private ListView mLvVideoList; private USBHelper mHelper; private VideoListAdapter adapter; private ReadVideoFile readVideoFile; // selected area private ListView mLvSelected; private int SELECTED_ITEM = 5; private VideoListSelectedAdapter mSelectedAdapter; private ArrayList<File> mSelectedVideoItem = new ArrayList<File>(); private ArrayList<File> mVideoLists =new ArrayList<File>(); // ok cancel private Button mOkBtn; private Button mCancelBtn; private File mParentFiles; private int selectedItemPosition = 0; private ListView mSelectedVideoLV; int SLVIDEOFILE = 6; SelectedVideoListAdapter mSelectedVideoFileAdapter; Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { int what = msg.what; if (SLVIDEOFILE==what) { slVideoFile.clear(); mSelectedVideoFileAdapter = new SelectedVideoListAdapter(paserAllVideoFile(mSelectedVideoItem.size())); Log.i("main", "mVideoLists.size = " + mSelectedVideoItem.size() + " slVideoFile.size = " + slVideoFile.size()); mSelectedVideoLV.setAdapter(mSelectedVideoFileAdapter); mSelectedVideoFileAdapter.notifyDataSetChanged(); }else if (what == SELECTED_ITEM&&mSelectedVideoItem.size()>0) { mSelectedAdapter = new VideoListSelectedAdapter(mSelectedVideoItem); mLvSelected.setAdapter(mSelectedAdapter); mSelectedAdapter.notifyDataSetChanged(); }else if (what == 500) // 从Sdcard 读取数据完成 { if (null!=readVideoFile&&null != readVideoFile.filesData) { mVideoLists = readVideoFile.filesData; mVideoPath.setText(mVideoLists.get(0).getAbsolutePath()); adapter = new VideoListAdapter(mVideoLists); mLvVideoList.setAdapter(adapter); adapter.notifyDataSetChanged(); } }else if (what == 200) // 读取usb数据完成 { if (null!=mHelper&&null!=mHelper.fileData&&mHelper.fileData.size()>0) { mVideoPath.setText(mHelper.fileData.get(0).getAbsolutePath()); adapter = new VideoListAdapter(mHelper.fileData); mLvVideoList.setAdapter(adapter); adapter.notifyDataSetChanged(); } }else if (what == 400) // 读取数据完成 { if (null!=adapter) { mVideoPath.setText("没有视频文件"); adapter.mData.clear(); adapter.notifyDataSetChanged(); } } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); // 读取U盘里面的数据 mHelper = new USBHelper(MainActivity.this,this); mHelper.init(); //readLocalData(); } void readLocalData() { //首先先检车Sdcard是否存在 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ readVideoFile = new ReadVideoFile(this,this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if ( readVideoFile.isGrantExternalRW(this)) { readVideoFile.readFile(); } }else { readVideoFile.readFile(); } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getAction()== KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_BACK) { if (mParentFiles == null|| mVideoLists ==null) { finish(); return true; } if ( "/storage/emulated/0".equals(mParentFiles.getPath()) ||"/storage/emulated/0".equals(mVideoLists.get(0).getParentFile().getPath())) { finish(); return true; } if (mVideoLists.isEmpty() ) { mVideoLists = readVideoFile.parseFileList(mParentFiles.getParentFile().listFiles()); mVideoPath.setText(mParentFiles.getAbsolutePath()); adapter.setmData(mVideoLists); }else { mVideoLists = readVideoFile.parseFileList(mVideoLists.get(0).getParentFile().getParentFile().listFiles()); // mVideoPath.setText(mVideoLists.get(0).getAbsolutePath()); adapter.setmData(mVideoLists); } adapter.notifyDataSetChanged(); return true; } if (event.getRepeatCount() == 12) { Log.i("main","currentitem = "+mVideoLists.get(selectedItemPosition)); if (mVideoLists.get(selectedItemPosition).isDirectory()&&event.getKeyCode()==KeyEvent.KEYCODE_DPAD_LEFT) { Log.i("main","--->currentitem = "+mVideoLists.get(selectedItemPosition)); mVideoPath.setText(mVideoLists.get(selectedItemPosition).getAbsolutePath()); mSelectedVideoItem.add(mVideoLists.get(selectedItemPosition)); mHandler.sendEmptyMessage(SELECTED_ITEM); mHandler.sendEmptyMessageDelayed(SLVIDEOFILE,100); } return true; } return super.onKeyDown(keyCode, event); } private void initView() { mVideoPath = (TextView)findViewById(R.id.video_path); mLvVideoList = (ListView)findViewById(R.id.lv_video_list); mLvVideoList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (mVideoLists.size()<position) return; // selectedItemPosition = position; mVideoPath.setText(mVideoLists.get(position).getAbsolutePath()); mParentFiles = mVideoLists.get(position); Log.i("main","onItemSelected position = "+position+" selectedItemPosition = "+selectedItemPosition+" mParentFiles = "+mParentFiles.getPath()); } @Override public void onNothingSelected(AdapterView<?> parent) { Log.i("main","onNothingSelected ------- = "); } }); mLvVideoList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mVideoLists.size()<position) return; if (!mVideoLists.get(position).isDirectory()) return; if (mVideoLists.get(position).listFiles().length == 0) return; mParentFiles = mVideoLists.get(position); mVideoLists = readVideoFile.parseFileList(mVideoLists.get(position).listFiles()); adapter.setmData(mVideoLists); adapter.notifyDataSetChanged(); // mVideoPath.setText(mVideoLists.get(position).getAbsolutePath()); // mSelectedVideoItem.add(mVideoLists.get(position)); // mHandler.sendEmptyMessage(SELECTED_ITEM); } }); mLvSelected = (ListView)findViewById(R.id.lv_selected); mOkBtn = (Button)findViewById(R.id.ok_btn); mOkBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i("main","**********************ok ***mSelectedVideoItem ****************"); if (mSelectedVideoItem.size()>0) { Log.i("main","**********************ok ***mSelectedVideoItem *************mSelectedVideoItem = "+mSelectedVideoItem.size()); for (File f: mSelectedVideoItem) { Log.i("main","mOkBtn.setOnClickListener f.name = "+f.getName()+" f.path = "+f.getPath()+" f.getABSPath = "+f.getAbsolutePath() ); } Intent intent = new Intent(MainActivity.this,VideoPlay.class); Bundle bundle = new Bundle(); bundle.putSerializable("selectedFile",mSelectedVideoItem); intent.putExtra("files",bundle); startActivity(intent); }else { Toast.makeText(MainActivity.this,"播放列表为空、请重新选择需要播放的文件",Toast.LENGTH_SHORT).show(); } } }); mCancelBtn = (Button)findViewById(R.id.cancel_btn); mCancelBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (null != mSelectedVideoItem&&mSelectedVideoItem.size()>0) { Log.i("main","**************cancel ***********mSelectedVideoItem ****************"); mSelectedVideoItem.clear(); mSelectedAdapter.mData.clear(); mSelectedAdapter.notifyDataSetChanged(); mSelectedVideoItem.clear(); mSelectedVideoFileAdapter.mData.clear(); mSelectedVideoFileAdapter.notifyDataSetChanged(); }else if (mSelectedVideoItem.isEmpty()) { Toast.makeText(MainActivity.this,"请重新选择播放的文件",Toast.LENGTH_SHORT).show(); } } }); mSelectedVideoLV = (ListView)findViewById(R.id.lv_selected_video_filelist); } private class VideoListAdapter extends BaseAdapter { public void setmData(ArrayList<File> mData) { this.mData = mData; } private ArrayList <File>mData; public VideoListAdapter(ArrayList mData) { this.mData = mData; } @Override public int getCount() { return null!=mData&&mData.size()>0?mData.size():0; } @Override public Object getItem(int position) { return mData!=null&&mData.size()>0?mData.get(position):null; } @Override public long getItemId(int position) { return null!=mData?position:0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (null == convertView) { convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.video_list_item, null); viewHolder = new ViewHolder(); viewHolder.viewName = convertView.findViewById(R.id.video_item); viewHolder.videoPath = convertView.findViewById(R.id.video_item_path); convertView.setTag(viewHolder); }else { viewHolder = (ViewHolder)convertView.getTag(); } viewHolder.viewName.setText(mData!=null?mData.get(position).getName():"123"); // viewHolder.videoPath.setText(mData!=null?mData.get(position).getAbsolutePath():"123"); return convertView; } class ViewHolder { TextView viewName; TextView videoPath; } } private class VideoListSelectedAdapter extends BaseAdapter { private ArrayList <File>mData; public VideoListSelectedAdapter(ArrayList mData) { this.mData = mData; } @Override public int getCount() { return null!=mData&&mData.size()>0?mData.size():0; } @Override public Object getItem(int position) { return mData!=null?mData.get(position):null; } @Override public long getItemId(int position) { return null!=mData&&mData.size()>0?position:0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (null == convertView) { convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.video_list_selected_item, null); viewHolder = new ViewHolder(); viewHolder.viewName = convertView.findViewById(R.id.video_seleceted_item); viewHolder.videoPath = convertView.findViewById(R.id.video_Selected_item_path); convertView.setTag(viewHolder); }else { viewHolder = (ViewHolder)convertView.getTag(); } viewHolder.viewName.setText(mData!=null?mData.get(position).getName():"**************"); // viewHolder.videoPath.setText(mData!=null?mData.get(position).getAbsolutePath():""); return convertView; } class ViewHolder { TextView viewName; TextView videoPath; } } private class SelectedVideoListAdapter extends BaseAdapter { public void setmData(ArrayList<File> mData) { this.mData = mData; } private ArrayList <File>mData; public SelectedVideoListAdapter(ArrayList mData) { this.mData = mData; } @Override public int getCount() { return null!=mData&&mData.size()>0?mData.size():0; } @Override public Object getItem(int position) { return mData!=null&&mData.size()>0?mData.get(position):null; } public ArrayList<File> getmData() { return mData; } @Override public long getItemId(int position) { return null!=mData?position:0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (null == convertView) { convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.selected_video_list_item, null); viewHolder = new ViewHolder(); viewHolder.viewName = convertView.findViewById(R.id.seleceted_video_list_item_name); viewHolder.videoPath = convertView.findViewById(R.id.selected_video_list_item_path); convertView.setTag(viewHolder); }else { viewHolder = (ViewHolder)convertView.getTag(); } viewHolder.viewName.setText(mData!=null?mData.get(position).getName():"123"); // viewHolder.videoPath.setText(mData!=null?mData.get(position).getAbsolutePath():"123"); return convertView; } class ViewHolder { TextView viewName; TextView videoPath; } } @Override protected void onDestroy() { // mHelper.unRegisterReceiver(); super.onDestroy(); } ArrayList <File>slVideoFile = new ArrayList<File>(); ArrayList<File> paserAllVideoFile(int count) { if (count ==0) return null; if (count>mSelectedVideoItem.size()) count=mSelectedVideoItem.size(); for (int i = 0; i<count;i++) { paraseVideFile(mSelectedVideoItem.get(i)); } return slVideoFile; } void paraseVideFile(File file) { File[] files = file.listFiles(); for (File f :files){ if (f.getName().endsWith(".mp4") ||f.getName().endsWith(".wma") ||f.getName().endsWith(".ogg") ||f.getName().endsWith(".pcm") ||f.getName().endsWith(".m4a") ||f.getName().endsWith(".ac3") ||f.getName().endsWith(".ec3") ||f.getName().endsWith(".dtshd") ||f.getName().endsWith(".wav") ||f.getName().endsWith(".rm") ||f.getName().endsWith(".ra") ||f.getName().endsWith(".cd") ||f.getName().endsWith(".amr") ||f.getName().endsWith(".dts") ||f.getName().endsWith(".dts") ||f.getName().endsWith(".midi") ||f.getName().endsWith(".snd") ||f.getName().endsWith(".vqf") ||f.getName().endsWith(".cda") ||f.getName().endsWith(".aiff")) { slVideoFile.add(f); } } } void startPlayVideo(int position) { if (null!=mHelper.fileData) { Intent intent = new Intent(MainActivity.this,VideoPlay.class); Bundle bundle = new Bundle(); bundle.putSerializable("viideoList",mHelper.fileData); intent.putExtra("position",position); intent.putExtra("video",bundle); startActivity(intent); } } } ``` ReadVideoFiles.java ```package com.cvim.v.play1; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.hardware.usb.UsbManager; import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; public class ReadVideoFiles { public static int indexFile = 0; public static int parseCount = 0; public static VideoPlay mVideoPlay; public static void setmVideoPlay(VideoPlay mVideoPlay) { ReadVideoFiles.mVideoPlay = mVideoPlay; } private static ArrayList<File> mMultixDirtory = new ArrayList<>(); private static ArrayList<File> mVideoMP4File = new ArrayList<>(); private static Activity mContext; public static ArrayList<File> getmVideoMP4File() { return mVideoMP4File; } public static void setIndex(int index) { ReadVideoFiles.indexFile = index; } public static Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { int msgIndex = msg.what; indexFile= 0; Log.i("play","readVdeioFile mHandler msgIndex = "+msgIndex+" indexFile = "+indexFile+" mMultixDirtory.size = "+mMultixDirtory.size()); mVideoMP4File.clear(); // 次解析之前清除上一次留下的数据 if(msgIndex==0){ //A parseCount = 1; if (mMultixDirtory.size()>0) { parseAllVideoFileItems(mMultixDirtory.get(0).listFiles()); }else { mVideoPlay.mHanlderUpdateVideoList.sendEmptyMessage(mVideoPlay.ClEAN_ALL_VIDEO_FILE_DATA); } }else if(msgIndex==1){ parseCount = 1; if (mMultixDirtory.size()>=2){ parseAllVideoFileItems(mMultixDirtory.get(1).listFiles()); ////B }else { mVideoPlay.mHanlderUpdateVideoList.sendEmptyMessage(mVideoPlay.ClEAN_ALL_VIDEO_FILE_DATA); } }else if(msgIndex==2){ parseCount = 1; if (mMultixDirtory.size()>=3){ parseAllVideoFileItems(mMultixDirtory.get(2).listFiles()); //C }else { mVideoPlay.mHanlderUpdateVideoList.sendEmptyMessage(mVideoPlay.ClEAN_ALL_VIDEO_FILE_DATA); } }else if(msgIndex==3){ parseCount = 1; if (mMultixDirtory.size()>=4){ parseAllVideoFileItems(mMultixDirtory.get(3).listFiles()); // D } }else if(msgIndex==4){ parseCount = 3; if (mMultixDirtory.size()>0) { paserAllVideoFile(3); // //ABC 目录循环 }else { mVideoPlay.mHanlderUpdateVideoList.sendEmptyMessage(mVideoPlay.ClEAN_ALL_VIDEO_FILE_DATA); } } Log.i("play","readVdeioFile mHandler msgIndex = "+msgIndex+" indexFile = "+indexFile+" parseCount = "+parseCount); } }; public static void reset(){ if (mMultixDirtory!=null) mMultixDirtory.clear(); if (mVideoMP4File!=null) mVideoMP4File.clear(); //if (null!=mVideoPlay) mVideoPlay.mHanlderUpdateVideoList.sendEmptyMessage(mVideoPlay.ClEAN_ALL_VIDEO_FILE_DATA); } public static void initPermission(Activity context) { mContext= context; if (!ReadManager.isMntUsb) { // readInternalStorage(context); } } public static void readInternalStorage(Activity context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) { if (isGrantExternalRW(context)){ readFile(); } }else { readFile(); } } public static boolean isGrantExternalRW(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { activity.requestPermissions(new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1); return false; } return true; } public static void setmMultixDirtory(ArrayList<File> mMultixDirtory) { ReadVideoFiles.mMultixDirtory = mMultixDirtory; } public static void readFile() { String videosPath = Environment.getExternalStorageDirectory().getPath() + File.separator + "video/"; // Log.i("play", "readFile videosPath = "+videosPath); File videosFile = new File(videosPath); // Log.i("play", "readFile videosFile = "+videosFile.exists()); if (!videosFile.exists()) return; File[] subVideoFiles = videosFile.listFiles(); if (subVideoFiles == null || subVideoFiles.length == 0) return; parseAllFiles(subVideoFiles); } public static void parseAllFiles(File[] subVideoFiles) { for (File f : subVideoFiles) { if (f.isDirectory()) { // Log.i("play", "readFile f.name = " + f.getName() + " f.path = " + f.getPath() + " f.getABSPath = " + f.getAbsolutePath()); mMultixDirtory.add(f); } } } public static void paserAllVideoFile(int count) { mVideoMP4File.clear(); // 次解析之前清除上一次留下的数据 if (count >=mMultixDirtory.size()) { count = mMultixDirtory.size(); parseCount = count; } for (int i = 0; i < count; i++) { if (mMultixDirtory.get(i).listFiles() != null || mMultixDirtory.get(i).listFiles().length != 0) { parseAllVideoFileItems(mMultixDirtory.get(i).listFiles()); } } } public static void parseAllVideoFileItems(File[] files) { // Log.i("play", " parseAllVideoFileItems indexFile = "+indexFile); for (File f : files) { if (f.getName().endsWith(".mp4") || f.getName().endsWith(".wma") || f.getName().endsWith(".ogg") || f.getName().endsWith(".pcm") || f.getName().endsWith(".m4a") || f.getName().endsWith(".mov") || f.getName().endsWith(".ac3") || f.getName().endsWith(".ec3") || f.getName().endsWith(".dtshd") || f.getName().endsWith(".wav") || f.getName().endsWith(".rm") || f.getName().endsWith(".ra") || f.getName().endsWith(".cd") || f.getName().endsWith(".amr") || f.getName().endsWith(".dts") || f.getName().endsWith(".dts") || f.getName().endsWith(".midi") || f.getName().endsWith(".snd") || f.getName().endsWith(".vqf") || f.getName().endsWith(".cda") || f.getName().endsWith(".aiff")) { mVideoMP4File.add(f); // Log.i("play", "parseFileList f.name = " + f.getName() + " f.path = " + f.getPath() + " f.getABSPath = " + f.getAbsolutePath()+" f = "+f.lastModified()); } } if (null!=mVideoPlay) { indexFile++; if (parseCount == indexFile) { // Collections.sort(mVideoMP4File); Collections.sort(mVideoMP4File,new CompareName()); Log.i("play", "数据解析完成 刷新播放列表 mVideoMP4File.size = "+mVideoMP4File.size()); if (mVideoMP4File.size() == 0) { mVideoPlay.mHanlderUpdateVideoList.sendEmptyMessage(mVideoPlay.ClEAN_ALL_VIDEO_FILE_DATA); }else { mVideoPlay.mHanlderUpdateVideoList.sendEmptyMessage(mVideoPlay.UPDATE_VIDEO_LIST); } } Log.i("play", "parseFileList parseCount = " +parseCount + " indexFile = "+indexFile); } } } ``` ReadVideoFile.java ```package com.cvim.v.play; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.Environment; import android.util.Log; import java.io.File; import java.util.ArrayList; public class ReadVideoFile { private Context mContext; private MainActivity mainActivity; public ArrayList<File> filesData = new ArrayList<File>(); public ReadVideoFile(Context mContext,MainActivity mainActivity) { this.mContext = mContext; this.mainActivity = mainActivity; } public boolean isGrantExternalRW(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { activity.requestPermissions(new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1); return false; } return true; } void readFile() { String filepath = Environment.getExternalStorageDirectory().getPath(); File[] files = Environment.getExternalStorageDirectory().getAbsoluteFile().listFiles();//new File(filepath); filesData = parseFileList(files); if (filesData.size()>0) { mainActivity.mHandler.sendEmptyMessage(500); } } ArrayList<File> parseFileList(File[] files) { ArrayList<File> tempFiles = new ArrayList<File>(); if (null== files) return null; for (File f: files) { Log.i("main","readFile f.name = "+f.getName()+" f.path = "+f.getPath()+" f.getABSPath = "+f.getAbsolutePath() ); // if (f.isDirectory()) { tempFiles.add(f); } } return tempFiles; } } ``` PlayHelper.java ```package com.cvim.v.play1; import android.content.Intent; import android.util.Log; import android.view.View; import android.widget.Button; import com.cvim.v.play.R; public class PlayHelper implements View.OnClickListener { PlayActivity mPlayActivity; private Button mBtn_a; private Button mBtn_b; private Button mBtn_c; private Button mBtn_d; private Button mBtn_m; public PlayHelper(PlayActivity mPlayActivity) { this.mPlayActivity = mPlayActivity; initView(); } void initView() { mBtn_a = (Button)mPlayActivity.findViewById(R.id.video_item_a); mBtn_b = (Button)mPlayActivity.findViewById(R.id.video_item_b); mBtn_c = (Button)mPlayActivity.findViewById(R.id.video_item_c); mBtn_d = (Button)mPlayActivity.findViewById(R.id.video_item_d); mBtn_m = (Button)mPlayActivity.findViewById(R.id.video_item_m); mBtn_a.setOnClickListener(this); mBtn_b.setOnClickListener(this); mBtn_c.setOnClickListener(this); mBtn_d.setOnClickListener(this); mBtn_m.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = new Intent(mPlayActivity,VideoPlay.class); Log.i("play","02 USBHelper readFileDa mntUsbRoot ReadManager.isUExist() = "+ReadManager.isUExist()); if (!ReadManager.isUExist()) return; Log.i("play","02 USBHelper readFileDa mntUsbRoot ReadManager.isUExist() = "+ReadManager.isUExist()); switch (v.getId()) { case R.id.video_item_a: // ReadVideoFiles.mHandler.sendEmptyMessage(0); intent.putExtra("index",0); Log.i("play","video_item_a"); break; case R.id.video_item_b: intent.putExtra("index",1); // ReadVideoFiles.mHandler.sendEmptyMessage(1); Log.i("play","video_item_b"); break; case R.id.video_item_c: intent.putExtra("index",2); // ReadVideoFiles.mHandler.sendEmptyMessage(2); Log.i("play","video_item_c"); break; case R.id.video_item_d: intent.putExtra("index",3); // ReadVideoFiles.mHandler.sendEmptyMessage(3); Log.i("play","video_item_d"); break; case R.id.video_item_m: intent.putExtra("index",4); // ReadVideoFiles.mHandler.sendEmptyMessage(4); Log.i("play","video_item_m"); break; } mPlayActivity.startActivity(intent); } } ``` VideoPlay.java ```package com.cvim.v.play; import android.media.MediaPlayer; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.widget.LinearLayout; import android.widget.VideoView; import java.io.File; import java.lang.reflect.Array; import java.util.ArrayList; public class VideoPlay extends AppCompatActivity { private VideoView mPlayVideo; private ArrayList <File>videoData; private int videoIndex = 0; private LinearLayout otherArea; private LinearLayout videoArea; ArrayList<File> tempFiles; private int mPaserFileCount = 1; // 从activity传递过来的所有文件夹 private ArrayList <File>mMultixFile; //解析出来的所有需要播放的视频文件 private ArrayList<File> playVideoFiles = new ArrayList<File>(); // 最大解析文件数量 private int mMaxParseFilseCount; // 用户选择解析文件索引 private int mUserSelectedIndex = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_play_main); initView(); Bundle bundle = getIntent().getBundleExtra("files"); if (bundle!=null) { mMultixFile = (ArrayList<File>) bundle.get("selectedFile"); if (null !=mMultixFile) { mMaxParseFilseCount = mMultixFile.size(); paserAllVideoFile(mMaxParseFilseCount); if (!playVideoFiles.isEmpty()) { Log.i("main","paraseVideFile videoIndex = "+videoIndex+" playVideoFiles.size = "+playVideoFiles.size()+"playVideoFiles.get(0).getPath() = "+playVideoFiles.get(0).getPath()); mPlayVideo.setVideoURI( Uri.parse(playVideoFiles.get(0).getPath())); mPlayVideo.start(); }else { finish(); } } } } void paserAllVideoFile(int count) { if (count>mMultixFile.size()) count=mMultixFile.size(); for (int i = 0; i<count;i++) { paraseVideFile(mMultixFile.get(i)); } } void paraseVideFile(File file) { File[] files = file.listFiles(); for (File f :files){ if (f.getName().endsWith(".mp4") ||f.getName().endsWith(".wma") ||f.getName().endsWith(".ogg") ||f.getName().endsWith(".pcm") ||f.getName().endsWith(".m4a") ||f.getName().endsWith(".ac3") ||f.getName().endsWith(".ec3") ||f.getName().endsWith(".dtshd") ||f.getName().endsWith(".wav") ||f.getName().endsWith(".rm") ||f.getName().endsWith(".ra") ||f.getName().endsWith(".cd") ||f.getName().endsWith(".amr") ||f.getName().endsWith(".dts") ||f.getName().endsWith(".dts") ||f.getName().endsWith(".midi") ||f.getName().endsWith(".snd") ||f.getName().endsWith(".vqf") ||f.getName().endsWith(".cda") ||f.getName().endsWith(".aiff")) { playVideoFiles.add(f); Log.i("main","paraseVideFile videoIndex = "+videoIndex+" playVideoFiles.size = "+playVideoFiles.size()); } } } void initView(){ mPlayVideo = (VideoView)findViewById(R.id.vv_play); mPlayVideo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { videoIndex++; if (videoIndex > playVideoFiles.size()-1)videoIndex = 0; mPlayVideo.setVideoURI( Uri.parse(playVideoFiles.get(videoIndex).getPath())); mPlayVideo.start(); } }); mPlayVideo.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { // finish(); // return false; playNext(true); return true; } }); } @Override public boolean dispatchKeyEvent(KeyEvent event) { Log.i("main","getCode = "+event.getKeyCode()); if (event.getAction() == KeyEvent.ACTION_DOWN &&event.getKeyCode()==KeyEvent.KEYCODE_DPAD_UP) { if (event.isLongPress()) { Log.i("main","****************************isLongPress"); } if (event.getRepeatCount()%20==0) { mUserSelectedIndex++; if (mUserSelectedIndex >mMaxParseFilseCount) mUserSelectedIndex = 0; Log.i("main","getCode = "+event.getKeyCode()+" count = "+event.getRepeatCount()); return true; } } if (event.getAction() == KeyEvent.ACTION_DOWN &&event.getKeyCode()==KeyEvent.KEYCODE_DPAD_DOWN) { if (event.getRepeatCount()%20==0) { mUserSelectedIndex--; if (mUserSelectedIndex <0) mUserSelectedIndex = mMaxParseFilseCount; Log.i("main","getCode = "+event.getKeyCode()+" count = "+event.getRepeatCount()); return true; } } if (event.getAction() == KeyEvent.ACTION_DOWN &&event.getKeyCode()==KeyEvent.KEYCODE_BACK) { return super.dispatchKeyEvent(event); } if (event.getRepeatCount() ==0 &&event.getAction() == KeyEvent.ACTION_DOWN &&event.getKeyCode()==KeyEvent.KEYCODE_DPAD_LEFT) { playNext(false); return true; } if (event.getRepeatCount() == 0&& event.getAction() == KeyEvent.ACTION_DOWN &&event.getKeyCode()==KeyEvent.KEYCODE_DPAD_RIGHT) { playNext(true); return true; } return super.dispatchKeyEvent(event); } void playNext(Boolean direction) { if (playVideoFiles.size()==0) return; Log.i("main","vvideoIndex = "+videoIndex+" playVideoFiles.size = "+playVideoFiles.size()); videoIndex = videoIndex+( direction?1:-1); if (videoIndex > playVideoFiles.size()-1)videoIndex = 0; else if (videoIndex == -1) videoIndex = playVideoFiles.size()-1; mPlayVideo.setVideoURI( Uri.parse(playVideoFiles.get(videoIndex).getPath())); mPlayVideo.start(); } } ``` USBHelper.java ```package com.cvim.v.play; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Message; import android.util.Log; import java.io.File; import java.util.ArrayList; public class USBHelper { private Context mContext; private MainActivity mMainActivity; public ArrayList<File> fileData = new <File>ArrayList(); public USBHelper(Context context,MainActivity mainActivity){ this.mContext = context; this.mMainActivity = mainActivity; } void init() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addDataScheme("file"); intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); intentFilter.addAction(Intent.ACTION_MEDIA_EJECT); intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); mContext.registerReceiver(usbReceiver,intentFilter); } void unRegisterReceiver() { mContext.unregisterReceiver(usbReceiver); } private BroadcastReceiver usbReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i("main","intent.getAction = "+intent.getAction()); if (intent.getAction()== Intent.ACTION_MEDIA_EJECT) { mMainActivity.mHandler.sendEmptyMessage(400); } if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)) { Log.i("main","intent.getdata = "+intent.getData()); if (intent.getData()!=null) { String usbPath = intent.getData().getPath(); Log.i("main","usbPath = "+usbPath); Log.i("main","intent.getScheme = "+intent.getScheme()); File file = new File(usbPath); Log.i("main","file = "+file.exists()); Log.i("main","file.getName = "+file.getName()); Log.i("main","file.getAbsolutePath = "+file.getAbsolutePath()); File []files = file.listFiles(); for (File f :files) { // if (f.getName().endsWith(".mp4")) { fileData.add(f); Log.i("main","f.name = "+f.getName()+" f.getAbsolutePath = "+f.getAbsolutePath()+" f.paht = "+f.getPath()); } } } // Message data = new Message(); // data.arg1 = 200; //MainActivity.mHandler.sendEmptyMessage(200); if (fileData.size()>0) mMainActivity.mHandler.sendEmptyMessage(200); } } }; } ``` PlayActivity.java ```package com.cvim.v.play1; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.KeyEvent; import com.cvim.v.play.R; import com.cvim.v.play.receiver.ReceiverHelper; public class PlayActivity extends AppCompatActivity { PlayHelper mPlayHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play); mPlayHelper = new PlayHelper(this); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if ( event.getKeyCode() == KeyEvent.KEYCODE_BACK) { if ((event.getRepeatCount() == 9) && event.getAction() == KeyEvent.ACTION_DOWN ) { finish(); } return true; } return super.dispatchKeyEvent(event); } @Override protected void onDestroy() { super.onDestroy(); } } ``` ReadManager.java ```package com.cvim.v.play1; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.Message; import android.util.Log; import com.cvim.v.play.ReadVideoFile; import java.io.File; import java.util.ArrayList; import java.util.Collections; public class ReadManager { private static final String readURootDir = "projectorad"; private static final String mntUsbRoot = "mnt/usb/projectorad"; public static boolean isMntUsb = true; public static ReadVideoFiles mReadVideoFile; private static VideoPlay mContext; private static int mDirIndex; public static void init(VideoPlay context,int index) { mContext = context; mDirIndex = index; ReadVideoFiles.initPermission(context); readUSB(context); } private static void readUSB(Activity context) { /** * U盘不存在的情况下 读取内部存储 video目录 */ ReadVideoFiles.reset(); readUContent(USBHelper.readFileDataFile(readURootDir)); } public static boolean isUExist() { if ( USBHelper.readFileDataFile(readURootDir).contains(readURootDir))return true; return false; } private static void readUContent(String usbPath) { // 读取U盘 if (usbPath.contains(readURootDir)) { File file = new File(usbPath); if (!file.exists()) return; ArrayList<File> tempArr = new ArrayList<>(); if (file == null|| file.listFiles().length==0) { if (null!=mContext) mContext.mHanlderUpdateVideoList.sendEmptyMessage(mContext.ClEAN_ALL_VIDEO_FILE_DATA); return; } for (File item:file.listFiles()) { if (item.isDirectory()) tempArr.add(item); Log.i("play","023 item.getName = "+item.getName()+" item.Path = "+item.getPath()); } Collections.sort(tempArr,new CompareName()); for (int i =0; i<tempArr.size();i++) { File item = tempArr.get(i); Log.i("play","023 Collections.sort item.getName = "+item.getName()+" item.Path = "+item.getPath()); } ReadVideoFiles.setmMultixDirtory(tempArr); // Log.i("play","023 USBHelper readFileDataFile file.exists() = "+file.exists()+" mntUsbRoot = "+mntUsbRoot+" mDirIndex = "+mDirIndex ); ReadVideoFiles.mHandler.sendEmptyMessage(mDirIndex); }else // 读取内存存储video目录 { isMntUsb = false; // ReadVideoFiles.paserAllVideoFile(0); // 默认第一个目录 } } public static void initRegisterUSB() { Log.i("play", "ReadManager initRegisterUSB"); IntentFilter intentFilter = new IntentFilter(); intentFilter.addDataScheme("file"); intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); intentFilter.addAction(Intent.ACTION_MEDIA_EJECT); intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); mContext.registerReceiver(usbReceiver,intentFilter); } public static void unRegisterReceiver() { mContext.unregisterReceiver(usbReceiver); } private static BroadcastReceiver usbReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i("main","intent.getAction = "+intent.getAction()); if (intent.getAction()== Intent.ACTION_MEDIA_EJECT) { ReadVideoFiles.reset(); isMntUsb = false; if (null!=mContext) mContext.mHanlderUpdateVideoList.sendEmptyMessage(mContext.ClEAN_ALL_VIDEO_FILE_DATA); } if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)) { if (intent.getData()!=null) { // String usbPath = intent.getData().getPath(); // Log.i("play","usbPath = "+usbPath); // Log.i("play","intent.getScheme = "+intent.getScheme()); // // File file = new File(usbPath); // Log.i("play","file = "+file.exists()); // Log.i("play","file.getName = "+file.getName()); // Log.i("play","file.getAbsolutePath = "+file.getAbsolutePath()); // File []files = file.listFiles(); // for (File f :files) // { // if (f.getPath().contains(readURootDir)) // { //// Log.i("play","f.name = "+f.getName()+" f.getAbsolutePath = "+f.getAbsolutePath()+" f.paht = "+f.getPath()); // readUContent(f.getPath()); // } // } isMntUsb = true; if (ReadManager.isUExist()) { readUSB(mContext); } } } } }; } ``` USBHelper.java ```package com.cvim.v.play1; import android.util.Log; import java.io.File; import java.util.ArrayList; public class USBHelper { private static String uabs1 = ""; private static String mntUsbRoot = "mnt/usb"; private static ArrayList<File> mData = new ArrayList<>(); public static String readFileDataFile(String path) { return readUsbDirtory(path); } private static String readUsbDirtory(String path) { // Log.i("play","01 USBHelper readFileDa mntUsbRoot = "+mntUsbRoot+" path = "+path); File file = new File(mntUsbRoot); // Log.i("play","02 USBHelper readFileDataFile file.exists() = "+file.exists()+" mntUsbRoot = "+mntUsbRoot); if (file.exists()) { File []files = file.listFiles(); for (File f:files) { // Log.i("play","readUsbDirtory mntUsbRoot = "+mntUsbRoot+" f = "+f.getName()+" f.getPath = "+f.getPath()); File subFile = new File(f.getPath()); // Log.i("play","--->readUsbDirtory mntUsbRoot = "+mntUsbRoot+" subFile = "+subFile.getName()+" subFile.getPath = "+subFile.getPath() // +" subFile.exist = "+subFile.exists()+" subFile = "+subFile); if (subFile==null||!subFile.exists()) return mntUsbRoot; File []subFileItems = subFile.listFiles(); if (subFileItems==null) return mntUsbRoot; for (File iteml:subFileItems) { // Log.i("play","readUsbDirtory mntUsbRoot "+mntUsbRoot+" iteml = "+iteml.getName()+" iteml.getPath = "+iteml.getPath()); if (path.equals(iteml.getName())) { // Log.i("play","=============readUsbDirtory mntUsbRoot "+mntUsbRoot+" f = "+iteml.getName()+" f.getPath = "+iteml.getPath()); return iteml.getPath(); } } } } return mntUsbRoot; } } ```
zhukaikang/Lintcode_ladder
zhukaikang/Lintcode_ladder LintCode33NQueens.java ```package chapter7; import java.util.*; public class LintCode33NQueens { public List<List<String>> solveNQueens(int n) { // write your code here // write your code here List<List<String>> res = new ArrayList<>(); if(n<=0){ return res; } search(res, new ArrayList<Integer>(), n); return res; } private void search(List<List<String>> res, List<Integer> cols, int n){ if(cols.size() == n){ res.add(drawChess(cols)); return; } for(int colIndex = 0; colIndex < n;colIndex++){ if(!isValid(cols, colIndex)) { continue; } cols.add(colIndex); search(res, cols, n); cols.remove(cols.size()-1); } } private boolean isValid(List<Integer> cols, int col) { int rows = cols.size(); for(int rowIndex=0; rowIndex < rows; rowIndex++) { if(cols.get(rowIndex) == col) { return false; } if(cols.get(rowIndex) + rowIndex == col + rows) { return false; } if(cols.get(rowIndex) - rowIndex == col - rows) { return false; } } return true; } private List<String> drawChess ( List<Integer> cols) { List<String> chess = new ArrayList<>(); for(int i = 0;i< cols.size(); i++) { StringBuilder sb = new StringBuilder(); for(int j=0;j<cols.size(); j++) { sb.append(j == cols.get(i)?'Q':'.'); } chess.add(sb.toString()); } return chess; } public static void main(String[] args) { LintCode33NQueens a = new LintCode33NQueens(); System.out.println(a.solveNQueens(4)); } } ``` LintCode209FirstUniqueLetterInaString.java ```package chapter8; import java.util.*; public class LintCode209FirstUniqueLetterInaString { public char firstUniqChar(String str) { // Write your code here // if(str == null) { // return '0'; // } // int[] arr = new int[256]; // for(int i=0;i<str.length();i++) { // arr[str.charAt(i)] += 1; // } // for(int i=0;i<str.length();i++) { // if(arr[str.charAt(i)]==1) { // return str.charAt(i); // } // } // return '0'; Map<Character, Integer> map = new HashMap<>(); for(int i=0;i<str.length();i++) { map.put(str.charAt(i), 0); } for(int i=0;i<str.length();i++) { map.put(str.charAt(i), map.get(str.charAt(i)) + 1); } for(int i=0;i<str.length();i++) { if(map.get(str.charAt(i)) == 1) { return str.charAt(i); } } return '0'; } public static void main(String[] args) { LintCode209FirstUniqueLetterInaString a = new LintCode209FirstUniqueLetterInaString(); System.out.println(a.firstUniqChar("abaccdeff")); } } ``` Lintcode16Permutation2.java ```public class Solution { /* * @param : A list of integers * @return: A list of unique permutations */ public List<List<Integer>> permuteUnique(int[] nums) { // write your code here List<Integer> per = new ArrayList<>(); List<List<Integer>> res = new ArrayList<>(); Arrays.sort(nums); dfs(nums, new boolean[nums.length], per, res); return res; } private void dfs(int[] nums, boolean[] visited, List<Integer> per, List<List<Integer>> res) { if(nums.length==per.size()){ res.add(new ArrayList<Integer>(per)); return; } for(int i=0;i<nums.length;i++) { if(visited[i]){ continue; } if(i>0 && nums[i]==nums[i-1] && !visited[i-1]) { continue; } per.add(nums[i]); visited[i] = true; dfs(nums, visited, per, res); visited[i] = false; per.remove(per.size()-1); } } };``` Lintcode17Subsets.java ```public class Solution { /** * @param nums: A set of numbers * @return: A list of lists */ public List<List<Integer>> subsets(int[] nums) { // write your code here List<List<Integer>> result = new ArrayList<>(); Arrays.sort(nums); dfs(nums, 0, new ArrayList<Integer>(), result); return result; } private void dfs(int[] nums, int index, List<Integer> com, List<List<Integer>> result) { result.add(new ArrayList<Integer>(com)); for(int i = index;i<nums.length;i++) { com.add(nums[i]); dfs(nums, i+1, com, result); com.remove(com.size()-1); } } } ``` Lintcode132WordSearch2.java ```package chapter7; import java.util.*; public class Lintcode132WordSearch2 { public static int[] dx = {0, 1, -1, 0}; public static int[] dy = {1, 0, 0, -1}; public List<String> wordSearchII(char[][] board, List<String> words) { // write your code here List<String> res = new ArrayList<>(); if(board == null || board.length == 0 || board[0] == null || board[0].length == 0 || words.size() == 0) { return res; } int row = board.length; int col = board[0].length; boolean[][] visited = new boolean[row][col]; Map<String, Boolean> map = getPrefixSet(words); Set<String> wordSet = new HashSet<>(); for(int j = 0;j<row;j++){ for(int k = 0;k<col;k++) { visited[j][k] = true; dfs(j, k, String.valueOf(board[j][k]), visited, board, map, wordSet); // dfs(board, visited, j, k, String.valueOf(board[j][k]), map, wordSet); visited[j][k] = false; } } return new ArrayList<String>(wordSet); } private Map<String, Boolean> getPrefixSet(List<String> words) { Map<String, Boolean> map = new HashMap<>(); for(String word: words) { for(int i = 0;i<word.length()-1;i++) { String prefix = word.substring(0, i+1); if(!map.containsKey(prefix)){ map.put(prefix, false); } } map.put(word, true); } return map; } private void dfs(int row, int col, String word, boolean[][] visited, char[][] board, Map<String, Boolean> map, Set<String> set) { if(!map.containsKey(word)) { return; } if(map.get(word)) { set.add(word); } for(int i=0;i<4;i++) { int adx = dx[i] + row; int ady = dy[i] + col; // if(!inside(board, adx, ady) || visited[adx][ady]) { // continue; // } if(adx < 0 || adx >= board.length || ady < 0 || ady >= board[0].length || visited[adx][ady]) { continue; } visited[adx][ady] = true; dfs(adx, ady, word + board[adx][ady], visited, board, map, set); visited[adx][ady] = false; } } private boolean inside(char[][] board, int x, int y) { return x >= 0 && x < board.length && y >= 0 && y < board[0].length; } public static void main(String[] args) { Lintcode132WordSearch2 a = new Lintcode132WordSearch2(); char[][] b = {{'d','o','a','f'},{'a','g','a','i'},{'d','c','a','n'}}; List<String> c = Arrays.asList("dog","dad","dgdg","can","again"); System.out.println(a.wordSearchII(b, c)); } } ``` Lintcode245DropEggs.java ```package chapter2; public class Lintcode245DropEggs { public static void main(String[] args) { Lintcode245DropEggs a = new Lintcode245DropEggs(); System.out.println(a.dropEggs(100)); } public int dropEggs(int n) { //TC O(logn) //SC O(1) long index = 1; while(index * (index + 1)/2 < n){ index = index * 2; } long left = 0, right = index; while(left < right -1){ long mid = left + (right - left)/2; if(mid * (mid + 1)/2 >= n){ right = mid; } else{ left = mid; } } if(left * (left + 1)/2 >= n){ return (int)left; } else { return (int)right; } //return 0; } } ``` Lintcode134LRUCache.java ```package chapter8; import java.util.*; public class Lintcode134LRUCache { int cap; Map<Integer, Integer> map; public static void main(String[] args) { Lintcode134LRUCache a = new Lintcode134LRUCache(2); a.set(2,1); a.set(1, 1); System.out.println(a.get(2)); a.set(4, 1); System.out.println(a.get(1)); System.out.println(a.get(2)); } /* * @param capacity: An integer */public Lintcode134LRUCache(int capacity) { // do intialization if necessary cap = capacity; map = new LinkedHashMap<Integer, Integer>(); } /* * @param key: An integer * @return: An integer */ public int get(int key) { // write your code here if(!map.containsKey(key)){ return -1; } int val = map.remove(key); map.put(key, val); return val; } /* * @param key: An integer * @param value: An integer * @return: nothing */ public void set(int key, int value) { // write your code here if(map.containsKey(key)){ map.remove(key); map.put(key, value); return; } map.put(key, value); if(map.size()>cap){ map.remove(map.entrySet().iterator().next().getKey()); } } } ``` Lintcode425LetterCombinationsofaPhoneNumber.java ```package chapter7; import java.util.ArrayList; import java.util.List; public class Lintcode425LetterCombinationsofaPhoneNumber { public List<String> letterCombinations(String digits) { // write your code here String[] phone = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; List<String> res = new ArrayList<>(); if(digits.equals("") || digits == null) { return res; } dfs(0, digits.length(), "", digits, phone, res); return res; } private void dfs(int l, int r, String str, String digits, String[] phone, List<String> res) { if(l == r){ res.add(str); return; } int d = digits.charAt(l)-'0'; // for(int i=0;i<phone[d].toCharArray().length;i++) { // str += phone[d].toCharArray()[i]; // dfs(i+1, r, str, digits, phone, res); // } for(char c: phone[d].toCharArray()){//啥意思???? dfs(l+1, r, str+c, digits, phone, res); } } public static void main(String[] args) { Lintcode425LetterCombinationsofaPhoneNumber a = new Lintcode425LetterCombinationsofaPhoneNumber(); System.out.println(a.letterCombinations("23")); } } ``` Lintcode680SplitString.java ```public class Solution { /* * @param : a string to be split * @return: all possible split string array */ public List<List<String>> splitString(String s) { // write your code here List<List<String>> res = new ArrayList<>(); List<String> com = new ArrayList<>(); char[] chars = s.toCharArray(); Arrays.sort(chars); dfs(s, com, res); return res; } private void dfs(String s, List<String> com, List<List<String>> res) { if(s.equals("")){ res.add(new ArrayList<String>(com)); return; } for(int i=1;i<=2;i++){ if(i<=s.length()){ com.add(s.substring(0,i)); //use s.length()。如果用i+2 when 剩下的s已经没有长度为0或为1,会出错。 //此外程序每次i从1开始,如果出现s长度为0,此时会出现越界错误,所以必须判断i小于等于s的长度。 dfs(s.substring(i, s.length()), com, res); com.remove(com.size()-1); } } } }``` Lintcode685FirstUniqueNumberInDataStream.java ```package chapter8; import java.util.*; public class Lintcode685FirstUniqueNumberInDataStream { public static void main(String[] args) { Lintcode685FirstUniqueNumberInDataStream a = new Lintcode685FirstUniqueNumberInDataStream(); System.out.println(a.firstUniqueNumber(new int[] {1, 2, 2, 1, 3, 4, 4, 5, 6}, 5)); } public int firstUniqueNumber(int[] nums, int number) { // Write your code here //HashMap不允许键值重复,所以没必要用set。 HashMap<Integer, Boolean> map = new HashMap<>(); HashSet<Integer> set = new HashSet<>(); if(nums==null||nums.length==0){ return -1; } for(int num: nums) { map.put(num, !map.containsKey(num)); if(num==number){ break; } } if(!map.containsKey(number)){ return -1; } for(int num: nums){ if(num==number){ return num; //break; } if(map.get(num)){ return num; } } return -1; } } ``` Lintcode153CombinationSum2.java ```package chaper6; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Lintcode153CombinationSum2 { public List<List<Integer>> combinationSum2(int[] num, int target) { // write your code here List<List<Integer>> res = new ArrayList<>(); List<Integer> com = new ArrayList<>(); Arrays.sort(num); dfs(num, 0, target, com, res); return res; } private void dfs(int[] num, int index, int target, List<Integer> com, List<List<Integer>> res) { if(target == 0){ res.add(new ArrayList<>(com)); return; } for(int i=index;i<num.length;i++) { if(num[i] > target) { break; } if(i!=index && num[i]==num[i-1]){ //判断条件改为i!=index的原因:使重复的数字能够被加入进去。因为每个数字只会考虑一次(i +1),所以不会有同一个数字用多次的情况, //碰到多个相同数字的情况时,i若已经不等于index,说明已经在考虑了这个数字之后又碰到了一次相同数值的数字,因此跳过防止重复解。 continue; } com.add(num[i]); dfs(num, i+1, target - num[i], com, res); com.remove(com.size()-1); } } public static void main(String[] args) { Lintcode153CombinationSum2 a = new Lintcode153CombinationSum2(); int[] num = {7,1,2,5,1,6,10}; System.out.println(a.combinationSum2(num, 8)); } } ``` Lintcode612KClosestPoints.java ```package chapter8; import java.util.*; class Point { int x; int y; Point() { x = 0; y = 0; } Point(int a, int b) { x = a; y = b; } } public class Lintcode612KClosestPoints { public Point[] kClosest(Point[] points, Point origin, int k) { // write your code here // if(k>points.size()){ // return null; // } // if(k==points.size()){ // return points; // } PriorityQueue<Point> pQueue = new PriorityQueue<Point> (k, new Comparator<Point>(){ @Override //Comparator函数无法重写int之外的数据类型。。想写double报错了 //不必返回double类型,返回int类型表示大小关系即可。compare也只能用int类型。 public int compare(Point a, Point b) { int difference = calDis(a, origin) - calDis(b, origin); if(difference==0){ difference = a.x - b.x; } if(difference==0){ difference = a.y - b.y; } return difference; } }); HashMap<Double, Point> map = new HashMap<Double, Point>(); Point[] sortedP = new Point[k]; for(Point point: points){ //double distance = calDis(point, origin); //map.put(distance, point); pQueue.add(point); } for(int i=0;i<k;i++){ Point minP = pQueue.poll(); //Point minP = map.get(minDis); sortedP[i] = minP; } return sortedP; } private int calDis(Point a, Point origin){ int square = (a.x - origin.x)*(a.x - origin.x) + (a.y - origin.y)*(a.y - origin.y); return square; } public static void main(String[] args) { Lintcode612KClosestPoints a = new Lintcode612KClosestPoints(); Point[] newP = new Point[5]; //ArrayList<Point> newP = new ArrayList<Point>(); newP[0] = new Point(4, 6); newP[1] = new Point(4, 7); newP[2] = new Point(4, 4); newP[3] = new Point(2, 5); newP[4] = new Point(1, 1); // newP.add(new Point(4, 7)); // newP.add(new Point(4, 4)); // newP.add(new Point(2, 5)); // newP.add(new Point(1, 1)); Point[] res = a.kClosest(newP, new Point(0, 0), 3); for(Point p: res) { System.out.println(p.x + " " + p.y); } } } ``` LintCode642MovingAveragefromDataStream.java ```package chapter8; import java.util.*; public class LintCode642MovingAveragefromDataStream { private Queue<Integer> deq; private int size; private double sum; /* * @param size: An integer */public LintCode642MovingAveragefromDataStream(int size) { // do intialization if necessary deq = new LinkedList<Integer>(); sum = 0.0; this.size = size; } /* * @param val: An integer * @return: */ public double next(int val) { // write your code here sum += val; //对队列元素个数进行判断,若没有达到size则添加后返回均值;若达到了size,则意味着滑动窗口往后移动一位 //将队首元素拿出,sum减去对应值。此时若返回则没有将新元素加入(之前犯了这个错误)。将新元素加入后, //正常计算均值,队列始终保持size的大小,所以不用分别对待。 if(deq.size() == size){ sum -= deq.poll(); //return sum/(1.0*size); } deq.offer(val); return sum/(1.0*deq.size()); } public static void main(String[] args) { LintCode642MovingAveragefromDataStream a = new LintCode642MovingAveragefromDataStream(3); System.out.println(a.next(1)); System.out.println(a.next(3)); System.out.println(a.next(10)); System.out.println(a.next(5)); } } ``` Lintcode494ImplementStackbyTwoQueues.java ```package chapter8; import java.util.*; public class Lintcode494ImplementStackbyTwoQueues { Queue<Integer> a = new LinkedList<>(); Queue<Integer> b = new LinkedList<>(); public void push(int x) { // write your code here if(a.isEmpty()) { a.offer(x); while(!b.isEmpty()) { a.offer(b.poll()); } } else{ b.offer(x); while(!a.isEmpty()){ b.offer(a.poll()); } } } /* * @return: nothing */ public void pop() { // write your code here if(!a.isEmpty()){ a.poll(); } else{ b.poll(); } } /* * @return: An integer */ public int top() { // write your code here //Integer res = 0; if(!a.isEmpty()){ return a.peek(); } else{ return b.peek(); } //return res; } /* * @return: True if the stack is empty */ public boolean isEmpty() { // write your code here return a.isEmpty() && b.isEmpty(); } public static void main(String[] args) { Lintcode494ImplementStackbyTwoQueues stack = new Lintcode494ImplementStackbyTwoQueues(); stack.push(1); stack.pop(); stack.push(2); System.out.println(stack.isEmpty()); System.out.println(stack.top()); stack.pop(); System.out.println(stack.isEmpty()); } } ``` Lintcode657InsertDeleteGetRandomO1.java ```package chapter8; import java.util.*; public class Lintcode657InsertDeleteGetRandomO1 { ArrayList<Integer> arr; HashMap<Integer, Integer> map; Random rand; public static void main(String[] args) { } public Lintcode657InsertDeleteGetRandomO1() { // do intialization if necessary arr = new ArrayList<>(); map = new HashMap<>(); rand = new Random(); } /* * @param val: a value to the set * @return: true if the set did not already contain the specified element or false */ public boolean insert(int val) { // write your code here if(map.containsKey(val)){ return false; } map.put(val, arr.size()); arr.add(val); return true; } /* * @param val: a value from the set * @return: true if the set contained the specified element or false */ public boolean remove(int val) { // write your code here if(!map.containsKey(val)){ return false; } int index = map.get(val); if(index<arr.size()-1){ int last = arr.get(arr.size()-1); arr.set(index, last); //加不加这句话都可以通过,why? //arr.set(arr.size()-1, val); //Re: 把需要remove的数替换掉即可,不需要swap。 map.put(last, index); } arr.remove(arr.size()-1); map.remove(val); return true; } /* * @return: Get a random element from the set */ public int getRandom() { // write your code here return arr.get(rand.nextInt(arr.size())); } } ``` Lintcode459ClosestNumberInSortedArray.java ```package chapter2; public class Lintcode459ClosestNumberInSortedArray { public static void main(String[] args) { Lintcode459ClosestNumberInSortedArray a = new Lintcode459ClosestNumberInSortedArray(); System.out.println(a.closestNumber(new int[] {1,4,6}, 3)); } public int closestNumber(int[] A, int target) { // write your code here if(A==null || A.length == 0){ return -1; } int left = 0, right = A.length - 1; while(left < right - 1){ int mid = left + (right - left)/2; if(A[mid] == target){ return mid; } else if(A[mid] > target){ right = mid; } else { left = mid; } } if(Math.abs(A[left] - target) > Math.abs(A[right] - target)){ return right; } else { return left; } } } ``` Lintcode18Subsets2.java ```public class Solution { /** * @param nums: A set of numbers. * @return: A list of lists. All valid subsets. */ public List<List<Integer>> subsetsWithDup(int[] nums) { // write your code here List<List<Integer>> results = new ArrayList<>(); if(nums == null ){ return results; } Arrays.sort(nums); dfs(nums, 0, new ArrayList<Integer>(), results); return results; } private void dfs(int[] nums, int index, List<Integer> subset, List<List<Integer>> results){ results.add(new ArrayList<Integer>(subset)); for(int i = index;i<nums.length;i++){ if(i!=0 && nums[i]==nums[i-1] && i>index){ continue; } subset.add(nums[i]); dfs(nums, i+1, subset, results); subset.remove(subset.size()-1); } } }``` Lintcode120WordLadder.java ```package chaper4; import java.util.*; public class Lintcode120WordLadder { public int ladderLength(String start, String end, Set<String> dict) { // write your code here if(dict == null) { return 0; } if(start.equals(end)) { return 1; } dict.add(start); dict.add(end); HashSet<String> hash = new HashSet<String>(); Queue<String> queue = new LinkedList<String>(); queue.offer(start); hash.add(start); int length = 1; while(!queue.isEmpty()) { length++; int size = queue.size(); for(int i = 0;i<size;i++) { String word = queue.poll(); for(String s : getNext(word, dict)) { if(hash.contains(s)) { continue; } if(s.equals(end)) { return length; } hash.add(s); queue.offer(s); } } } return 0; } private List<String> getNext(String word, Set<String> dict) { List<String> newWords = new ArrayList<String>(); for(char c = 'a';c<='z';c++) { for(int i=0;i<word.length();i++) { if(c==word.charAt(i)) { continue; } String newWord = replace(word, c, i); if(dict.contains(newWord)){ newWords.add(newWord); } } } return newWords; } private String replace(String word, char c, int index) { char[] chars = word.toCharArray(); chars[index] = c; return new String(chars); } public static void main(String[] args) { Lintcode120WordLadder a = new Lintcode120WordLadder(); Set<String> set = new HashSet<>(Arrays.asList("hot","dot","dog","lot","log")); System.out.println(a.ladderLength("hit", "cog", set)); } } ``` Lintcode40ImplementQueueBytwoStacks.java ```package chapter8; public class Lintcode40ImplementQueueBytwoStacks { } ``` Lintcode829WordPattern2.java ```package chapter7; import java.util.HashMap; import java.util.Map; public class Lintcode829WordPattern2 { public boolean wordPatternMatch(String pattern, String str) { // write your code here Map<Character, String> map = new HashMap<>(); return dfs(pattern, str, map); } private boolean dfs(String pattern, String str, Map<Character, String> map) { if(pattern.length() == 0 && str.length() == 0) { return true; } if(pattern.length() == 0 || str.length() == 0) { return false; } if(map.containsKey(pattern.charAt(0))) { String prefix = map.get(pattern.charAt(0)); if(!str.startsWith(prefix)) { return false; } return dfs(pattern.substring(1), str.substring(prefix.length()), map); } for(int i = 1;i <= str.length();i++) { String prefix = str.substring(0, i); if(map.containsValue(prefix)) { continue; } map.put(pattern.charAt(0), prefix); if(dfs(pattern.substring(1), str.substring(prefix.length()), map)){ return true; } map.remove(pattern.charAt(0)); } return false; } public static void main(String[] args) { Lintcode829WordPattern2 a = new Lintcode829WordPattern2(); System.out.println(a.wordPatternMatch("abab", "redblueredblue")); } } ``` Lintcode10StringPermutation2.java ```public class Solution { /** * @param str: A string * @return: all permutations */ public List<String> stringPermutation2(String str) { // write your code here List<String> res = new ArrayList<>(); if(str == null) { return res; } char[] chars = str.toCharArray(); Arrays.sort(chars); String per = new String(); //StringBuilder sb = new StringBuilder(per); //Arrays.sort(str); dfs(chars, new boolean[str.length()], per, res); return res; } private void dfs(char[] chars, boolean[] visited, String per, List<String> res) { if(chars.length==per.length()) { res.add(new String(per)); return; } for(int i=0;i<chars.length;i++) { if(visited[i]) { continue; } if(i>0 && chars[i] == chars[i-1] && !visited[i-1]) { continue; } per += chars[i]; visited[i] = true; dfs(chars, visited, per, res); visited[i] = false; per = per.substring(0, per.length()-1); //per = sb.toString(); } } }``` Lintcode135CombinationSum.java ```package chaper6; public class Lintcode135CombinationSum { } ``` Lintcode128HashFunction.java ```package chapter8; public class Lintcode128HashFunction { public static void main(String[] args) { Lintcode128HashFunction a = new Lintcode128HashFunction(); System.out.println(a.hashCode(new char[] {'a','b','c','d'}, 1000)); } public int hashCode(char[] key, int HASH_SIZE) { // write your code here long sum = 0; //同余定理,没搞懂。。循环相乘,见https://www.jianshu.com/p/9a67268b5a94 for(int i=0;i<key.length;i++){ sum = (sum*33+key[i]) % HASH_SIZE; } return (int)sum; } } ``` Lintcode123WordSearch.java ```package chapter7; public class Lintcode123WordSearch { public boolean exist(char[][] board, String word) { // write your code here if(board == null || board.length == 0) { return false; } if(board[0] == null || board[0].length == 0) { return false; } int row = board.length; int col = board[0].length; boolean[][] visited = new boolean[row][col]; //从每个元素依次寻找。 //base case: index == word.length() //subProblem: 判断每个元素是否在board里 //recursion rule: search(row, col +/-1) || search(row+/-1, col)是否为true //time complexity : O(i*j*n) n = words.length(), i = row, j = col //space complexity : O(i*j) for(int i = 0;i<row;i++) { for(int j = 0;j<col;j++) { if(search(i, j, 0, visited, board, word)){ return true; } } } return false; } private boolean search(int row, int col, int index, boolean[][] visited, char[][] board, String word) { if(index == word.length()) { return true; } if(row < 0 || row >= board.length || col < 0 || col >= board[0].length) { return false; } if(visited[row][col] || board[row][col] != word.charAt(index)) { return false; } visited[row][col] = true; if(search(row, col - 1, index + 1, visited, board, word) || search(row, col + 1, index + 1, visited, board, word) || search(row - 1, col, index + 1, visited, board, word) || search(row + 1, col, index + 1, visited, board, word)) { return true; } //若上下左右都没有找到对应的下一个元素,则将true改回false。 visited[row][col] = false; return false; } public static void main(String[] args) { Lintcode123WordSearch a = new Lintcode123WordSearch(); char[][] b = {{'A', 'B', 'C', 'E'}, {'S','F','C','F'}, {'A', 'D', 'E', 'E'}}; char[][] c = {{'z'}}; System.out.println(a.exist(c, "z")); } } ``` Lintcode544TopKLargestNumbers.java ```package chapter8; import java.util.*; public class Lintcode544TopKLargestNumbers { public int[] topk(int[] nums, int k) { // write your code here if(k>nums.length || nums.length==0){ return null; } PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(k, new Comparator<Integer>(){ public int compare(Integer a, Integer b){ //int difference = Integer.parseInt(a)-Integer.parseInt(b); int difference = a - b; return -1*difference; } }); for(int num: nums){ pQueue.add(num); } int[] res = new int[k]; for(int i=0;i<k;i++){ int max = pQueue.poll(); res[i] = max; } return res; } public static void main(String[] args) { Lintcode544TopKLargestNumbers a = new Lintcode544TopKLargestNumbers(); int[] nums = {3, 10, 1000, -99, 4, 100}; int[] res = a.topk(nums, 3); for(int num: res) { System.out.println(num); } } } ``` Lintcode136PalindromePartitioning.java ```package chaper6; import java.util.ArrayList; import java.util.List; public class Lintcode136PalindromePartitioning { public List<List<String>> partition(String s) { // write your code here List<List<String>> res = new ArrayList<>(); List<String> com = new ArrayList<>(); if(s.length() == 0 || s == null) { return res; } dfs(0, s, com, res); return res; } private void dfs(int index, String s, List<String> com, List<List<String>> res) { if(s.equals("")) { res.add(new ArrayList<String>(com)); return; } for(int i = 1; i<=s.length();i++) { if(!isPalindrome(s.substring(0, i))) { continue; } com.add(s.substring(0, i)); dfs(i, s.substring(i), com, res); com.remove(com.size()-1); } } private boolean isPalindrome(String s) { for(int i=0; i<s.length()/2;i++) { if(s.charAt(i) != s.charAt(s.length()-i-1)) { return false; } } return true; } public static void main(String[] args) { Lintcode136PalindromePartitioning a = new Lintcode136PalindromePartitioning(); System.out.println(a.partition("aab")); } } ``` Lintcode34NQueens2.java ```public class Solution { /** * @param n: The number of queens. * @return: The total number of distinct solutions. */ public int totalNQueens(int n) { // write your code here List<List<Integer>> res = new ArrayList<>(); List<Integer> cols = new ArrayList<>(); dfs(n, cols, res); return res.size(); } private void dfs(int n, List<Integer> cols, List<List<Integer>> res) { if(cols.size()==n) { res.add(new ArrayList<Integer>(cols)); return; } for(int i=0;i<n;i++){ if(!isValid(cols, i)){ continue; } cols.add(i); dfs(n, cols, res); cols.remove(cols.size()-1); } } private boolean isValid(List<Integer> cols, int index) { int rows = cols.size(); for(int i=0;i<rows;i++) { if(cols.get(i)==index){ return false; } if(cols.get(i) + i== index + rows) return false; if(cols.get(i) - i == index - rows) return false; } return true; } }``` Lintcode828WordPattern.java ```package chapter7; import java.util.*; public class Lintcode828WordPattern { public boolean wordPattern(String pattern, String teststr) { Map<Character, String> map = new HashMap<>(); String[] str = teststr.split(" "); for(int i=0;i<pattern.length();i++) { char c = pattern.charAt(i); if(!map.containsKey(c)) { if(map.containsValue(str[i])){ return false; } map.put(c, str[i]); } else{ if(!str[i].equals(map.get(c))){ return false; } } } return true; } public static void main(String[] args) { Lintcode828WordPattern a = new Lintcode828WordPattern(); boolean res = a.wordPattern("abba", "dog cat cat dog"); System.out.println(res); } } ``` Lintcode152Combinations.java ```public class Solution { /** * @param n: Given the range of numbers * @param k: Given the numbers of combinations * @return: All the combinations of k numbers out of 1..n */ public List<List<Integer>> combine(int n, int k) { // write your code here List<Integer> com = new ArrayList<Integer>(); List<List<Integer>> res = new ArrayList<>(); dfs(n, k, 1, com, res); return res; } private void dfs(int n, int k, int index, List<Integer> com, List<List<Integer>> res) { if(com.size()==k){ res.add(new ArrayList<Integer>(com)); return; } for(int i=index;i<=n;i++){ com.add(i); dfs(n, k, i+1, com,res); com.remove(com.size()-1); } } }``` Lintcode4UglyNumber2.java ```package chapter8; import java.util.*; public class Lintcode4UglyNumber2 { public static void main(String[] args) { Lintcode4UglyNumber2 a = new Lintcode4UglyNumber2(); System.out.println(a.nthUglyNumber(10)); } public int nthUglyNumber(int n) { // write your code here //过于数学不懂。 // if(n<=0){ // return -1; // } // int[] arr = new int[n]; // arr[0] = 1; // int p2 = 0, p3=0,p5=0; // for(int i=1;i<n;i++){ // arr[i]=Math.min(arr[p2]*2, Math.min(arr[p3]*3, arr[p5]*5)); // if(arr[i] == arr[p2]*2){ // p2++; // } // if(arr[i] == arr[p3]*3){ // p3++; // } // if(arr[i] == arr[p5]*5){ // p5++; // } // } // return arr[n-1]; // } Queue<Long> Q = new PriorityQueue<Long>(); HashSet<Long> inQ = new HashSet<Long>(); Long[] primes = new Long[3]; primes[0] = Long.valueOf(2); primes[1] = Long.valueOf(3); primes[2] = Long.valueOf(5); for(int i=0;i<3;i++){ Q.add(primes[i]); inQ.add(primes[i]); } Long number = Long.valueOf(1); for(int i=1;i<n;i++){ number = Q.poll(); for(int j=0;j<3;j++){ if(inQ.contains(number*primes[j])){ continue; } Q.add(number*primes[j]); inQ.add(number*primes[j]); } } return number.intValue(); } } ``` Lintcode15Permutations.java ```public class Solution { /* * @param nums: A list of integers. * @return: A list of permutations. */ public List<List<Integer>> permute(int[] nums) { // write your code here List<List<Integer>> res = new ArrayList<>(); List<Integer> per = new ArrayList<>(); Arrays.sort(nums); dfs(nums, new boolean[nums.length], per, res); return res; } //递归的定义 private void dfs(int[] nums, boolean[] visited, List<Integer> per, List<List<Integer>> res) { // 递归的出口 if(per.size() == nums.length) { res.add(new ArrayList<Integer>(per)); return; } // 3.递归的拆解 for(int i=0;i<nums.length;i++) { if(visited[i]==true) { continue; } //[] --> [1] per.add(nums[i]); visited[i] = true; dfs(nums, visited, per, res); //[1] --> [] visited[i] = false; per.remove(per.size()-1); } } } ```
zhukoedov/Algorithms
zhukoedov/Algorithms Hash_Table_DoubleHash.h ```#include <iostream> #include <string> #include <vector> #include <fstream> template <typename ValType> class HashTable { private: class TableCell { public: bool isset; std::string key; ValType value; TableCell() { isset = false; key = ""; value = ValType(); } }; std::vector<TableCell> hash_table; public: explicit HashTable () { hash_table.assign(8, TableCell()); insertions = 0; } bool contains( const std::string &key ) { size_t real_index = getRealIndex(hash_table, key, hash_table.size()); return hash_table[real_index].isset; } ValType& get( const std::string &key ) { size_t real_index = getRealIndex(hash_table, key, hash_table.size()); return hash_table[real_index].value; } void remove( const std::string& key ) { size_t real_index = getRealIndex(hash_table, key, hash_table.size()); hash_table[real_index].isset = false; } void insert( const std::string& key, const ValType& value ) { if (((double)insertions)/hash_table.size() >= 0.7) { rehash(); } size_t real_index = getRealIndex(hash_table, key, hash_table.size()); hash_table[real_index].key = key; hash_table[real_index].value = value; if (!hash_table[real_index].isset) { ++insertions; } hash_table[real_index].isset = true; } bool erase(const std::string& key) { return false; } ValType& operator [] (const std::string &key) { if (!contains(key)) { insert(key, ValType()); } return get(key); } const ValType& operator [] (const std::string &key) const { return get(key); } private: size_t insertions; size_t getRealIndex ( const std::vector<TableCell> &table, const std::string& key, size_t size ) { size_t i = hash(key, size); size_t h2 = hash2(key, size); size_t k = 0; while (table[i].key != key && table[(i + h2 * k) % size].isset) { ++k; } return (i + h2 * k) % size; } size_t hash(const std::string &s, size_t size) { size_t result = 0; int p = 3; for (char i : s) { result += (size_t)i; result *= p; result %= size; } return result; } size_t hash2(const std::string &s, size_t size) { return (s.length() + (size_t)(s.length() % 2 == 0)) % size; } void rehash() { size_t new_size = 2 * hash_table.size(); std::vector<TableCell> new_table(new_size); size_t new_insertions = 0; for (auto& element : hash_table) { if (element.isset) { size_t real_index = getRealIndex(new_table, element.key, new_size); new_table[real_index].key = element.key; new_table[real_index].value = element.value; new_table[real_index].isset = true; ++new_insertions; } } hash_table = new_table; insertions = new_insertions; } }; void makeTable(std::istream &in, HashTable<std::string> &ht) { char line[512]; while (in.getline(line, 512)) { size_t i = 0; std::string number; std::string data; while (line[i] != ',') { number += line[i]; ++i; } ++i; while (line[i] == ' ') { ++i; } while (line[i] != '\0') { data += line[i]; ++i; } ht[number] = data; } } int main() { HashTable<std::string> ht; std::ifstream fs("/home/vh/CLionProjects/DoubleHashF/data.txt"); makeTable(fs, ht); std::cout << ht["788GGG7"] << std::endl; std::cout << ht.get("AI9896D") << std::endl; std::cout << ht["AC57577"] << std::endl; std::cout << ht.contains("AJ89899") << std::endl; ht.remove("AJ89899"); std::cout << ht.contains("AJ89899") << std::endl; return 0; } ``` README.md ```# My algorithms and data structures collection * [BigInteger and Big Rational](https://github.com/VladislavHacker/Algorithms/blob/master/BigInteger/BigInt.cpp) * [Data structures](https://github.com/VladislavHacker/Algorithms/tree/master/DataStructures) + [Tuple](https://github.com/VladislavHacker/Algorithms/tree/master/Tuple) + [Heap](https://github.com/VladislavHacker/Algorithms/blob/master/DataStructures/heap.cpp) + [Stack based on list](https://github.com/VladislavHacker/Algorithms/blob/master/DataStructures/stack.cpp) + [Stack based on two queue](https://github.com/VladislavHacker/Algorithms/blob/master/DataStructures/stack_queue.cpp) + [Persistent stack](https://github.com/VladislavHacker/Algorithms/blob/master/DataStructures/persistent_stack.cpp) + [Hash table with double hash](https://github.com/VladislavHacker/Algorithms/blob/master/DataStructures/Hash_Table_DoubleHash.h) + [Hash table](https://github.com/VladislavHacker/Algorithms/blob/master/DataStructures/hash_table.cpp) + [Segment tree](https://github.com/VladislavHacker/Algorithms/blob/master/DataStructures/SegmentTree.cpp) + [Sparse table](https://github.com/VladislavHacker/Algorithms/blob/master/DataStructures/SparseTable.cpp) * [Graphs](https://github.com/VladislavHacker/Algorithms/tree/master/GraphTheory) + [BFS](https://github.com/VladislavHacker/Algorithms/blob/master/GraphTheory/dfs%26bfs/bfs.cpp) + [Kosaraju algorithms](https://github.com/VladislavHacker/Algorithms/blob/master/GraphTheory/dfs%26bfs/kosarajuAlgorithm.cpp) + [Topological sort](https://github.com/VladislavHacker/Algorithms/blob/master/GraphTheory/dfs%26bfs/topologicalSort.cpp) + [Kuhn algorithm](https://github.com/VladislavHacker/Algorithms/blob/master/GraphTheory/Kuhn/kuhn.cpp) + [Prima algorithm](https://github.com/VladislavHacker/Algorithms/blob/master/GraphTheory/MST/prima.cpp) + [Deikstra O(N^2)](https://github.com/VladislavHacker/Algorithms/blob/master/GraphTheory/ways/deikstraN2.cpp) + [Deikstra O(N log N)](https://github.com/VladislavHacker/Algorithms/blob/master/GraphTheory/ways/deikstraNlogN.cpp) + [Transitive closure with Floyd algorithm and bitset](https://github.com/VladislavHacker/Algorithms/blob/master/GraphTheory/ways/transitibeClosure.cpp) + [Gamma algorithm](https://github.com/VladislavHacker/Algorithms/blob/master/GammaAlgorithm/gamma.cpp) * [Numbers theory](https://github.com/VladislavHacker/Algorithms/tree/master/NumbersTheory) + [Evclid algorithm](https://github.com/VladislavHacker/Algorithms/blob/master/NumbersTheory/evclid_algorithm.cpp) + [Is prime](https://github.com/VladislavHacker/Algorithms/blob/master/NumbersTheory/simple_number.cpp) * [Trees](https://github.com/VladislavHacker/Algorithms/tree/master/Trees) + [Trivial binary tree](https://github.com/VladislavHacker/Algorithms/blob/master/Trees/bynary_tree.cpp) + [Treap](https://github.com/VladislavHacker/Algorithms/blob/master/Trees/treap.cpp) + [Splay tree](https://github.com/VladislavHacker/Algorithms/blob/master/Trees/SplayTree.cpp) + [AVL tree](https://github.com/VladislavHacker/Algorithms/blob/master/Trees/AvlTree.cpp) + [Expressions tree](https://github.com/VladislavHacker/Algorithms/blob/master/Trees/ExpressionsTree.cpp) * [Some metaprogramming algorithms](https://github.com/VladislavHacker/Algorithms/tree/master/Metaprogramming) + [Compile-time is simple](https://github.com/VladislavHacker/Algorithms/blob/master/Metaprogramming/is_simple_metafunction.cpp) + [Is constructible](https://github.com/VladislavHacker/Algorithms/blob/master/Metaprogramming/is_constructible.cpp) + [Has member](https://github.com/VladislavHacker/Algorithms/blob/master/Metaprogramming/has_member.cpp) * [Sorting algorithms](https://github.com/VladislavHacker/Algorithms/tree/master/Sorts) + [Radix sort (binary variant)](https://github.com/VladislavHacker/Algorithms/blob/master/Sorts/binary_lsd.cpp) + [MSD sort](https://github.com/VladislavHacker/Algorithms/blob/master/Sorts/binary_msd.cpp) + [Sorting with bitset](https://github.com/VladislavHacker/Algorithms/blob/master/Sorts/bit_sort.cpp) + [Heap sort](https://github.com/VladislavHacker/Algorithms/blob/master/Sorts/heap_sort.cpp) + [Merge sort](https://github.com/VladislavHacker/Algorithms/blob/master/Sorts/merge_sort.cpp) + [Qsort with dofferent optimizations](https://github.com/VladislavHacker/Algorithms/blob/master/Sorts/qsort.cpp) + [K-stat (k-th order element)](https://github.com/VladislavHacker/Algorithms/blob/master/Sorts/k-stat.cpp) * [Strings algorithms](https://github.com/VladislavHacker/Algorithms/tree/master/Sorts) + [Knut-Morris-Prat algorithm with z-function](https://github.com/VladislavHacker/Algorithms/blob/master/Strings/KnutMorrisPrat.cpp) + [Aho-Korasik algorithm](https://github.com/VladislavHacker/Algorithms/blob/master/Strings/AhoKorasik.cpp) + [Manakers algorithm](https://github.com/VladislavHacker/Algorithms/blob/master/Strings/ManakersAlgorithm.cpp) + [Suffix tree (Ukkonen algorithm)](https://github.com/VladislavHacker/Algorithms/blob/master/Strings/Ukkonen.cpp) + [Suffix array and unique substrungs count](https://github.com/VladislavHacker/Algorithms/blob/master/Strings/SuffixArrayUniqueStrings.cpp) + [Suffix array and unique substrungs k-statistics](https://github.com/VladislavHacker/Algorithms/blob/master/Strings/SuffixArrayKStatSubstring.cpp)``` SparseTable.cpp ```#include <algorithm> #include <iostream> #include <vector> #include <cmath> class SparseTable { public: explicit SparseTable (const std::vector<long long> &v) { v_ = v; for (size_t i = 0; i < v_.size() + 2; ++i) { log_.push_back(ceil(log2(i))); } table_.assign( ceil(log2(v_.size())), std::vector< std::pair <long long, long long> > (v_.size(), std::make_pair(0, 0)) ); for (size_t i = 0; i < v_.size(); ++i) { table_[0][i] = std::make_pair(v_[i], v_[i]); } for (size_t i = 1; i < table_.size(); ++i) { for (size_t j = 0; j < table_[i].size() - pow2(i) + 1; ++j) { table_[i][j] = min(table_[i - 1][j], table_[i - 1][j + pow2(i - 1)]); } } } ~SparseTable() = default; long long query (size_t l, size_t r) { size_t k = log_[r - l + 1] - 1; return min(table_[k][l], table_[k][r - pow2(k) + 1]).second; } private: static std::pair <long long, long long> min ( const std::pair <long long, long long> &a, const std::pair <long long, long long> &b ) { std::vector <long long> v = { a.first, a.second, b.first, b.second }; std::sort(v.begin(), v.end()); long long first = v[0]; for (long long x : v) { if (x != first) { return std::make_pair(first, x); } } return std::make_pair(first, first); } static size_t pow2 (size_t k) { return 1 << k; } typedef std::vector < std::vector< std::pair <long long, long long> > > Table; std::vector <long long> v_; Table table_; std::vector <size_t> log_; }; void getInput ( std::istream &in, std::vector<long long> &v, std::vector< std::pair <size_t, size_t> > &queries ) { size_t n, m; in >> n >> m; long long x; for (size_t i = 0; i < n; ++i) { in >> x; v.push_back(x); } size_t l, r; for (size_t i = 0; i < m; ++i) { in >> l >> r; queries.emplace_back(l, r); } } void makeQueries ( const std::vector<long long> &v, const std::vector< std::pair <size_t, size_t> > &queries, std::vector<long long> &results ) { SparseTable st(v); for (auto q : queries) { results.push_back(st.query(q.first - 1, q.second - 1)); } } void setOutput ( std::ostream &out, std::vector <long long> &result ) { for (size_t res : result) { out << res << std::endl; } } int main() { std::vector<long long> v; std::vector< std::pair <size_t, size_t> > queries; getInput(std::cin, v, queries); std::vector <long long> results; makeQueries(v, queries, results); setOutput(std::cout, results); return 0; }``` SplayTree.cpp ```#include <iostream> #include <functional> template <typename T, typename V> class SplayTree { private: class Node { public: Node(const T& key, Node* left, Node* right, Node* parent, const V& value) : key(key), left(left), right(right), parent(parent), value(value) {} T key; V value; Node* left; Node* right; Node* parent; }; public: SplayTree() { root = nullptr; } ~SplayTree() { postOrder(root, [](Node* v) { delete v; }); } void postOrder(Node* v, const std::function<void(Node*)>& callback) { if (v == nullptr) { return; } postOrder(v->left, callback); postOrder(v->right, callback); callback(v); } std::pair<Node*, Node*> split(Node* v, T key) { if (v == nullptr) { return std::make_pair(nullptr, nullptr); } Node* left; Node* right; if (v->key > key) { std::pair<Node*, Node*> t = split(v->left, key); v->left = t.second; if (t.second != nullptr) { p(t.second) = v; } left = t.first; right = v; } else { std::pair<Node*, Node*> t = split(v->right, key); v->right = t.first; if (t.first != nullptr) { p(t.first) = v; } right = t.second; left = v; } return std::make_pair(left, right); } Node* merge(Node* l, Node* r) { if (l == nullptr) { return r; } if (r == nullptr) { return l; } Node* m = max(l); splay(m); m->right = r; p(r) = m; return m; } void add(T x, const V& value) { if (root == nullptr) { root = new Node(x, nullptr, nullptr, nullptr, V()); } else { add(root, x, value); } } void remove(T key) { Node* v = find(root, key); splay(v); if (v->left != nullptr) { v->left->parent = nullptr; } if (v->right != nullptr) { v->right->parent = nullptr; } Node* tree = merge(v->left, v->right); delete v; root = tree; tree->parent = nullptr; } V& operator [] (T key) { Node* v = find(root, key); splay(v); root = v; return v->value; } private: void add(Node*, T key, const V& value) { auto trees = split(root, key); root = merge(merge(trees.first, new Node(key, nullptr, nullptr, nullptr, value)), trees.second); } Node* max(Node* v) { if (v->right == nullptr) { return v; } else { return max(v->right); } } Node* find(Node* v, T key) { if (v->key == key) { return v; } if (v->key > key) { return find(v->left, key); } else { return find(v->right, key); } } Node*& p(Node* v) { return v->parent; } Node*& g(Node* v) { return p(p(v)); } void rotateLeft(Node* v) { Node* p = this->p(v); Node* r = v->right; if (p != nullptr) { (p->left == v ? p->left : p->right) = r; } Node* tmp = r->left; r->left = v; v->right = tmp; this->p(v) = r; this->p(r) = p; if (v->right != nullptr) { this->p(v->right) = v; } } void rotateRight(Node* v) { Node* p = this->p(v); Node* l = v->left; if (p != nullptr) { (p->right == v ? p->right : p->left) = l; } Node* tmp = l->right; l->right = v; v->left = tmp; this->p(v) = l; this->p(l) = p; if (v->left != nullptr) { this->p(v->left) = v; } } void splay(Node* v) { while (p(v) != nullptr) { if (v == p(v)->left) { if (g(v) == nullptr) { rotateRight(p(v)); // zig } else if (p(v) == g(v)->left) { rotateRight(g(v)); // zig-zig rotateRight(p(v)); } else { rotateRight(p(v)); // zig-zag rotateLeft(p(v)); } } else { if (g(v) == nullptr) { rotateLeft(p(v)); // zig } else if (p(v) == g(v)->right) { rotateLeft(g(v)); // zig-zig rotateLeft(p(v)); } else { rotateLeft(p(v)); // zig-zag rotateRight(p(v)); } } } } Node* root; }; int main() { SplayTree<int, std::string> t; t.add(5, "hh"); t.add(7, "hhi"); t.add(1, "hh"); t.add(8, "hh"); t.remove(1); std::cout << t[7]; std::cout << t[7]; std::cout << t[7]; std::cout << t[7]; return 0; } ``` simple_number.cpp ```#include <iostream> using namespace std; bool is_simple(int a){ if (a <=1 ) return false; for (int d = 2; d*d<=a; d++) if (a % d == 0) return false; return true; } int main(){ cout<<"Please, write number for testing"<<endl; int a; cin>>a; if (is_simple(a)) cout<<"This number is simple"; else cout<<"This number isn't simple"; return 0; } ``` k-stat.cpp ```#include <iostream> #include <algorithm> using std::cin; using std::cout; using std::endl; using std::swap; using std::rand; template <typename T> int partition(T *a, int l, int r) { int mid = l + (r - l) / 2; if (a[l] > a[r]) swap(a[l], a[r]); if (a[mid] > a[r]) swap(a[mid],a[r]); if (a[l] < a[mid]) swap(a[l],a[mid]); int pivot = a[l]; int i = r; for (int j = r; j > l; j--) { if (a[j] > pivot) { swap(a[i],a[j]); i--; } } swap(a[i],a[l]); return i; } template <typename T> T kstat(T *a, int l, int r,int& k) { int p; while (l < r){ p = partition(a, l, r); if (p == k) return a[k]; if (k < p) r = p - 1; else l = p + 1; } return a[k]; } int main() { int n, k; cin >> n >> k; int* a = new int[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } cout << kstat(a,0,n-1,k); delete[] a; return 0; } ``` KnutMorrisPrat.cpp ```#include <iostream> #include <vector> #include <string> std::vector<size_t> findPositions( const std::string &pattern, const std::string &text ) { std::string s = pattern + "#" + text; size_t n = s.length(); size_t p = pattern.length(); std::vector<size_t> z (p, 0); std::vector<size_t> positions; size_t left = 0; size_t right = 0; for (size_t i = 1; i < n; ++i) { size_t z_val = 0; if (i <= right) { z_val = std::min(right - i + 1, z[i - left]); } while ( i + z_val < n && s[z_val] == s[i + z_val] ) { ++z_val; } if (i + z_val - 1 > right) { left = i; right = i + z_val - 1; } if (i < pattern.length()) { z[i] = z_val; //save only prefix } if (i > pattern.length() && z_val == pattern.length()) { positions.push_back(i - pattern.length() - 1); } } return positions; } void getInput( std::istream &in, std::string &find_template, std::string &text ) { in >> find_template; in >> text; } void setOutput( std::ostream &out, std::vector<size_t> &positions ) { for (auto& pos : positions) { out << pos << " "; } } int main() { /* cin&cout optimization */ std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::string pattern, text; getInput(std::cin, pattern, text); std::vector <size_t> result = findPositions(pattern, text); setOutput(std::cout, result); return 0; }``` lsd_sort.cpp ```#include <iostream> #include <cmath> int getDigit(int i, int a){ int d = std::pow(10,i + 1); int d2 = d/10; return a % d / d2; } void LSD(unsigned long long *a,int n, int k) { int *c = new int[10]; unsigned long long *b = new unsigned long long[n]; for (int i = 0; i < k; i++) { for (int j = 0; j < 10; j++) c[j] = 0; for (int j = 0; j < n; j++){ c[getDigit(i, a[j])]++; } for (int j = 1; j < 10; j++) { c[j]+=c[j-1]; } for (int j = n - 1; j >= 0; j--) { b[c[getDigit(i, a[j])]-1] = a[j]; c[getDigit(i, a[j])]--; } for (int j = 0; j < n; j++){ a[j] = b[j]; } } delete []b; delete []c; } int main() { int n; std::cin>>n; auto *a = new unsigned long long[n]; int k = 1; unsigned long long t = 10; for (int i = 0; i < n; i++) { std::cin>>a[i]; while (a[i] >= t ){ k++; t*=10; } } LSD(a,n,k); for (int i = 0; i < n; i++){ std::cout<<a[i]<<" "; } return 0; } ``` evclid_algorithm.cpp ```#include <iostream> using namespace std; int gcd(int a,int b){ while ( a != 0 && b != 0 ) if ( a > b) a = a%b; else b = b%a; return a + b; } int main(){ int a,b; cout<<"Please, write two numbers for search gcd"<<endl; cin>>a>>b; cout<<"gcd "<<a<<" and "<<b<<": "<<gcd(a,b); return 0; } ``` stack.cpp ```#include <iostream> using std::cin; using std::cout; using std::freopen; class Elem { private: Elem* next; int val; public: /* constructor */ Elem(int val) { this->val = val; this->next = nullptr; } /* check next element */ bool hasNext() { if (this->next != nullptr) { return true; } else { return false; } } /* set next element */ void setNext(Elem* next) { this->next = next; } /* get pointer */ Elem* getNext() { return this->next; } /* set value */ void setVal(int val) { this->val = val; } /* get value */ int getVal() { return this->val; } }; class Stack{ private: Elem* first; //stack front public: /* constructor */ Stack() { this->first = nullptr; } /* destructor */ ~Stack() { while (!this->is_empty()) { this->pop(); } } /* push new element */ void push(int val){ if (this->first == nullptr) { this->first = new Elem(val); } else { Elem* tmp = this->first; this->first = new Elem(val); this->first->setNext(tmp); } } /* get and delete front element */ int pop(){ if (!this->is_empty()) { Elem* tmp = this->first; this->first = this->first->getNext(); int val = tmp->getVal(); delete tmp; return val; } else return -1; } /* check for items */ bool is_empty() { if (this->first != nullptr) { return false; } else { return true; } } }; int main() { Stack* st= new Stack(); st->push(5); cout<<st->pop(); return 0; } ``` bit_sort.cpp ```#include <vector> #include <iostream> #include <fstream> #include <string> template <size_t size> class BitSet { public: BitSet () { bits.assign(size, 0); } void set (size_t i) { size_t element_size = sizeof(size_t) * 8; size_t number_index = i / element_size; size_t position = i % element_size; bits[number_index] |= 1ull << position; } bool test (size_t i) { size_t element_size = sizeof(size_t) * 8; size_t number_index = i / element_size; size_t position = i % element_size; return (bits[number_index] & (1ull << position)) == (1ull << position); } private: std::vector<size_t> bits; }; void sort_bit (std::vector<size_t> &array) { BitSet <10000000> b; for (size_t x : array) { b.set(x); } array.clear(); for (size_t i = 0; i < 1000000; ++i) { if (b.test(i)) { array.push_back(i); } } } void read_file_to_vector (const std::string &file, std::vector<size_t> &numbers) { std::ifstream fin(file); while (!fin.eof()) { size_t x; fin >> x; numbers.push_back(x); } fin.close(); } void write_vector_to_file (const std::string &file, std::vector<size_t> &numbers) { std::ofstream out(file); for (size_t x : numbers) { out << x << " "; } out.close(); } void optimum_sort_bit (const std::string &file1, const std::string &file2) { BitSet <10000000> b; std::ifstream fin(file1); while (!fin.eof()) { size_t x; fin >> x; b.set(x); } std::ofstream out(file2); for (size_t i = 0; i < 1000000; ++i) { if (b.test(i)) { out << i << " "; } } } int main () { std::vector<size_t> array; read_file_to_vector("/home/vh/CLionProjects/sort_bits/nums.txt",array); sort_bit(array); write_vector_to_file("/home/vh/CLionProjects/sort_bits/result1.txt", array); optimum_sort_bit("/home/vh/CLionProjects/sort_bits/nums.txt", "/home/vh/CLionProjects/sort_bits/result2.txt"); return 0; } ``` persistent_stack.cpp ```#include <iostream> #include <vector> template <typename T> class Node { public: T key; Node* prev; Node(T key) { this->key = key; this->prev = nullptr; } Node(T key, Node<T>* prev) { this->key = key; this->prev = prev; } }; template <typename T> class PersistentStack { private: std::vector <Node<T>*> states; public: PersistentStack() { states.push_back(nullptr); } ~PersistentStack() { for (Node<T>*& node : states) { delete node; } } int push(int state, T key) { states.push_back(new Node<T>(key, states[state])); return states.size() - 1; } int pop(int state) { Node<T>* current = states[state]; Node<T>* newTop = nullptr; if (current->prev == nullptr) newTop = nullptr; else newTop = new Node<T>(current->prev->key, current->prev->prev); states.push_back(newTop); return states.size() - 1; } T top(int state) { return states[state]->key; } }; int main() { PersistentStack<int> ps; int state1 = ps.push(0,5); state1 = ps.push(state1, 6); state1 = ps.push(state1, 8); std::cout << ps.top(state1) << std::endl; int state2 = ps.push(0,15); state2 = ps.push(state2, 56); state2 = ps.push(state2, 87); std::cout << ps.top(state2) << std::endl; int state3 = ps.pop(state2); std::cout << ps.top(state2) << std::endl; std::cout << ps.top(state3) << std::endl; return 0; } ``` hash_table.cpp ```#include <iostream> #include <vector> #include <string> using std::string; using std::vector; class Element { public: string key; int value; bool deleted; explicit Element(const string key, int value) { this->key = key; this->value = value; this->deleted = false; } ~Element() { } }; class HashTable{ private: Element** v; int size; int n; /* хэш-функция для строки по схеме Горнера */ int HashFunction(const string &key, int &size, int p) { long long result = 0; for (int i = 0; i < key.length(); i++) result = (result * p + (int)key[i] + 1) % size; return result % size; } /* поиск */ int Find(string &key) { int hash = HashFunction(key, size, 3); //считаем хеш функцию int i = 1; int index = hash; while (v[index] != nullptr && v[index]->key != key) { //квадратичное пробирование index = (index + i) % size; i++; } if (v[index] == nullptr || v[index]->deleted) return -1; else return index; } /* вставка, перегруженный метод */ bool Insert(Element** v, int size, string key, int value) { int hash = HashFunction(key, size, 3); //считаем хеш функцию int i = 1; int index = hash; while (v[index] != nullptr && v[index]->key != key) { //квадратичное пробирование index = (index + i) % size; i++; } if (v[index] == nullptr || v[index]->deleted) { if (v[index] != nullptr) delete v[index]; v[index] = new Element(key, value); return true; } else { return false; } } /* перехеширование */ bool ReHash() { Element** arr = new Element*[size * 2]; InitNull(arr, size * 2); int newn = 0; for (int i = 0; i < size; i++) { if (v[i] != nullptr && !v[i]->deleted) { Insert(arr, this->size * 2, v[i]->key, v[i]->value); newn++; } if (v[i] != nullptr) delete v[i]; } delete []v; this->v = arr; this->size *= 2; this->n = newn; } /* инициализация nullptr */ void InitNull(Element** v, int size) { for (int i = 0; i < size; i++) v[i] = nullptr; } public: /* конструктор */ explicit HashTable() { this->size = 8; this->n = 0; v = new Element * [this->size]; InitNull(v, size); } /* деструктор */ ~HashTable() { for (int i = 0; i < size; i++) { if (v[i] != nullptr) delete v[i]; } delete []v; } /* вставка, перегруженный метод */ bool Insert(string key, int value) { if (((double)this->n) / ((double)this->size) >= 0.75) ReHash(); if (Insert(this->v, this->size, key, value)) { n++; return true; } else return false; } /* Удаление */ bool Delete(string key) { int index = Find(key); if (index != -1) { v[index]->deleted = true; return true; } else return false; } /* Проверка на наличие */ bool Has(string key) { int index = Find(key); if (index != -1) return true; else return false; } }; int main() { HashTable ht; string cmd, str; while ( !std::cin.fail() ) { std::cin >> cmd >> str; if (std::cin.fail()) break; if (cmd == "+"){ if (ht.Insert(str, 0)) std::cout << "OK" << std::endl; else std::cout << "FAIL" << std::endl; } else if (cmd == "-") { if (ht.Delete(str)) std::cout << "OK" << std::endl; else std::cout << "FAIL" << std::endl; } else if (cmd == "?") { if (ht.Has(str)) std::cout << "OK" << std::endl; else std::cout << "FAIL" << std::endl; } } return 0; } ``` kuhn.cpp ```#include <iostream> #include <string> #include <vector> enum { white = 0, grey = 1, black = 2 }; bool dfs ( std::vector < std::vector <size_t> > &graph, std::vector <char> &colors, std::vector <long long> &matching, size_t v ) { if (colors[v] != white) { return false; } colors[v] = grey; for (size_t i = 0; i < graph[v].size(); ++i) { if (matching[graph[v][i]] == -1 || dfs(graph, colors, matching, matching[graph[v][i]])) { matching[graph[v][i]] = v; return true; } } colors[v] = black; return false; } size_t kun ( std::vector < std::vector <size_t> > &graph, std::vector <long long> &matching ) { matching.assign(graph.size(), -1); std::vector <char> colors; size_t size = 0; for (size_t i = 0; i < graph.size(); ++i) { colors.assign(graph.size(), white); if (dfs(graph, colors, matching, i)) { ++size; } } return size; } void addVertixes ( std::vector <std::string> &str_graph, std::vector < std::vector <size_t> > &graph, long long x, long long y, size_t n, size_t m ) { for (long long i = x - 1; i <= x + 1; ++i) { if (i < 0 || i >= n) { continue; } if (i == x) { continue; } if (str_graph[i][y] == '*') { graph[x * m + y].push_back(i * m + y); } } for (long long j = y - 1; j <= y + 1; ++j) { if (j < 0 || j >= m) { continue; } if (j == y) { continue; } if (str_graph[x][j] == '*') { graph[x * m + y].push_back(x * m + j); } } } void getInput ( std::istream &in, std::vector < std::vector <size_t> > &graph, size_t &n, size_t &m, long long &a, long long &b, size_t &k ) { in >> n >> m >> a >> b; k = 0; std::vector <std::string> str_graph; graph.assign(n * m, std::vector <size_t>()); for (size_t i = 0; i < n; ++i) { std::string tmp; std::cin >> tmp; str_graph.push_back(tmp); } for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < m; ++j) { if (str_graph[i][j] == '*') { ++k; addVertixes(str_graph, graph, i, j, n, m); } } } } long long getTime ( std::vector < std::vector <size_t> > &graph, long long a, long long b, size_t k ) { if (a >= 2 * b) { return k * b; } else { std::vector <long long> matching; size_t size = kun(graph, matching); return size / 2 * a + (k - size) * b; } } void setOutput ( std::ostream &out, long long time ) { out << time; } int main() { size_t n, m, k; long long a, b; std::vector < std::vector <size_t> > graph; getInput(std::cin, graph, n, m, a, b, k); setOutput(std::cout, getTime(graph, a, b, k)); return 0; }``` treap.cpp ```#include <iostream> template <typename keyT, typename priorityT> class Treap{ public: keyT x; priorityT y; Treap<keyT, priorityT>* left; Treap<keyT, priorityT>* right; Treap<keyT, priorityT>* parent; Treap(keyT x, priorityT y, Treap<keyT, priorityT>* left, Treap<keyT, priorityT>* right) { this->x = x; this->y = y; this->left = left; this->right = right; } ~Treap() { if (this->left != nullptr) { delete this->left; } if (this->right != nullptr) { delete this->right; } } Treap<keyT, priorityT>* Merge(Treap<keyT, priorityT>* firstTree, Treap<keyT, priorityT>* secondTree) { if (firstTree == nullptr) return secondTree; if (secondTree == nullptr) return firstTree; if (firstTree->y > secondTree->y) { firstTree->right = Merge(firstTree->right, secondTree); return firstTree; } else { secondTree->left = Merge(firstTree, secondTree->left); return secondTree; } } void Split(keyT x, Treap<keyT, priorityT>*& outLeft, Treap<keyT, priorityT>*& outRight) { Treap<keyT, priorityT>* newTreap = nullptr; if (this->x <= x) { if (this->right == nullptr) outRight = nullptr; else this->right->Split(x, newTreap, outRight); this->right = newTreap; outLeft = this; } else { if (this->left == nullptr) outLeft = nullptr; else this->left->Split(x, outLeft, newTreap); this->left = newTreap; outRight = this; } } Treap<keyT, priorityT>* Insert(Treap<keyT, priorityT>* tp, keyT x, priorityT y) { if (tp == nullptr) return new Treap<keyT, priorityT>(x, y, nullptr, nullptr); if (tp->y > y) { if (x < tp->x) tp->left = Insert(tp->left, x, y); else tp->right = Insert(tp->right, x, y); return tp; } else { Treap<keyT, priorityT>* outLeft = nullptr; Treap<keyT, priorityT>* outRight = nullptr; tp->Split(x, outLeft, outRight); return new Treap<keyT, priorityT>(x, y, outLeft, outRight); } } int Depth(Treap<keyT, priorityT>* tp) { int lDepth = 0; int rDepth = 0; if (tp->left != nullptr) lDepth = Depth(tp->left); if (tp->right != nullptr) rDepth = Depth(tp->right); return 1 + ( lDepth > rDepth ? lDepth : rDepth); } }; int main() { int n; std::cin >> n; int x, y; std::cin >> x >> y; Treap <int, int>* tp = new Treap <int, int>(x, y, nullptr, nullptr); for (int i = 1; i < n; i++) { std::cin >> x >> y; tp = tp->Insert(tp, x, y); } delete tp; return 0; } ``` prima.cpp ```#include <algorithm> #include <iostream> #include <limits> #include <set> #include <vector> enum { unused = 0, used = 1, }; size_t primaMinOstovTree ( size_t &n, size_t &m, std::vector < std::vector < std::pair <size_t, size_t> > > &graph ) { std::set < std::pair <size_t, size_t> > queue; std::vector <size_t> min_edges(n, std::numeric_limits<size_t>::max()); std::vector <long long> end_edges(n, -1); std::vector <char> is_used(n, unused); min_edges[0] = 0; queue.emplace(0, 0); for (size_t i = 0; i < n; ++i) { size_t v = queue.begin()->second; is_used[v] = used; queue.erase(queue.begin()); for (size_t j = 0; j < graph[v].size(); ++j) { if (is_used[graph[v][j].first] == unused && graph[v][j].second < min_edges[graph[v][j].first]) { queue.erase(std::pair <size_t, size_t> (min_edges[graph[v][j].first], graph[v][j].first)); min_edges[graph[v][j].first] = graph[v][j].second; end_edges[graph[v][j].first] = v; queue.emplace(min_edges[graph[v][j].first], graph[v][j].first); } } } size_t cost = 0; for (size_t i = 0; i < n; ++i) { cost += min_edges[i]; } return cost; } void getInput ( std::istream &in, size_t &n, size_t &m, std::vector < std::vector < std::pair <size_t, size_t> > > &graph ) { in >> n >> m; graph.assign(n, std::vector < std::pair <size_t, size_t> > ()); size_t from, to, weight; for (size_t i = 0; i < m; ++i) { in >> from >> to >> weight; if (from != to) { graph[from - 1].emplace_back(to - 1, weight); graph[to - 1].emplace_back(from - 1, weight); } } } void setOutput ( std::ostream &out, size_t size ) { out << size; } int main () { size_t n, m; std::vector < std::vector < std::pair <size_t, size_t> > > graph; getInput(std::cin, n, m, graph); setOutput(std::cout, primaMinOstovTree(n, m, graph)); return 0; }``` stack_queue.cpp ```#include <iostream> using std::cin; using std::cout; using std::freopen; class Elem { private: Elem* next; int val; public: /* constructor */ Elem(int val) { this->val = val; this->next = nullptr; } /* check next element */ bool hasNext() { if (this->next != nullptr) { return true; } else { return false; } } /* set next element */ void setNext(Elem* next) { this->next = next; } /* get pointer */ Elem* getNext() { return this->next; } /* set value */ void setVal(int val) { this->val = val; } /* get value */ int getVal() { return this->val; } }; class Stack{ private: Elem* first; //stack front public: /* constructor */ Stack() { this->first = nullptr; } /* destructor */ ~Stack() { while (!this->is_empty()) { this->pop(); } } /* push new element */ void push(int val){ if (this->first == nullptr) { this->first = new Elem(val); } else { Elem* tmp = this->first; this->first = new Elem(val); this->first->setNext(tmp); } } /* get and delete front element */ int pop(){ if (!this->is_empty()) { Elem* tmp = this->first; this->first = this->first->getNext(); int val = tmp->getVal(); delete tmp; return val; } else return -1; } /* check for items */ bool is_empty() { if (this->first != nullptr) { return false; } else { return true; } } }; class Queue { private: Stack* left; //первый стек Stack* right; //второй стек public: /* constructor */ Queue() { this->left = new Stack(); this->right = new Stack(); } /* destructor */ ~Queue() { delete this->left; delete this->right; } /* push element in the end */ void push_back(int val) { left->push(val); } /* get and delete first element */ int pop_front() { if (!this->right->is_empty()) { return this->right->pop(); } else if (!this->left->is_empty()) { while (!this->left->is_empty()) { this->right->push( this->left->pop() ); } return this->right->pop(); } else { return -1; } } }; int main() { Queue *q = new Queue(); q->push_back(5); cout<<q->pop_front(); return 0; } ``` has_member.cpp ```#include <iostream> /* Трюк для выполнения попыток создать объект */ template <typename...> using void_t = void; template <typename Void, typename T, typename... Args> struct my_is_constructible : std::false_type {}; /* тут все также как с is_constructible только пытаемся обратьться к функции-члену. */ template <typename T, typename... Args> struct my_is_constructible < void_t < decltype(T::member(std::declval<Args>()...)) >, T, Args... > : std::true_type { }; /* компилятор будет пытаться применить специализацию (когда T(std::declval<Args>()...) работает он сможет это сделать) * Если данная конструкция не валидна, компилятор будет использовать более общий случай */ template <typename T, typename... Args> using is_constructible = my_is_constructible<void_t<>, T, Args...>; class Test { public: explicit Test(int x) { } static void member(int z){ std::cout << z; } }; int main() { std::cout << is_constructible<Test, int>() << std::endl; std::cout << is_constructible<Test, std::string>() << std::endl; return 0; } ``` kosarajuAlgorithm.cpp ```/* Troyan-Golovyan Vladislav */ /* Contest 1, Task C */ #include <iostream> #include <vector> #include <utility> #include <functional> /* DFS */ void dfs ( const std::vector< std::vector<size_t> > &graph, size_t v, std::vector<char> &colors, const std::function<void (const size_t)> &in_callback, const std::function<void (const size_t)> &out_callback ) { colors[v] = 1; in_callback(v); for (size_t i = 0; i < graph[v].size(); ++i) { if (colors[graph[v][i]] == 0) { dfs(graph, graph[v][i], colors, in_callback, out_callback); } } out_callback(v); colors[v] = 2; } /* Function for graph condensation */ void condense_graph ( const std::vector< std::vector<size_t> > &graph, std::vector< std::vector<size_t> > &condensed_graph, std::vector<size_t> v_comp ) { for (size_t i = 0; i < graph.size(); ++i) { for (size_t j = 0; j < graph[i].size(); ++j) { if (v_comp[i] != v_comp[graph[i][j]]) { condensed_graph[v_comp[i]].push_back(v_comp[graph[i][j]]); } } } } /* Function for getting condensed oriented graph from */ void make_condensed_graph ( const std::vector<std::vector<size_t>> &graph, const std::vector<std::vector<size_t>> &trans_graph, std::vector<std::vector<size_t>> &condensed_graph ) { std::vector<size_t> order; std::vector<char> colors(graph.size(), 0); for (size_t i = 0; i < graph.size(); ++i) { if (colors[i] == 0) { dfs( graph, i, colors, [&] (const size_t v) { }, [&] (const size_t v) { order.push_back(v); } ); } } colors.assign(trans_graph.size(), 0); std::vector<std::vector<size_t>> components; std::vector<size_t> v_comp(graph.size(), 0); for (size_t i = 0; i < trans_graph.size(); ++i) { if (colors[order[graph.size() - i - 1]] == 0) { std::vector<size_t> component; dfs( trans_graph, order[graph.size() - i - 1], colors, [&] (const size_t v) { component.push_back(v); v_comp[v] = components.size(); }, [&] (const size_t v) {} ); components.push_back(component); } } condensed_graph.clear(); condensed_graph.assign(components.size(), std::vector<size_t> ()); condense_graph(graph, condensed_graph, v_comp); } /* Finds min edges count we need to build to make your graph strongly connected */ size_t count_roads ( const std::vector< std::vector<size_t> > &graph, std::vector< std::pair<size_t, size_t> > &in_out ) { if (graph.size() == 1) return 0; for (size_t i = 0; i < graph.size(); ++i) { in_out[i].first += graph[i].size(); for (size_t j : graph[i]) { in_out[j].second++; } } size_t count1 = 0; size_t count2 = 0; for (auto & deg : in_out) { if (deg.first == 0) { count1++; } if (deg.second == 0) { count2++; } } return count1 < count2 ? count2 : count1; } /* Get input data */ void get_input ( size_t &n, size_t &m, std::vector< std::vector<size_t> > &graph, std::vector< std::vector<size_t> > &trans_graph ) { std::cin >> n >> m; graph.assign(n, std::vector<size_t> ()); trans_graph.assign(n, std::vector<size_t> ()); for (size_t i = 0; i < m; ++i) { size_t a, b; std::cin >> a >> b; graph[a - 1].push_back(b - 1); trans_graph[b - 1].push_back(a - 1); } } /* Set output data */ void set_output (size_t count) { std::cout << count; } /* Main function */ int main () { size_t n, m; std::vector< std::vector<size_t> > graph; std::vector< std::vector<size_t> > trans_graph; get_input(n, m, graph, trans_graph); std::vector< std::vector<size_t> > condensed_graph; make_condensed_graph(graph, trans_graph, condensed_graph); std::vector< std::pair<size_t, size_t> > in_out_counts(condensed_graph.size(), std::pair<size_t, size_t>(0, 0)); set_output(count_roads(condensed_graph, in_out_counts)); return 0; }``` AhoKorasik.cpp ```#include <bitset> #include <iostream> #include <limits> #include <cstdint> #include <unordered_map> #include <vector> #include <functional> #include <thread> #include <queue> #include <chrono> #include <mutex> const int32_t ST_MAX = std::numeric_limits<int32_t>::max(); // max int32_t const int32_t RESERVE_TEXT_SIZE = 2000005; // reserve text size for optimization buffer const int32_t RESERVE_PATTERN_SIZE = 5000; // reserve pattern size for optimization buffer std::mutex protect_queue_mutex; /* Wrapper class for result processing */ template <typename T> class ResultProcessWrapper { public: explicit ResultProcessWrapper ( T& container, const std::function<void(T&, size_t)> processor ) : container(container), processor(processor) {} void process(size_t pos) { processor(container, pos); } private: T& container; std::function<void(T&, size_t)> processor; }; /* Trie class for Aho-Korasik algorithm */ template <typename T> class Trie { private: /* Trie vertex class with getters and setters */ class TrieVertex { public: TrieVertex(int32_t parent, char symbol, size_t alphabet_size); const int32_t& getLetterChild(const char& symbol) const; void setNextLetterChild(const char& symbol, const int32_t& vertex); const int32_t& getSuffix() const; void setSuffix(const int32_t &suffix); const int32_t& getGoodSuffix() const; void setGoodSuffix(const int32_t& suffix); const int32_t& getParent() const; void setParent(const int32_t& parent); const int32_t& getAutomateMove(const char& symbol) const; void setAutomateMove(const char& symbol, int32_t vertex); const char& getSymbol() const; void setTrueFlag(); const bool& getFlag() const; const int32_t& getPatternNumber() const; void setPatternNumber(const int32_t& number); private: std::vector<int32_t> children_; std::vector<int32_t> automate_move_; int32_t suffix_link_; int32_t good_suffix_link_; bool flag_; char symbol_; int32_t parent_; int32_t pattern_number_; }; public: explicit Trie (size_t alphabet_size = 256); const int32_t& next(const int32_t& vertex, const char& ); void addVertex(const int32_t& parent, const char& ); void addString(const std::string &s); const int32_t& getSuffixLink(const int32_t& vertex); const int32_t& getGoodSuffixLink(const int32_t& vertex); const int32_t& getAutomateMove(const int32_t& vertex, const char& i); void check( ResultProcessWrapper<T> &out, const std::string &s, const int32_t& v, const int32_t& i, std::vector<std::vector<int32_t>> &patterns_positions, std::vector<int32_t> &patterns_pos_vector_indexes, std::vector<int32_t> &result, const int32_t& pattern_len ); void findPositions( ResultProcessWrapper<T> &out, const std::string& s, std::vector<std::vector<int32_t>> &patterns_positions, std::vector<int32_t> &patterns_pos_vector_indexes, std::vector<int32_t> &result, int32_t pattern_len ); private: std::vector<TrieVertex> Trie_; std::vector<std::string> patterns_; size_t alphabet_size_; }; template <typename T> Trie<T>::Trie(size_t alphabet_size) : alphabet_size_(alphabet_size) { Trie_.emplace_back(0, 120, alphabet_size); } /* create vertex */ template <typename T> void Trie<T>::addVertex(const int32_t& parent, const char& i) { Trie_.emplace_back(parent, i, alphabet_size_); Trie_[parent].setNextLetterChild(i, Trie_.size() - 1); } /* next vertex getter */ template <typename T> const int32_t& Trie<T>::next(const int32_t& vertex, const char& i) { return Trie_[vertex].getLetterChild(i); } /* add string to Trie */ template <typename T> void Trie<T>::addString(const std::string &s) { int32_t num = 0; for (int32_t i = 0; i < s.length(); ++i) { const char& ch = s[i]; char index = static_cast<char>(ch - 'a'); if (next(num, index) == ST_MAX) { addVertex(num, index); } num = next(num, index); } patterns_.push_back(s); Trie_[num].setTrueFlag(); Trie_[num].setPatternNumber(patterns_.size() - 1); } /* suffix link getter */ template <typename T> const int32_t& Trie<T>::getSuffixLink(const int32_t& vertex) { if (Trie_[vertex].getSuffix() == ST_MAX) { if (vertex == 0 || Trie_[vertex].getParent() == 0) { Trie_[vertex].setSuffix(0); } else { Trie_[vertex].setSuffix ( getAutomateMove ( getSuffixLink(Trie_[vertex].getParent()), Trie_[vertex].getSymbol() ) ); } } return Trie_[vertex].getSuffix(); } /* compressed suffix link getter */ template <typename T> const int32_t& Trie<T>::getGoodSuffixLink(const int32_t& vertex) { if (Trie_[vertex].getGoodSuffix() == ST_MAX) { int32_t u = getSuffixLink(vertex); if (u == 0) { Trie_[vertex].setGoodSuffix(0); } else { Trie_[vertex].setGoodSuffix( Trie_[u].getFlag() ? u : getGoodSuffixLink(u) ); } } return Trie_[vertex].getGoodSuffix(); } /* automate step */ template <typename T> const int32_t& Trie<T>::getAutomateMove(const int32_t& vertex, const char& i) { if (Trie_[vertex].getAutomateMove(i) == ST_MAX) { if (Trie_[vertex].getLetterChild(i) != ST_MAX) { Trie_[vertex].setAutomateMove ( i, Trie_[vertex].getLetterChild(i) ); } else if (vertex == 0) { Trie_[vertex].setAutomateMove(i, 0); } else { Trie_[vertex].setAutomateMove( i, getAutomateMove(getSuffixLink(vertex), i) ); } } return Trie_[vertex].getAutomateMove(i); } /* check positions and write to stream results */ template <typename T> void Trie<T>::check( ResultProcessWrapper<T> &out, const std::string &s, const int32_t& v, const int32_t& i, std::vector<std::vector<int32_t>> &patterns_positions, std::vector<int32_t> &patterns_pos_vector_indexes, std::vector<int32_t> &result, const int32_t& pattern_len ) { int32_t u = v; int32_t patterns_count = patterns_.size(); int32_t patterns_last = patterns_count - 1; int32_t s_len = s.length(); while (u != 0) { if (Trie_[u].getFlag()) { const std::string& pat = patterns_[Trie_[u].getPatternNumber()]; int32_t pos = i - pat.length() + 1; const std::vector<int32_t>& pat_pos = patterns_positions[patterns_pos_vector_indexes[Trie_[u].getPatternNumber()]]; for (int32_t it = 0; it < pat_pos.size(); ++it) { const int32_t& my_p = pat_pos[it]; if (pos >= my_p) { int32_t index = pos - my_p; ++result[index]; if ( Trie_[u].getPatternNumber() == patterns_last && result[index] == patterns_count && index <= s_len - pattern_len ) { out.process(index); result[index] = 0; } } } } u = getGoodSuffixLink(u); } if (patterns_.empty() && i <= s_len - pattern_len) { out.process(i); } } template <typename T> void Trie<T>::findPositions( ResultProcessWrapper<T> &out, const std::string &s, std::vector<std::vector<int32_t>> &patterns_positions, std::vector<int32_t> &patterns_pos_vector_indexes, std::vector<int32_t> &result, int32_t pattern_len ) { int32_t now = 0; int32_t s_len = s.length(); for (int32_t i = 0; i < s_len; ++i) { now = getAutomateMove(now, static_cast<char>(s[i] - 'a')); check(out, s, now, i, patterns_positions, patterns_pos_vector_indexes, result, pattern_len); } } template <typename T> Trie<T>::TrieVertex::TrieVertex( int32_t parent, char symbol, size_t alphabet_size ) : parent_(parent), symbol_(symbol), suffix_link_(ST_MAX), good_suffix_link_(ST_MAX), pattern_number_(ST_MAX), flag_(false) { children_.assign(alphabet_size, ST_MAX); automate_move_.assign(alphabet_size, ST_MAX); } template <typename T> const int32_t& Trie<T>::TrieVertex::getLetterChild(const char& symbol) const { return children_[symbol]; } template <typename T> void Trie<T>::TrieVertex::setNextLetterChild(const char& symbol, const int32_t& vertex) { children_[symbol] = vertex; } template <typename T> const int32_t& Trie<T>::TrieVertex::getSuffix() const { return suffix_link_; } template <typename T> void Trie<T>::TrieVertex::setSuffix(const int32_t &suffix) { suffix_link_ = suffix; } template <typename T> const int32_t& Trie<T>::TrieVertex::getGoodSuffix() const { return good_suffix_link_; } template <typename T> void Trie<T>::TrieVertex::setGoodSuffix(const int32_t &suffix) { good_suffix_link_ = suffix; } template <typename T> const int32_t& Trie<T>::TrieVertex::getParent() const { return parent_; } template <typename T> void Trie<T>::TrieVertex::setParent(const int32_t &parent) { parent_ = parent; } template <typename T> const int32_t& Trie<T>::TrieVertex::getPatternNumber() const { return pattern_number_; } template <typename T> void Trie<T>::TrieVertex::setPatternNumber(const int32_t &num) { pattern_number_ = num; } template <typename T> const int32_t& Trie<T>::TrieVertex::getAutomateMove(const char& symbol) const { return automate_move_[symbol]; } template <typename T> void Trie<T>::TrieVertex::setAutomateMove(const char& symbol, int32_t vertex) { automate_move_[symbol] = vertex; } template <typename T> void Trie<T>::TrieVertex::setTrueFlag() { flag_ = true; } template <typename T> const bool& Trie<T>::TrieVertex::getFlag() const { return flag_; } template <typename T> const char& Trie<T>::TrieVertex::getSymbol() const { return symbol_; } template <typename T> void fillTrieWithPattern( Trie<T>& Trie, std::string &pattern, std::vector<std::vector<int32_t>> &positions, std::vector<int32_t> &patterns_pos_vector_indexes, bool &has_fictive_symbol ) { std::string current; int32_t pos = 0; if (pattern[pattern.length() - 1] != '?') { pattern += '?'; has_fictive_symbol = true; } std::unordered_map<std::string, int32_t> patterns_positions; for (int32_t i = 0; i < pattern.size(); ++i) { const char &ch = pattern[i]; if (ch != '?') { current += ch; } else if (!current.empty()){ Trie.addString(current); if (patterns_positions.find(current) != patterns_positions.end()) { positions[patterns_positions[current]].push_back(pos - current.length()); } else { patterns_positions[current] = positions.size(); positions.emplace_back(1, pos - current.length()); } patterns_pos_vector_indexes.push_back(patterns_positions[current]); current.clear(); } ++pos; } if (!current.empty()) { Trie.addString(current); --pos; if (patterns_positions.find(current) != patterns_positions.end()) { positions[patterns_positions[current]].push_back(pos - current.length()); } else { patterns_positions[current] = positions.size(); positions.emplace_back(1, pos - current.length()); } patterns_pos_vector_indexes.push_back(patterns_positions[current]); current.clear(); } } template <typename T> void search( ResultProcessWrapper<T> out, std::string &pattern, const std::string &s ) { Trie<T> Trie; std::vector<std::vector<int32_t>> patterns_positions; std::vector<int32_t> patterns_pos_vector_indexes; bool has_fictive_symbol = false; // true if we have fictive '?' in the end fillTrieWithPattern(Trie, pattern, patterns_positions, patterns_pos_vector_indexes, has_fictive_symbol); std::vector<int32_t> result(s.length(), 0); Trie.findPositions( out, s, patterns_positions, patterns_pos_vector_indexes, result, pattern.length() - static_cast<int32_t>(has_fictive_symbol) ); } void getInput( std::istream &in, std::string &pattern, std::string &s ) { in >> pattern >> s; } void threadOut(std::queue<size_t>& queue, std::ostream& out, bool& finished) { while (!finished || !queue.empty()) { protect_queue_mutex.lock(); while (!queue.empty()) { out << queue.front() << " "; queue.pop(); } protect_queue_mutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } } int main() { std::string pattern; std::string s; /* reserve space to increase performance (we needn't reallocate space) */ s.reserve(RESERVE_TEXT_SIZE); pattern.reserve(RESERVE_PATTERN_SIZE); /* cin&cout optimization */ std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); getInput(std::cin, pattern, s); std::queue<size_t> res_queue{}; bool finished = false; std::thread th(threadOut, std::ref(res_queue), std::ref(std::cout), std::ref(finished)); search( ResultProcessWrapper<std::queue<size_t>>( res_queue, [](std::queue<size_t>& out, size_t pos){ protect_queue_mutex.lock(); out.push(pos); protect_queue_mutex.unlock(); } ), pattern, s ); finished = true; th.join(); return 0; } ``` merge_sort.cpp ```#include <iostream> class isLess{ public: bool operator ()(int & a, int & b) { return a < b; } }; template <typename T, typename TLess> void merge(T *a, int l, int r, TLess& isLess) { int mid = l + (r - l) / 2; int i = 0; int j = 0; T *res = new int[r - l]; while(l + i < mid && mid + j < r) { if (isLess( a[l+i], a[mid + j]) ) { res[i + j] = a[l + i]; i++; } else { res[i + j] = a[mid + j]; j++; } } while(l + i < mid) { res[i + j] = a[l + i]; i++; } while(mid + j < r) { res[i + j] = a[mid + j]; j++; } for (int z = 0; z < r - l; z++){ a[l + z] = res[z]; } delete []res; } template <typename T, typename TLess> void mergeSort(T *a, int l, int r, TLess& isLess) { if (l + 1 >= r) return; int mid = l + (r - l) / 2; mergeSort(a, l, mid, isLess); mergeSort(a, mid, r, isLess); merge(a, l, r, isLess); } int main() { int *a = new int[10]; for (int i = 0; i < 10; i++) a[i] = 0; mergeSort(a, 0, 10, isLess()); return 0; }``` ManakersAlgorithm.cpp ```#include <iostream> #include <vector> #include <string> #include <cstdint> std::vector <int64_t> getManakerVector(const std::string &s, bool flag) { std::vector <int64_t> v(s.size(), 0); size_t n = s.size(); int64_t l = 0; int64_t r = -1; for (int64_t i = 0; i < n; ++i) { int64_t k; if (i > r) { k = static_cast<int>(flag); } else { k = std::min(v[l + r - i + static_cast<int>(!flag)], r - i + 1); } while ( i + k < n && i - k - static_cast<int>(!flag) >= 0 && s[i + k] == s[i - k - static_cast<int>(!flag)] ) { ++k; } v[i] = k; if (i + k - 1 > r) { l = i - k + static_cast<int>(flag); r = i + k - 1; } } return v; } size_t manakerAlgorithm(const std::string &s) { std::vector <int64_t> d1 = getManakerVector(s, true); // odd std::vector <int64_t> d2 = getManakerVector(s, false); // even size_t result = 0; for (size_t i = 0; i < s.size(); ++i) { result += d1[i] + d2[i]; } return result - s.size(); } void getInput( std::istream &in, std::string &s ) { in >> s; } void setOutput( std::ostream &out, const size_t &result ) { out << result; } int main() { std::string s; getInput(std::cin, s); setOutput(std::cout, manakerAlgorithm(s)); return 0; } ``` transitibeClosure.cpp ```#include <bitset> #include <iostream> #include <vector> void getInput ( std::vector < std::bitset < 1000 > > &graph, ) { int n; std::cin >> n; std::string data; for (int i = 0; i < n; ++i) { std::cin >> data; graph.emplace_back(data); } } void floydAlgorithm ( std::vector < std::bitset < 1000 > > &graph ) { int n = graph.size(); for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { if (graph[i].test(k)) { graph[i] |= graph[n - 1 - k]; } } } } void setOutput ( std::vector < std::bitset < 1000 > > &graph ) { int n = graph.size(); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { std::cout << graph[i][n - j - 1]; } std::cout << std::endl; } } int main() { std::vector < std::bitset <1000> > graph; std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); getInput(graph, n); floydAlgorithm(graph); setOutput(graph); return 0; }``` ExpressionsTree.cpp ```#include <iostream> #include <functional> class Tree { public: Tree(Tree* left, Tree*right) : left(left), right(right) {} Tree* left; Tree* right; void inOrder( const std::function<void(Tree*)> &callback ) { if (left != nullptr) { left->inOrder(callback); } callback(this); if (right != nullptr) { right->inOrder(callback); } } void preOrder ( const std::function<void(Tree*)> &callback ) { callback(this); if (left != nullptr) { left->preOrder(callback); } if (right != nullptr) { right->preOrder(callback); } } void postOrder( const std::function<void(Tree*)> &callback ) { if (left != nullptr) { left->postOrder(callback); } if (right != nullptr) { right->postOrder(callback); } callback(this); } int countLevel( int current_level, int find_level ) const { if (current_level == find_level) { return 1; } int result = 0; if (left != nullptr) { result += left->countLevel(current_level + 1, find_level); } if (right != nullptr) { result += right->countLevel(current_level + 1, find_level); } return result; } virtual void view(std::ostream &out) = 0; virtual int calculate() = 0; virtual ~Tree() = default; }; class MultiplyTree : public Tree { public: MultiplyTree(Tree* left, Tree*right) : Tree(left, right) {} int calculate() override { return left->calculate() * right->calculate(); } void view(std::ostream &out) override { out << '*'; } ~MultiplyTree() override = default; }; class SumTree : public Tree { public: SumTree(Tree* left, Tree*right) : Tree(left, right) {} int calculate() override { return left->calculate() + right->calculate(); } void view(std::ostream &out) override { out << '+'; } ~SumTree() override = default; }; class SubtractionTree : public Tree { public: SubtractionTree(Tree* left, Tree*right) : Tree(left, right) {} int calculate() override { return left->calculate() - right->calculate(); } void view(std::ostream& out) override { out << '-'; } ~SubtractionTree() override = default; }; class NumberTree : public Tree { public: NumberTree(Tree* left, Tree*right, int number) : Tree(left, right), number(number) {} int calculate() override { return number; } void view(std::ostream& out) override { out << number; } ~NumberTree() override = default; private: int number; }; bool sign(char ch) { if (ch == '+') { return true; } if (ch == '-') { return true; } if (ch == '*') { return true; } return false; } Tree* operand(const std::string& expression, size_t &i) { int number = 0; while (i < expression.length() && !sign(expression[i])) { number *= 10; number += expression[i] - 48; ++i; } return new NumberTree(nullptr, nullptr, number); } Tree* term(const std::string& expression, size_t &i) { Tree* tree = operand(expression, i); while (i < expression.length() && expression[i] == '*') { ++i; tree = new MultiplyTree(tree, operand(expression, i)); } return tree; } Tree* buildTree(const std::string& expression) { size_t i = 0; Tree* tree = term(expression, i); while (i < expression.length()) { if (sign(expression[i])) { if (expression[i] == '+') { ++i; tree = new SumTree(tree, term(expression, i)); } else if (expression[i] == '-') { ++i; tree = new SubtractionTree(tree, term(expression, i)); } } } return tree; } void prefixForm(std::ostream& out, Tree* tree) { tree->preOrder( [&](Tree* node) { node->view(out); std::cout << " "; } ); out << std::endl; } void removeTree(Tree* tree) { tree->postOrder( [&](Tree* node) { delete node; } ); } int calculateCount(Tree* tree, int level) { return tree->countLevel(0, level); } int main() { std::string expression; std::cin >> expression; Tree* tree = buildTree(expression); int level; std::cin >> level; std::cout << "Count elements in level " << level << ":" << std::endl; std::cout << calculateCount(tree, level) << std::endl; std::cout << "Prefix form:" << std::endl; prefixForm(std::cout, tree); std::cout << "Left calculate:" << std::endl; if (tree != nullptr && tree->left != nullptr) { std::cout << tree->left->calculate() << std::endl; } else { std::cout << "tree left or tree is empty :(" << std::endl; } removeTree(tree); return 0; } ``` deikstraN2.cpp ```#include <iostream> #include <vector> #include <utility> using namespace std; int min(int a,int b){ return a > b ? b : a; } int main(){ int n,s,f; cin>>n>>s>>f; s--; f--; int a[n][n]; int w[n]; bool u[n]; for (int i = 0; i < n; i++){ w[i] = 100000000;//расстояние до всех вершин бесконечно u[i] = false; } w[s] = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++){ cin>>a[i][j]; if (a[i][j]==-1) a[i][j] = 100000000000; //бесконечные ребра } for (int i = 1; i < n; i++){//просмотрим все вершины int v = -1; // индекс вершины расстояние от s до которой минимально for (int j = 0; j < n; j++){//поиск вершины if ( !u[j] && (v == -1 || w[j] < w[v])){ v = j; } } if (w[v] == 100000000) break; //не осталось вершин до которых можно дойти u[v] = true;//пометили что эту вершину мы уже посетили for (int j = 0; j < n; j++){ w[j] = min(w[j],w[v]+a[v][j]);//ищем что меньше , предыдущее найденное расстояние или сейчас найденное } } cout<< (w[f] == 100000000 ? -1 : w[f]); return 0; } ``` topologicalSort.cpp ``` CLion /* Troyan-Golovyan Vladislav*/ /* Contest 1, Task B*/ #include <iostream> #include <vector> #include <functional> /* DFS */ void dfs ( const std::vector< std::vector<size_t> > &graph, std::vector <char> &colors, size_t v, const std::function < void(size_t) > &in_callback, const std::function < void(size_t) > &out_callback, const std::function < bool(size_t) > &call_dfs_checker ) { colors[v] = 1; in_callback(v); for (size_t i = 0; i < graph[v].size(); ++i) { if (call_dfs_checker(graph[v][i])) { dfs(graph, colors, graph[v][i], in_callback, out_callback, call_dfs_checker); } } out_callback(v); colors[v] = 2; } /* Topological sort */ bool top_sort (const std::vector<std::vector<size_t>> &graph, std::vector<size_t> &sort_result) { std::vector<char> colors(graph.size(), 0); sort_result.clear(); bool res = true; for (size_t i = 0; i < graph.size() && res; ++i) { if (colors[i] == 0) { dfs( graph, colors, i, [&] (size_t v) { }, [&] (size_t v) { sort_result.push_back(v); }, [&] (size_t v) -> bool { if (colors[v] == 1) { res = false; } return colors[v] == 0; } ); } } return res; } /* Get input */ void get_input ( size_t &n, size_t &m, std::vector< std::vector<size_t> > &graph ) { std::cin >> n >> m; graph.assign(n, std::vector <size_t> ()); for (size_t i = 0; i < m; ++i) { size_t a, b; std::cin >> a >> b; graph[a].push_back(b); } } /* Set output */ void set_output ( const bool res, std::vector <size_t> sort_result ) { if (res) { std::cout << "YES" << std::endl; for (size_t i = 0; i < sort_result.size(); ++i) { std::cout << sort_result[sort_result.size() - i - 1] << " "; } } else { std::cout << "NO"; } } /* Main function */ int main() { size_t n, m; std::vector< std::vector<size_t> > graph; get_input(n, m, graph); std::vector <size_t> sort_result; bool res = top_sort(graph, sort_result); set_output(res, sort_result); return 0; }``` Ukkonen.cpp ```#include <iostream> #include <map> #include <string> #include <utility> #include <vector> #include <cstdint> #include <functional> enum { in_use = 1, not_used = 0 }; const std::string ALPHABET("qazwsxedcrfvtgbyhnujmikolp"); class TreeVertex { public: int64_t link_; int64_t parent_; int64_t left_; int64_t right_; std::map<char, int64_t> next_; TreeVertex() : left_(-1), right_(-1), parent_(-1), link_(0) {} TreeVertex (int64_t left, int64_t right, int64_t parent) : left_(left), right_(right), parent_(parent), link_(0) {} }; class State { public: int64_t node_; int64_t position_; State (int64_t node, int64_t pos) : node_(node), position_(pos) { } }; class SuffixTree { public: SuffixTree(std::string alphabet, const std::string& source, int64_t first_length) : first_length_(first_length), source_(source), size_(2), current_position_(0), source_length_(source.length()), state_(0, 0), tree_(source.length() << 2), letters_(std::move(alphabet)) { TreeVertex root; tree_[0] = root; build_(); } int64_t getsize_() const { return size_; } /* DFS with callback */ void dfs( std::vector<int64_t>& re_num, const std::function< void(const std::vector<TreeVertex>&, int64_t&, int64_t&) > &callback ) { std::vector<char> used(getsize_(), not_used); int64_t i = 1; dfs_(re_num, used, callback, 0, i); } private: void dfs_( std::vector<int64_t>& re_num, std::vector<char>& used, const std::function< void(const std::vector<TreeVertex>&, int64_t&, int64_t&) > &callback, int64_t vertex_number, int64_t &i ) { used[vertex_number] = in_use; if (vertex_number > 0) { re_num[vertex_number] = i; callback(tree_, vertex_number, first_length_); ++i; } for (auto elem : tree_[vertex_number].next_) { if (used[elem.second] == not_used) { dfs_(re_num, used, callback, elem.second, i); } } } void build_() { for (int64_t i = 2; i < tree_.size(); ++i) { tree_[i].right_ = source_length_ - 1; } for (char ch : letters_) { tree_[1].next_[ch] = 0; } tree_[1].next_['$'] = 0; tree_[1].next_['#'] = 0; tree_[0].link_ = 1; for (char& i : source_) { insertLetter_(i); ++current_position_; } } void insertLetter_(const char& symbol) { bool continueFlag; do { continueFlag = false; bool skipFlag = false; if (state_.position_ > tree_[state_.node_].right_) { if (tree_[state_.node_].next_.find(symbol) == tree_[state_.node_].next_.end()) { tree_[state_.node_].next_[symbol] = size_; tree_[size_].left_ = current_position_; tree_[size_].parent_ = state_.node_; ++size_; state_.node_ = tree_[state_.node_].link_; state_.position_ = tree_[state_.node_].right_ + 1; continueFlag = true; skipFlag = true; } if (!skipFlag) { state_.node_ = tree_[state_.node_].next_[symbol]; state_.position_ = tree_[state_.node_].left_; } } if (!skipFlag) { if (state_.position_ == -1 || source_[state_.position_] == symbol) { ++state_.position_; } else { tree_[size_] = TreeVertex(tree_[state_.node_].left_, state_.position_ - 1, tree_[state_.node_].parent_); tree_[size_].next_[source_[state_.position_]] = state_.node_; tree_[size_].next_[symbol] = size_ + 1; tree_[size_ + 1].left_ = current_position_; tree_[size_ + 1].parent_ = size_; tree_[state_.node_].left_ = state_.position_; tree_[state_.node_].parent_ = size_; tree_[tree_[size_].parent_].next_[source_[tree_[size_].left_]] = size_; size_ += 2; state_.node_ = tree_[tree_[size_ - 2].parent_].link_; state_.position_ = tree_[size_ - 2].left_; while (tree_[size_ - 2].right_ >= state_.position_) { state_.node_ = tree_[state_.node_].next_[source_[state_.position_]]; state_.position_ += 1 + tree_[state_.node_].right_ - tree_[state_.node_].left_; } if (state_.position_ == tree_[size_ - 2].right_ + 1) { tree_[size_ - 2].link_ = state_.node_; } else { tree_[size_ - 2].link_ = size_; } state_.position_ = tree_[state_.node_].right_ - (state_.position_ - tree_[size_ - 2].right_) + 2; continueFlag = true; } } } while (continueFlag); } std::vector<TreeVertex> tree_; int64_t current_position_; int64_t source_length_; int64_t first_length_; int64_t size_; std::string source_; State state_; std::string letters_; }; void getResultToStream( std::ostream& out, std::string& firstString, std::string& secondString ) { SuffixTree suffix_tree( ALPHABET, firstString + secondString, firstString.length() ); std::vector<int64_t> re_num(suffix_tree.getsize_(), 0); re_num[0] = 0; out << suffix_tree.getsize_() - 1 << "\n"; suffix_tree.dfs( re_num, [&] (const std::vector<TreeVertex>& tree, int64_t& vertex_number, int64_t& first_len) { out << re_num[tree[vertex_number].parent_] << " "; if (tree[vertex_number].left_ < first_len) { out << 0 << " "; out << tree[vertex_number].left_ << " "; if (tree[vertex_number].right_ < first_len ) { out << tree[vertex_number].right_ + 1; } else { out << first_len; } out << "\n"; } if (tree[vertex_number].left_ >= first_len) { out << 1 << " "; out << tree[vertex_number].left_ - first_len << " "; out << tree[vertex_number].right_ - first_len + 1; out << "\n"; } } ); } void getInput( std::istream& in, std::string& first_string, std::string& second_string ) { in >> first_string >> second_string; } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::string first_string, second_string; getInput(std::cin, first_string, second_string); getResultToStream(std::cout, first_string, second_string); return 0; } ``` BigInt.cpp ```#include <iostream> #include <vector> #include <string> #include <cassert> #include <ctime> class BigInteger { public: BigInteger () { sign_ = true; }; BigInteger (int b) { sign_ = b >= 0; b = b < 0 ? -b : b; number_.clear(); do { number_.push_back(b % base_); b /= base_; } while (b != 0); } BigInteger (size_t b, bool sign) { sign_ = sign; number_.clear(); do { number_.push_back(b % base_); b /= base_; } while (b != 0); } ~BigInteger () = default; BigInteger (const BigInteger& b) { base_ = b.base_; sign_ = b.sign_; number_ = b.number_; } BigInteger (const bool sign, const std::vector<size_t>& number, size_t base) { base_ = base; sign_ = sign; number_ = number; } BigInteger (const std::string& s) { sign_ = s[0] != '-'; size_t num_count = (s.length() - (s[0] == '-' ? 1 : 0)) / baze_pow_; size_t number; bool has = false; for (size_t i = 0; i < num_count; ++i) { number = 0; size_t j = 0; size_t k = s.length() - (i + 1) * baze_pow_ + j; while (j != baze_pow_ && k < s.length()) { number = number * 10 + static_cast<size_t>(s[k]) - 48; ++j; k = s.length() - (i + 1) * baze_pow_ + j; } number_.push_back(number); has = true; } number = 0; for (size_t i = (s[0] == '-' ? 1 : 0); i < s.length() - num_count * baze_pow_; ++i) { number = number * 10 + static_cast<size_t>(s[i]) - 48; } if (number != 0 || !has) { number_.push_back(number); } } BigInteger& operator = (const BigInteger& b) { if (this == &b) { return *this; } base_ = b.base_; sign_ = b.sign_; number_ = b.number_; return *this; } BigInteger& operator = (BigInteger&& b) noexcept { if (this == &b) { return *this; } base_ = b.base_; sign_ = b.sign_; number_ = b.number_; return *this; } BigInteger& operator ++ () { *this = *this + BigInteger(1); return *this; } BigInteger operator ++ (int) { BigInteger tmp = *this; *this = *this + BigInteger(1); return tmp; } BigInteger operator -- (int) { BigInteger tmp = *this; *this = *this - BigInteger(1); return tmp; } BigInteger& operator += (const BigInteger& a) { *this = *this + a; return *this; } BigInteger& operator -= (const BigInteger& a) { *this = *this - a; return *this; } BigInteger& operator *= (const BigInteger& a) { *this = *this * a; return *this; } BigInteger& operator /= (const BigInteger& a) { *this = *this / a; return *this; } BigInteger& operator %= (const BigInteger& a) { *this = *this % a; return *this; } friend BigInteger operator + (const BigInteger& a, const BigInteger& b) { if (!a.sign_ && b.sign_) { return b - (-a); } if (a.sign_ && !b.sign_) { return a - (-b); } size_t tmp = 0; std::vector <size_t> new_int; size_t n = a.number_.size() > b.number_.size() ? a.number_.size() : b.number_.size(); for (size_t i = 0; i < n; ++i) { if (i < a.number_.size()) { tmp += a.number_[i]; } if (i < b.number_.size()) { tmp += b.number_[i]; } new_int.push_back(tmp % a.base_); tmp -= tmp % a.base_; tmp = tmp / a.base_; } if (tmp != 0) { new_int.push_back(tmp); } return BigInteger(a.sign_, new_int, a.base_); } friend BigInteger operator - (const BigInteger& a, const BigInteger& b) { if (!a.sign_ && !b.sign_) return -((-a) - (-b)); if (!a.sign_) { return -(-a + b); } if (!b.sign_) { return a + (-b); } bool result_sign = a >= b; BigInteger x = a < b ? b : a; BigInteger y = a < b ? a : b; ssize_t tmp = 0; std::vector <size_t> new_int; for (size_t i = 0; i < y.number_.size(); ++i) { tmp += x.number_[i] - y.number_[i]; if (tmp < 0) { new_int.push_back(y.base_ + tmp); tmp = -1; } else { new_int.push_back(tmp % y.base_); tmp /= y.base_; } } for (size_t i = y.number_.size(); i < x.number_.size(); ++i) { tmp += x.number_[i]; if (tmp < 0) { new_int.push_back(x.base_ + tmp); tmp = -1; } else { new_int.push_back(tmp % y.base_); tmp /= y.base_; } } if (new_int.empty()) { return BigInteger("0"); } while (new_int[new_int.size() - 1] == 0 && new_int.size() > 1) { new_int.resize(new_int.size() - 1); } return BigInteger(result_sign, new_int, a.base_); } /* Multiply */ friend BigInteger operator * (const BigInteger& a, const BigInteger& b) { BigInteger x = a >= 0 ? a : -a; BigInteger y = b >= 0 ? b : -b; if (x == BigInteger(0) || y == BigInteger(0)) return BigInteger("0"); size_t n = x.number_.size() > y.number_.size() ? x.number_.size() : y.number_.size(); if (n == 1) { return BigInteger(x.toInt() * y.toInt(), a.sign_ == b.sign_); } size_t n_fix = n; size_t shift = 0; size_t x_shift = 0; size_t y_shift = 0; if (x > y) { shift += x.number_.size() - y.number_.size(); y_shift = x.number_.size() - y.number_.size(); } else { shift += y.number_.size() - x.number_.size(); x_shift = y.number_.size() - x.number_.size(); } if ((x.number_.size() + x_shift) % 2 != 0) { shift += 2; ++x_shift; ++y_shift; ++n_fix; } y.shiftLeft(y_shift); x.shiftLeft(x_shift); BigInteger x_l = x.getBigIntegerWithNumbers(0, n_fix / 2); BigInteger x_r = x.getBigIntegerWithNumbers(n_fix / 2, n_fix); BigInteger y_l = y.getBigIntegerWithNumbers(0, n_fix / 2); BigInteger y_r = y.getBigIntegerWithNumbers(n_fix / 2, n_fix); BigInteger first_multiply = x_l * y_l; BigInteger second_multiply; second_multiply = x_r * y_r; BigInteger third_multiply = (x_l + x_r) * (y_l + y_r); BigInteger calc = third_multiply - first_multiply - second_multiply; first_multiply.shiftLeft(n_fix); calc.shiftLeft(n_fix / 2); BigInteger result = first_multiply + calc + second_multiply; if (a.sign_ != b.sign_) { result = -result; } if (result != BigInteger(0)) return result.shiftRight(shift); else return result; } /* / operator */ friend BigInteger operator / (const BigInteger& a, const BigInteger& b) { if (b == BigInteger(0)) return BigInteger(0); if (a.sign_ && !b.sign_) { return -(a / (-b)); } if (!a.sign_ && b.sign_) { return -((-a) / b); } if (!a.sign_ && !b.sign_) { return (-a) / (-b); } if (b > a) { return BigInteger("0"); } if (b < a.base_) { return a.shortDiv((size_t)b); } ssize_t range_helper = a.number_.size() - b.number_.size(); BigInteger left(makeDecPow(range_helper - 1)); BigInteger right(makeDecPow(range_helper + 1)); BigInteger tmp = left + right; BigInteger tmpres; BigInteger difference = a - b; while (right - left > 1) { tmp = left + right; tmp = tmp.shortDiv(2); tmpres = tmp * b; if (tmpres > difference && tmpres <= a) return tmp; if (tmpres > a) { right = tmp; } else { left = tmp; } } if (left * b > difference && left * b <= a) return left; if (right * b > difference && right * b <= a) return right; return tmp; } friend BigInteger operator % (const BigInteger& a, const BigInteger& b) { return a - b * (a / b); } static std::string makeDecPow(ssize_t pow) { if (pow <= 0) { return "0"; } std::string t = "1"; for (ssize_t i = 0; i < pow; ++i) { t += "000000000"; } return t; } /* To string method */ std::string toString () const { std::string s; if (!sign_ && !(number_.size() == 1 && number_[0] == 0)) { s += "-"; } for (size_t i = 0; i < number_.size(); ++i) { std::string number; s += intToString(number_[number_.size() - i - 1], i != 0); } return s; } /* Unary + */ BigInteger operator - () const { return BigInteger(!sign_, number_, base_); } /* Unary - */ BigInteger operator + () const { return BigInteger(!sign_, number_, base_); } friend bool operator < (const BigInteger& a, const BigInteger& b) { if (a.sign_ && !b.sign_) { return false; } if (!a.sign_ && b.sign_) { return true; } if (!a.sign_ && !b.sign_) { return -a > -b; } if (a.number_.size() > b.number_.size()) { return false; } else if (a.number_.size() < b.number_.size()) { return true; } else { for (size_t i = 0; i < a.number_.size(); ++i) { size_t a_index = a.number_.size() - i - 1; size_t b_index = b.number_.size() - i - 1; if (a.number_[a_index] < b.number_[b.number_.size() - i - 1]) { return a.sign_; } else if (a.number_[a_index] > b.number_[b_index]) { return !a.sign_; } } return false; } } /* inequalities */ friend bool operator > (const BigInteger& a, const BigInteger& b) { return b < a; } friend bool operator >= (const BigInteger& a, const BigInteger& b) { return !(a < b); } friend bool operator <= (const BigInteger& a, const BigInteger& b) { return !(a > b); } friend bool operator != (const BigInteger& a, const BigInteger& b) { return a < b || b < a; } friend bool operator == (const BigInteger& a, const BigInteger& b) { return !(a != b); } /* out operator */ friend std::ostream& operator << (std::ostream& out, const BigInteger& a) { out << a.toString(); return out; } /* in operator */ friend std::istream& operator >> (std::istream& in, BigInteger& a) { std::string s; in >> s; a = BigInteger(s); return in; } explicit operator bool () const { return *this != BigInteger("0"); } explicit operator double () const { ssize_t num = 0; for (size_t i = 0; i < number_.size(); ++i) { num *= base_; num += number_[number_.size() - 1 - i]; } return num; } explicit operator size_t () const { size_t num = 0; for (size_t i = 0; i < number_.size(); ++i) { num *= base_; num += number_[number_.size() - 1 - i]; } return num; } private: BigInteger getBigIntegerWithNumbers (size_t l, size_t r) const { std::vector<size_t> new_nums; for (size_t i = l; i < r && i < number_.size(); ++i) { new_nums.push_back(number_[number_.size() - 1 - i]); } for (size_t i = 0; i < new_nums.size() / 2; ++i) { size_t tmp = new_nums[i]; new_nums[i] = new_nums[new_nums.size() - 1 - i]; new_nums[new_nums.size() - 1 - i] = tmp; } while (new_nums.size() > 1 && new_nums[new_nums.size() - 1] == 0) { new_nums.pop_back(); } if (!new_nums.empty()) { return BigInteger(true, new_nums, base_); } else { return BigInteger("0"); } } std::string intToString (size_t a, bool f=true) const { std::string result; size_t divide = base_; for (size_t i = 0; i < baze_pow_; ++i) { char num = static_cast<char>(a % divide / (divide / 10) + 48); if (num != '0' || f) { result += num; f = true; } divide /= 10; } return result.empty() ? "0" : result; } /* b < base */ BigInteger shortDiv (size_t b) const { size_t carry = 0; std::vector<size_t> res(number_.size(), 0); for (size_t i = 0; i < number_.size(); ++i) { size_t index = number_.size() - 1 - i; size_t current = number_[index] + carry * base_; res[index] = current / b; carry = current % b; } while (res.size() > 1 && res[res.size() - 1] == 0) { res.pop_back(); } return BigInteger(true, res, base_); } void shiftLeft (size_t n) { if (n == 0 || *this == BigInteger("0")) return; std::vector<size_t> tmp = number_; for (size_t i = 0; i < n; ++i) { number_.push_back(0); } for (size_t i = 0; i < number_.size() - n; ++i) { number_[number_.size() - 1 - i] = number_[number_.size() - n - 1 - i]; } for (size_t i = 0; i < n; ++i) { number_[i] = 0; } } BigInteger shiftRight (size_t n) { if (n == 0) { return *this; } for (size_t i = 0; i < number_.size() - n; ++i) { number_[i] = number_[i + n]; } number_.resize(number_.size() - n); return *this; } size_t toInt () const { ssize_t res = 0; for (size_t i = 0; i < number_.size(); ++i) { res = res * base_ + number_[number_.size() - 1 - i]; } if (!sign_) return -res; return res; } size_t base_ = 1000000000; size_t baze_pow_ = 9; bool sign_; std::vector <size_t> number_; }; class Rational { public: Rational (int b) { numerator_ = BigInteger(b); denominator_ = BigInteger(1); } Rational () { numerator_ = BigInteger(1); denominator_ = BigInteger(1); } Rational (const BigInteger &b) { numerator_ = b; denominator_ = BigInteger(1); } Rational (const BigInteger &a, const BigInteger &b) { if (a > 0 && b < 0) numerator_ = -a; else if (a < 0 && b < 0) { numerator_ = -a; } else { numerator_ = a; } denominator_ = b >= 0 ? b : -b; reduce(); } Rational (const Rational& b) { numerator_ = b.numerator_; denominator_ = b.denominator_; } std::string toString() { if (denominator_ == 1) { return numerator_.toString(); } else { return numerator_.toString() + "/" + denominator_.toString(); } } std::string asDecimal(size_t precision = 0) { BigInteger tmp = numerator_ / denominator_; BigInteger new_numerator = numerator_ % denominator_; std::string result = tmp.toString(); if (precision > 0) { result += "."; for (size_t i = 0; i < precision; ++i) { new_numerator *= 10; tmp = new_numerator / denominator_; if (tmp < 0) { tmp = -tmp; } new_numerator %= denominator_; if (i != precision - 1) result += tmp.toString(); } new_numerator *= 10; BigInteger next_tmp = new_numerator / denominator_; if (next_tmp >= 5 || next_tmp <= -5) { ++tmp; } result += tmp.toString(); } if (numerator_ < 0 && result[0] != '-') return '-' + result; return result; } Rational operator - () const { return -1 * *this; } Rational operator + () const { return *this; } Rational& operator += (const Rational& a) { *this = *this + a; return *this; } Rational& operator -= (const Rational& a) { *this = *this - a; return *this; } Rational& operator *= (const Rational& a) { *this = *this * a; return *this; } Rational& operator /= (const Rational& a) { *this = *this / a; return *this; } friend Rational operator + (const Rational& a, const Rational&b) { return Rational(a.numerator_ * b.denominator_ + b.numerator_ * a.denominator_, a.denominator_*b.denominator_); } friend Rational operator - (const Rational& a, const Rational&b) { return Rational(a.numerator_ * b.denominator_ - b.numerator_ * a.denominator_, a.denominator_*b.denominator_); } friend Rational operator * (const Rational& a, const Rational&b) { return Rational(a.numerator_ * b.numerator_ , a.denominator_*b.denominator_); } friend Rational operator / (const Rational& a, const Rational&b) { return Rational(a.numerator_ * b.denominator_, a.denominator_*b.numerator_); } friend bool operator < (const Rational& a, const Rational& b) { Rational tmp = a / b; return tmp.numerator_ < tmp.denominator_; } friend bool operator > (const Rational& a, const Rational& b) { return b < a; } friend bool operator >= (const Rational& a, const Rational& b) { return !(a < b); } friend bool operator <= (const Rational& a, const Rational& b) { return !(a > b); } friend bool operator == (const Rational& a, const Rational& b) { return !(a < b) && !(a > b); } friend bool operator != (const Rational& a, const Rational& b) { return !(a == b); } explicit operator double () { return ((double)numerator_ ) / ((double)denominator_); } private: void reduce () { BigInteger x = numerator_ >= 0 ? numerator_ : -numerator_; BigInteger y = denominator_ >= 0 ? denominator_ : - denominator_; while (x != 0 && y != 0) { if (x > y) { x = x % y; } else { y = y % x; } } numerator_ /= x + y; denominator_ /= x + y; } BigInteger numerator_; BigInteger denominator_; }; int main() { BigInteger a("9000"); BigInteger b("5000"); BigInteger c("4"); BigInteger d("-5"); BigInteger e("7"); BigInteger f("505"); BigInteger p("-25000"); assert(a + b == BigInteger("14000")); assert(a + c == BigInteger("9004")); assert(a + d == BigInteger("8995")); assert(a + d == BigInteger("8995")); assert(b - a == BigInteger("-4000")); assert(a - c == BigInteger("8996")); assert(a - d == BigInteger("9005")); assert(d - e == BigInteger("-12")); assert(c - e == BigInteger("-3")); assert(-a == BigInteger("-9000")); assert(-d == BigInteger("5")); assert(!(c > e)); assert(b > c); assert(c * e == BigInteger("28"));assert(b * d == BigInteger("-25000")); assert(b * e == BigInteger("35000")); assert(c * e == BigInteger("28")); assert(f * d == BigInteger("-2525")); BigInteger x; BigInteger y; Rational s; Rational t = -402365939; ((s = 1000000007) *= 1000000009) *= 2147483647; std::cout << (t/s).asDecimal(25); return 0; } ``` stack_alloc.cpp ```#include <iostream> template <typename T, size_t size = 1000> class StackAllocator { public: T mem[size]; //массив T* used; StackAllocator() { used = mem; } StackAllocator(const StackAllocator<T>& other) { used = other.used; mem = other.mem; } T* allocate(std::size_t n){ used += n; //заняли память return used - n; //вернули указатель на начало выделенного куска } void deallocate(T* p, size_t n) { if (p + n == used) { //Проверяем выполняется ли условие LIFO (стековый же аллокатор) used -= n; //освободили место } } }; int main() { /* выделяем 2 независимых куска */ StackAllocator<int> a; int* x = a.allocate(2); *x = 2; *(x + 1) = 3; std::cout << *(x + 1) << std::endl; int* y = a.allocate(2); *y = 21; *(y + 1) = 3; std::cout << *(x + 1) << std::endl; std::cout << *(y) << std::endl; return 0; } ``` SuffixArrayUniqueStrings.cpp ``` CLion #include <iostream> #include <string> #include <vector> #include <numeric> std::vector<int64_t> calculateLCP( const std::string &s, const std::vector<int64_t> &inverse_suffix_array, const std::vector<int64_t> &suffix_array ) { std::vector<int64_t> lcp(s.size()); size_t n = s.size(); int64_t current_lcp = 0; bool skip_iteration; for (int64_t i = 0; i < n; ++i) { skip_iteration = false; if (inverse_suffix_array[i] == n - 1) { skip_iteration = true; } if (!skip_iteration) { int64_t next = suffix_array[inverse_suffix_array[i] + 1]; while ( current_lcp + (i > next ? i : next) < n && s[i + current_lcp] == s[next + current_lcp] ) { ++current_lcp; } lcp[inverse_suffix_array[i]] = current_lcp; current_lcp = (current_lcp - 1 > 0l ? current_lcp - 1 : 0); } } return lcp; } std::vector<int64_t> buildSuffixArray( std::string s ) { s += "$"; int64_t n = s.size(); int64_t equivalence_classes_count = 0; int64_t sort_counter = 0; std::vector< std::vector <int64_t> > class_helper(256); std::accumulate( s.begin(), s.end(), 0, [&] (int64_t index, char el) -> int64_t { class_helper[el].emplace_back(index); return ++index; } ); std::vector<int64_t> suffix_array(n); /* zero step */ std::vector<int64_t> classes = std::accumulate( class_helper.begin(), class_helper.end(), std::vector<int64_t>(n), [&] (std::vector<int64_t>& classes, auto &element) -> std::vector<int64_t>& { for (int64_t u : element) { classes[u] = equivalence_classes_count; suffix_array[sort_counter++] = u; } if (element.size() != 0) { ++equivalence_classes_count; } return classes; } ); // get unique suffixes for (size_t l = 1; equivalence_classes_count < n; ++l) { std::vector< std::vector<int64_t> > a(equivalence_classes_count); // counting sort array std::vector<int64_t> new_classes(n, 0); int64_t new_classes_count = 0; sort_counter = 0; int64_t d = 1ull << (l - 1); int64_t k; for (size_t i = 0; i < n; ++i) { k = (suffix_array[i] - d + n) % n; a[classes[k]].emplace_back(k); } for (size_t i = 0; i < equivalence_classes_count; ++i) { for (size_t j = 0; j < a[i].size(); ++j) { // new class if ( j == 0 || classes[(a[i][j - 1] + d) % n] != classes[(a[i][j] + d) % n] ) { ++new_classes_count; } new_classes[a[i][j]] = new_classes_count - 1; suffix_array[sort_counter++] = a[i][j]; } } equivalence_classes_count = new_classes_count; classes = new_classes; } return std::vector<int64_t>( suffix_array.begin() + 1, suffix_array.end() ); } std::vector<int64_t> inverseSuffixArray( std::vector<int64_t>& suffix_array ) { std::vector<int64_t> inverse_suffix_array(suffix_array.size()); std::accumulate( suffix_array.begin(), suffix_array.end(), static_cast<uint64_t>(0), [&] (int64_t index, int64_t element) -> uint64_t { inverse_suffix_array[element] = index; return ++index; } ); return inverse_suffix_array; } size_t getUniqueSubstringsCount( std::string& s ) { std::vector<int64_t> suffix_array = buildSuffixArray(s); std::vector<int64_t> inverse_suffix_array = inverseSuffixArray(suffix_array); std::vector<int64_t> lcp = calculateLCP( s, inverse_suffix_array, suffix_array ); int64_t one = suffix_array.size() * suffix_array.size() - (suffix_array.size() * (suffix_array.size() - 1)) / 2; int64_t two = std::accumulate( lcp.begin(), lcp.end(), 0, [] (int64_t res, int64_t element) -> int64_t { return res + element; } ); return one - two; } void getInput( std::istream& in, std::string& s ) { in >> s; } void setOutput( std::ostream& out, const size_t& count ) { out << count; } int main() { /* in&out optimization */ std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::string s; getInput(std::cin, s); setOutput(std::cout, getUniqueSubstringsCount(s)); return 0; }``` is_simple_metafunction.cpp ```#include <iostream> /* Template params: * 1) number * 2) is number simple now * 3) sqrt(number) == counter size or number is simple * 4) counter params * */ template <int num, bool isSimple, bool isEnd, int... counter> class IsSimpleHelp { public: enum { result = IsSimpleHelp < num, !isSimple || num % sizeof...(counter) != 0, !isSimple || sizeof...(counter) * sizeof...(counter) >= num + 1, counter..., 1 >::result }; }; /* number is simple*/ template <int num, int... counter> class IsSimpleHelp <num, true, true, counter...> { public: enum { result = true }; }; /* isn't simple*/ template <int num, bool isEnd, int... counter> class IsSimpleHelp <num, false, isEnd, counter...> { public: enum { result = false }; }; template <int num> class IsSimple { public: enum { result = IsSimpleHelp<num, true, false, 1, 1>::result }; }; int main() { std::cout << IsSimple<120>::result << std::endl; std::cout << IsSimple<11>::result << std::endl; std::cout << IsSimple<112>::result << std::endl; std::cout << IsSimple<5>::result << std::endl; return 0; } ``` tuple.h ```#include <iostream> #include <vector> #include <utility> #include <cassert> #include <functional> #include <algorithm> #include <string> #include <tuple> #include <optional> template<typename... Args> class Tuple; template <> class Tuple<> { public: enum { size = 0 }; Tuple<> () { } virtual Tuple<>& operator = (const Tuple<>& other) { return *this; } Tuple (const Tuple<>& other) = default; virtual bool operator > (const Tuple <>& other) { return false; } virtual bool operator < (const Tuple <>& other) { return false; } void swap(Tuple<>& t) { } }; template <typename Top, typename... Bottom> class Tuple <Top, Bottom...> : public Tuple <Bottom...>{ public: enum { size = Tuple <Bottom...>::size + 1 }; typedef Tuple<Top, Bottom...> tuple_type; typedef Top type; Tuple() { } Tuple(const Top& top, const Bottom&... bottom) : Tuple<Bottom...>(bottom...) { top_ = top; } Tuple(Top&& top, Bottom&&... bottom) : Tuple<Bottom...>(std::forward<Bottom>(bottom)...) { top_ = top; } void swap(tuple_type& other) { type tmp = std::move(other.top_); other.top_ = std::move(top_); top_ = std::move(tmp); children_.swap(other.children_); } std::optional<type> top_; Tuple<Bottom...>& children_ = static_cast<Tuple<Bottom...>&>(*this); virtual bool operator < (const Tuple <Top, Bottom...>& other) { return top_ < other.top_ || children_ < other.children_; } virtual bool operator > (const Tuple <Top, Bottom...>& other) { return top_ > other.top_ || children_ > other.children_; } virtual bool operator != (const Tuple <Top, Bottom...>& other) { return *this < other || *this > other; } virtual bool operator == (const Tuple <Top, Bottom...>& other) { return !(*this < other) && !(*this > other); } virtual bool operator <= (const Tuple <Top, Bottom...>& other) { return !(*this > other); } virtual bool operator >= (const Tuple <Top, Bottom...>& other) { return !(*this < other); } virtual Tuple <Top, Bottom...>& operator = (const Tuple <Top, Bottom...>& other) { if (&other != this) { top_ = other.top_; children_ = other.children_; } return *this; } }; template<typename T, typename U> struct is_same { enum { value = 0 }; }; template<typename T> struct is_same<T, T> { enum { value = 1 }; }; template<int Index, typename Top, typename... Bottom> class GetByIndex { public: typedef typename GetByIndex<Index - 1, Bottom...>::return_type return_type; static return_type get (const Tuple<Top, Bottom...>& t) { return GetByIndex<Index - 1, Bottom...>::get(t); } static return_type& get (Tuple<Top, Bottom...> &t) { return GetByIndex<Index - 1, Bottom...>::get(t); } static return_type&& get (Tuple<Top, Bottom...> &&t) { return GetByIndex<Index - 1, Bottom...>::get(t); } }; template <typename Top, typename... Bottom> class GetByIndex <0, Top, Bottom...> { public: typedef typename Tuple<Top, Bottom...>::type return_type; static return_type get (const Tuple<Top, Bottom...>& t) { return *t.top_; } static return_type& get (Tuple<Top, Bottom...> &t) { return *t.top_; } static return_type&& get (Tuple<Top, Bottom...> &&t) { return *t.top_; } }; template<int Index, typename Head, typename... Bottom> const typename GetByIndex<Index, Head, Bottom...>::return_type& get (const Tuple<Head, Bottom...> &t) { return GetByIndex<Index, Head, Bottom...>::get(t); } template<int Index, typename Head, typename... Bottom> typename GetByIndex<Index, Head, Bottom...>::return_type&& get (Tuple<Head, Bottom...> &&t) { return std::move(GetByIndex<Index, Head, Bottom...>::get(t)); } template<int Index, typename Head, typename... Bottom> typename GetByIndex<Index, Head, Bottom...>::return_type& get (Tuple<Head, Bottom...>& t) { return GetByIndex<Index, Head, Bottom...>::get(t); } template <typename T, bool isEnd, typename Head, typename... Bottom> class GetIndexByType { public: using tuple_t = Tuple<Bottom...>; enum { index = GetIndexByType<T, is_same<T, Head>::value == 1 || sizeof...(Bottom) == 1, Bottom...>::index }; }; template <typename T, typename Head, typename... Bottom> class GetIndexByType <T, true, Head, Bottom...> { public: using tuple_t = Tuple<Head, Bottom...>; enum { index = tuple_t::size }; }; template <typename T, typename Head> class GetIndexByType <T, true, Head> { public: enum { index = 1 - is_same<T, Head>::value }; }; template<typename T, typename Head, typename... Bottom> typename GetByIndex< Tuple<Head, Bottom...>::size - GetIndexByType<T, false, Head, Bottom...>::index - 1, Head, Bottom...>::return_type get (const Tuple<Head, Bottom...>& t) { return GetByIndex< Tuple<Head, Bottom...>::size - GetIndexByType<T, false, Head, Bottom...>::index - 1, Head, Bottom...>::get(t); } template<typename T, typename Head, typename... Bottom> typename GetByIndex< Tuple<Head, Bottom...>::size - GetIndexByType<T, false, Head, Bottom...>::index - 1, Head, Bottom...>::return_type& get (Tuple<Head, Bottom...>& t) { return GetByIndex< Tuple<Head, Bottom...>::size - GetIndexByType<T, false, Head, Bottom...>::index - 1, Head, Bottom...>::get(t); } template <typename... Args> Tuple<Args...> makeTuple (Args... args) { return Tuple<Args...> (args...); } template <typename Tuple, bool isEnd, int Size, int... Index> class callHelp2 { public: enum { count = sizeof...(Index) }; template <typename... Args> static auto call (Tuple t, Args... args) { return callHelp2< Tuple, Size <= sizeof...(Index) + 1, Size, Index... # if Size >= count , sizeof...(Index) # endif >::call(t, args...); } }; template <typename Tuple, int Size, int... Index> class callHelp2 <Tuple, true, Size, Index...> { public: template <typename... Args> static auto call (Tuple t, Args... args) { return makeTuple(get<Index>(t)..., args...); } }; template <typename Tuple1, typename Tuple2, bool isEnd, int Size, int... Index> class callHelp { public: enum { count = sizeof...(Index) }; static auto call (Tuple1 t1, Tuple2 t2) { return callHelp< Tuple1, Tuple2, Size <= sizeof...(Index) + 1, Size, Index... # if Size >= count , sizeof...(Index) # endif >::call(t1,t2); } }; template <typename Tuple1, typename Tuple2, int Size, int... Index> class callHelp <Tuple1, Tuple2, true, Size, Index...> { public: using tuple2_t = typename std::remove_reference<Tuple1>::type; static auto call (Tuple1 t1, Tuple2 t2) { return callHelp2<Tuple1, false, tuple2_t::size, 0>::call(t1, get<Index>(t2)...); } }; template <typename Tuple1, typename Tuple2> auto concat (Tuple1 t1, Tuple2 t2) { using tuple1_t = typename std::remove_reference<Tuple2>::type; return callHelp<Tuple1, Tuple2, false, tuple1_t::size, 0>::call(t1, t2); } template <typename First, typename... Other> class concatter { public: static auto tupleCat(First f, Other... other) { return concat(f, concatter<Other...>::tupleCat(other...)); } }; template <typename First> class concatter <First> { public: static auto tupleCat(First f) { return f; } }; template <typename... Args> auto tupleCat(Args... args) { return concatter<Args...>::tupleCat(args...); } ``` bynary_tree.cpp ```#include <iostream> template <typename keyT> class Elem{ private: keyT x; Elem<keyT>* left; Elem<keyT>* right; public: Elem(keyT x) { this->x = x; this->left = nullptr; this->right = nullptr; } ~Elem() { } int GetVal() { return this->x; } void SetLeft(Elem<keyT>* left) { this->left = left; } void SetRight(Elem<keyT>* right) { this->right = right; } Elem* GetLeft() { return this->left; } Elem* GetRight() { return this->right; } }; template <typename keyT> class BinTree{ private: Elem<keyT>* root; Elem<keyT>* Add(Elem<keyT> * node, keyT x) { if (node == nullptr) { return new Elem<keyT>(x); } else if (node->GetVal() < x) { node->SetRight( Add(node->GetRight(), x) ); } else { node->SetLeft( Add(node->GetLeft(),x) ); } return node; } void DeleteTree(Elem<keyT>* node) { if (node != nullptr) { if ( node->GetLeft() != nullptr) { DeleteTree(node->GetLeft()); } if ( node->GetRight() != nullptr) { DeleteTree(node->GetRight()); } delete node; } } public: BinTree() { this->root = nullptr; } ~BinTree() { DeleteTree(this->root); } Elem<keyT>* GetRoot() { return this->root; } void Insert(keyT x) { this->root = this->Add(this->root, x); } void InorderTraversal(Elem<keyT>* node) { if (node != nullptr) { if (node->GetLeft() != nullptr) { InorderTraversal(node->GetLeft()); } std::cout << node->GetVal() << " "; if (node->GetRight() != nullptr) { InorderTraversal(node->GetRight()); } } } int Depth(Elem<keyT>* t) { int lDepth = 0; int rDepth = 0; if (t->GetLeft() != nullptr) lDepth = Depth(t->GetLeft()); if (t->GetRight() != nullptr) rDepth = Depth(t->GetRight()); return 1 + ( lDepth > rDepth ? lDepth : rDepth); } }; int main() { int n; std::cin >> n; int x; std::cin >> x; BinTree <int>* bt = new BinTree<int>(); bt->Insert(x); for (int i = 1; i < n; i++) { std::cin >> x; bt->Insert(x); } delete bt; return 0; } ``` qsort.cpp ```#include <iostream> #include <stack> #include <utility> #include <cstdlib> #include <ctime> using std::cin; using std::cout; using std::stack; using std::pair; using std::endl; using std::rand; using std::clock; void swap(int &a, int &b) { if (a == b) return; a = a ^ b; b = a ^ b; a = a ^ b; } int median (int a, int b, int c) { if (a > b) swap (a, b) ; if (b > c) swap (b, c) ; return b; } int randNum(int l, int r) { return rand() % (r - l + 1) + l; } void copy(int* a, int* b, int n) { for (int i = 0; i < n; i++) a[i] = b[i]; } void insertSort(int* a, int &l, int &r) { for (int i = l + 1; i <= r; i++) { int j = i; int x = a[i]; while (j > l && x < a[j - 1]) { a[j] = a[j - 1]; j--; } a[j] = x; } } int partition(int *a, int &l, int &r) { int piv = a[l + (r - l) / 2]; //Оказалось найболее эффективно //int piv = a[randNum(l,r)]; //Плохо оптимизирует //int piv = median(a[l], a[l + (r - l) / 2], a[r]); // +- так же по эффективности как выбор центрального элемента. int i = l - 1; int j = r + 1; do { do { i++; } while(a[i] < piv); do { j--; } while(a[j] > piv); if (i >= j) return j; swap(a[i],a[j]); } while (true); } void StandartQsort(int *a, int l, int r) { if (l < r) { int p = partition(a, l, r); StandartQsort(a, l, p); StandartQsort(a, p + 1 , r); } } void QsortWithOneRecursionBranch(int *a, int l, int r) { while (l < r) { int p = partition(a, l, r); if (p > l + ( r - l ) / 2) { QsortWithOneRecursionBranch(a, p + 1, r); r = p; } else { QsortWithOneRecursionBranch(a, l, p); l = p + 1; } } } void QsortWithoutRecursion(int *a, int l, int r) { stack < pair<int, int> > st; st.push(pair<int, int> (l, r)); while (!st.empty()) { pair <int, int> t = st.top(); st.pop(); if (t.first < t.second) { int p = partition(a, t.first, t.second); st.push(pair<int, int> (t.first, p)); st.push(pair<int, int> (p + 1, t.second)); } } } void QsortWithInsertionSortOptimization(int *a, int l, int r) { while (l < r) { if (r - l < 32){ insertSort(a, l ,r); l = r; } else { int p = partition(a, l, r); if (p > l + ( r - l ) / 2) { QsortWithInsertionSortOptimization(a, p + 1, r); r = p; } else { QsortWithInsertionSortOptimization(a, l, p); l = p + 1; } } } } void randomTestGenerator(int* a, int n) { for (int i = 0; i < n; i++) { a[i] = randNum(0,50000); } } int main() { int n; int k; cout << "Enter array size and tests count:" << endl; cin >> n >> k; cout << endl; int *b = new int[n]; int *a = new int[n]; double s1 = 0; double s2 = 0; double s3 = 0; double s4 = 0; cout << "Qsort" << "|" << "One branch" << "|" << "No recursively" << "|" << "One branch + insertSort" << " " << endl; for (int i = 0; i < k; i++) { srand(time(nullptr) + i); clock_t start; clock_t end; randomTestGenerator(b, n); // генерируем тест copy(a, b, n); start = clock(); StandartQsort(a, 0, n - 1); //обычная рекурсивная реализация end = clock(); double time1 = (((double)end / (double)CLOCKS_PER_SEC) - ((double)start / (double)CLOCKS_PER_SEC)); copy(a, b, n); start = clock(); QsortWithOneRecursionBranch(a, 0, n - 1); //одна ветка рекурсии - работает чуть чуть быстрее чем с двумя ветками end = clock(); double time2 = (((double)end / (double)CLOCKS_PER_SEC) - ((double)start / (double)CLOCKS_PER_SEC)); copy(a, b, n); start = clock(); QsortWithoutRecursion(a, 0, n - 1); //без рекурсии - работает очень медленно. end = clock(); double time3 = (((double)end / (double)CLOCKS_PER_SEC) - ((double)start / (double)CLOCKS_PER_SEC)); copy(a, b, n); start = clock(); QsortWithInsertionSortOptimization(a, 0, n - 1); //сортировка с оптимизацией вставками и одной веткой рекурсии, самый оптимальный алгоритм который я смог сделать end = clock(); double time4 = (((double)end / (double)CLOCKS_PER_SEC) - ((double)start / (double)CLOCKS_PER_SEC)); cout << time1 << " " << time2 << " " << time3 << " " << time4 << " " << endl; s1+= time1; s2+= time2; s3+= time3; s4+= time4; } double sa1 = s1 / k; double sa2 = s2 / k; double sa3 = s3 / k; double sa4 = s4 / k; cout << "Average Time" << endl; cout << "Qsort" << "|" << "One branch" << "|" << "No recursively" << "|" << "One branch + insertSort" << " " << endl; cout << sa1 << " " << sa2 << " " << sa3 << " " << sa4 << " "; delete []a; delete []b; return 0; } ``` heap_sort.cpp ```#include <iostream> using std::cin; using std::cout; template <typename MyType> void shiftDown( MyType* a, int i, int n) { int firstChild = 2 * i + 1; int secondChild = 2 * i + 2; int max = i; if (firstChild < n && a[max] < a[firstChild]) { max = firstChild; } if (secondChild < n && a[max] < a[secondChild]) { max = secondChild; } if (max != i) { //нам не нужно менять элемент так как он уже максимальный. MyType t = a[i]; a[i] = a[max]; a[max] = t; shiftDown(a, max, n); //востанавливакм свойство кучи } } template <typename MyType> void buildHeap(MyType* a, int n) { for (int i = n/2; i >= 0; i--){ shiftDown(a, i, n); //востанавливакм свойство кучи } } template <typename MyType> void heapSort( MyType* a, int n) { buildHeap(a, n); //строим кучу О(n) int m = n; for (int i = n - 1; i > 0; i--){ MyType t = a[i]; a[i] = a[0]; a[0] = t; //меняем местами последний элемент с корнем кучи m--; // на i-m месте стоит нужный элемент, он не нужен в куче shiftDown(a,0,m); //востановление свойства кучи } } int main() { int n; cin>>n; int* a = new int[n]; for (int i = 0; i < n; i++) { cin>>a[i]; } heapSort(a, n); for (int i = 0; i < n; i++) { cout<<a[i]<<" "; } return 0; } ``` AvlTree.cpp ```#include <iostream> template < typename T > class AVLTree{ public: T x; short height; int children; AVLTree<T>* left; AVLTree<T>* right; /* Конструктор */ AVLTree(T x) { this->x = x; this->left = nullptr; this->right = nullptr; this->height = 1; this->children = 1; } /* Деструктор */ ~AVLTree() { } /* Метод, возвращающий высоту дерева */ short GetHeight(AVLTree<T>* p) { return p == nullptr ? 0 : p->height; } /* Метод, возвращающий количество детей */ int CountChildren(AVLTree<T>* p) { return (p != nullptr ? p->children : 0); } /* Метод, считающий баланс-фактор дерева */ short BalanceFactor(AVLTree<T>* p) { if (p == nullptr) return 0; return GetHeight(p->right) - GetHeight(p->left); } /* Метод для исправления высоты при поворотах*/ void FixHeight(AVLTree<T>* p) { short LeftHeight = GetHeight(p->left); short RightHeight = GetHeight(p->right); p->height = LeftHeight > RightHeight ? LeftHeight + 1 : RightHeight + 1; } /* Метод для пересчета детей при поворотах*/ void FixChildren(AVLTree<T>* p) { short LeftCountChildren = CountChildren(p->left); short RightCountChildren = CountChildren(p->right); p->children = LeftCountChildren + RightCountChildren + 1; } /* Метод для поворота вправо, вокруг вершины */ AVLTree<T>* RotateRight(AVLTree<T>* p) { AVLTree<T>* q = p->left; p->left = q->right; q->right = p; FixHeight(p); FixChildren(p); FixHeight(q); FixChildren(q); return q; } /* Метод для поворота влево, вокруг вершины */ AVLTree<T>* RotateLeft(AVLTree<T>* q) { AVLTree<T>* p = q->right; q->right = p->left; p->left = q; FixHeight(q); FixChildren(q); FixHeight(p); FixChildren(p); return p; } /* Метод для балансировки дерева */ AVLTree<T>* BalanceAVLTree(AVLTree<T>* p) { FixHeight(p); FixChildren(p); if (BalanceFactor(p) == 2) { if (BalanceFactor(p->right) < 0) p->right = RotateRight(p->right); return RotateLeft(p); } if (BalanceFactor(p) == -2) { if (BalanceFactor(p->left) > 0) p->left = RotateLeft(p->left); return RotateRight(p); } return p; } /* Метод для вставки элемента*/ AVLTree<T>* Insert(AVLTree<T>* p, T x, int& result) { if (p == nullptr) return new AVLTree(x); p->children++; if (x < p->x) { result += CountChildren(p->right) + 1; p->left = Insert(p->left, x, result); } else { p->right = Insert(p->right, x, result); } return BalanceAVLTree(p); } /* Поиск минимума в дереве */ AVLTree<T>* FindMin(AVLTree<T>* p) { if (p->left != nullptr) return FindMin(p->left); else return p; } /* Удаление минимума в дереве*/ AVLTree<T>* RemoveMin(AVLTree<T>* p) { if( p->left == nullptr ) return p->right; p->left = RemoveMin(p->left); return BalanceAVLTree(p); } /* Удаление по ключу */ AVLTree<T>* Remove(AVLTree<T>* p, T x) { if (p == nullptr) return nullptr; p->children--; if(x < p->x) p->left = Remove(p->left, x); else if(x > p->x) p->right = Remove(p->right, x); else { AVLTree<T>* l = p->left; AVLTree<T>* r = p->right; delete p; if (r == nullptr) return l; AVLTree<T>* min = FindMin(r); min->right = RemoveMin(r); min->left = l; return BalanceAVLTree(min); } return p; } /* Метод для удаления дерева */ void DeleteTree(AVLTree<T>* p) { if (p->left != nullptr) DeleteTree(p->left); if (p->right != nullptr) DeleteTree(p->right); delete p; } /* Поиск ключа по номеру ребенка в порядке убывания */ int FindKeyByNumber(AVLTree<T>* p, int num) { if (p == nullptr) return 0; if (CountChildren(p->right) == num) return p->x; if (CountChildren(p->right) > num) return FindKeyByNumber(p->right, num); else return FindKeyByNumber(p->left, num - CountChildren(p->right) - 1); } }; int main() { int n; std::cin >> n; int command, height; AVLTree<int> *avl = nullptr; int res; for (int i = 0; i < n; i++) { std::cin >> command >> height; if (command == 1) { res = 0; if (avl == nullptr) { avl = new AVLTree<int> (height); std::cout << 0 << std::endl; } else { avl = avl->Insert(avl, height, res); std::cout << res << std::endl; } } else { if (avl != nullptr) avl = avl->Remove(avl, avl->FindKeyByNumber(avl, height)); } } if (avl != nullptr) avl->DeleteTree(avl); return 0; } ``` heap.cpp ```#include <iostream> #include <limits> using std::cin; using std::cout; using std::endl; using std::numeric_limits; /* Класс элемента бинарной кучи */ class Node{ private: int index; int val; public: Node(int index, int val) { this->index = index; this->val = val; } int getVal() { return this->val; } int getIndex() { return this->index; } }; /* Класс бинарной кучи */ class BinHeap { private: int size; Node **a; /* функция для обмена местами */ void swap(int i, int j){ Node* t = a[i]; a[i] = a[j]; a[j] = t; } public: /* Кунструктор кучи, принимает параметр - максимальный размер кучи */ BinHeap(int max) { this->size = 0; this->a = new Node*[max]; } /* Деструктор */ ~BinHeap() { for (int i = 0; i < size; i++) { delete a[i]; } delete []a; } /* Добавление элемента в кучу */ void add(int index, int val) { a[this->size++] = new Node(index, val); //создали элемент int i = size -1; int parent = (i - 1) / 2; //индекс родителя while (i > 0 && a[parent]->getVal() < a[i]->getVal()) { //поднимаем элемент пока он больше родителя, чтобы не потерять свойтво кучи this->swap(parent, i); i = parent; parent = (i - 1) / 2; } } /* востановление свойтв для вершины i */ void heapify(int i) { int leftChild; int rightChild; int bigestChild; bool f = true; //переменная, для хранения информации нужен ли нам еще цикл do { leftChild = 2 * i + 1; rightChild = 2 * i + 2; bigestChild = i; if (leftChild < this->size && a[leftChild]->getVal() > a[bigestChild]->getVal()) { bigestChild = leftChild; } if (rightChild < this->size && a[rightChild]->getVal() > a[bigestChild]->getVal()) { bigestChild = rightChild; } this->swap(i, bigestChild); if (i == bigestChild) //свойство выполняется, нам нужно закончить цикл f = false; i = bigestChild; } while (f); } /* извлечение корня */ Node* getRoot() { Node* res = a[0]; a[0] = a[this->size - 1]; this->size--; if (this->size > 0) this->heapify(0); //востановить свойства кучи, если в ней есть элементы return res; } /* получить размер кучи */ int getSize() { return this->size; } }; int main() { int n, k; cin >> n; BinHeap* bh = new BinHeap(n+10); delete bh; return 0; } ``` bfs.cpp ```#include <iostream> #include <vector> #include <queue> /* BFS */ void bfs (const std::vector <std::vector <size_t> > &graph, const size_t &v, const size_t &f, std::vector<ssize_t> &ways) { std::queue<size_t> q; q.push(v); ways[v] = 0; while (!q.empty()) { int current = q.front(); q.pop(); for (size_t u : graph[current]) { if (ways[u] == -1) { q.push(u); ways[u] = ways[current] + 1; } } } } /* Find ways count */ size_t find_way_count ( const std::vector<ssize_t> &matilda_ways, const std::vector<ssize_t> &leon_ways, const std::vector<ssize_t> &milk_ways ) { size_t min = matilda_ways[0] + milk_ways[0] + leon_ways[0]; for (size_t i = 0; i < matilda_ways.size(); i++) { if (matilda_ways[i] + milk_ways[i] + leon_ways[i] < min) { min = matilda_ways[i] + milk_ways[i] + leon_ways[i]; } } return min; } /* Get input */ void get_input ( std::vector <std::vector <size_t> > &graph, size_t &n, size_t &m, size_t &matilda, size_t &leon, size_t &milk ) { std::cin >> n >> m >> leon >> matilda >> milk; graph.assign(n, std::vector<size_t> ()); int a, b; for (int i = 0; i < m; ++i) { std::cin >> a >> b; graph[a - 1].push_back(b - 1); graph[b - 1].push_back(a - 1); } } /* Set output */ void set_output(size_t count) { std::cout << count; } /* Main function */ int main() { size_t n, m, matilda, leon, milk; std::vector <std::vector <size_t> > graph; get_input(graph, n, m, matilda, leon, milk); std::vector<ssize_t> matilda_ways(graph.size(), -1); bfs(graph, matilda - 1, milk - 1, matilda_ways); std::vector<ssize_t> leon_ways(graph.size(), -1); bfs(graph, leon - 1, milk - 1, leon_ways); std::vector<ssize_t> milk_ways(graph.size(), -1); bfs(graph, milk - 1, milk - 1, milk_ways); set_output(find_way_count(matilda_ways, leon_ways, milk_ways)); return 0; }``` SegmentTree.cpp ```#include <iostream> #include <vector> #include <tuple> #include <algorithm> #include <cmath> class SegmentTree { public: explicit SegmentTree (const std::vector <size_t> &tickets, size_t size) { size_t n = 2 * (1 << (size_t)ceil(log2((double)size))); tree_.assign(n - 1, std::make_pair(0, 0)); size_ = n / 2; for (size_t i = 0; i < tickets.size(); ++i) { tree_[tree_.size() / 2 + i].first = tickets[i]; } for (size_t i = tree_.size() / 2; i >= 1; --i) { tree_[i - 1].first = std::max( tree_[2 * (i - 1) + 1].first, tree_[2 * (i - 1) + 2].first ); } } size_t size () { return size_; } size_t getMax (size_t node, size_t tl, size_t tr, size_t l, size_t r) { if (tl > tr || l > r) { return 0; } if (l == tl && r == tr) { return tree_[node].first + tree_[node].second; } size_t p = tl + (tr - tl) / 2; size_t result = std::max ( getMax(2 * node + 1, tl, p, l, std::min(r, p)), getMax(2 * node + 2, p + 1, tr, std::max(l, p + 1), r) ) + tree_[node].second; return result; } void update (size_t node, size_t tl, size_t tr, size_t l, size_t r, size_t change) { if (tl > tr) { return; } if (l > r) { return; } if (l == tl && tr == r) { tree_[node].second += change; } else { size_t p = tl + (tr - tl) / 2; update(2 * node + 1, tl, p, l, std::min(r, p), change); update(2 * node + 2, p + 1, tr, std::max(l, p + 1), r, change); tree_[node].first = std::max( tree_[node * 2 + 1].first + tree_[2 * node + 1].second, tree_[node * 2 + 2].first + tree_[2 * node + 2].second ); } } private: std::vector < std::pair<size_t, size_t> > tree_; size_t size_; }; void getInput ( std::istream &in, std::vector <size_t> &tickets, size_t &volume, std::vector < std::tuple <size_t, size_t, size_t> > &queries ) { size_t n; in >> n; tickets.assign(n - 1, 0); for (size_t i = 0; i < n - 1; ++i) { in >> tickets[i]; } in >> volume; size_t m; in >> m; size_t x, y, count; for (size_t i = 0; i < m; ++i) { in >> x >> y >> count; queries.emplace_back(x, y, count); } } void setOutput ( std::ostream &out, std::vector <size_t> &result ) { for (size_t x : result) { out << x << " "; } } void makeQueries ( std::vector <size_t> &tickets, std::vector < std::tuple <size_t, size_t, size_t> > &queries, size_t volume, std::vector <size_t> &result ) { SegmentTree tree(tickets, tickets.size()); size_t i = 0; for (auto& q : queries) { if (tree.getMax(0, 0, tree.size() - 1, std::get<0>(q), std::get<1>(q) - 1) + std::get<2>(q) > volume) { result.push_back(i); } else { tree.update(0, 0, tree.size() - 1, std::get<0>(q), std::get<1>(q) - 1 , std::get<2>(q)); } ++i; } std::cout << std::endl; } int main() { std::vector <size_t> tickets; std::vector < std::tuple <size_t, size_t, size_t> > queries; size_t volume; getInput(std::cin, tickets, volume, queries); std::vector <size_t> result; makeQueries(tickets, queries, volume, result); setOutput(std::cout, result); return 0; }``` deikstraNlogN.cpp ``` CLion #include <algorithm> #include <iostream> #include <queue> #include <limits> #include <tuple> #include <vector> class IsLess { public: bool operator () ( std::tuple<size_t, ssize_t, size_t> &a, std::tuple<size_t, ssize_t, size_t> &b ) { return std::get<1>(a) < std::get<1>(b); } }; ssize_t deikstra ( std::vector < std::vector <std::pair <size_t, size_t > > > &graph, size_t n, size_t k, size_t s, size_t f ) { std::vector <size_t> ways(n, std::numeric_limits<size_t>::max()); std::priority_queue < std::tuple <size_t, ssize_t, size_t>, std::vector < std::tuple<size_t, ssize_t, size_t>>, IsLess > order ( (IsLess()) ); ways[s] = 0; order.emplace(s, ways[s], 0); for (size_t i = 0; i < graph.size(); ++i) { size_t v = std::get<0>(order.top()); size_t check = -std::get<1>(order.top()); size_t step = std::get<2>(order.top()); order.pop(); if (check != ways[v] || step >= k) { continue; } if (ways[v] == std::numeric_limits<size_t>::max()) { break; } for (size_t j = 0; j < graph[v].size(); ++j) { if (check + graph[v][j].second < ways[graph[v][j].first]) { ways[graph[v][j].first] = check + graph[v][j].second; order.emplace(graph[v][j].first, -ways[graph[v][j].first], step + 1); } } } return ways[f] != std::numeric_limits<size_t>::max() ? ways[f] : -1; } void getInput ( std::istream &in, std::vector < std::vector <std::pair <size_t, size_t > > > &graph, size_t &n, size_t &m, size_t &k, size_t &s, size_t &f ) { in >> n >> m >> k >> s >> f; --s; --f; graph.assign(n, std::vector <std::pair <size_t, size_t > > ()); for (size_t i = 0; i < m; ++i) { size_t s_i, f_i, p_i; in >> s_i >> f_i >> p_i; graph[s_i - 1].emplace_back(f_i - 1, p_i); } } void setOutput ( std::ostream &out, ssize_t cost ) { out << cost; } int main() { std::vector < std::vector <std::pair <size_t, size_t > > > graph; size_t n, m, k, s, f; getInput(std::cin, graph, n, m, k, s, f); setOutput(std::cout, deikstra(graph, n, k, s, f)); return 0; }``` binary_lsd.cpp ```#include <iostream> #include <cmath> using std::cin; using std::endl; using std::cout; using std::pow; int digit(unsigned long long n, unsigned long long k) { cout<<n<<" "<<k; return n & k == k ? 1 : 0; } void radixSort(unsigned long long *a, int n, int m){ int* c = new int[2]; unsigned long long* b = new unsigned long long[n]; int bin = 1; for(int i = 0; i < m; i++) { for (int j = 0; j < 2; j++) { c[j] = 0; } for (int j = 0; j < n; j++) { c[digit(a[j], bin)]++; } cout<<c[0]<<" "<<c[1]<<endl; int count = 0; for (int j = 0; j < 2; j++) { int t = c[j]; c[j] = count; count += t; } for (int j = 0; j < n; j++) { b[c[digit(a[j], bin)]++] = a[j]; } for (int j = 0; j < n; j++) { a[j] = b[j]; cout<<a[j]<<" "; } cout<<endl; bin*=2; cout<<bin<<endl; } delete []b; delete []c; } int main() { int n; cin>>n; unsigned long long* a = new unsigned long long[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } radixSort(a,n,32); for (int i = 0; i < n; i++) cout << a[i] << " "; return 0; } ``` binary_msd.cpp ```#include <iostream> using std::cin; using std::cout; using std::endl; unsigned long long pow(int a, int k) { if (k == 0) return 1; if (k % 2 == 1) return pow (a, k - 1) * a; else { unsigned long long res = pow (a, k / 2); return res * res; } } short kBit(unsigned long long a, int k) { unsigned long long u = pow(2, k); if ((a & u) == u) return 1; else return 0; } void MSDSort(long long * a, int l, int r, int k) { long long *b = new long long[r - l]; //перестановка на отрезке int *c = new int[2]; //массив для сортировки подсчетом for (int i = 0; i < 2; i++) { c[i] = 0; //обнуляем значения } for (int i = l; i < r; i++) { c[kBit(a[i], k)]++; //считаем биты } int* indexes = new int[2]; //массив для индексации for (int i = 0; i < 2; i++) { indexes[i] = c[i]; } int count = 0; //количество элементов которые находяться до iого элемента for (int i = 0; i < 2; i++) { int t = indexes[i]; indexes[i] = count; count += t; //увеличили счетчик } for (int i = l; i < r; i++) { //перестановка элементов int bit = kBit(a[i], k); b[indexes[bit]] = a[i]; indexes[bit]++; } for (int i = l; i < r; i++) { a[i] = b[i - l]; } delete []b; if (k > 0) { if (c[0] > 0) MSDSort(a, l, l + c[0], k - 1); if (c[1] - 1 > 0) MSDSort(a,l + c[0], l + c[0] + c[1], k - 1); } delete []c; delete []indexes; } int main() { int n; cin >> n; auto *a = new long long[n]; long long max = 0; for (int i = 0; i < n; i++) { cin >> a[i]; if (a[i] > max) max = a[i]; } int k = 0; while (max != 0){ max /= 2; k++; } MSDSort(a, 0, n, k); for (int i = 0; i < n; i++) cout << a[i] << " "; delete []a; return 0; }``` gamma.cpp ``` #include <iostream> #include <vector> #include <functional> #include <algorithm> class ComponentVertix { public: /* Default constructor */ ComponentVertix() { v_ = -1; type_ = false; } /* Constructor */ ComponentVertix (size_t v, bool type) { v_ = v; type_ = type; } /* = operator */ ComponentVertix& operator =(const ComponentVertix &right) { if (this == &right) { return *this; } v_ = right.v_; type_ = right.type_; return *this; } /* Get Vertex Number */ size_t GetNumber () const { return v_; } /* Check Point is Extreme */ bool IsExtreme () const { return type_; } private: size_t v_; bool type_; }; /* Component class */ class Component { public: /* Constructor */ Component () = default; /* Constructor */ Component (size_t u, size_t v) { vertix_.emplace_back(u, true); vertix_.emplace_back(v, true); } /* Get component size */ size_t Size() { return vertix_.size(); } /* Get component vertix */ const ComponentVertix& GetVertix(size_t i) { return vertix_[i]; } void AddVertix(size_t v, bool type) { vertix_.emplace_back(v, type); } /* Checks if vertix lie in component */ bool HasVertix(size_t v) { for (ComponentVertix &u : vertix_) { if (v == u.GetNumber()) { return true; } } return false; } private: std::vector<ComponentVertix> vertix_; }; /* Face class */ class Face { public: /* Default constructor */ Face () { external_ = false; } /* Face constructor */ Face (std::vector <size_t> &vertix, bool external) { vertix_ = vertix; external_ = external; } /* Split Face with chain*/ std::pair <Face, Face> Split (std::vector <size_t> &chain) { size_t start = chain[0]; size_t end = chain[chain.size() - 1]; size_t start_it = 0; while (vertix_[start_it] != start) { ++start_it; } size_t end_it = 0; while (vertix_[end_it] != end) { ++end_it; } std::vector<size_t > new_face(0); for (size_t i = start_it; i != end_it; i = (i + 1) % vertix_.size()) { new_face.push_back(vertix_[i]); } new_face.push_back(vertix_[end_it]); for (ssize_t i = 1; i < chain.size() - 1; ++i) { new_face.push_back(chain[chain.size() - i - 1]); } Face first = Face(new_face, external_); new_face.clear(); for (ssize_t i = start_it; i != end_it; i = i < 0 ? vertix_.size() - 1 : i - 1) { new_face.push_back(vertix_[i]); } new_face.push_back(vertix_[end_it]); for (ssize_t i = 1; i < chain.size() - 1; ++i) { new_face.push_back(chain[chain.size() - i - 1]); } Face second = Face(new_face, false); return std::pair <Face, Face> (first, second); } /* Check if Face contains components */ bool ContainsComponent (Component &component) { for (size_t i = 0; i < component.Size(); ++i) { if (component.GetVertix(i).IsExtreme()) { bool res = false; for (size_t v : vertix_) { if (v == component.GetVertix(i).GetNumber()) { res = true; } } if (!res) { return false; } } } return true; } private: std::vector <size_t> vertix_; //Face vertex bool external_; }; class Graph { public: /* Default constructor */ Graph () = default; /* Constructor */ explicit Graph (size_t n) { matrix_.assign(n, std::vector<bool> (n, false)); } /* Constructor */ Graph (Graph &g, Component &comp) { matrix_.assign(g.Size(), std::vector<bool> (g.Size(), false)); for (size_t i = 0; i < comp.Size(); ++i) { for (size_t j = 0; j < g.Size(); ++j) { if (g.HasEdge(comp.GetVertix(i).GetNumber(), j) && comp.HasVertix(j)) { matrix_[comp.GetVertix(i).GetNumber()][j] = true; } } } for (size_t i = 0; i < matrix_.size(); ++i) { bool test = false; for (size_t j = 0; j < matrix_[i].size(); ++j) { test |= matrix_[i][j]; } if (!test) { matrix_.erase(matrix_.begin() + i); --i; } } for (size_t j = 0; j < matrix_[comp.Size() - 1].size(); ++j) { bool test = false; for (size_t i = 0; i < comp.Size(); ++i) { test |= matrix_[i][j]; } if (!test) { for (size_t i = 0; i < comp.Size(); ++i) { matrix_[i].erase(matrix_[i].begin() + j); } j--; } } } /* Reassign graph with new size */ void Reassign (size_t n) { matrix_.assign(n, std::vector<bool> (n, false)); } /* Get Size */ size_t Size () { return matrix_.size(); } /* Add Edge to Graph */ void AddEdge (size_t u, size_t v) { matrix_[u][v] = true; matrix_[v][u] = true; } /* Has Edge */ bool HasEdge(size_t i, size_t j) const { return matrix_[i][j]; } /* Check and returns true if Graph planary via Gamma Algorithm */ bool IsPlanar() { if (IsForest()) { return true; } RemoveCutpoints(); RemoveBridges(); std::vector <Component> components; GetComponents(components); for (Component &comp: components) { if (comp.Size() > 1) { Graph g(*this, comp); if (!g.GammaAlgorithm()) { return false; } } } return true; } /* Check and returns true if Graph planary via Gamma Algorithm */ bool GammaAlgorithm () { if (matrix_.empty()) return true; if (IsForest()) return true; Graph laid_graph (matrix_.size()); std::vector <bool> laid_vertix (matrix_.size(), false); /* #1 Find cycle */ std::vector <size_t> cycle; GetRandomCycle(cycle); cycle.push_back(cycle[0]); PutChain(laid_graph, laid_vertix, cycle); cycle.resize(cycle.size() - 1); /* Add First Faces */ std::vector <Face> faces; faces.emplace_back(cycle, true); faces.emplace_back(cycle, false); std::vector<Component> components; do { components.clear(); GetGammaComponents(laid_graph, laid_vertix, components); std::vector < std::pair <size_t, size_t> > contains(components.size(), std::pair <size_t, size_t> (0, 0)); GetContainsCount(faces, components, contains ); //Get faces count contains every components if (!components.empty()) { if (contains[0].second == 0) { return false; } std::vector <size_t> chain; GetChain(laid_graph, laid_vertix, components[contains[0].first], chain); // Extract chain from component size_t i = 0; while (!faces[i].ContainsComponent(components[contains[0].first])) { //Find face that contain component i++; } PutChain(laid_graph, laid_vertix, chain); // Make chai std::pair <Face, Face> tmp = faces[i].Split(chain); faces[i] =tmp.first; faces.push_back(tmp.second); } } while (!components.empty()); return true; } /* Check if graph is Forest */ bool IsForest () { std::vector<char> colors(matrix_.size(), 0); for (size_t i = 0; i < matrix_.size(); ++i) { if (colors[i] == 0) { bool res = true; DFS( colors, i, -1, [&] (size_t v) { }, [&] (size_t v) { }, [&] (size_t v) -> bool { if (colors[v] == 1) { res = false; } return colors[v] == 0; } ); if (!res) { return res; } } } return true; } private: /* DFS */ void DFS ( std::vector <char> &colors, size_t v, size_t p, const std::function < void(size_t) > &in_callback, const std::function < void(size_t) > &out_callback, const std::function < bool(size_t) > &call_dfs_checker ) { colors[v] = 1; in_callback(v); for (size_t i = 0; i < matrix_[v].size(); ++i) { if ( i != p && matrix_[v][i] && call_dfs_checker(i) ) { DFS(colors, i, v, in_callback, out_callback, call_dfs_checker); } } out_callback(v); colors[v] = 2; } /* Overloaded DFS */ void DFS ( std::vector <char> &colors, size_t v, size_t p, const std::function < void(size_t, size_t) > &in_callback, const std::function < void(size_t, size_t) > &out_callback, const std::function < void(size_t, size_t) > &fail_dfs_callback, const std::function < bool(size_t, size_t) > &call_dfs_checker, const std::function < void(size_t, size_t) > &after_dfs_callback ) { colors[v] = 1; in_callback(v, p); for (size_t i = 0; i < matrix_[v].size(); ++i) { if ( i != p && matrix_[v][i]) { if (call_dfs_checker(i, v)) { DFS(colors, i, v, in_callback, out_callback, fail_dfs_callback, call_dfs_checker, after_dfs_callback); after_dfs_callback(i, v); } else { fail_dfs_callback(i, v); } } } out_callback(v, p); colors[v] = 2; } /* Overloaded DFS2 */ void DFS ( std::vector <char> &colors, size_t v, size_t p, const std::function < void(size_t, size_t, size_t* &) > &in_callback, const std::function < void(size_t, size_t, size_t* &) > &out_callback, const std::function < void(size_t, size_t, size_t* &) > &fail_dfs_callback, const std::function < bool(size_t, size_t, size_t* &) > &call_dfs_checker, const std::function < void(size_t, size_t, size_t* &) > &after_dfs_callback ) { colors[v] = 1; size_t* buffer = nullptr; in_callback(v, p, buffer); for (size_t i = 0; i < matrix_[v].size(); ++i) { if (i != p && matrix_[v][i]) { if (call_dfs_checker(i, v, buffer)) { DFS(colors, i, v, in_callback, out_callback, fail_dfs_callback, call_dfs_checker, after_dfs_callback); after_dfs_callback(i, v, buffer); } else { fail_dfs_callback(i, v, buffer); } } } out_callback(v, p, buffer); colors[v] = 2; } /* Get Random Cycle */ void GetRandomCycle (std::vector <size_t> &cycle) { std::vector <char> colors (matrix_.size(), 0); bool cycle_found; size_t cycle_start = -1; DFS( colors, 0, -1, [&] (size_t v) { }, [&] (size_t v) { if (v == cycle_start) { cycle.push_back(v); cycle_start = -1; } if (cycle_start != -1) { cycle.push_back(v); } }, [&] (size_t child) -> bool { if (colors[child] == 1) { cycle_start = child; } return cycle.empty() && cycle_start == -1 && colors[child] == 0; } ); } /* Get not laid components */ void GetGammaComponents ( const Graph &laid_graph, const std::vector <bool> &laid_vertix, std::vector <Component>& components ) { /* Get one edge segments */ for (size_t i = 0; i < matrix_.size(); ++i) { for (size_t j = i + 1; j < matrix_.size(); ++j) { if (i != j && matrix_[i][j] && !laid_graph.HasEdge(i, j) && laid_vertix[i] && laid_vertix[j]) { components.emplace_back(i, j); } } } /* Get Other Components */ std::vector<char> colors(matrix_.size(), 0); for (size_t i = 0; i < matrix_.size(); ++i) { if (!laid_vertix[i] && colors[i] == 0) { Component comp; DFS( colors, i, -1, [&] (size_t v) { comp.AddVertix(v, laid_vertix[v]); }, [&] (size_t v) {}, [&] (size_t v) -> bool { if (colors[v] == 0 && laid_vertix[v]) { comp.AddVertix(v, true); return false; } return colors[v] == 0; } ); if (comp.Size() != 1) { components.push_back(comp); } } } } /* Get Contains Count */ static void GetContainsCount ( std::vector <Face> &faces, std::vector <Component> &components, std::vector < std::pair <size_t, size_t> > &contains ) { for (size_t i = 0; i < components.size(); ++i) { contains[i].first = i; for (auto & face : faces) { if (face.ContainsComponent(components[i])) { contains[i].second++; } } } std::sort( contains.begin(), contains.end(), [] (std::pair <size_t, size_t> a, std::pair <size_t, size_t> b) -> bool { return a.second < b.second; } ); } /*Get chain method */ void GetChain ( Graph &laid_graph, std::vector <bool> &laid_vertex, Component &component, std::vector <size_t> &chain ) { ssize_t start = -1; for (size_t i = 0; i < component.Size() && start == -1; ++i) { if (component.GetVertix(i).IsExtreme()) { start = component.GetVertix(i).GetNumber(); } } ssize_t end = -1; std::vector <char> colors(matrix_.size(), 0); colors[start] = 1; for (size_t i = 0; i < matrix_[start].size(); ++i) { if (colors[i] == 0 && matrix_[start][i] && !laid_graph.HasEdge(start, i) && component.HasVertix(i)) { DFS( colors, i, component.GetVertix(start).GetNumber(), [&] (size_t v) { if (laid_vertex[v]) { chain.push_back(v); end = v; } }, [&] (size_t v) { if (end != -1) { chain.push_back(v); } }, [&] (size_t v) -> bool { if (!component.HasVertix(v)) { return false; } if (v == start) { return false; } if (end != -1) { return false; } return colors[v] == 0; } ); break; } } chain.push_back(start); std::reverse(chain.begin(), chain.end()); colors[start] = 2; } /*Put chain method */ static void PutChain ( Graph &laid_graph, std::vector <bool> &laid_vertex, std::vector <size_t> &chain, bool f = true ) { for (size_t i = 0; i < chain.size() - 1; ++i) { laid_graph.AddEdge(chain[i], chain[i + 1]); laid_vertex[chain[i]] = true; } laid_vertex[chain[chain.size() - 1]] = true; } /* Get graph components */ void GetComponents (std::vector <Component>& components) { std::vector<char> colors(matrix_.size(), 0); for (size_t i = 0; i < matrix_.size(); ++i) { if (colors[i] == 0) { Component comp; DFS( colors, i, -1, [&] (size_t v) { comp.AddVertix(v,false); }, [&] (size_t v) {}, [&] (size_t v) -> bool { return colors[v] == 0; } ); components.push_back(comp); } } }; /* Delete bridges */ void RemoveBridges () { size_t timer = 0; std::vector <char> colors(matrix_.size(), 0); std::vector <size_t> enter(matrix_.size(), std::numeric_limits<size_t>::max()); std::vector <size_t> ret(matrix_.size(), std::numeric_limits<size_t>::max()); std::vector < std::pair <size_t, size_t> > bridges; for (size_t i = 0; i < matrix_.size(); ++i) { if (colors[i] == 0) { DFS( colors, i, -1, [&] (size_t v, size_t p) { enter[v] = timer; ret[v] = timer; timer++; }, [&] (size_t v, size_t p) { }, [&] (size_t v, size_t p) { ret[p] = std::min(ret[p], enter[v]); }, [&] (size_t v, size_t p) -> bool { return colors[v] == 0; }, [&] (size_t v, size_t p) { ret[p] = std::min(ret[p], ret[v]); if (ret[v] > enter[p]) { bridges.emplace_back(v, p); } } ); } } for (auto & bridge : bridges) { matrix_[bridge.first][ bridge.second] = false; matrix_[bridge.second][ bridge.first] = false; } } /* Remove bridge */ void RemoveCutpoints () { size_t timer = 0; std::vector <char> colors(matrix_.size(), 0); std::vector <size_t> enter(matrix_.size(), std::numeric_limits<size_t>::max()); std::vector <size_t> ret(matrix_.size(), std::numeric_limits<size_t>::max()); std::vector < size_t > points; for (size_t i = 0; i < matrix_.size(); ++i) { if (colors[i] == 0) { DFS( colors, i, -1, [&] (size_t v, size_t p, size_t* &buffer) { enter[v] = timer; ret[v] = timer; timer++; buffer = new size_t[2]; buffer[0] = 0; buffer[1] = p; }, [&] (size_t v, size_t p, size_t* &buffer) { if (p == -1 && buffer[0] > 1) { points.push_back(v); } delete []buffer; }, [&] (size_t v, size_t p, size_t* &buffer) { ret[p] = std::min(ret[p], enter[v]); }, [&] (size_t v, size_t p, size_t* &buffer) -> bool { return colors[v] == 0; }, [&] (size_t v, size_t p, size_t* &buffer) { ret[p] = std::min(ret[p], ret[v]); if (ret[v] >= enter[p] && buffer[1] != -1) { points.push_back(p); } buffer[0]++; } ); } } for (size_t point : points) { TransformPoint(point); } } /* Transform points */ void TransformPoint (size_t v) { std::vector < std::vector <size_t> > children_groups; std::vector <char> colors(matrix_.size(), 0); for (size_t i = 0; i < matrix_[v].size(); ++i) { if (matrix_[v][i] && i != v && colors[i] == 0) { size_t start_point = v; std::vector <size_t> group; DFS( colors, i, v, [&] (size_t v, size_t p) { if (p == start_point) { group.push_back(v); } }, [&] (size_t v, size_t p) { }, [&] (size_t v, size_t p) { }, [&] (size_t v, size_t p) -> bool { if (v == start_point) { group.push_back(p); return false; } return colors[v] == 0; }, [&] (size_t v, size_t p) { } ); children_groups.push_back(group); } } for (size_t i = 0; i < matrix_.size(); ++i) { matrix_[v][i] = false; } for (size_t i = 0; i < children_groups[0].size(); ++i) { matrix_[v][children_groups[0][i]] = true; } for (size_t i = 1; i < children_groups.size(); ++i) { matrix_.emplace_back(matrix_.size(), false); for (size_t j = 0; j < matrix_.size(); ++j) { matrix_[j].push_back(false); } for (size_t j = 0; j < children_groups[i].size(); ++j) { matrix_[matrix_.size() - 1][children_groups[i][j]] = true; matrix_[children_groups[i][j]][matrix_.size() - 1] = true; } } } /* Graph matrix */ std::vector < std::vector<bool> > matrix_; }; /* Get input data */ void GetInput (size_t &n, size_t &m, Graph &g) { std::cin >> n >> m; g.Reassign(n); size_t u, v; for (size_t i = 0; i < m; ++i) { std::cin >> u >> v; if (u != v) { g.AddEdge(u, v); } } } /* Set output */ void SetOutput (const bool &res) { std::cout << (res ? "YES" : "NO"); } /* Main function */ int main() { size_t n, m; Graph g; GetInput(n, m, g); SetOutput(g.IsPlanar()); return 0; } ```
zhuli8com/WeChat
zhuli8com/WeChat README.md ```# WeChat 利用XMPPFramework框架实现一个类似微信功能的及时通讯APP。 ``` Readme.md ```1、引用mqtt第三方框架时提示某个架构不支持,最后根据cocoapds提示发现other link flags处设置不对,恢复默认值($(inherited))正常运行。 The `WeChat [Debug]` target overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Target Support Files/Pods/Pods.debug.xcconfig'. This can lead to problems with the CocoaPods installation The `WeChat [Release]` target overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Target Support Files/Pods/Pods.release.xcconfig'. This can lead to problems with the CocoaPods installation``` Macro.h ```// // Macro.h // WeChat // // Created by lizhu on 16/4/22. // Copyright © 2016年 zhuli8. All rights reserved. // #ifndef Macro_h #define Macro_h //#define MQTT_HOST @"broker.mqttdashboard.com" //#define MQTT_PORT 1883 //#define MQTT_TLS NO //#define MQTT_BASE @"MQTTChat" #define MQTT_HOST @"test.dehuinet.com" #define MQTT_PORT 1830 #define MQTT_TLS YES #define MQTT_BASE @"/u/eWgveuUL7Mvw3_MWKg2pfWi56FY=" #define MQTT_CLIENTID @"66701" #endif /* Macro_h */ ```
zhulvlong/MVVMDemo
zhulvlong/MVVMDemo CustomInterceptor.java ```package com.example.myapplication.util.interceptor; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import okhttp3.FormBody; import okhttp3.Headers; import okhttp3.Interceptor; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import okio.BufferedSource; /** * Function: 自定义OkHttp拦截器 * Author: ShiJingFeng * Date: 2019/10/10 9:17 * Description: */ public class CustomInterceptor implements Interceptor { @NotNull @Override public Response intercept(@NotNull Chain chain) throws IOException { Request request = chain.request(); RequestBody requestBody = request.body(); if (requestBody instanceof FormBody) { //表单请求 FormBody formBody = (FormBody) requestBody; // for (int i = 0; i < formBody.size(); ++i) { // String encodeName = formBody.encodedName(i); // String encodeValue = formBody.encodedValue(i); // String name = formBody.name(i); // String value = formBody.value(i); // strBuilder.append(name + "=" + value + "\n"); // strBuilder.append(" encodeName: " + encodeName + " encodeValue: " + encodeValue + " name: " + name + " value: " + value); // } System.out.println("请求头: " + formBody.contentType()); System.out.println("请求体: " + ""); System.out.println("url:" + request.url()); } else if (requestBody instanceof MultipartBody) { //文件上传请求(未实验,不知道好不好使) MultipartBody body = (MultipartBody) requestBody; Map<String, String> params = new HashMap<>(); Map<String, String> files = new HashMap<>(); for (MultipartBody.Part part : body.parts()) { RequestBody body1 = part.body(); Headers headers = part.headers(); if (headers != null && headers.size() > 0) { String[] split = headers.value(0).replace(" ", "").replace("\"", "").split(";"); if (split.length == 2) { //文本 String[] keys = split[1].split("="); if (keys.length > 1 && body1.contentLength() < 1024) { String key = keys[1]; String value; Buffer buffer = new Buffer(); body.writeTo(buffer); value = buffer.readUtf8(); params.put(key, value); } } else if (split.length == 3) { //文件 String fileKey = ""; String fileName = ""; String[] keys = split[1].split("="); String[] names = split[2].split("="); if (keys.length > 1) fileKey = keys[1]; if (names.length > 1) fileName = names[1]; files.put(fileKey, fileName); } } } System.out.println("文本参数-->" + params); System.out.println("文件参数-->" + files); } Response response = chain.proceed(request); ResponseBody responseBody = response.body(); assert responseBody != null; BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.getBuffer(); Charset UTF8 = StandardCharsets.UTF_8; System.out.println("返回数据: " + buffer.clone().readString(UTF8)); return response; } /** * 打印请求消息 * * @param request 请求的对象 */ private String getRequestInfo(Request request) { String str = ""; if (request == null) { return str; } RequestBody requestBody = request.body(); if (requestBody == null) { return str; } try { Buffer bufferedSink = new Buffer(); requestBody.writeTo(bufferedSink); Charset charset = StandardCharsets.UTF_8; str = bufferedSink.readString(charset); } catch (IOException e) { e.printStackTrace(); } return str; } /** * 打印返回消息 * * @param response 返回的对象 */ private String getResponseInfo(Response response) { String str = ""; if (response == null || !response.isSuccessful()) { return str; } ResponseBody responseBody = response.body(); assert responseBody != null; long contentLength = responseBody.contentLength(); BufferedSource source = responseBody.source(); try { source.request(Long.MAX_VALUE); // Buffer the entire body. } catch (IOException e) { e.printStackTrace(); } Buffer buffer = source.buffer(); Charset charset = StandardCharsets.UTF_8; if (contentLength != 0) { str = buffer.clone().readString(charset); } return str; } } ``` README.md ```### 使用方法 ----------------- ## 一.导入 ### 1.下载代码后,把framework依赖导入项目中 ### 2.app build.gradle中加入 ``` implementation project(path: ':framework') ``` ### 3.project build.gradle中加入 ``` mavenCentral() maven { url 'https://jitpack.io' } maven { url 'https://maven.google.com' } ``` ### 4.app build.gradle添加java1.8支持和databinding支持 ``` //java1.8支持 compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } //databinding支持 buildFeatures { dataBinding = true } ``` ## 二、新建MyApplication ``` public class MyApplication extends BaseApplication { @Override public void onCreate() { super.onCreate(); } /** * 设置服务器地址集合 * * @return 服务器地址集 */ @Override protected List<String> initBaseUrl() { List<String> urlList = new ArrayList<>(); urlList.add("http://www.xxx.com"); urlList.add("http://www.yyy.com"); return urlList; } } ``` *别忘了在AndroidManifest.xml中添加MyApplication* ## 三、创建新Activity或Fragment ### 1.新建网络数据操作接口 ``` public interface IDemoNetworkSource { } ``` ### 2.新建网络数据操作实现类 ``` public class DemoNetworkSource extends BaseNetworkSource implements IDemoNetworkSource { } ``` ### 3.新建网络数据仓库 ``` public class DemoRepository extends BaseRepository implements IDemoNetworkSource { private DemoRepository() { } public static DemoRepository create() { return new DemoRepository(); } } ``` ### 4.新建ViewModel操作类 ``` public class DemoViewModel extends BaseViewModel<DemoRepository> { public DemoViewModel(DemoRepository repository) { super(repository); } } ``` ### 5.新建ViewModel简单工厂类 ``` public class DemoModelFactory extends ViewModelProvider.NewInstanceFactory { /** * 简单工厂模式创建对象 * * @return 对象 */ public static DemoModelFactory create() { return new DemoModelFactory(); } @NonNull @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { DemoRepository demoRepository = DemoRepository.create() .setNetworkSource(new DemoNetworkSource()); return CastUtil.cast(new DemoViewModel(demoRepository)); } } ``` ### 6.新建布局文件 ``` <?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"> <data> <import type="com.demo.mvvm.viewmodel.DemoViewModel" /> <variable name="demoViewModel" type="DemoViewModel" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> </layout> ``` ### 7.新建Activity或Fragment ``` public class DemoActivity extends AppBaseActivity<ActivityDemoBinding, DemoViewModel> { @Override protected int getLayoutId() { return R.layout.activity_demo; } @Override protected DemoViewModel getViewModel() { return createViewModel(DemoViewModel.class, DemoModelFactory.create()); } @Override protected SparseArray<Object> getVariableSparseArray() { SparseArray<Object> variableSA = new SparseArray<>(); variableSA.put(BR.demoViewModel, mViewModel); return variableSA; } } ``` *以上7步完成了一次Activity或Fragment的创建,另外,如果是创建Activity别忘了在AndroidManifest.xml中注册Activity* ``` CommonAdapter.java ```package com.example.myapplication.base.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.ViewGroup; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import androidx.recyclerview.widget.RecyclerView; import com.example.myapplication.listener.OnItemEventListener; import org.greenrobot.eventbus.EventBus; import java.util.List; public abstract class CommonAdapter<DB extends ViewDataBinding, T> extends RecyclerView.Adapter { protected List<T> dataList; protected Context context; protected OnItemEventListener mOnItemEventListener; public List<T> getDataList() { return dataList; } public void setDataList(List<T> dataList) { this.dataList = dataList; } public CommonAdapter(Context context, List<T> dataList) { this.dataList = dataList; this.context = context; } // 抽象函数 获取布局资源id public abstract int getLayoutId(); // 抽象函数 通过databinding为布局设置数据 public abstract void bindView(CommonViewHolder viewHolder, int position); @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // 生成DB对象 (这个方法是不是和View.inflate()很像?) DB bindView = DataBindingUtil.inflate(LayoutInflater.from(context), getLayoutId(), parent, false); return new CommonViewHolder(bindView); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // 调用抽象函数,将holder强转为CommonViewHodler,供子类Adapter使用其成员对象bindView; bindView((CommonViewHolder) holder, position); } /** * 设置回调监听器 * * @param listener 回调监听器 */ public void setOnItemEventListener(OnItemEventListener listener) { this.mOnItemEventListener = listener; } @Override public int getItemCount() { return dataList.size(); } @Override public int getItemViewType(int position) { return super.getItemViewType(position); } public class CommonViewHolder extends RecyclerView.ViewHolder { public DB bindView; // 每一个item都必须持有的一个ViewDataBinding子类对象 public CommonViewHolder(DB bindView) { super(bindView.getRoot()); this.bindView = bindView; } } } ``` ResourceUtil.java ```package com.example.myapplication.util; import androidx.annotation.NonNull; import java.lang.reflect.Field; /** * Function: 资源工具类 * Author: ShiJingFeng * Date: 2019/11/25 21:05 * Description: */ public class ResourceUtil { /** * 通过反射获取资源ID * @param variableName 资源ID 名称 * @param cls 资源ID 类型 * @return 资源ID */ public static int getResId(@NonNull String variableName, @NonNull Class<?> cls) { try { final Field idField = cls.getDeclaredField(variableName); return idField.getInt(idField); } catch (Exception e) { e.printStackTrace(); return -1; } } } ``` EmptyCallback.java ```//package com.example.myapplication.widget.callback; // //import com.example.myapplication.R; //import com.kingja.loadsir.callback.Callback; // ///** // * Function: 没有数据 Callback // * Author: ShiJingFeng // * Date: 2019/11/14 11:08 // * Description: // */ //public class EmptyCallback extends Callback { // // @Override // protected int onCreateView() { // return R.layout.callback_empty; // } //} ``` BaseNetworkSource.java ```package com.example.myapplication.base.source; import com.example.myapplication.base.util.CastUtil; /** * 文件名: BaseNetworkSource * 作者: yin * 日期: 2020/4/16 23:42 * 描述: 网络资源基类 */ public abstract class BaseNetworkSource { /** * 获取子类类型实例 * * @param <T> 泛型 * @return 子类类型实例 */ public <T extends BaseNetworkSource> T get() { return CastUtil.cast(this); } /** * 销毁回调 */ public void onCleared() { } } ``` DemoActivity.java ```package com.demo.mvvm.view.activity; import android.util.SparseArray; import com.demo.mvvm.BR; import com.demo.mvvm.R; import com.demo.mvvm.databinding.ActivityDemoBinding; import com.demo.mvvm.viewmodel.DemoViewModel; import com.demo.mvvm.viewmodel.factory.DemoModelFactory; import com.example.myapplication.base.activity.AppBaseActivity; /** * 文件名: DemoActivity * 日期: 2020/11/19 10:17 * 描述: Activity */ public class DemoActivity extends AppBaseActivity<ActivityDemoBinding, DemoViewModel> { @Override protected int getLayoutId() { return R.layout.activity_demo; } @Override protected DemoViewModel getViewModel() { return createViewModel(DemoViewModel.class, DemoModelFactory.create()); } @Override protected SparseArray<Object> getVariableSparseArray() { SparseArray<Object> variableSA = new SparseArray<>(); variableSA.put(BR.demoViewModel, mViewModel); return variableSA; } @Override protected void initData() { super.initData(); } /** * 设置是否自定义导航栏设置状态栏高度(默认true) * * @return true:导航栏留出状态栏高度 false: 不留状态栏高度 */ @Override protected boolean isSetCustomStatusBarHeight() { return true; } /** * 设置状态栏内容颜色(默认false) * * @return true:深色 false:浅色 */ @Override protected boolean getStatusBarTextStyle() { return true; } /** * 设置状态栏背景色(默认透明) * * @return 颜色id */ @Override protected int getStatusBarBackgroundStyle() { return R.color._00000000; } }``` CommonRecycleViewAdapter.java ```package com.example.myapplication.base.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.databinding.DataBindingUtil; import androidx.databinding.ObservableList; import androidx.databinding.ViewDataBinding; import androidx.recyclerview.widget.RecyclerView; public class CommonRecycleViewAdapter<T> extends RecyclerView.Adapter { private ObservableList<T> observableList; private int variableId; private @LayoutRes int layoutId; private OnRecycleViewItemClickListener onRecycleViewItemClickListener; public CommonRecycleViewAdapter(@NonNull ObservableList<T> observableList, int variableId, @LayoutRes int layoutId) { this.observableList = observableList; this.variableId = variableId; this.layoutId = layoutId; observableList.addOnListChangedCallback(new BaseOnListChangeCallback()); } @NonNull @Override public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { //这里的第四个参数必须为 false 这在Google ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), layoutId, viewGroup, false); return new BaseViewHolder(binding.getRoot()); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, final int i) { ViewDataBinding binding = DataBindingUtil.getBinding(viewHolder.itemView); binding.setVariable(variableId, observableList.get(i)); //设置item点击监听 binding.getRoot().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (onRecycleViewItemClickListener != null) { onRecycleViewItemClickListener.itemClick(observableList.get(i), i); } } }); } @Override public int getItemCount() { return observableList != null ? observableList.size() : 0; } class BaseViewHolder extends RecyclerView.ViewHolder { public BaseViewHolder(@NonNull View itemView) { super(itemView); } } public OnRecycleViewItemClickListener getOnRecycleViewItemClickListener() { return onRecycleViewItemClickListener; } public void setOnRecycleViewItemClickListener(OnRecycleViewItemClickListener onRecycleViewItemClickListener) { this.onRecycleViewItemClickListener = onRecycleViewItemClickListener; } //数据变化监听 class BaseOnListChangeCallback extends ObservableList.OnListChangedCallback { @Override public void onChanged(ObservableList sender) { } @Override public void onItemRangeChanged(ObservableList sender, int positionStart, int itemCount) { CommonRecycleViewAdapter.this.notifyItemRangeChanged(positionStart, itemCount); } @Override public void onItemRangeInserted(ObservableList sender, int positionStart, int itemCount) { CommonRecycleViewAdapter.this.notifyItemRangeInserted(positionStart, itemCount); } @Override public void onItemRangeMoved(ObservableList sender, int fromPosition, int toPosition, int itemCount) { CommonRecycleViewAdapter.this.notifyItemMoved(fromPosition, toPosition); } @Override public void onItemRangeRemoved(ObservableList sender, int positionStart, int itemCount) { CommonRecycleViewAdapter.this.notifyItemRangeRemoved(positionStart, itemCount); } } /** * RecycleView 的 Item 点击监听 * @param <T> */ interface OnRecycleViewItemClickListener<T> { /** * * @param item 点击的 Item 对应的数据 * @param position 点击的 Item 位置 */ void itemClick(T item, int position); } }``` WebViewUtil.java ```package com.example.myapplication.util; import android.webkit.WebSettings; import androidx.annotation.NonNull; import com.blankj.utilcode.util.NetworkUtils; /** * Function: WebView工具类 * Author: ShiJingFeng * Date: 2019/10/7 9:35 * Description: */ public class WebViewUtil { /** * 设置默认 WebView设置 * @param webSettings WebView设置 */ public static void setDefaultWebSettings(@NonNull WebSettings webSettings) { //支持js交互 webSettings.setJavaScriptEnabled(true); //支持通过JS打开新窗口 webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //设置字符编码 webSettings.setDefaultTextEncodingName("utf-8"); //提高渲染的优先级 webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH); //将图片加载放在最后来加载渲染 // webSettings.setBlockNetworkImage(true); //支持缩放,适配到当前屏幕 webSettings.setSupportZoom(true); webSettings.setBuiltInZoomControls(false); //不显示WebView缩放按钮 webSettings.setDisplayZoomControls(false); webSettings.setLoadsImagesAutomatically(true); //设置此属性,可任意比例缩放 webSettings.setUseWideViewPort(true); //设置WebView为全屏显示 webSettings.setLoadWithOverviewMode(true); if (NetworkUtils.isConnected()) { //网络可用时,不使用缓存 webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); } else { //网络不可用时,设置优先从缓存中获取数据 webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); } } } ``` TitleBarBean.java ```package com.example.myapplication.base.entity; import android.content.res.Resources; import android.database.Observable; import android.graphics.Color; import android.view.View; import androidx.databinding.ObservableField; import androidx.databinding.ObservableInt; import com.bumptech.glide.load.engine.Resource; import com.example.myapplication.R; import com.example.myapplication.listener.OnItemEventListener; import com.example.myapplication.util.DisplayMetricsUtil; /** * @作者:Administrator * @时间:2020/5/25 11:37 * @描述: **/ public class TitleBarBean { public interface OnItemEventListener { void onClick(); } public interface OnRightTextClickListener { void onClick(); } public interface OnRightLinearClickListener { void onClick(); } private OnItemEventListener mOnItemEventListener; private OnRightTextClickListener mOnRightTextClickListener; private OnRightLinearClickListener mOnRightLinearClickListener; public ObservableInt titlebarVisibility = new ObservableInt(View.VISIBLE); public ObservableInt titlebarColor = new ObservableInt(R.color._FFFFFF); public ObservableInt ivLeft = new ObservableInt(R.mipmap.back); public ObservableInt ivLeftColor = new ObservableInt(R.color._000000); public ObservableInt tvCenterColor = new ObservableInt(R.color._000000); public View.OnClickListener ivLeftOnClick = v -> { if (mOnItemEventListener != null) { mOnItemEventListener.onClick(); } }; public View.OnClickListener tvRightOnClick = v -> { if (mOnRightTextClickListener != null) { mOnRightTextClickListener.onClick(); } }; public View.OnClickListener llRightOnClick = v -> { if (mOnRightLinearClickListener != null) { mOnRightLinearClickListener.onClick(); } }; public ObservableField<String> tvCenter = new ObservableField<>(""); public ObservableInt tvRightVisibility = new ObservableInt(View.GONE); public ObservableField<String> tvRight = new ObservableField<>(""); public ObservableInt tvRightColor = new ObservableInt(R.color._333333); public ObservableInt tvRightTextSize = new ObservableInt(12); public ObservableInt ivRightVisibility = new ObservableInt(View.GONE); public ObservableInt ivRight = new ObservableInt(R.mipmap.ic_launcher); public ObservableInt llRightVisibility = new ObservableInt(View.GONE); public ObservableInt llIvRight = new ObservableInt(R.mipmap.ic_launcher); public ObservableField<String> llTvRight = new ObservableField<>(""); public ObservableInt llTvColor = new ObservableInt(R.color._666666); public void onBack(OnItemEventListener onItemEventListener) { mOnItemEventListener = onItemEventListener; } public void onRightTextClick(OnRightTextClickListener onRightTextClickListener) { mOnRightTextClickListener = onRightTextClickListener; } public void onRightLinearClick(OnRightLinearClickListener onRightLinearClickListener) { mOnRightLinearClickListener = onRightLinearClickListener; } } ``` ImageLoaderUtil.java ```package com.example.myapplication.util; import android.content.Context; import android.graphics.Bitmap; import android.widget.ImageView; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import com.blankj.utilcode.util.ImageUtils; import com.bumptech.glide.Glide; import com.bumptech.glide.GlideContext; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.load.resource.bitmap.CircleCrop; import com.bumptech.glide.load.resource.bitmap.RoundedCorners; import com.bumptech.glide.request.RequestOptions; import com.bumptech.glide.request.target.SimpleTarget; import com.example.myapplication.R; /** * 图片加载工具类 */ public class ImageLoaderUtil { private static volatile ImageLoaderUtil imageLoaderUtils; private ImageLoaderUtil() { } /** * DSL 双重检查 单例 * * @return 单例 */ public synchronized static ImageLoaderUtil getInstance() { if (imageLoaderUtils == null) { synchronized (ImageLoaderUtil.class) { if (imageLoaderUtils == null) { imageLoaderUtils = new ImageLoaderUtil(); } } } return imageLoaderUtils; } /** * 显示图片 * * @param context Context * @param imageView ImageView控件 * @param path 路径 */ public void display(Context context, ImageView imageView, String path) { if (imageView == null) { throw new IllegalArgumentException("argument error"); } Glide.with(context) .load(path) .dontAnimate() .into(imageView); } /** * 显示图片 * * @param context Context * @param imageView ImageView控件 * @param path 路径 * @param placeholder 加载占位符 * @param error 错误占位符 */ public void display(Context context, ImageView imageView, String path, int placeholder, int error) { if (imageView == null) { throw new IllegalArgumentException("argument error"); } Glide.with(context) .load(path) .dontAnimate() .placeholder(placeholder) .error(error) .into(imageView); } /** * 显示图片 * * @param context Context * @param imageView ImageView控件 * @param drawableResource 项目中的Drawable资源 * @param placeholder 加载占位符 * @param error 错误占位符 */ public void display(Context context, ImageView imageView, @DrawableRes int drawableResource, int placeholder, int error) { if (imageView == null) { throw new IllegalArgumentException("argument error"); } Glide.with(context) .load(drawableResource) .dontAnimate() .placeholder(placeholder) .error(error) .into(imageView); } /** * 显示视频缩略图 * * @param context Context * @param imageView ImageView控件 * @param videoFilePath 视频本地路径 */ public void displayVideoThumb(Context context, ImageView imageView, String videoFilePath) { displayVideoThumb(context, imageView, videoFilePath, 0, 0); } /** * 显示视频缩略图 * * @param context Context * @param imageView ImageView控件 * @param videoFilePath 视频本地路径 * @param placeholder 加载中占位符 * @param error 错误占位符 */ public void displayVideoThumb(Context context, ImageView imageView, String videoFilePath, int placeholder, int error) { Glide.with(context) .load(videoFilePath) .diskCacheStrategy(DiskCacheStrategy.RESOURCE) .centerCrop() .placeholder(placeholder) .error(error) .into(imageView); } /** * 显示视频缩略图 * * @param context Context * @param imageView ImageView * @param videoFilePath 视频文件地址 * @param placeholder 加载中占位符 * @param error 错误占位符 * @param target 目标回调接口 */ public void displayVideoThumb(Context context, ImageView imageView, String videoFilePath, int placeholder, int error, SimpleTarget<Bitmap> target) { Glide.with(context) .asBitmap() .load(videoFilePath) .diskCacheStrategy(DiskCacheStrategy.RESOURCE) .centerCrop() .placeholder(placeholder) .error(error) .into(target); } } ``` RxUtil.java ```package com.example.myapplication.util; import android.view.View; import com.jakewharton.rxbinding3.view.RxView; import java.util.concurrent.TimeUnit; import io.reactivex.functions.Consumer; import kotlin.Unit; /** * Function: View防止连击工具类 * Author: ShiJingFeng * Date: 2019/11/14 13:46 * Description: */ public class RxUtil { /** * 连击间隔2秒 * @param activity BaseActivity * @param view View * @param onNext Consumer<Unit> */ // public static void throttleClick(BaseActivity activity, View view, Consumer<Unit> onNext) { // activity.addDisposable(RxView.clicks(view) // .throttleFirst(2, TimeUnit.SECONDS) // .subscribe(onNext) // ); // } /** * 连击间隔2秒 * @param activity BaseActivity * @param view View * @param ms 间隔毫秒值 * @param onNext Consumer<Unit> */ // public static void throttleClick(BaseActivity activity, View view, int ms, Consumer<Unit> onNext) { // activity.addDisposable(RxView.clicks(view) // .throttleFirst(ms, TimeUnit.MILLISECONDS) // .subscribe(onNext) // ); // } } ``` NetworkURL.java ```package com.example.myapplication.constant; import java.util.List; /** * 文件名: NetworkConstant * 作者: yin * 日期: 2020/4/16 23:42 * 描述: 网络常量 */ public class NetworkURL { // /** // * 请求成功 // */ // public static final int SUCCESS = 1; // public static String SERVER_URL = ""; /** * 请求地址集合 */ public static List<String> mUrlList; } ``` CommonDialog.java ```package com.example.myapplication.widget.dialog; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.PopupWindow; import androidx.annotation.DrawableRes; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.StyleRes; import com.example.myapplication.util.WindowUtil; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; /** * Function: 自定义 提示 PopupWindow * Author: ShiJingFeng * Date: 2019/11/5 10:32 * Description: */ public class CommonDialog { private final Attr mAttr; private final Listener mListener; private final View mParentView; private PopupWindow mCommonPw; private CommonDialog(Attr attr, Listener listener) { this.mAttr = attr; this.mListener = listener; this.mParentView = this.mAttr.activity.findViewById(android.R.id.content); } /** * 显示 PopupWindow */ public void show() { if (mCommonPw != null) { if (!mCommonPw.isShowing()) { WindowUtil.setWindowOutsideBackground(mAttr.activity, mAttr.windowOutsideAlpha); mCommonPw.update(); } return; } mCommonPw = new PopupWindow(); mCommonPw.setContentView(mAttr.contentView); mCommonPw.setWidth(mAttr.windowWidth); mCommonPw.setHeight(mAttr.windowHeight); mCommonPw.setOutsideTouchable(mAttr.outsideTouchable); mCommonPw.setTouchable(mAttr.touchable); mCommonPw.setFocusable(mAttr.focusable); mCommonPw.setAnimationStyle(mAttr.animStyle); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mCommonPw.setElevation(mAttr.elevation); } mCommonPw.setBackgroundDrawable(mAttr.drawable); WindowUtil.setWindowOutsideBackground(mAttr.activity, mAttr.windowOutsideAlpha); mCommonPw.showAtLocation(mParentView, mAttr.gravity,mAttr.x,mAttr.y); mCommonPw.setOnDismissListener(() -> { WindowUtil.setWindowOutsideBackground(mAttr.activity, 1F); if (mListener.onDismissListener != null) { mListener.onDismissListener.onDismiss(); } }); } /** * 更新 PopupWindow */ public void update() { if (mCommonPw != null) { WindowUtil.setWindowOutsideBackground(mAttr.activity, mAttr.windowOutsideAlpha); mCommonPw.update(); } } /** * 隐藏 PopupWindow */ public void hide() { if (mCommonPw != null) { mCommonPw.dismiss(); } } /** * 是否正在显示 * @return true 正在显示 false 没有显示 */ public boolean isShowing() { if (mCommonPw != null) { return mCommonPw.isShowing(); } return false; } /** * 获取 Content View * @return Content View */ public View getContentView() { if (mCommonPw != null) { return mCommonPw.getContentView(); } return null; } public static class Builder { private Attr mAttr = new Attr(); private Listener mListener = new Listener(); public Builder(@NonNull Activity activity) { mAttr.activity = activity; } /** * 设置 PopupWindow Content View * @param contentView PopupWindow Content View * @return Builder */ public Builder setContentView(@NonNull View contentView) { mAttr.contentView = contentView; return this; } /** * 设置 PopupWindow Content View * @param layoutId PopupWindow Content View Layout Id * @return Builder */ public Builder setContentView(@LayoutRes int layoutId) { if (mAttr.activity != null) { mAttr.contentView = LayoutInflater.from(mAttr.activity).inflate(layoutId, null); } return this; } /** * 设置窗口宽度 * @param windowWidth 窗口宽度 * @return Builder */ public Builder setWindowWidth(int windowWidth) { this.mAttr.windowWidth = windowWidth; return this; } /** * 设置窗口高度 * @param windowHeight 窗口高度 * @return Builder */ public Builder setWindowHeight(int windowHeight) { this.mAttr.windowHeight = windowHeight; return this; } /** * 设置外部是否可触摸 * @param outsideTouchable 外部是否可触摸 * @return Builder */ public Builder setOutsideTouchable(boolean outsideTouchable) { this.mAttr.outsideTouchable = outsideTouchable; return this; } /** * 设置是否可触摸 * @param touchable 是否可触摸 * @return Builder */ public Builder setTouchable(boolean touchable) { this.mAttr.touchable = touchable; return this; } /** * 设置是否可聚焦 * @param focusable 是否可聚焦 * @return Builder */ public Builder setFocusable(boolean focusable) { this.mAttr.focusable = focusable; return this; } /** * 设置点击外部是否可取消 * @param cancelable 点击外部是否可取消 * @return Builder */ public Builder setCancelable(boolean cancelable) { this.mAttr.outsideTouchable = true; return this; } /** * 设置阴影宽度 * @param elevation 阴影宽度 * @return Builder */ public Builder setElevation(float elevation) { this.mAttr.elevation = elevation; return this; } /** * 设置背景资源 * @param drawableRes 背景资源 * @return Builder */ public Builder setBackgroundDrawable(@DrawableRes int drawableRes) { if (mAttr.activity != null) { mAttr.drawable = mAttr.activity.getResources().getDrawable(drawableRes); } return this; } /** * 设置背景Drawable * @param drawable 背景Drawable * @return Builder */ public Builder setBackgroundDrawable(@NonNull Drawable drawable) { this.mAttr.drawable = drawable; return this; } /** * 设置外部窗口透明度 * @param windowOutsideAlpha 外部窗口透明度 * @return Builder */ public Builder setWindowOutsideAlpha(float windowOutsideAlpha) { mAttr.windowOutsideAlpha = windowOutsideAlpha; return this; } /** * 设置动画样式 * @param animStyle 动画样式 * @return Builder */ public Builder setAnimStyle(@StyleRes int animStyle) { mAttr.animStyle = animStyle; return this; } /** * 设置 PopupWindow Gravity * @param gravity PopupWindow Gravity * @return Builder */ public Builder setGravity(int gravity, int x, int y) { mAttr.gravity = gravity; mAttr.x = x; mAttr.y = y; return this; } /** * 设置 PopupWindow 取消监听器 * @param onDismissListener PopupWindow 取消监听器 * @return Builder */ public Builder setOnDismissListener(PopupWindow.OnDismissListener onDismissListener) { mListener.onDismissListener = onDismissListener; return this; } /** * 创建 提示PopupWindow * @return 提示PopupWindow */ public CommonDialog create() { return new CommonDialog(mAttr, mListener); } /** * 显示 提示PopupWindow * @return 提示PopupWindow */ public CommonDialog show() { final CommonDialog commonDialog = new CommonDialog(mAttr, mListener); commonDialog.show(); return commonDialog; } } /** * 属性数据 */ private static class Attr { /** Activity环境 */ private Activity activity; /** PopupWindow Content View */ private View contentView; /** 窗口宽度 */ private int windowWidth = WRAP_CONTENT; /** 窗口高度 */ private int windowHeight = WRAP_CONTENT; /** 外部是否可触摸 */ private boolean outsideTouchable = false; /** 是否可触摸 */ private boolean touchable = true; /** 是否可聚焦 */ private boolean focusable = false; /** 阴影宽度 */ private float elevation = 0F; /** 背景Drawable */ private Drawable drawable; /** 外部窗口透明度 */ private float windowOutsideAlpha = 1F; /** 动画样式 */ private int animStyle = 0; /** PopupWindow Gravity */ private int gravity = Gravity.CENTER; /** X轴偏移量 */ private int x = 0; /** Y轴偏移量 */ private int y = 0; } /** * 监听器 */ private static class Listener { /** PopupWindow 取消回调 */ private PopupWindow.OnDismissListener onDismissListener; } } ``` MvvmActivity.java ```package com.example.myapplication.base.activity; import android.app.Activity; import android.os.Bundle; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import androidx.lifecycle.ViewModelProvider; import com.example.myapplication.R; import com.example.myapplication.base.viewmodel.BaseViewModel; /** * 文件名: MvvmActivity * 作者: yin * 日期: 2020/4/16 23:42 * 描述: MVVM架构Activity基类 */ public abstract class MvvmActivity<V extends ViewDataBinding, VM extends BaseViewModel> extends AppCompatActivity { /** * DataBinding */ protected V mDataBinding; /** * ViewModel */ protected VM mViewModel; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initAAC(); } /** * 获取视图ID * * @return 视图ID */ protected abstract int getLayoutId(); /** * 获取ViewModel * * @return ViewModel */ protected abstract VM getViewModel(); /** * 初始化 DataBinding 变量ID 和 变量实体类 Map * * @return DataBinding 变量SparseArray */ protected abstract SparseArray<Object> getVariableSparseArray(); /** * 初始化AAC组件 */ private void initAAC() { mDataBinding = DataBindingUtil.setContentView(this, getLayoutId()); mViewModel = getViewModel(); final SparseArray<Object> variableSA = getVariableSparseArray(); if (variableSA != null && variableSA.size() > 0) { for (int i = 0; i < variableSA.size(); ++i) { final int variableId = variableSA.keyAt(i); final Object variableValue = variableSA.valueAt(i); mDataBinding.setVariable(variableId, variableValue); } } //让ViewModel拥有View的生命周期感应 if (mViewModel != null) { getLifecycle().addObserver(mViewModel); } } // /** // * 创建ViewModel // * // * @param cls Activity Class // * @return ViewModel子类 // */ // public VM createViewModel(@NonNull Class<VM> cls) { // return new ViewModelProvider(this).get(cls); // } /** * 工厂模式创建ViewModel * * @param cls Activity Class * @param factory 工厂 * @return ViewModel子类 */ public VM createViewModel(@NonNull Class<VM> cls, @NonNull ViewModelProvider.NewInstanceFactory factory) { return new ViewModelProvider(this, factory).get(cls); } @Override protected void onDestroy() { super.onDestroy(); //销毁DataBinding if (mDataBinding != null) { mDataBinding.unbind(); } } } ``` EmptyRecyclerView.java ```package com.example.myapplication.base.view; import android.annotation.SuppressLint; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import com.blankj.utilcode.util.ConvertUtils; import com.example.myapplication.R; /** * 空数据提示的RecyclerView */ public class EmptyRecyclerView extends RecyclerView { private View emptyView; private Context mContext; private ViewGroup parentView; @SuppressLint("InflateParams") public EmptyRecyclerView(@NonNull Context context) { super(context); mContext = context; emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_recycleview_empty, null, false); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); emptyView.setLayoutParams(layoutParams); } @SuppressLint("InflateParams") public EmptyRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); mContext = context; emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_recycleview_empty, null, false); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); emptyView.setLayoutParams(layoutParams); } @SuppressLint("InflateParams") public EmptyRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_recycleview_empty, null, false); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); emptyView.setLayoutParams(layoutParams); } final private AdapterDataObserver observer = new AdapterDataObserver() { @Override public void onChanged() { checkIfEmpty(); } @Override public void onItemRangeInserted(int positionStart, int itemCount) { Log.i("tag", "onItemRangeInserted" + itemCount); checkIfEmpty(); } @Override public void onItemRangeRemoved(int positionStart, int itemCount) { checkIfEmpty(); } }; private void checkIfEmpty() { if (parentView == null) { parentView = (ViewGroup) getParent(); int index = parentView.indexOfChild(this); parentView.addView(emptyView, index); } if (emptyView != null && getAdapter() != null) { final boolean emptyViewVisible = getAdapter().getItemCount() == 0; emptyView.setVisibility(emptyViewVisible ? VISIBLE : GONE); setVisibility(emptyViewVisible ? GONE : VISIBLE); } } @Override public void setAdapter(Adapter adapter) { Adapter oldAdapter = getAdapter(); if (oldAdapter != null) { oldAdapter.unregisterAdapterDataObserver(observer); } super.setAdapter(adapter); if (adapter != null) { adapter.registerAdapterDataObserver(observer); } checkIfEmpty(); } } ``` RetrofitUtil.java ```package com.example.myapplication.util; import com.blankj.utilcode.util.ToastUtils; import com.example.myapplication.constant.NetworkURL; import com.example.myapplication.util.factory.CustomGsonConverterFactory; import com.example.myapplication.util.interceptor.CustomInterceptor; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; /** * Retrofit工具类 */ public class RetrofitUtil { // private Retrofit sRetrofit; public List<Retrofit> mRetrofitList; private RetrofitUtil() { // sRetrofit = initRetrofit(); mRetrofitList = initRetrofits(); } private static class Inner { private static final RetrofitUtil INSTANCE = new RetrofitUtil(); } /** * 获取 静态内部类单例 * * @return 静态内部类单例 */ public static RetrofitUtil getInstance() { return Inner.INSTANCE; } /** * 创建 Retrofit 实例 * * @return Retrofit实例 */ private List<Retrofit> initRetrofits() { final OkHttpClient.Builder builder = new OkHttpClient().newBuilder() .readTimeout(10, TimeUnit.SECONDS) .connectTimeout(10, TimeUnit.SECONDS) //网络数据查看拦截器 .addInterceptor(new CustomInterceptor()); final Gson gson = new GsonBuilder() .disableHtmlEscaping() //禁止转码 .setLenient() //允许超长字符串 .create(); List<Retrofit> retrofits = new ArrayList<>(); for (int i = 0; i < NetworkURL.mUrlList.size(); i++) { retrofits.add(new Retrofit.Builder() .baseUrl(NetworkURL.mUrlList.get(i)) .client(builder.build()) .addConverterFactory(CustomGsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build()); } return retrofits; } /** * 创建 Api 请求类 * * @param api Api请求原始反射类 * @param <T> 泛型 * @return Api请求类 */ public <T> T create(int position, final Class<T> api) { try { return mRetrofitList.get(position).create(api); } catch (IndexOutOfBoundsException e) { ToastUtils.showShort("url配置不正确或pos设置不正确"); } return null; } }``` OnResultListener.java ```package com.example.myapplication.listener; /** * function: 结果监听器 * date: 2019/6/3 */ public abstract class OnResultListener<S, F> { /** * 成功 回调 * @param data 结果 */ public void onSuccess(S data) {} /** * 失败 回调 * @param data 错误信息 * @param e 错误异常 */ public void onFailure(F data, Throwable e) {} } ``` DemoModelFactory.java ```package com.demo.mvvm.viewmodel.factory; import androidx.annotation.NonNull; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; import com.demo.mvvm.network.DemoNetworkSource; import com.demo.mvvm.repository.DemoRepository; import com.demo.mvvm.viewmodel.DemoViewModel; import com.example.myapplication.base.util.CastUtil; /** * 文件名: DemoModelFactory * 日期: 2020/11/19 10:17 * 描述: ViewModel Factory */ public class DemoModelFactory extends ViewModelProvider.NewInstanceFactory { /** * 简单工厂模式创建对象 * * @return 对象 */ public static DemoModelFactory create() { return new DemoModelFactory(); } @NonNull @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { DemoRepository demoRepository = DemoRepository.create() .setNetworkSource(new DemoNetworkSource()); return CastUtil.cast(new DemoViewModel(demoRepository)); } } ``` CodeConstant.java ```package com.example.myapplication.constant; /** * Function: Activity请求Code 和 权限请求Code 静态常量字符串 * Author: ShiJingFeng * Date: 2019/10/12 22:08 * Description: */ public class CodeConstant { /** * Request Code: 相册 */ public static final int RESULT_PHOTO = 1; /** * Request Code: 相机 */ public static final int RESULT_CAMERA = 2; /** * Request Code: 裁剪 */ public static final int RESULT_CLIP = 3; /** * Permission Code: 打开相机 */ public static final int PERMISSION_CAMERA = 1; /** * Permission Code: 读写外部存储权限 */ public static final int PERMISSION_EXTERNAL_STORAGE = 2; /** * Permission Code: 打开gps */ public static final int REQUEST_GPS = 3; } ``` DemoNetworkSource.java ```package com.demo.mvvm.network; import android.annotation.SuppressLint; import androidx.annotation.NonNull; import com.blankj.utilcode.util.ToastUtils; import com.demo.mvvm.constants.NetworkConstant; import com.demo.mvvm.entity.DemoEntity; import com.demo.mvvm.entity.ResultEntity; import com.demo.mvvm.network.api.ServerApi; import com.demo.mvvm.network.interfaces.IDemoNetworkSource; import com.example.myapplication.base.source.BaseNetworkSource; import com.example.myapplication.listener.OnResultListener; import com.example.myapplication.util.RetrofitUtil; import java.util.List; import java.util.Map; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; /** * 文件名: DemoNetworkSource * 日期: 2020/11/19 9:36 * 描述: 网络数据操作实现类 */ public class DemoNetworkSource extends BaseNetworkSource implements IDemoNetworkSource { @SuppressLint("CheckResult") @Override public void demo1(int position, @NonNull Map<String, Object> postMap, @NonNull OnResultListener<ResultEntity<DemoEntity>, String> listener) { ServerApi serverApi = RetrofitUtil.getInstance().create(position, ServerApi.class); if (serverApi != null) { serverApi .demo1(postMap) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe((ResultEntity<DemoEntity> result) -> { if (result.code == NetworkConstant.SUCCESS) { listener.onSuccess(result); } else { listener.onFailure(result.msg, null); } }, (Throwable throwable) -> { listener.onFailure("请求失败", throwable); }); } } @SuppressLint("CheckResult") @Override public void demo2(int position, @NonNull Map<String, Object> postMap, @NonNull OnResultListener<ResultEntity<List<DemoEntity>>, String> listener) { ServerApi serverApi = RetrofitUtil.getInstance().create(position, ServerApi.class); if (serverApi != null) { serverApi .demo2(postMap) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe((ResultEntity<List<DemoEntity>> result) -> { if (result.code == NetworkConstant.SUCCESS) { listener.onSuccess(result); } else { listener.onFailure(result.msg, null); } }, (Throwable throwable) -> { listener.onFailure("请求失败", throwable); }); } } } ``` AppBaseFragment.java ```package com.example.myapplication.base.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.IdRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.databinding.ViewDataBinding; import com.example.myapplication.R; import com.example.myapplication.base.viewmodel.BaseViewModel; import com.example.myapplication.util.LogUtil; import com.example.myapplication.util.ResourceUtil; import com.example.myapplication.util.StatusBarUtil; /** * 文件名: AppBaseFragment * 作者: yin * 日期: 2020/4/16 23:42 * 描述: Fragment的基类 */ public abstract class AppBaseFragment<V extends ViewDataBinding, VM extends BaseViewModel> extends MvvmBaseFragment<V, VM> { protected boolean statusBarHeight = false; protected boolean statusBarDark = false; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { LogUtil.d("页面", this.getClass().getSimpleName()); return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onStart() { super.onStart(); initStatusBar(); } @Override protected void initView(View view) { } /** * 初始化数据 */ @Override protected void initData() { super.initData(); //Activity默认背景为白色 getContentView().setBackgroundResource(R.color._FFFFFF); //设置状态栏高度 if (isSetCustomStatusBarHeight()) { @IdRes final int id = ResourceUtil.getResId("rl_layout_title_bar", R.id.class); if (id != -1) { final View view = getContentView().findViewById(id); if (view != null) { view.setPadding(0, StatusBarUtil.getStatusBarHeight(getContext()), 0, 0); view.setMinimumHeight(view.getHeight() + StatusBarUtil.getStatusBarHeight(getContext())); } } } } /** * 初始化状态栏 */ private void initStatusBar() { //设置默认状态栏背景颜色 为透明色 StatusBarUtil.setStatusBarColor(getActivity(), getStatusBarBackgroundStyle()); //设置默认状态栏字体颜色为浅色 StatusBarUtil.setStatusBarContentColor(getActivity(), getStatusBarTextStyle()); } /** * 设置导航栏是否预留出状态栏高度 * * @return true 预留 false 不预留 */ protected boolean isSetCustomStatusBarHeight() { return true; } /** * 设置状态栏内容颜色 */ protected boolean getStatusBarTextStyle() { return false; } /** * 设置状态栏背景颜色 */ protected int getStatusBarBackgroundStyle() { return R.color._00000000; } } ``` UserUtil.java ```//package com.example.myapplication.util; // //import androidx.annotation.NonNull; // //import com.blankj.utilcode.util.SPUtils; //import com.wicep.juheyijia.constant.SPConstant; //import com.wicep.juheyijia.entity.network.UserInfoEntity; // //import static com.wicep.juheyijia.constant.SPConstant.LOGIN; //import static com.wicep.juheyijia.constant.SPConstant.LOGIN_INFO; //import static com.wicep.juheyijia.constant.SPConstant.SP_APP_NAME; // ///** // * Function: 用户工具类 // * Author: ShiJingFeng // * Date: 2019/10/7 14:04 // * Description: // */ //public class UserUtil { // // private static volatile UserUtil sInstance; // // /** 是否已登录 true: 已登录 false: 未登录 */ // private boolean mLogin; // /** 登录数据 */ // private UserInfoEntity mUserInfoEntity; // // private UserUtil() {} // // /** // * DCL双重检查单例 // * @return 单例 // */ // public static UserUtil getInstance() { // if (sInstance == null) { // synchronized (UserUtil.class) { // if (sInstance == null) { // sInstance = new UserUtil(); // } // } // } // return sInstance; // } // // /** // * 是否已登录 // * @return true: 已登录 false: 未登录 // */ // public boolean isLogin() { // if (!mLogin) { // mLogin = SPUtils.getInstance(SP_APP_NAME).getBoolean(LOGIN, false); // } // return mLogin; // } // // /** // * 获取用户ID // * @return 用户ID // */ // public String getId() { // return getLoginInfo().user_id; // } // // /** // * 获取用户ID // * @return 用户ID // */ // public String getSessionKey() { // return getLoginInfo().session_key; // } // // /** // * 获取登录数据 // * @return 登录数据 // */ // public UserInfoEntity getLoginInfo() { // if (mUserInfoEntity == null) { // final String encryptLoginDataStr = SPUtils.getInstance(SP_APP_NAME).getString(LOGIN_INFO, ""); // final String loginDataStr = SecurityUtil.decrypt(encryptLoginDataStr); // // mUserInfoEntity = JsonUtils.deserialize(loginDataStr, UserInfoEntity.class); // } // return mUserInfoEntity; // } // // /** // * 更新登录数据 // * @param userInfoEntity 新的登录数据 // */ // public void updateLoginInfo(@NonNull UserInfoEntity userInfoEntity) { // mUserInfoEntity = userInfoEntity; // SPUtils.getInstance(SP_APP_NAME).put(LOGIN_INFO, SecurityUtil.encrypt(JsonUtils.serialize(userInfoEntity)), false); // } // // /** // * 登录 // * @param userInfoEntity 登录信息 // */ // public void login(@NonNull UserInfoEntity userInfoEntity) { // mLogin = true; // mUserInfoEntity = userInfoEntity; // // SPUtils.getInstance(SP_APP_NAME).put(SPConstant.LOGIN, true); // SPUtils.getInstance(SP_APP_NAME).put(SPConstant.LOGIN_INFO, SecurityUtil.encrypt(JsonUtils.serialize(userInfoEntity))); // } // // /** // * 退出登录 // */ // public void logout() { // mLogin = false; // mUserInfoEntity = null; // // SPUtils.getInstance(SP_APP_NAME).remove(LOGIN, false); // SPUtils.getInstance(SP_APP_NAME).remove(LOGIN_INFO, false); // } // //} ``` MD5Util.java ```/** * FileName: MD5Util * Author: yin * Date: 2020/3/13 11:33 * Description: 1 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ package com.example.myapplication.util; import android.text.TextUtils; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * @ClassName: MD5Util * @Description: md5加密类 * @Author: yin * @Date: 2020/3/13 11:33 */ public class MD5Util { public static String getMD5(String msg){ if (TextUtils.isEmpty(msg)) { return ""; } MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); byte[] bytes = md5.digest(msg.getBytes()); String result = ""; for (byte b : bytes) { String temp = Integer.toHexString(b & 0xff); if (temp.length() == 1) { temp = "0" + temp; } result += temp; } return result; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } }``` Base64Util.java ```package com.example.myapplication.util; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Base64; import androidx.annotation.NonNull; import java.io.ByteArrayOutputStream; import java.io.File; /** * Function: Base64工具类 * Author: ShiJingFeng * Date: 2019/10/9 14:11 * Description: */ public class Base64Util { // public static byte[] encode(@NonNull byte[] byteArray) { // return Base64.encode(byteArray, Base64.DEFAULT); // } /** * Base64加密 * @param byteArray 原字节数组数据 * @return 加密后的字节数组数据 */ public static String encode(@NonNull byte[] byteArray) { return Base64.encodeToString(byteArray, Base64.DEFAULT); } /** * 将图片转换为Base64格式字符串 * @param bitmap bitmap * @return Base64格式字符串 */ public static String encode(@NonNull Bitmap bitmap) { return encode(bitmap, 100); } /** * 将图片转换为Base64格式字符串 (指定图片质量) * @param bitmap bitmap * @param quality 图片质量 * @return Base64格式字符串 */ public static String encode(@NonNull Bitmap bitmap, int quality) { byte[] byteArray; try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream); byteArray = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.close(); } catch (Exception e) { e.printStackTrace(); return ""; } return Base64.encodeToString(byteArray, Base64.DEFAULT); } /** * 根据本地图片路径 转为 Base64格式字符串 * @param localFilePath 本地文件路径 * @return Base64格式字符串 */ public static String encode(@NonNull String localFilePath) { return encode(localFilePath, 100); } /** * 根据本地图片路径 转为 Base64格式字符串 (指定图片质量) * @param localFilePath 本地文件路径 * @param quality 图片质量 * @return Base64格式字符串 */ public static String encode(@NonNull String localFilePath, int quality) { final File localFile = new File(localFilePath); if (localFile.exists()) { final Bitmap bitmap = BitmapFactory.decodeFile(localFilePath); return encode(bitmap, quality); } else { return ""; } } /** * 将Base64格式字符串转换为位图 * @param encodeString 图片的Base64格式字符串 * @return 位图 */ public static byte[] decode(@NonNull String encodeString) { return Base64.decode(encodeString, Base64.DEFAULT); } } ``` MvvmBaseFragment.java ```package com.example.myapplication.base.fragment; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.provider.Settings; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.core.content.FileProvider; import androidx.databinding.ViewDataBinding; import com.example.myapplication.annotation.BindEventBus; import com.example.myapplication.annotation.NeedPermissions; import com.example.myapplication.base.viewmodel.BaseViewModel; import com.example.myapplication.widget.dialog.LoadingDialog; import com.tbruyelle.rxpermissions2.RxPermissions; import org.greenrobot.eventbus.EventBus; import java.io.File; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import static android.Manifest.permission.CAMERA; import static android.Manifest.permission.READ_EXTERNAL_STORAGE; import static com.example.myapplication.constant.CodeConstant.RESULT_CAMERA; import static com.example.myapplication.constant.CodeConstant.RESULT_CLIP; import static com.example.myapplication.constant.CodeConstant.RESULT_PHOTO; /** * 文件名: MvvmBaseFragment * 作者: yin * 日期: 2020/4/16 23:42 * 描述: 用于MVVM或AAC模式的 Fragment基类 */ @NeedPermissions public abstract class MvvmBaseFragment<V extends ViewDataBinding, VM extends BaseViewModel> extends MvvmFragment<V, VM> { /** * Disposable容器 */ private CompositeDisposable mCompositeDisposable; /** * RxPermission (响应式权限申请框架) */ protected RxPermissions mRxPermissions; /** * 页面跳转携带的数据Bundle */ protected Bundle mBundle; /** * 相机Uri */ protected Uri mCameraUri; /** * 相机图片缓存文件地址 */ protected String mCameraTempFilePath; /** * 裁剪图片缓存文件地址 */ protected String mClipTempFilePath; // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onResume() { super.onResume(); initObserver(); } /** * 初始化参数 */ protected void initParam() { if (getActivity().getIntent() != null) { mBundle = getActivity().getIntent().getExtras(); } } /** * 初始化数据 */ protected void initData() { //创建RxPermission对象 if (this.getClass().isAnnotationPresent(NeedPermissions.class)) { mRxPermissions = new RxPermissions(this); } //注册EventBus if (this.getClass().isAnnotationPresent(BindEventBus.class) && !EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } } /** * 初始化事件 */ protected void initAction() { } /** * 初始化 LiveData Observer */ protected void initObserver() { //显示加载中提示对话框 mViewModel.getUiChangeLiveDataManager().getShowLoadingDialogEvent().observe(this, s -> { LoadingDialog.getInstance() .setHintText(s) .show(getActivity()); }); //隐藏加载中提示对话框 mViewModel.getUiChangeLiveDataManager().getHideLoadingDialogEvent().observe(this, o -> { LoadingDialog.getInstance().hide(); }); //切换Activity mViewModel.getUiChangeLiveDataManager().getStartActivityEvent().observe(this, paramSA -> { final Class<?> cls = (Class<?>) paramSA.get(BaseViewModel.ParamConstant.CLASS); final Bundle bundle = (Bundle) paramSA.get(BaseViewModel.ParamConstant.BUNDLE); final Integer requestCode = (Integer) paramSA.get(BaseViewModel.ParamConstant.REQUEST_CODE); if (requestCode == null) { startActivity(cls, bundle); } else { startActivityForResult(cls, bundle, requestCode); } }); //关闭销毁Activity mViewModel.getUiChangeLiveDataManager().getFinishEvent().observe(this, o -> { getActivity().finish(); }); } /** * 通过Class跳转界面 **/ public void startActivity(Class<?> cls) { startActivity(cls, null); } /** * 含有Bundle通过Class跳转界面 **/ public void startActivity(Class<?> cls, Bundle bundle) { Intent intent = new Intent(); intent.setClass(getActivity(), cls); if (bundle != null) { intent.putExtras(bundle); } startActivity(intent); } /** * 通过Class跳转界面 **/ public void startActivityForResult(Class<?> cls, int requestCode) { startActivityForResult(cls, null, requestCode); } /** * 含有Bundle通过Class跳转界面 **/ public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) { Intent intent = new Intent(); intent.setClass(getActivity(), cls); if (bundle != null) { intent.putExtras(bundle); } startActivityForResult(intent, requestCode); } /** * 打开相机 */ public void openCamera(String path) { final File saveFile = new File(path, "shoot_" + System.currentTimeMillis() + ".jpg"); mCameraTempFilePath = saveFile.getAbsolutePath(); final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { mCameraUri = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationInfo().processName + ".FileProvider", saveFile); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } else { mCameraUri = Uri.fromFile(saveFile); } intent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraUri); startActivityForResult(intent, RESULT_CAMERA); } /** * 先检查权限然后打开相机 */ public void openCameraWithCheckPermission(String path) { addDisposable( mRxPermissions .requestEachCombined(CAMERA) .subscribe(permission -> { if (permission.granted) { openCamera(path); } else if (permission.shouldShowRequestPermissionRationale) { Toast.makeText(getContext(), "相机权限授予失败", Toast.LENGTH_SHORT).show(); } else { new AlertDialog.Builder(getActivity()) .setMessage("需要您去设置页面,「权限管理」,开启「相机」权限") .setPositiveButton("去设置", (DialogInterface dialog, int which) -> { Intent settingIntent = new Intent(); settingIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); settingIntent.setData(Uri.fromParts("package", getActivity().getPackageName(), null)); settingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(settingIntent); }) .setOnDismissListener(null) .setCancelable(false) .show(); } }) ); } /** * 打开相册 */ public void openPhoto() { final Intent intent = new Intent(); intent.setAction(Intent.ACTION_PICK); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(Intent.createChooser(intent, "选择图片"), RESULT_PHOTO); } /** * 先检查权限然后打开相册 */ public void openPhotoWithCheckPermission() { addDisposable( mRxPermissions .requestEachCombined(READ_EXTERNAL_STORAGE) .subscribe(permission -> { if (permission.granted) { openPhoto(); } else if (permission.shouldShowRequestPermissionRationale) { Toast.makeText(getContext(), "外部存储权限授予失败", Toast.LENGTH_SHORT).show(); } else { new AlertDialog.Builder(getActivity()) .setMessage("需要您去设置页面,「权限管理」,开启「外部存储」权限") .setPositiveButton("去设置", (DialogInterface dialog, int which) -> { Intent settingIntent = new Intent(); settingIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); settingIntent.setData(Uri.fromParts("package", getActivity().getPackageName(), null)); settingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(settingIntent); }) .setOnDismissListener(null) .setCancelable(false) .show(); } }) ); } /** * 对图片进行裁剪 * * @param data 原始图片URI */ public void startImageClip(String path, Uri data) { final Intent intent = new Intent("com.android.camera.action.CROP"); final File saveClipImageFile = new File(path, "clip_" + System.currentTimeMillis() + ".jpg"); mClipTempFilePath = saveClipImageFile.getAbsolutePath(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } intent.setDataAndType(data, "image/*"); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(saveClipImageFile)); // intent.putExtra("aspectX", 1); // 裁剪框 X轴比例 // intent.putExtra("aspectY", 1); //裁剪框 Y轴比例 // intent.putExtra("outputX", 200); // 输出图片 X轴大小 // intent.putExtra("outputY", 200); //输出图片 Y轴大小 // intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); //设置图片格式 intent.putExtra("crop", "true"); //是否剪切 intent.putExtra("scale", true); //设置可缩放 intent.putExtra("scaleUpIfNeeded", true); // c去黑边 intent.putExtra("return-data", false); //禁止startActivityOnResult返回Bitmap startActivityForResult(intent, RESULT_CLIP); } /** * 获取 ContentView * * @return ContentView */ public View getContentView() { return getActivity().findViewById(android.R.id.content); } /** * 添加Disposable * * @param disposable Disposable */ public void addDisposable(@NonNull Disposable disposable) { if (mCompositeDisposable == null) { mCompositeDisposable = new CompositeDisposable(); } mCompositeDisposable.add(disposable); } /** * 清空Disposable */ private void clearDisposable() { if (mCompositeDisposable != null) { mCompositeDisposable.clear(); mCompositeDisposable = null; } } @Override public void onDestroy() { super.onDestroy(); //销毁加载中Dialog LoadingDialog.getInstance().destory(); //销毁权限申请框架 mRxPermissions = null; //清空Disposable clearDisposable(); //反注册EventBus if (this.getClass().isAnnotationPresent(BindEventBus.class) && EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this); } } } ``` LoadingCallback.java ```//package com.example.myapplication.widget.callback; // //import android.animation.ObjectAnimator; //import android.animation.ValueAnimator; //import android.content.Context; //import android.view.View; //import android.view.animation.LinearInterpolator; // //import com.blankj.utilcode.util.LogUtils; //import com.example.myapplication.R; //import com.kingja.loadsir.callback.Callback; // ///** // * Function: // * Author: ShiJingFeng // * Date: 2019/11/11 10:26 // * Description: // */ //public class LoadingCallback extends Callback { // // private ObjectAnimator mAnimator; // // @Override // protected int onCreateView() { // return R.layout.callback_loading; // } // // @Override // protected void onViewCreate(Context context, View view) { // super.onViewCreate(context, view); // LogUtils.log(LogUtils.E, "测试", "LoadingCallback onViewCreate()"); // startAnimator(view.findViewById(R.id.iv_callback_loading_img)); // } // // @Override // public void onDetach() { // super.onDetach(); // LogUtils.log(LogUtils.E, "测试", "LoadingCallback onDetach()"); // destroyAnimator(); // } // // /** // * 开始旋转动画 // */ // private void startAnimator(View view) { // mAnimator = ObjectAnimator.ofFloat(view, "rotation", 0, 360); // mAnimator.setInterpolator(new LinearInterpolator()); // mAnimator.setDuration(1000); // mAnimator.setRepeatCount(ValueAnimator.INFINITE); // mAnimator.start(); // } // // /** // * 销毁旋转动画 // */ // private void destroyAnimator() { // if (mAnimator != null) { // mAnimator.cancel(); // mAnimator = null; // } // } //} ``` CharacterUtil.java ```package com.example.myapplication.util; import androidx.annotation.NonNull; import java.util.Map; /** * Function: 字符操作工具类 * Author: ShiJingFeng * Date: 2019/10/6 15:27 * Description: */ public class CharacterUtil { /** * 向URL字符串中添加参数 * @param url * @param key * @param value * @return */ public static String addUrlParam(@NonNull String url, @NonNull String key, @NonNull String value) { String newUrl; if (url.contains("?")) { newUrl = url + "&"+ key + "=" + value; } else { newUrl = url + "?" + key + "=" + value; } return newUrl; } /** * 向URL字符串中添加多个参数 * @param url * @param paramMap * @return */ public static String addUrlParam(@NonNull String url, @NonNull Map<String, Object> paramMap) { StringBuilder newUrlBuilder = new StringBuilder(url); for (Map.Entry<String, Object> entry : paramMap.entrySet()) { final String key = entry.getKey(); final Object value = entry.getValue(); if (newUrlBuilder.toString().contains("?")) { newUrlBuilder.append("&"); newUrlBuilder.append(key); newUrlBuilder.append("="); newUrlBuilder.append(value); } else { newUrlBuilder.append("?"); newUrlBuilder.append(key); newUrlBuilder.append("="); newUrlBuilder.append(value); } } return newUrlBuilder.toString(); } } ``` NetworkConstant.java ```package com.demo.mvvm.constants; /** * 文件名: NetworkConstant * 日期: 2020/11/19 9:42 * 描述: 网络常量 */ public class NetworkConstant { /** * 请求成功 */ public static final int SUCCESS = 200; } ``` BaseEntity.java ```package com.example.myapplication.base.entity; import com.example.myapplication.base.util.CastUtil; import java.io.Serializable; /** * 文件名: BaseEntity * 作者: yin * 日期: 2020/4/16 23:42 * 描述: 全实体类的基类 */ public abstract class BaseEntity implements Serializable { /** * 获取子类 * * @param <T> 子类类型 * @return 子类 */ public <T extends BaseEntity> T get() { return CastUtil.cast(this); } /** * 获取ID * * @return ID */ public String getId() { return ""; } } ``` DoubleClickExitUtil.java ```package com.example.myapplication.util; import android.content.Context; import android.os.Handler; import android.widget.Toast; import com.blankj.utilcode.util.ActivityUtils; /** * Function: 双击退出Util * Author: ShiJingFeng * Date: 2019/11/14 14:21 * Description: */ public class DoubleClickExitUtil { /** 退出应用 */ private static boolean mExitApp = false; public static void execute(Context context) { if (mExitApp) { //关闭所有的Activity ActivityUtils.finishAllActivities(); } else { mExitApp = true; Toast.makeText(context,"再按一次退出应用",Toast.LENGTH_SHORT).show(); //超过两秒没有再次点击,则不退出App new Handler().postDelayed(() -> mExitApp = false, 2000); } } } ``` MyBindingAdapter.java ```package com.example.myapplication.base.adapter; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.core.content.ContextCompat; import androidx.databinding.BindingAdapter; import com.example.myapplication.base.util.PhotoFromPhotoAlbum; import com.example.myapplication.util.ImageLoaderUtil; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener; import com.scwang.smartrefresh.layout.listener.OnRefreshListener; public class MyBindingAdapter { @BindingAdapter("android:src") public static void setSrc(ImageView view, Object object) { if (object instanceof Integer) { view.setImageResource((Integer) object); } else if (object instanceof Uri) { view.setImageURI((Uri) object); } else if (object instanceof String) { ImageLoaderUtil.getInstance().display(view.getContext(), view, (String) object); } else if (object instanceof Bitmap) { view.setImageBitmap((Bitmap) object); } } @BindingAdapter("setWidth") public static void setWidth(View view, double width) { if (view == null || width < 0) return; ViewGroup.LayoutParams params = view.getLayoutParams(); if (params != null) { params.width = (int) (width); } } @BindingAdapter(value = "android:background", requireAll = false) public static void setBackground(View view, Object object) { if (object instanceof Integer) { try { view.setBackgroundResource((Integer) object); } catch (Resources.NotFoundException e) { view.setBackgroundColor((Integer) object); } } else if (object instanceof Uri) { String path = PhotoFromPhotoAlbum.getRealPathFromUri(view.getContext(), (Uri) object); view.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(path))); } else if (object instanceof Bitmap) { view.setBackground(new BitmapDrawable((Bitmap) object)); } } @BindingAdapter(value = "android:backgroundTint", requireAll = false) public static void setTintColor(ImageView imageView, int colorId) { imageView.setColorFilter(imageView.getContext().getColor(colorId)); } @BindingAdapter(value = "android:textColor", requireAll = false) public static void setTextColor(TextView textView, int colorId) { try { textView.setTextColor(ContextCompat.getColor(textView.getContext(), colorId)); } catch (Resources.NotFoundException e) { textView.setTextColor(colorId); } } @BindingAdapter(value = "android:textSize", requireAll = false) public static void setTextSize(TextView textView, int size) { textView.setTextSize(size); } @BindingAdapter(value = "android:setOnLoadMoreListener", requireAll = false) public static void setOnLoadMoreListener(SmartRefreshLayout smartRefreshLayout, OnLoadMoreListener onLoadMoreListener) { if (smartRefreshLayout != null) { smartRefreshLayout.setOnLoadMoreListener(onLoadMoreListener); } } @BindingAdapter(value = "android:setOnRefreshListener", requireAll = false) public static void setOnRefreshListener(SmartRefreshLayout smartRefreshLayout, OnRefreshListener onRefreshListener) { if (smartRefreshLayout != null) { smartRefreshLayout.setOnRefreshListener(onRefreshListener); } } } ``` LogUtil.java ```package com.example.myapplication.util; import android.util.Log; import androidx.annotation.NonNull; /** * Function: 日志工具类 * Author: ShiJingFeng * Date: 2019/11/30 23:20 * Description: */ public class LogUtil { private static boolean sEnable = true; /** * 是否开启日志 * @param enable true 开启 false 关闭 */ public static void enable(boolean enable) { sEnable = enable; } /** * 日志级别:verbose * @param tag 日志标签 * @param msg 日志内容 */ public static void v(@NonNull String tag, @NonNull String msg) { if (sEnable) { Log.v(tag, msg); } } /** * 日志级别:info * @param tag 日志标签 * @param msg 日志内容 */ public static void i(@NonNull String tag, @NonNull String msg) { if (sEnable) { Log.i(tag, msg); } } /** * 日志级别:debug * @param tag 日志标签 * @param msg 日志内容 */ public static void d(@NonNull String tag, @NonNull String msg) { if (sEnable) { Log.d(tag, msg); } } /** * 日志级别:warn * @param tag 日志标签 * @param msg 日志内容 */ public static void w(@NonNull String tag, @NonNull String msg) { if (sEnable) { Log.w(tag, msg); } } /** * 日志级别:error * @param tag 日志标签 * @param msg 日志内容 */ public static void e(@NonNull String tag, @NonNull String msg) { if (sEnable) { Log.e(tag, msg); } } } ``` StatusBarUtil.java ```package com.example.myapplication.util; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.os.Build; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import androidx.annotation.ColorRes; /** * function: 状态栏工具类 * date: 2019/7/3 */ public class StatusBarUtil { /** * 设置 状态栏背景 颜色 * * @param color 颜色资源 */ public static void setStatusBarColor(Activity activity, @ColorRes int color) { final Window window = activity.getWindow(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(activity.getResources().getColor(color)); } } /** * 设置 状态栏内容 颜色 * * @param dark 深色 或 浅色 true: 深色 false: 浅色 */ @TargetApi(Build.VERSION_CODES.M) public static void setStatusBarContentColor(Activity activity, final boolean dark) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { final View decor = activity.getWindow().getDecorView(); final int flag = decor.getSystemUiVisibility(); if (dark) { if ((View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) != flag) { decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); } } else { if ((View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != flag) { decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); } } } } /** * 获取状态栏高度 * * @param context Context * @return 高度 */ public static int getStatusBarHeight(Context context) { int result = 36; int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } Log.e("tag", "status_bar_height=" + result); return result; } } ``` AppBaseActivity.java ```package com.example.myapplication.base.activity; import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.view.View; import android.widget.Toast; import androidx.annotation.IdRes; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.databinding.ViewDataBinding; import com.blankj.utilcode.util.ActivityUtils; import com.example.myapplication.R; import com.example.myapplication.annotation.NeedPermissions; import com.example.myapplication.base.viewmodel.BaseViewModel; import com.example.myapplication.util.LogUtil; import com.example.myapplication.util.ResourceUtil; import com.example.myapplication.util.StatusBarUtil; /** * 文件名: AppBaseActivity * 作者: yin * 日期: 2020/4/16 23:42 * 描述: Activity基类 */ @NeedPermissions public abstract class AppBaseActivity<V extends ViewDataBinding, VM extends BaseViewModel> extends MvvmBaseActivity<V, VM> { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); LogUtil.d("页面", this.getClass().getSimpleName()); } @Override protected void onStart() { super.onStart(); initStatusBar(); } /** * 初始化数据 */ protected void initData() { super.initData(); //Activity默认背景为白色 getContentView().setBackgroundResource(R.color._FFFFFF); //设置状态栏高度 if (isSetCustomStatusBarHeight()) { @IdRes final int id = ResourceUtil.getResId("rl_layout_title_bar", R.id.class); if (id != -1) { final View view = findViewById(id); if (view != null) { view.setPadding(0, StatusBarUtil.getStatusBarHeight(this), 0, 0); view.setMinimumHeight(view.getHeight() + StatusBarUtil.getStatusBarHeight(this)); } } } } /** * 初始化状态栏 */ private void initStatusBar() { //设置默认状态栏背景颜色 为透明色 StatusBarUtil.setStatusBarColor(this, getStatusBarBackgroundStyle()); //设置默认状态栏字体颜色为浅色 StatusBarUtil.setStatusBarContentColor(this, getStatusBarTextStyle()); } /** * 设置导航栏是否预留出状态栏高度 * * @return true 预留 false 不预留 */ protected boolean isSetCustomStatusBarHeight() { return true; } /** * 设置状态栏内容颜色 */ protected boolean getStatusBarTextStyle() { return false; } /** * 设置状态栏背景颜色 */ protected int getStatusBarBackgroundStyle() { return R.color._00000000; } /** * 连续双击退出应用 */ protected boolean mExitApp; /** * 指定间隔时间内 按下两次返回键退出App */ protected void doubleDownExitApp() { if (mExitApp) { //关闭所有的Activity ActivityUtils.finishAllActivities(); } else { mExitApp = true; Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show(); //超过两秒没有再次点击,则不退出App new Handler().postDelayed(() -> mExitApp = false, 2000); } } protected void openPhotoWithPermission() { addDisposable( mRxPermissions .requestEachCombined(Manifest.permission.READ_EXTERNAL_STORAGE) .subscribe(permission -> { if (permission.granted) { openPhoto(); } else if (permission.shouldShowRequestPermissionRationale) { Toast.makeText(this, "外部存储权限授予失败", Toast.LENGTH_SHORT).show(); } else { new AlertDialog.Builder(this) .setMessage("需要您去设置页面,「权限管理」,开启「外部存储」权限") .setPositiveButton("去设置", (DialogInterface dialog, int which) -> { Intent settingIntent = new Intent(); settingIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); settingIntent.setData(Uri.fromParts("package", getPackageName(), null)); settingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(settingIntent); }) .setOnDismissListener(null) .setCancelable(false) .show(); } }) ); } } ``` RoundImageView.java ```package com.example.myapplication.base.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Path; import android.os.Build; import android.util.AttributeSet; import android.view.View; /** * 文件名: RoundImageView * 日期: 2020/11/20 13:58 * 描述: 圆角图片控件 */ public class RoundImageView extends androidx.appcompat.widget.AppCompatImageView { private static final int ROUND = 15; private int defaultRadius = 0; private int radius; private int leftTopRadius; private int rightTopRadius; private int rightBottomRadius; private int leftBottomRadius; float width, height; public RoundImageView(Context context) { this(context, null); } public RoundImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); if (Build.VERSION.SDK_INT < 18) { setLayerType(View.LAYER_TYPE_SOFTWARE, null); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); width = getWidth(); height = getHeight(); } @Override protected void onDraw(Canvas canvas) { leftTopRadius = ROUND; //左上角 rightTopRadius = ROUND; //右上角 rightBottomRadius = ROUND; //右下角 leftBottomRadius = ROUND; //左下角 int maxLeft = Math.max(leftTopRadius, leftBottomRadius); int maxRight = Math.max(rightTopRadius, rightBottomRadius); int minWidth = maxLeft + maxRight; int maxTop = Math.max(leftTopRadius, rightTopRadius); int maxBottom = Math.max(leftBottomRadius, rightBottomRadius); int minHeight = maxTop + maxBottom; if (width >= minWidth && height > minHeight) { Path path = new Path(); path.moveTo(leftTopRadius, 0); path.lineTo(width - rightTopRadius, 0); path.quadTo(width, 0, width, rightTopRadius); path.lineTo(width, height - rightBottomRadius); path.quadTo(width, height, width - rightBottomRadius, height); path.lineTo(leftBottomRadius, height); path.quadTo(0, height, 0, height - leftBottomRadius); path.lineTo(0, leftTopRadius); path.quadTo(0, 0, leftTopRadius, 0); canvas.clipPath(path); } super.onDraw(canvas); } } ``` GpsUtil.java ```package com.example.myapplication.util; import android.app.Activity; import android.app.ActivityManager; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.LocationManager; import android.net.Uri; import android.provider.Settings; import androidx.appcompat.app.AlertDialog; import com.example.myapplication.constant.CodeConstant; import static android.content.Context.ACTIVITY_SERVICE; public class GpsUtil { /** * 判断GPS是否开启,GPS或者AGPS开启一个就认为是开启的 * * @param context * @return true 表示开启 */ public static final boolean isOPen(final Context context) { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); // 通过GPS卫星定位,定位级别可以精确到街(通过24颗卫星定位,在室外和空旷的地方定位准确、速度快) boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); // 通过WLAN或移动网络(3G/2G)确定的位置(也称作AGPS,辅助GPS定位。主要用于在室内或遮盖物(建筑群或茂密的深林等)密集的地方定位) boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (gps) { return true; } return false; } /** * 提示打开GPS * * @param context */ public static void openGPS(Context context) { new AlertDialog.Builder(context) .setMessage("需要开启定位功能") .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { android.os.Process.killProcess(android.os.Process.myPid()); } }) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); ((Activity) context).startActivityForResult(intent, CodeConstant.REQUEST_GPS); dialogInterface.dismiss(); } }) .show(); } } ``` JsonUtils.java ```package com.example.myapplication.util; import androidx.annotation.NonNull; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.lang.reflect.Type; /** * Json转换工具类 */ public class JsonUtils { /** * 将对象准换为json字符串 * @param object 要序列化的对象 * @param <T> 对象类型 * @return Json序列化字符串 */ public static <T> String serialize(T object) { final Gson gson = new GsonBuilder() .disableHtmlEscaping() //禁止转码 .setLenient() //允许超长字符串 .create(); return gson.toJson(object); } /** * 将json字符串转换为对象 * @param json Json字符串 * @param type 对象类型 * @param <T> 对象泛型类型 * @return 对象 */ public static <T> T deserialize(@NonNull String json, @NonNull Type type) { final Gson gson = new GsonBuilder() .disableHtmlEscaping() //禁止转码 .setLenient() //允许超长字符串 .create(); return gson.fromJson(json, type); } /** * 将json字符串转换为对象 * @param json Json字符串 * @param clz 对象类型 * @param <T> 对象泛型类型 * @return 对象 */ public static <T> T deserialize(@NonNull String json, @NonNull Class<T> clz) { final Gson gson = new GsonBuilder() .disableHtmlEscaping() //禁止转码 .setLenient() //允许超长字符串 .create(); return gson.fromJson(json, clz); } } ``` IDemoNetworkSource.java ```package com.demo.mvvm.network.interfaces; import androidx.annotation.NonNull; import com.demo.mvvm.entity.DemoEntity; import com.demo.mvvm.entity.ResultEntity; import com.example.myapplication.listener.OnResultListener; import java.util.List; import java.util.Map; /** * 文件名: IDemoNetworkSource * 日期: 2021/01/25 11:18 * 描述: 网络数据操作接口 */ public interface IDemoNetworkSource { /** * 解析data对象 * * @param position url数据集中的url坐标 * @param postMap 数据 * @param listener 回调监听 */ void demo1(int position, @NonNull Map<String, Object> postMap, @NonNull OnResultListener<ResultEntity<DemoEntity>, String> listener); /** * 解析data数组 * * @param position url数据集中的url坐标 * @param postMap 数据 * @param listener 回调监听 */ void demo2(int position, @NonNull Map<String, Object> postMap, @NonNull OnResultListener<ResultEntity<List<DemoEntity>>, String> listener); } ``` DateTimeUtil.java ```package com.example.myapplication.util; import android.text.TextUtils; import androidx.annotation.NonNull; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Function: 日期时间工具类 * Author: ShiJingFeng * Date: 2019/10/8 15:25 * Description: */ public class DateTimeUtil { /** * 将时间毫秒值 转换为 指定格式的字符串 * @param millisecond 时间毫秒值 * @param pattern 格式 * @return 指定格式的字符串 */ public static String getFormativeDateTimeStr(long millisecond, String pattern) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, Locale.CHINESE); Date date = new Date(millisecond); return simpleDateFormat.format(date); } /** * 将时间毫秒值 转换为 默认格式的字符串 * @param millisecond 时间毫秒值 * @return 默认格式的字符串 */ public static String getDefaultDateStr(long millisecond) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE); Date date = new Date(millisecond); return simpleDateFormat.format(date); } /** * 将年月日转换为时间毫秒值 * @param dateTime 日期时间字符串 * @param pattern 模式 * @return 毫秒值 */ public static long getMillisecondFromDateTime(@NonNull String dateTime, @NonNull String pattern) { if (TextUtils.isEmpty(dateTime)) { return 0; } SimpleDateFormat format = new SimpleDateFormat(pattern); try { return format.parse(dateTime).getTime(); } catch (ParseException e) { e.printStackTrace(); } return 0; } } ``` ChangeBaseUrlInterceptor.java ```package com.example.myapplication.util.interceptor; import android.text.TextUtils; import org.jetbrains.annotations.NotNull; import java.io.IOException; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; /** * Function: 改变BaseUrl OkHttp拦截器 * Author: ShiJingFeng * Date: 2019/10/12 13:33 * Description: */ public class ChangeBaseUrlInterceptor implements Interceptor { @NotNull @Override public Response intercept(@NotNull Interceptor.Chain chain) throws IOException { //获取request Request request = chain.request(); //从request中获取原有的HttpUrl实例oldHttpUrl HttpUrl oldHttpUrl = request.url(); //获取request的创建者builder Request.Builder builder = request.newBuilder(); //从request中获取headers,通过给定的键url_name String baseUrlHeader = request.header("baseUrl"); // String baseUrl; // if (!TextUtils.isEmpty(baseUrlHeader)) { // switch (baseUrlHeader) { // default: // baseUrl = NetworkConstant.COMPANY_SERVICE_BASE_URL; // break; // } // } //TODO 待完善 return chain.proceed(request); } } ``` SecurityUtil.java ```package com.example.myapplication.util; import androidx.annotation.NonNull; import com.blankj.utilcode.util.EncryptUtils; import java.nio.charset.StandardCharsets; /** * Function: 安全 工具类 * Author: ShiJingFeng * Date: 2019/10/10 13:17 * Description: */ public class SecurityUtil { private static final byte[] sKeyByteArray = "w7kqxCbW13IN3LG9".getBytes(); private static final String sTransformation = "AES/CBC/PKCS5Padding"; private static final byte[] sIvByteArray = "FEE7qJlMkRYiXzkB".getBytes(); /** * 加密数据 * @param str 要加密的数据 */ public static String encrypt(@NonNull String str) { final byte[] encryptByteArray = EncryptUtils.encryptAES2Base64(str.getBytes(StandardCharsets.UTF_8), sKeyByteArray, sTransformation, sIvByteArray); return new String(encryptByteArray, StandardCharsets.UTF_8); } /** * 解密数据 * @param str 要解密的数据 */ public static String decrypt(@NonNull String str) { final byte[] decryptByteArray = EncryptUtils.decryptBase64AES(str.getBytes(StandardCharsets.UTF_8), sKeyByteArray, sTransformation, sIvByteArray); return new String(decryptByteArray, StandardCharsets.UTF_8); } } ``` BaseLocalSource.java ```package com.example.myapplication.base.source; import com.example.myapplication.base.util.CastUtil; /** * 文件名: BaseLocalSource * 作者: yin * 日期: 2020/4/16 23:42 * 描述: 本地资源基类 */ public abstract class BaseLocalSource { /** * 获取子类类型实例 * * @param <T> 泛型 * @return 子类类型实例 */ public <T extends BaseLocalSource> T get() { return CastUtil.cast(this); } /** * 销毁回调 */ public void onCleared() { } } ``` DemoEntity.java ```package com.demo.mvvm.entity; import com.example.myapplication.base.entity.BaseEntity; import com.google.gson.annotations.SerializedName; public class DemoEntity extends BaseEntity { @SerializedName("id") public String id; @SerializedName("username") public String username; @SerializedName("nickname") public String nickname; //图片url @SerializedName("avatar") public Object avatar; @SerializedName("password") public String password; } ``` DemoViewModel.java ```package com.demo.mvvm.viewmodel; import android.os.Handler; import android.view.View; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.databinding.ObservableArrayList; import androidx.databinding.ObservableBoolean; import androidx.databinding.ObservableField; import androidx.databinding.ObservableInt; import androidx.databinding.ObservableList; import com.blankj.utilcode.util.ToastUtils; import com.demo.mvvm.BR; import com.demo.mvvm.R; import com.demo.mvvm.entity.DemoEntity; import com.demo.mvvm.entity.ResultEntity; import com.demo.mvvm.repository.DemoRepository; import com.example.myapplication.base.entity.TitleBarBean; import com.example.myapplication.base.viewmodel.BaseViewModel; import com.example.myapplication.listener.OnResultListener; import com.example.myapplication.widget.dialog.LoadingDialog; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener; import com.scwang.smartrefresh.layout.listener.OnRefreshListener; import java.util.HashMap; import java.util.List; import java.util.Map; import me.tatarka.bindingcollectionadapter2.ItemBinding; /** * 文件名: DemoViewModel * 日期: 2020/11/19 10:17 * 描述: ViewModel */ public class DemoViewModel extends BaseViewModel<DemoRepository> { //导航栏bean类 private TitleBarBean titleBarBean = new TitleBarBean(); //顶部导航栏 public ObservableField<TitleBarBean> titleBar = new ObservableField<>(titleBarBean); //文本文字 public ObservableField<String> text = new ObservableField<>("啦啦啦"); //文字颜色 public ObservableInt textColor = new ObservableInt(R.color._000000); //文本大小 public ObservableInt textSize = new ObservableInt(14); //背景 public ObservableField<Object> background = new ObservableField<>(R.color._FF7F29); //资源图片 public ObservableField<Object> image1 = new ObservableField<>(R.mipmap.ic_launcher); //网络图片 public ObservableField<Object> image2 = new ObservableField<>("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1606381411448&di=ad8e79e78aa1b468829f8641dccade57&imgtype=0&src=http%3A%2F%2F9.pic.9ht.com%2Fup%2F2018-5%2F2018530172841.jpg"); //按钮点击事件 public View.OnClickListener click1 = v -> { click2(); }; public void click2() { ToastUtils.showShort("点击"); } //单选 public ObservableBoolean check1 = new ObservableBoolean(false); //多选 public ObservableBoolean check2 = new ObservableBoolean(false); //recycleview public final ObservableList<DemoEntity> items = new ObservableArrayList<>(); public final ItemBinding<DemoEntity> itemBinding = ItemBinding.of(BR.demoEntity, R.layout.item); public OnLoadMoreListener loadMoreListener = new OnLoadMoreListener() { @Override public void onLoadMore(@NonNull RefreshLayout refreshLayout) { showLoadingDialog("加载中..."); //假数据 for (int i = 0; i < 5; i++) { DemoEntity demoEntity = new DemoEntity(); demoEntity.username = String.valueOf(i); demoEntity.id = String.valueOf(i); demoEntity.nickname = String.valueOf(i); demoEntity.password = String.valueOf(i); items.add(demoEntity); } hideLoadingDialog(); refreshLayout.finishLoadMore(); } }; public OnRefreshListener onRefreshListener = new OnRefreshListener() { @Override public void onRefresh(@NonNull RefreshLayout refreshLayout) { items.clear(); showLoadingDialog("加载中..."); //假数据 for (int i = 0; i < 5; i++) { DemoEntity demoEntity = new DemoEntity(); demoEntity.username = String.valueOf(i); demoEntity.id = String.valueOf(i); demoEntity.nickname = String.valueOf(i); demoEntity.password = String.valueOf(i); items.add(demoEntity); } new Handler().postDelayed(new Runnable() { @Override public void run() { hideLoadingDialog(); } }, 1000); refreshLayout.finishRefresh(); } }; public DemoViewModel(DemoRepository repository) { super(repository); //导航栏中心文字 titleBarBean.tvCenter.set("示例"); //导航栏左侧图标点击事件 titleBarBean.onBack(new TitleBarBean.OnItemEventListener() { @Override public void onClick() { finish(); } }); } @Override protected void onCreate() { super.onCreate(); showLoadingDialog("123"); //假数据 for (int i = 0; i < 5; i++) { DemoEntity demoEntity = new DemoEntity(); demoEntity.username = String.valueOf(i); demoEntity.id = String.valueOf(i); demoEntity.nickname = String.valueOf(i); demoEntity.password = String.valueOf(i); items.add(demoEntity); } hideLoadingDialog(); //返回json中data数据为{} Map<String, Object> postMap1 = new HashMap<>(); postMap1.put("username", "123"); postMap1.put("password", "123"); mRepository.demo1(1, postMap1, new OnResultListener<ResultEntity<DemoEntity>, String>() { @Override public void onSuccess(ResultEntity<DemoEntity> data) { super.onSuccess(data); } @Override public void onFailure(String data, Throwable e) { super.onFailure(data, e); } }); //返回json中data数据为[] Map<String, Object> postMap2 = new HashMap<>(); postMap2.put("username", "123"); postMap2.put("password", "123"); mRepository.demo2(1, postMap2, new OnResultListener<ResultEntity<List<DemoEntity>>, String>() { @Override public void onSuccess(ResultEntity<List<DemoEntity>> data) { super.onSuccess(data); } @Override public void onFailure(String data, Throwable e) { super.onFailure(data, e); } }); } } ``` MyApplication.java ```package com.demo.mvvm; import com.example.myapplication.base.application.BaseApplication; import java.util.ArrayList; import java.util.List; public class MyApplication extends BaseApplication { @Override public void onCreate() { super.onCreate(); } /** * 设置服务器地址集合 * * @return 服务器地址集 */ @Override protected List<String> initBaseUrl() { List<String> urlList = new ArrayList<>(); urlList.add("http://www.xxx.com"); urlList.add("http://www.yyy.com"); return urlList; } } ``` BaseRepository.java ```package com.example.myapplication.base.repository; import androidx.annotation.NonNull; import com.example.myapplication.base.source.BaseLocalSource; import com.example.myapplication.base.source.BaseNetworkSource; import com.example.myapplication.base.util.CastUtil; /** * 文件名: BaseRepository * 作者: yin * 日期: 2020/4/16 23:42 * 描述: 网络仓库基类 */ public abstract class BaseRepository { protected BaseLocalSource mLocalSource; protected BaseNetworkSource mNetworkSource; /** * 设置网络源 * * @param networkSource 网络源 * @param <T> 泛型 * @return Repository */ public final <T extends BaseRepository> T setNetworkSource(@NonNull BaseNetworkSource networkSource) { this.mNetworkSource = networkSource; return CastUtil.cast(this); } /** * 设置本地源 * * @param localSource 本地源 * @param <T> 泛型 * @return Repository */ public final <T extends BaseRepository> T setLocalSource(@NonNull BaseLocalSource localSource) { this.mLocalSource = localSource; return CastUtil.cast(this); } /** * 获取子类类型实例 * * @param <T> 泛型 * @return 子类类型实例 */ public final <T extends BaseRepository> T get() { return CastUtil.cast(this); } /** * 销毁回调 */ public void onCleared() { if (mLocalSource != null) { mLocalSource.onCleared(); } if (mNetworkSource != null) { mNetworkSource.onCleared(); } } } ``` BaseViewModel.java ```package com.example.myapplication.base.viewmodel; import android.net.Uri; import android.os.Bundle; import android.util.SparseArray; import androidx.annotation.NonNull; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleObserver; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.OnLifecycleEvent; import androidx.lifecycle.ViewModel; import com.example.myapplication.annotation.BindEventBus; import com.example.myapplication.base.repository.BaseRepository; import com.example.myapplication.livedata.SingleLiveEvent; import org.greenrobot.eventbus.EventBus; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; /** * 文件名: AppBaseActivity * 作者: yin * 日期: 2020/4/16 23:42 * 描述: ViewModel基类 */ public abstract class BaseViewModel<R extends BaseRepository> extends ViewModel implements LifecycleObserver { protected R mRepository; /** * UI改变 LiveData管理器 */ private UIChangeLiveDataManager mUiChangeLiveDataManager; /** * Disposable容器 */ private CompositeDisposable mCompositeDisposable; /** * 连续双击退出应用 */ // protected boolean mExitApp; public BaseViewModel(R repository) { this.mRepository = repository; registerEventBus(); } /** * 注册EventBus */ private void registerEventBus() { //绑定EventBus if (this.getClass().isAnnotationPresent(BindEventBus.class) && !EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } } /** * 解注册EventBus */ private void unregisterEventBus() { //解绑EventBus if (this.getClass().isAnnotationPresent(BindEventBus.class) && EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this); } } /** * 获取 UI改变 LiveData管理器 * * @return UI改变 LiveData管理器 */ public UIChangeLiveDataManager getUiChangeLiveDataManager() { if (mUiChangeLiveDataManager == null) { mUiChangeLiveDataManager = new UIChangeLiveDataManager(); } return mUiChangeLiveDataManager; } /** * 显示加载中Dialog * * @param hint 提示文本 */ public void showLoadingDialog(@NonNull String hint) { getUiChangeLiveDataManager().getShowLoadingDialogEvent().postValue(hint); } /** * 隐藏加载中Dialog */ public void hideLoadingDialog() { getUiChangeLiveDataManager().getHideLoadingDialogEvent().call(); } /** * 通过Class跳转界面 **/ public void startActivity(Class<?> cls) { startActivity(cls, null); } /** * 通过Class跳转界面 (有结果返回) * * @param cls 要跳转到的Activity * @param requestCode 请求码 **/ public void startActivityForResult(Class<?> cls, int requestCode) { startActivityForResult(cls, null, requestCode); } /** * 含有Bundle通过Class跳转界面 * * @param cls 要跳转到的Activity * @param bundle 携带的数据 **/ public void startActivity(Class<?> cls, Bundle bundle) { final SparseArray<Object> paramSA = new SparseArray<>(2); paramSA.put(ParamConstant.CLASS, cls); if (bundle != null) { paramSA.put(ParamConstant.BUNDLE, bundle); } getUiChangeLiveDataManager().getStartActivityEvent().postValue(paramSA); } /** * 通过String执行动作 **/ public void startActivity(String str) { startActivity(str, null); } /** * 含有Uri通过String执行动作 **/ public void startActivity(String str, Uri uri) { final SparseArray<Object> paramSA = new SparseArray<>(2); paramSA.put(ParamConstant.ACTION, str); if (uri != null) { paramSA.put(ParamConstant.DATA, uri); } getUiChangeLiveDataManager().getStartActionEvent().postValue(paramSA); } /** * 含有Bundle通过Class跳转界面 * * @param cls 要跳转到的Activity * @param bundle 要携带的数据 * @param requestCode 请求码 **/ public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) { final SparseArray<Object> paramSA = new SparseArray<>(3); paramSA.put(ParamConstant.CLASS, cls); if (bundle != null) { paramSA.put(ParamConstant.BUNDLE, bundle); } paramSA.put(ParamConstant.REQUEST_CODE, requestCode); getUiChangeLiveDataManager().getStartActivityEvent().postValue(paramSA); } /** * 销毁Activity */ public void finish() { getUiChangeLiveDataManager().getFinishEvent().call(); } /** * 添加Disposable * * @param disposable Disposable */ public void addDisposable(@NonNull Disposable disposable) { if (mCompositeDisposable == null) { mCompositeDisposable = new CompositeDisposable(); } mCompositeDisposable.add(disposable); } /** * 清空Disposable */ private void clearDisposable() { if (mCompositeDisposable != null) { mCompositeDisposable.clear(); mCompositeDisposable = null; } } /** * 指定间隔时间内 按下两次返回键退出App */ // public void doubleDownExitApp() { // if (mExitApp) { // //关闭所有的Activity // ActivityUtils.finishAllActivities(); // } else { // mExitApp = true; //// ToastUtils.showShort(MyApplication.get,"再按一次退出应用"); // //超过两秒没有再次点击,则不退出App // new Handler().postDelayed(() -> mExitApp = false, 2000); // } // } /** * ViewModel销毁回调 */ @Override protected void onCleared() { super.onCleared(); //解注册EventBus unregisterEventBus(); //取消所有异步任务 clearDisposable(); //销毁Model if (mRepository != null) { mRepository.onCleared(); } } @OnLifecycleEvent(Lifecycle.Event.ON_ANY) protected void onAny(LifecycleOwner owner, Lifecycle.Event event) { } @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) protected void onCreate() { } @OnLifecycleEvent(Lifecycle.Event.ON_START) protected void onStart() { } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) protected void onResume() { } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) protected void onPause() { } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) protected void onStop() { } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) protected void onDestroy() { } /** * UI改变 LiveData管理器 */ public static class UIChangeLiveDataManager { private SingleLiveEvent<String> showLoadingDialogEvent; private SingleLiveEvent<Object> hideLoadingDialogEvent; private SingleLiveEvent<SparseArray<Object>> startActivityEvent; private SingleLiveEvent<Object> finishEvent; private SingleLiveEvent<SparseArray<Object>> startActionEvent; /** * 获取 显示加载中Dialog SingleLiveEvent * * @return 显示加载中Dialog SingleLiveEvent */ public SingleLiveEvent<String> getShowLoadingDialogEvent() { if (showLoadingDialogEvent == null) { showLoadingDialogEvent = new SingleLiveEvent<>(); } return showLoadingDialogEvent; } /** * 获取 隐藏加载中Dialog SingleLiveEvent * * @return 隐藏加载中Dialog SingleLiveEvent */ public SingleLiveEvent<Object> getHideLoadingDialogEvent() { if (hideLoadingDialogEvent == null) { hideLoadingDialogEvent = new SingleLiveEvent<>(); } return hideLoadingDialogEvent; } /** * 获取 跳转Activity SingleLiveEvent * * @return 跳转Activity SingleLiveEvent */ public SingleLiveEvent<SparseArray<Object>> getStartActivityEvent() { if (startActivityEvent == null) { startActivityEvent = new SingleLiveEvent<>(); } return startActivityEvent; } /** * 获取 关闭销毁Activity SingleLiveEvent * * @return 关闭销毁Activity SingleLiveEvent */ public SingleLiveEvent<Object> getFinishEvent() { if (finishEvent == null) { finishEvent = new SingleLiveEvent<>(); } return finishEvent; } /** * 执行 动作Action SingleLiveEvent * * @return 跳转Activity SingleLiveEvent */ public SingleLiveEvent<SparseArray<Object>> getStartActionEvent() { if (startActionEvent == null) { startActionEvent = new SingleLiveEvent<>(); } return startActionEvent; } } /** * 静态常量 */ public static class ParamConstant { /** * Class */ public static final int CLASS = 1; /** * Bundle数据 */ public static final int BUNDLE = 2; /** * 请求码 */ public static final int REQUEST_CODE = 3; /** * Activity Class 全限定名称 */ public static final int CANONICAL_NAME = 4; /** * Bundle数据 */ public static final int ACTION = 5; /** * Bundle数据 */ public static final int DATA = 6; } } ``` EditTextInputFilterUtil.java ```package com.example.myapplication.util; import android.content.Context; import android.text.InputFilter; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.widget.Toast; /** * Function: EditText 输入文本过滤器工具类 * Author: ShiJingFeng * Date: 2019/10/6 17:34 * Description: */ public class EditTextInputFilterUtil { private EditTextInputFilterUtil() {} /** * 简单工厂模式创建对象 * @return 对象 */ public static EditTextInputFilterUtil create() { return new EditTextInputFilterUtil(); } /** * 获取 禁止系统表情输入 过滤器 * @return 禁止系统表情输入 过滤器 */ public InputFilter getProhibitSystemEmojiInputFilter(Context context) { return (CharSequence source, int start, int end, Spanned dest, int dstart, int dend) -> { StringBuffer buffer = new StringBuffer(); for (int i = start; i < end; i++) { char codePoint = source.charAt(i); if (!isSystemEmoji(codePoint)) { buffer.append(codePoint); } else { Toast.makeText(context,"暂不支持系统表情",Toast.LENGTH_SHORT).show(); i++; continue; } } if (source instanceof Spanned) { SpannableString sp = new SpannableString(buffer); TextUtils.copySpansFrom((Spanned) source, start, end, null, sp, 0); return sp; } else { return buffer; } }; } /** * 判断是不是系统表情 * @param codePoint 字符 * @return true: 是系统表情 false: 不是系统表情 */ private boolean isSystemEmoji(char codePoint) { if ((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF))) { return false; } return true; } } ``` BaseApplication.java ```package com.example.myapplication.base.application; import android.app.Application; import android.content.Context; import com.blankj.utilcode.util.LogUtils; import com.blankj.utilcode.util.Utils; import com.example.myapplication.constant.NetworkURL; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.footer.ClassicsFooter; import com.scwang.smartrefresh.layout.header.ClassicsHeader; import java.util.List; /** * 文件名: AppBaseActivity * 作者: yin * 日期: 2020/4/16 23:42 * 描述: 工程总Application */ public abstract class BaseApplication extends Application { protected static Application sInstance; //static 代码段可以防止内存泄露 static { //设置全局的Header构建器 SmartRefreshLayout.setDefaultRefreshHeaderCreator((Context context, RefreshLayout layout) -> { //全局设置主题颜色 layout.setPrimaryColorsId(android.R.color.white, android.R.color.black); //.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header,默认是 贝塞尔雷达Header return new ClassicsHeader(context); }); //设置全局的Footer构建器 SmartRefreshLayout.setDefaultRefreshFooterCreator((Context context, RefreshLayout layout) -> { //指定为经典Footer,默认是 BallPulseFooter return new ClassicsFooter(context).setDrawableSize(20); }); } @Override public void onCreate() { super.onCreate(); sInstance = this; NetworkURL.mUrlList = initBaseUrl(); init(); } protected abstract List<String> initBaseUrl(); @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); // //初始化MultiDex // MultiDex.install(this); } /** * 初始化 */ private void init() { initUtils(); } /** * 初始化万能工具类 */ private void initUtils() { //初始化万能工具类 (神器) Utils.init(this); //万能工具类 -> 日志相关 LogUtils.getConfig() .setLogSwitch(true); //设置 Log 总开关 } /** * 获取 Application; * * @return Application */ public static Application getInstance() { if (sInstance == null) { throw new NullPointerException("Application还没有初始化"); } return sInstance; } } ``` LoadingDialog.java ```package com.example.myapplication.widget.dialog; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.app.Activity; import android.os.Handler; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.animation.LinearInterpolator; import android.widget.TextView; import androidx.annotation.NonNull; import com.example.myapplication.R; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; /** * Function: Loading Dialog * Author: ShiJingFeng * Date: 2019/11/11 14:54 * Description: */ public class LoadingDialog { private static LoadingDialog sInstance; private CommonDialog mDialog; private ObjectAnimator mAnimator; private String mHintText = "提交中..."; private LoadingDialog() { } public static LoadingDialog getInstance() { if (sInstance == null) { sInstance = new LoadingDialog(); } return sInstance; } /** * 开始旋转动画 */ private void startAnimator() { try { final View view = mDialog.getContentView(); if (view == null) { return; } mAnimator = ObjectAnimator.ofFloat(view.findViewById(R.id.iv_dialog_loading_img), "rotation", 0, 360); mAnimator.setInterpolator(new LinearInterpolator()); mAnimator.setDuration(1000); mAnimator.setRepeatCount(ValueAnimator.INFINITE); mAnimator.start(); } catch (Exception e) { e.printStackTrace(); } } /** * 销毁旋转动画 */ private void destroyAnimator() { if (mAnimator != null) { mAnimator.cancel(); mAnimator = null; } } /** * 设置提示文本 * * @param hintText 提示文本 */ public LoadingDialog setHintText(@NonNull String hintText) { if (TextUtils.isEmpty(hintText)) { this.mHintText = "提交中..."; } else { this.mHintText = hintText; } return this; } /** * 显示加载中Dialog * * @param activity Activity */ public void show(Activity activity) { if (mDialog != null) { if (!mDialog.isShowing()) { final TextView tvText = mDialog.getContentView().findViewById(R.id.tv_dialog_loading_text); final String oldText = tvText.getText().toString(); if (!oldText.equals(mHintText)) { tvText.setText(mHintText); } startAnimator(); mDialog.show(); } return; } final View vGetVerifyCode = LayoutInflater.from(activity).inflate(R.layout.dialog_loading, null); ((TextView) vGetVerifyCode.findViewById(R.id.tv_dialog_loading_text)).setText(mHintText); try { mDialog = new CommonDialog.Builder(activity) .setContentView(vGetVerifyCode) .setWindowWidth(MATCH_PARENT) .setWindowHeight(MATCH_PARENT) .setOnDismissListener(this::hide) .show(); } catch (Exception e) { e.printStackTrace(); } startAnimator(); } /** * 隐藏加载中Dialog */ public void hide() { if (mDialog != null) { mDialog.hide(); mDialog = null; }else { new Handler().postDelayed(new Runnable() { @Override public void run() { if (mDialog != null) { mDialog.hide(); mDialog = null; } } },1000); } destroyAnimator(); } /** * 关闭加载中Dialog (注意一定要调用,否则会导致内存泄漏) */ public void destory() { hide(); mDialog = null; } } ``` ViewPagerAdapter.java ```package com.example.myapplication.base.adapter; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import com.example.myapplication.base.fragment.AppBaseFragment; import java.util.List; /** * @作者:Administrator * @时间:2020/5/25 15:14 * @描述:viewpager+fragment **/ public class ViewPagerAdapter extends FragmentPagerAdapter { private List<AppBaseFragment> list; public ViewPagerAdapter(FragmentManager fm, List<AppBaseFragment> list) { super(fm); this.list = list; } @Override public Fragment getItem(int position) { return list.get(position); } @Override public int getCount() { return list.size(); } } ``` MvvmFragment.java ```package com.example.myapplication.base.fragment; import android.os.Bundle; import android.util.SparseArray; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatDialogFragment; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import com.example.myapplication.base.viewmodel.BaseViewModel; /** * 文件名: MvvmFragment * 作者: yin * 日期: 2020/4/16 23:42 * 描述: MVVM架构Fragment基类 */ public abstract class MvvmFragment<V extends ViewDataBinding, VM extends BaseViewModel> extends Fragment { private String tag; /** * DataBinding */ protected V mDataBinding; /** * ViewModel */ protected VM mViewModel; protected View view; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mDataBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false); initAAC(); initParam(); initView(view); initData(); initAction(); view = mDataBinding.getRoot(); return view; } /** * 获取视图ID * * @return 视图ID */ protected abstract int getLayoutId(); /** * 获取ViewModel * * @return ViewModel */ protected abstract VM getViewModel(); protected abstract void initView(View view); protected abstract void initData(); protected abstract void initAction(); protected abstract void initParam(); /** * 初始化 DataBinding 变量ID 和 变量实体类 Map * * @return DataBinding 变量SparseArray */ protected abstract SparseArray<Object> getVariableSparseArray(); /** * 初始化AAC组件 */ private void initAAC() { mViewModel = getViewModel(); final SparseArray<Object> variableSA = getVariableSparseArray(); if (variableSA != null && variableSA.size() > 0) { for (int i = 0; i < variableSA.size(); ++i) { final int variableId = variableSA.keyAt(i); final Object variableValue = variableSA.valueAt(i); mDataBinding.setVariable(variableId, variableValue); } } //让ViewModel拥有View的生命周期感应 if (mViewModel != null) { getLifecycle().addObserver(mViewModel); } } // /** // * 创建ViewModel // * // * @param cls Activity Class // * @return ViewModel子类 // */ // public VM createViewModel(@NonNull Class<VM> cls) { // return new ViewModelProvider(this).get(cls); // } /** * 工厂模式创建ViewModel * * @param cls Activity Class * @param factory 工厂 * @return ViewModel子类 */ public VM createViewModel(@NonNull Class<VM> cls, @NonNull ViewModelProvider.NewInstanceFactory factory) { return new ViewModelProvider(this, factory).get(cls); } @Override public void onDestroy() { super.onDestroy(); //销毁DataBinding if (mDataBinding != null) { mDataBinding.unbind(); } } public void setFragmentTag(String tag) { this.tag = tag; } public String getFragmentTag() { return tag; } /** * 模拟 Activity key down 事件 * * @param keyCode key down code * @param event key down event * @return 是否消费 true 消费 false 不消费 */ public boolean onKeyDown(int keyCode, KeyEvent event) { return false; } } ``` AspectTest.java ```package com.example.myapplication.doubleclick; import android.util.Log; import android.view.View; import com.example.myapplication.util.NoDoubleClickUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class AspectTest { private boolean canDoubleClick = false; private View mLastView; @Before("@annotation(com.example.myapplication.annotation.DoubleClick)") public void beforeEnableDoubleClick(JoinPoint joinPoint) throws Throwable { canDoubleClick = true; } @Around("execution(* android.view.View.OnClickListener.onClick(..)) && target(Object) && this(Object)") public void OnClickListener(ProceedingJoinPoint joinPoint) throws Throwable { Object[] objects = joinPoint.getArgs(); View view = objects.length == 0 ? null : (View) objects[0]; Log.e("tag", "OnClick:" + view); if (view != mLastView || canDoubleClick || !NoDoubleClickUtils.isDoubleClick()) { joinPoint.proceed(); canDoubleClick = false; } mLastView = view; } } ``` DemoRepository.java ```package com.demo.mvvm.repository; import androidx.annotation.NonNull; import com.demo.mvvm.entity.DemoEntity; import com.demo.mvvm.entity.ResultEntity; import com.demo.mvvm.network.interfaces.IDemoNetworkSource; import com.example.myapplication.base.repository.BaseRepository; import com.example.myapplication.listener.OnResultListener; import java.util.List; import java.util.Map; /** * 文件名: BaseRepository * 日期: 2020/11/19 9:48 * 描述: Demo网络仓库 */ public class DemoRepository extends BaseRepository implements IDemoNetworkSource { private DemoRepository() { } public static DemoRepository create() { return new DemoRepository(); } @Override public void demo1(int position, @NonNull Map<String, Object> postMap, @NonNull OnResultListener<ResultEntity<DemoEntity>, String> listener) { if (mNetworkSource != null) { IDemoNetworkSource demoNetworkSource = mNetworkSource.get(); demoNetworkSource.demo1(position, postMap, listener); } else { throw new IllegalArgumentException("网络源不能为空"); } } @Override public void demo2(int position, @NonNull Map<String, Object> postMap, @NonNull OnResultListener<ResultEntity<List<DemoEntity>>, String> listener) { if (mNetworkSource != null) { IDemoNetworkSource demoNetworkSource = mNetworkSource.get(); demoNetworkSource.demo2(position, postMap, listener); } else { throw new IllegalArgumentException("网络源不能为空"); } } } ``` MaskLayout.java ```package com.example.myapplication.base.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.util.AttributeSet; import android.util.TypedValue; import android.widget.LinearLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.example.myapplication.R; /** * @author zhaofusen * @describe 动态设置布局嵌套View圆角 * @date 2019/4/15 19:45 */ public class MaskLayout extends LinearLayout { /** * 推荐的圆角角度 * 也可自定义圆角角度 * 换算单位为DP */ public final static int ANGLE_DP_5 = 5; public final static int ANGLE_DP_10 = 10; /** * 0 无圆角 */ public final static int VIEW_NO_CORNER_PART = 0; /** * 1 设置 Top Left,Top Right 圆角 */ public final static int VIEW_TOP_CORNER_PART = 1; /** * 2 设置 Bottom Left ,Bottom Right 圆角 */ public final static int VIEW_BOTTOM_CORNER_PART = 2; /** * 3 设置全圆角,四个角为圆角 */ public final static int VIEW_CORNER_ALL_PART = 3; private Context mContext; private GradientDrawable maskDrawable; private GradientDrawable cloneMaskDrawable; private PorterDuffXfermode mDuffXfermode; /** * 设置的角度值 */ private float[] cornerRadiusValue = {0,0,0,0,0,0,0,0}; private Paint maskPaint; private Canvas mCanvas; public MaskLayout(@NonNull Context context) { this(context, null); } public MaskLayout(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); this.mContext = context; TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MaskLayout); maskDrawable = (GradientDrawable)array.getDrawable(R.styleable.MaskLayout_xhg_mask_drawable); array.recycle(); maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG); maskPaint.setFilterBitmap(true); mDuffXfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN); maskPaint.setXfermode(mDuffXfermode); setWillNotDraw(false); } @Override public void draw(Canvas canvas) { if (cloneMaskDrawable != null) { this.mCanvas = canvas; int width = getMeasuredWidth(); int height = getMeasuredHeight(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { canvas.saveLayer(0f, 0f, width, height, null); } else { canvas.saveLayer(0f, 0f, width, height, null, Canvas.ALL_SAVE_FLAG); } cloneMaskDrawable.setBounds(getPaddingLeft(), getPaddingTop(), width - getPaddingRight(), height - getPaddingBottom()); cloneMaskDrawable.draw(canvas); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { canvas.saveLayer(0f, 0f, width, height, maskPaint); } else { canvas.saveLayer(0f, 0f, width, height, maskPaint, Canvas.ALL_SAVE_FLAG); } super.draw(canvas); canvas.restore(); } else { super.draw(canvas); } postInvalidateDelayed(100); // invalidate(); } /** * 模板圆角 number Y * Value: 0=无圆角,1=圆角头,2=圆角尾,3=圆角头尾 */ public void setTemplateCorner(int cornerPartType,float angleValue) { if (maskDrawable != null) { if (cloneMaskDrawable == null){ cloneMaskDrawable = (GradientDrawable) maskDrawable.getConstantState().newDrawable(); cloneMaskDrawable.mutate(); } if (cornerPartType == VIEW_TOP_CORNER_PART){ cornerRadiusValue = getCornerRadii(angleValue,angleValue,0,0); // cloneMaskDrawable.setCornerRadii(getCornerRadii(angleValue,angleValue,0,0)); } else if (cornerPartType == VIEW_BOTTOM_CORNER_PART){ cornerRadiusValue = getCornerRadii(0,0,angleValue,angleValue); // cloneMaskDrawable.setCornerRadii(getCornerRadii(0,0,angleValue,angleValue)); } else if (cornerPartType == VIEW_CORNER_ALL_PART){ cornerRadiusValue = getCornerRadii(angleValue,angleValue,angleValue,angleValue); // cloneMaskDrawable.setCornerRadii(getCornerRadii(angleValue,angleValue,angleValue,angleValue)); // cloneMaskDrawable.setCornerRadius(dp2px(angleValue)); } else { cornerRadiusValue = getCornerRadii(0,0,0,0); // cloneMaskDrawable.setCornerRadii(getCornerRadii(0,0,0,0)); // cloneMaskDrawable.setCornerRadius(0); } // cloneMaskDrawable.setCornerRadii(cornerRadiusValue); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (cloneMaskDrawable != null){ cloneMaskDrawable.setCornerRadii(cornerRadiusValue); } } /** * 当Holder从屏幕离开的时候进行设置数据 */ @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (cloneMaskDrawable != null){ cloneMaskDrawable.setCornerRadius(0); } } /** * 设置圆角 * @param leftTop * @param rightTop * @param leftBottom * @param rightBottom * @return */ private float[] getCornerRadii(float leftTop,float rightTop, float leftBottom,float rightBottom){ //这里返回的一个浮点型的数组,一定要有8个元素,不然会报错 return new float[]{dp2px(leftTop), dp2px(leftTop), dp2px(rightTop),dp2px(rightTop),dp2px(rightBottom), dp2px(rightBottom),dp2px(leftBottom),dp2px(leftBottom)}; } /** * 转换 * @param dpVal * @return */ private float dp2px(float dpVal){ return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, mContext.getResources().getDisplayMetrics()); } } ``` ServerApi.java ```package com.demo.mvvm.network.api; import com.demo.mvvm.entity.DemoEntity; import com.demo.mvvm.entity.ResultEntity; import java.util.List; import java.util.Map; import io.reactivex.Single; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.Part; import retrofit2.http.PartMap; /** * 文件名: ServerApi * 作者: yin * 日期: 2020/11/19 9:17 * 描述: 网络请求回调接口 */ public interface ServerApi { /** * data为对象的写法 * "success":true, * "data":{ * "username":"123", * "password":"123" * }, * "code":200 * } * * @param postMap 数据 * @return Single */ @FormUrlEncoded @POST("api/demo/demo") Single<ResultEntity<DemoEntity>> demo1(@FieldMap Map<String, Object> postMap); /** * data为数组的写法 * * @param postMap 数据 * @return Single */ @FormUrlEncoded @POST("api/demo/demo") Single<ResultEntity<List<DemoEntity>>> demo2(@FieldMap Map<String, Object> postMap); /** * 文件上传 * * @param postMap 数据 * @return Single */ @Multipart @POST("api/demo/demo") Single<ResultEntity<List<DemoEntity>>> demo3(@PartMap Map<String, RequestBody> postMap, @Part List<MultipartBody.Part> files); } ``` NetworkUnavailableCallback.java ```//package com.example.myapplication.widget.callback; // //import com.example.myapplication.R; //import com.kingja.loadsir.callback.Callback; // ///** // * function: 网络中断 Callback // * date: 2019/5/16 // */ //public class NetworkUnavailableCallback extends Callback { // // @Override // protected int onCreateView() { // return R.layout.callback_network_unavailable; // } // //} ``` BitmapUtils.java ```package com.example.myapplication.util; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Message; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import static android.os.FileUtils.copy; public class BitmapUtils { private static Bitmap bitmap; /** * 根据 图片URL 转换成 Bitmap * * @param url * @return */ public static Bitmap getBitMap(final String url, final android.os.Handler handler) { new Thread(new Runnable() { @Override public void run() { URL imageurl = null; try { imageurl = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); Message message = handler.obtainMessage(); message.obj = bitmap; message.arg1 = 1; handler.sendMessage(message); is.close(); } catch (IOException e) { e.printStackTrace(); } } }).start(); return bitmap; } } ``` ResultEntity.java ```package com.demo.mvvm.entity; import com.example.myapplication.base.entity.BaseEntity; import com.example.myapplication.base.util.CastUtil; import com.google.gson.annotations.SerializedName; public class ResultEntity<T> extends BaseEntity { /** *{ * "success":true, * "data":{ * "username":"123", * "password":"123" * }, * "code":200 * } */ /** * { * "success":true, * "data":[ * { * "username":"123", * "password":"123" * }, * { * "username":"123", * "password":"123" * } * ], * "code":200 * } */ @SerializedName("code") public int code; @SerializedName("msg") public String msg; @SerializedName("data") public T data; public T getData() { return CastUtil.cast(data); } } ```
zhumakhan/MinerGameGUIJava
zhumakhan/MinerGameGUIJava README.md ```# MinerSweeperGameInJava This Miner Game written in Java, you can find a classic version of game by following [link](http://minesweeperonline.com/#) or just type http://minesweeperonline.com/# ``` graphic.java ```import javax.swing.*; import java.util.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; public class graphic extends JFrame{ int spacing=1; public int mx=-100; public int my=-100; boolean firstClick = true; Position pos = new Position(); boolean victory=false; boolean defeat=false; boolean reset = false; int counter = 0; public graphic() { this.setTitle("Minesweeper1.0LevelB"); this.setSize(800,800); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// close when press X this.setVisible(true);//whenever window created it is visible this.setResizable(true);// Resize Grid grid=new Grid(); this.setContentPane(grid); Move move=new Move(); this.addMouseMotionListener(move); Click click=new Click(); this.addMouseListener(click); } public class Position{ int bomb = 10; int[][] mines = new int[9][9]; int[][] numbers = new int[9][9]; boolean[][] revealed = new boolean[9][9]; boolean[][] flagged= new boolean[9][9]; boolean[][] rightclicked= new boolean [9][9]; boolean[][] guessed= new boolean [9][9]; Random rand=new Random(); public void fillMines() { while (bomb>0) { int bx,by=0; bx=rand.nextInt(9); by=rand.nextInt(9); if(bx!=inBoxX() && by!=inBoxY() && mines[bx][by] == 0) { mines[bx][by]=1; bomb--; } } } public void generateNumbers() { for(int i=0;i<9;i++){ for(int j=0; j<9;j++){ if(mines[i][j]==1)fillNumber(i,j); } } } public void fillNumber(int x, int y) { if(x-1>-1 && y-1>-1 && x-1<9 && y-1<9 && mines[x-1][y-1]!=1) { numbers[x-1][y-1]++; } if(y-1>-1 && y-1<9 && mines[x][y-1]!=1) { numbers[x][y-1]++; } if(x+1>-1 && y-1>-1 && x+1<9 && y-1<9 && mines[x+1][y-1]!=1) { numbers[x+1][y-1]++; } if(x+1>-1 && x+1<9 && mines[x+1][y]!=1) { numbers[x+1][y]++; } if(x-1>-1 && x-1<9 && mines[x-1][y]!=1) { numbers[x-1][y]++; } if(x-1>-1 && y+1>-1 && x-1<9 && y+1<9 && mines[x-1][y+1]!=1) { numbers[x-1][y+1]++; } if(y+1>-1 && y+1<9 && mines[x][y+1]!=1) { numbers[x][y+1]++; } if(x+1>-1 && y+1>-1 && x+1<9 && y+1<9 && mines[x+1][y+1]!=1) { numbers[x+1][y+1]++; } } public void splash(int i, int j) { if(pos.revealed[i][j] == false) {pos.revealed[i][j] = true; counter++;} //right if(i+1 < 9 && revealed[i+1][j] == false) { if(numbers[i+1][j] != 0) {revealed[i+1][j] = true; counter++;} else if(mines[i+1][j] == 0)splash(i+1,j); } //left if(i-1 > -1 && revealed[i-1][j] == false) { if(numbers[i-1][j] != 0) {revealed[i-1][j] = true; counter++;} else if(mines[i-1][j] == 0)splash(i-1,j); } //up if(j+1 < 9 && revealed[i][j+1] == false) { if(numbers[i][j+1] != 0) {revealed[i][j+1] = true; counter++;} else if(mines[i][j+1] == 0)splash(i,j+1); } //down if(j-1 > -1 && revealed[i][j-1] == false) { if(numbers[i][j-1] != 0) {revealed[i][j-1] = true; counter++;} else if(mines[i][j-1] == 0)splash(i,j-1); } } } public class Grid extends JPanel{ public void paintComponent(Graphics g){ g.setColor(Color.LIGHT_GRAY); g.fillRect(0, 0, 800, 800); g.setColor(Color.GRAY); for(int i=0;i<9;i++){ for(int j=0;j<9;j++) { g.setColor(Color.gray); if (pos.revealed[i][j] && pos.mines[i][j]==1) { //if you step on mine defeat=true; g.setColor(Color.RED); } if(pos.flagged[i][j]==true && pos.rightclicked[i][j]==true) { g.setColor(Color.WHITE); } if(mx>=spacing+i*80+10 && mx< spacing+i*80+10+80-2*spacing && my>= spacing+j*80+26 && my<spacing+j*80+26+80-2*spacing){ //in rectangle, mouse moved; g.setColor(Color.ORANGE); } g.fillRect(spacing+i*80+10, spacing+j*80+10, 80-2*spacing, 80-2*spacing); //if number is in rectangle; if(pos.revealed[i][j]) { if(pos.numbers[i][j] != 0) { //the numbers pos.flagged[i][j]=false; g.setColor(Color.WHITE); g.setFont(new Font("Tahoma",Font.BOLD, 40)); g.drawString(Integer.toString(pos.numbers[i][j]), spacing+i*80+3+40-spacing, spacing+j*80+17+40-spacing); }else if(pos.mines[i][j] == 0){ //splash function pos.flagged[i][j]=false; pos.splash(i,j); g.setColor(Color.GREEN); g.fillRect(spacing+i*80+10, spacing+j*80+10, 80-2*spacing, 80-2*spacing); }else if(pos.mines[i][j]==1 && pos.flagged[i][j]==true) { pos.guessed[i][j]=true;} else { //shape of mine g.setColor(Color.BLACK); g.fillRect(i*80+35, j*80+25, 30, 50); g.fillRect(i*80+25, j*80+35, 50, 30); g.fillRect(i*80+30, j*80+30, 40, 40); g.fillRect(i*80+20, j*80+45, 60, 10); g.fillRect(i*80+45, j*80+20, 10, 60); } } if(defeat) { if(pos.revealed[i][j] == false) {pos.revealed[i][j] = true; counter++;}} if (pos.flagged[i][j]==true && pos.rightclicked[i][j]==true) { g.setColor(Color.BLACK); g.fillRect(i*80+35, j*80+25, 5, 50); g.fillRect(i*80+40, j*80+27, 4, 30); g.fillRect(i*80+44, j*80+29, 4, 26); g.fillRect(i*80+48, j*80+31, 4, 22); g.fillRect(i*80+52, j*80+33, 4, 18); g.fillRect(i*80+56, j*80+37, 4, 14); g.fillRect(i*80+60, j*80+39, 4, 10); g.fillRect(i*80+64, j*80+40, 4, 5); } } } if(defeat)reset = true; } } public class Move implements MouseMotionListener{ @Override public void mouseDragged(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseMoved(MouseEvent e) { //System.out.println("The mouse was moved"); mx=e.getX(); my=e.getY(); } } public class Click implements MouseListener{ @Override public void mouseClicked(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1) { if(firstClick) { firstClick = false; mx = e.getX(); my = e.getY(); pos.fillMines(); pos.generateNumbers(); }else { mx = e.getX(); my = e.getY(); } int x = inBoxX();// returns the coordinates of the box to reveal int y = inBoxY(); if(x != -1 && y != -1) { if(pos.revealed[x][y] == false) {pos.revealed[x][y] = true;counter++;} if(counter == 71 && pos.mines[x][y] != 1) { victory = true; } } } if(e.getButton()== MouseEvent.BUTTON3) { int x = inBoxX();// returns the coordinates of the box to reveal int y = inBoxY(); if(x != -1 && y != -1) { if(pos.revealed[x][y] == false && pos.flagged[x][y]==false) { pos.rightclicked[x][y]=true; pos.flagged[x][y] = true; } else if (pos.revealed[x][y] == false && pos.rightclicked[x][y]==true) { pos.flagged[x][y]= false; } } } } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } } public void resetGame(){ victory=false; //defeat=false; System.out.println("YES"); } public int inBoxX(){ for(int i=0;i<9;i++){ for(int j=0;j<9;j++) { if(mx>=spacing+i*80+10 && mx< spacing+i*80+10+80-2*spacing && my>= spacing+j*80+26 && my<spacing+j*80+26+80-2*spacing){ return i; } } } return -1; } public int inBoxY() { for(int i=0;i<9;i++){ for(int j=0;j<9;j++) { if(mx>=spacing+i*80+10 && mx< spacing+i*80+10+80-2*spacing && my>= spacing+j*80+26 && my<spacing+j*80+26+80-2*spacing){ return j; } } } return -1; } } ``` Main.java ```import javax.swing.JOptionPane; public class Main implements Runnable{ static graphic gui; public static void main(String[] args) throws InterruptedException{ int YesorNo = JOptionPane.YES_OPTION; while(YesorNo == JOptionPane.YES_OPTION) { gui =new graphic(); new Thread(new Main()).start(); while(!gui.reset && !gui.victory) { //throws InterruptedException, so no problem Thread.sleep(1000); } if(gui.reset) { YesorNo= JOptionPane.showConfirmDialog(null,"Do you want ot start again", "You Lose! HAHA!", JOptionPane.YES_NO_OPTION); if(YesorNo==JOptionPane.YES_OPTION) { gui.dispose(); continue; }else if(YesorNo==JOptionPane.NO_OPTION){ System.exit(0); } } else { YesorNo= JOptionPane.showConfirmDialog(null,"Do you want ot start again", "You win!", JOptionPane.YES_NO_OPTION); if(YesorNo==JOptionPane.YES_OPTION) { gui.dispose(); continue; }else if(YesorNo==JOptionPane.NO_OPTION){ System.exit(0); } } } } @Override public void run() { while(true) { try { //prevents heating 100 is optimal Thread.sleep(100); }catch (InterruptedException e){ System.out.println("I was interrupted!"); e.printStackTrace(); } gui.repaint(); } } } ```
zhumingcheng697/ARTest
zhumingcheng697/ARTest ViewController.swift ```// // ViewController.swift // ARTest // // Created by McCoy Zhu on 1/10/20. // Copyright © 2020 McCoy Zhu. All rights reserved. // import UIKit import SceneKit import ARKit class ViewController: UIViewController, ARSCNViewDelegate { @IBOutlet var sceneView: ARSCNView! public let undergroundVid = AVPlayer(url: Bundle.main.url(forResource: "Underground", withExtension: "mov", subdirectory: "art.scnassets")!) public let plasticVid = AVPlayer(url: Bundle.main.url(forResource: "Plastic", withExtension: "mov", subdirectory: "art.scnassets")!) public let laserVid = AVPlayer(url: Bundle.main.url(forResource: "Laser", withExtension: "mov", subdirectory: "art.scnassets")!) func loopVideo(videoPlayer: AVPlayer) { NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: videoPlayer.currentItem, queue: nil) { notification in videoPlayer.seek(to: CMTime.zero) videoPlayer.play() } } override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self // Show statistics such as fps and timing information sceneView.showsStatistics = false // Create a new scene let scene = SCNScene() // Set the scene to the view sceneView.scene = scene for vid in [self.undergroundVid, self.plasticVid, self.laserVid] { loopVideo(videoPlayer: vid) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Create a session configuration let configuration = ARImageTrackingConfiguration() let trackingImages = ARReferenceImage.referenceImages(inGroupNamed: "Photos", bundle: Bundle.main)! configuration.trackingImages = trackingImages configuration.maximumNumberOfTrackedImages = 3 // Run the view's session sceneView.session.run(configuration) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) for vid in [self.undergroundVid, self.plasticVid, self.laserVid] { if vid.rate != 0 { vid.pause() vid.seek(to: .zero) } } // Pause the view's session sceneView.session.pause() } // MARK: - ARSCNViewDelegate // Override to create and configure nodes for anchors added to the view's session. func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { let node = SCNNode() if let imageAnchor = anchor as? ARImageAnchor { var vid: AVPlayer switch imageAnchor.referenceImage.name { case "Underground": vid = self.undergroundVid case "Plastic": vid = self.plasticVid case "Laser": vid = self.laserVid default: return SCNNode() } let vidPlane = SCNPlane(width: max(imageAnchor.referenceImage.physicalSize.width, imageAnchor.referenceImage.physicalSize.height) * 1.01, height: min(imageAnchor.referenceImage.physicalSize.width, imageAnchor.referenceImage.physicalSize.height) * 1.01) vidPlane.firstMaterial?.diffuse.contents = vid vid.volume = 0 let vidNode = SCNNode(geometry: vidPlane) vidNode.eulerAngles.x = -.pi / 2 vidNode.eulerAngles.y = (imageAnchor.referenceImage.physicalSize.width > imageAnchor.referenceImage.physicalSize.height ? 0 : -.pi/2) vidNode.opacity = 0 DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { vid.play() vidNode.opacity = 0.01 } let imgPlane1 = SCNPlane(width: imageAnchor.referenceImage.physicalSize.width * 1.01, height: imageAnchor.referenceImage.physicalSize.height * 1.01) imgPlane1.firstMaterial?.diffuse.contents = UIImage(named: "\(imageAnchor.referenceImage.name!)_") let imgPlane2 = SCNPlane(width: imageAnchor.referenceImage.physicalSize.width * 1.01, height: imageAnchor.referenceImage.physicalSize.height * 1.01) imgPlane2.firstMaterial?.diffuse.contents = UIImage(named: "\(imageAnchor.referenceImage.name!)") let imgNode1 = SCNNode(geometry: imgPlane1) let imgNode2 = SCNNode(geometry: imgPlane2) node.addChildNode(vidNode) node.addChildNode(imgNode1) node.addChildNode(imgNode2) node.opacity = 0 } return node } func renderer(_ renderer: SCNSceneRenderer, willUpdate node: SCNNode, for anchor: ARAnchor) { if let vid = node.childNodes[0].geometry?.firstMaterial?.diffuse.contents as? AVPlayer { if (anchor as? ARImageAnchor == nil) || !(anchor as? ARImageAnchor)!.isTracked { vid.pause() vid.seek(to: .zero) } else { if let cam = sceneView.session.currentFrame?.camera { let d = simd_distance(node.simdTransform.columns.3, cam.transform.columns.3) let h = Float((anchor as! ARImageAnchor).referenceImage.physicalSize.height) * 1.01 node.childNodes[1].position.y = (h + 0.01) / 2 * sin(atan(h / d)) node.childNodes[2].position.y = (h + 0.01) / 2 * sin(atan(h / d)) node.childNodes[1].position.z = (h + 0.01) / 2 * (-cos(atan(h / d)) - 1) node.childNodes[2].position.z = (h + 0.01) / 2 * (cos(atan(h / d)) + 1) node.childNodes[1].eulerAngles.x = -.pi / 2 + atan(h / d) node.childNodes[2].eulerAngles.x = -.pi / 2 - atan(h / d) } if vid.rate == 0 { if vid.currentTime() == CMTime.zero { node.childNodes[0].opacity = 0 node.opacity = 0 vid.volume = 0 DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { vid.play() node.childNodes[0].opacity = 0.01 } } else { vid.play() } } else if node.childNodes[0].opacity > 0 && node.childNodes[0].opacity < 1 { node.childNodes[0].opacity += 0.035 node.opacity = node.childNodes[0].opacity vid.volume = Float(node.childNodes[0].opacity) } } } } func session(_ session: ARSession, didFailWithError error: Error) { // Present an error message to the user } func sessionWasInterrupted(_ session: ARSession) { // Inform the user that the session has been interrupted, for example, by presenting an overlay for vid in [self.undergroundVid, self.plasticVid, self.laserVid] { if vid.rate != 0 { vid.pause() } } } func sessionInterruptionEnded(_ session: ARSession) { // Reset tracking and/or remove existing anchors if consistent tracking is required } } ```
zhuo1angT/cryptopals
zhuo1angT/cryptopals lib.rs ```pub use conversion::hex_str_to_u8_vec; pub use conversion::single_hex_to_u8; pub use conversion::u8_vec_to_hex_str; pub use crate::base64::encode; pub use crate::base64::encode_one_byte; pub use crate::base64::encode_two_bytes; pub use fixed_xor::fixed_xor; pub use break_single_xor::all_single_byte_xors; pub use break_single_xor::best_english_text; pub use break_single_xor::xor_cipher; pub use repeating_key_xor::repeating_key_xor; pub use bitwise_hamming_dis::bitwise_hamming_dis; pub use pkcs7::pkcs7; pub mod base64; pub mod bitwise_hamming_dis; pub mod break_single_xor; pub mod conversion; pub mod fixed_xor; pub mod pkcs7; pub mod repeating_key_xor; ``` bitwise_hamming_dis.rs ```pub fn bitwise_hamming_dis(s1: &[u8], s2: &[u8]) -> usize { assert!(s1.len() == s2.len()); let mut res = 0; let len = s1.len(); for i in 0..len { for j in 0..8 { res += (((s1[i] >> j) & 1) ^ ((s2[i] >> j) & 1)) as usize; } } res } ``` README.md ```## [The cryptopals crypto challenges](https://cryptopals.com/). in pure ***Rust***~ My intension of doing these challenges is to practice Rust and to get myself started with cryptography.``` repeating_key_xor_test.rs ```use cryptopals::repeating_key_xor; use cryptopals::u8_vec_to_hex_str; #[test] fn repeating_key_xor_test() { assert_eq!( u8_vec_to_hex_str(&repeating_key_xor( "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal".as_bytes(), "ICE".as_bytes() )), "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f" ); } ``` base64.rs ```// Convert hex to base64 static ENCODE_TABLE: [char; 64] = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', ]; pub fn encode(hex: &[u8]) -> String { let mut res = String::new(); let mut cur: usize = 0; while cur + 3 <= hex.len() { let all: u32 = ((hex[cur] as u32) << 16) | ((hex[cur + 1] as u32) << 8) | (hex[cur + 2] as u32); let a = ((all >> 18) & 0b111111) as usize; let b = ((all >> 12) & 0b111111) as usize; let c = ((all >> 6) & 0b111111) as usize; let d = ((all >> 0) & 0b111111) as usize; res.push(ENCODE_TABLE[a]); res.push(ENCODE_TABLE[b]); res.push(ENCODE_TABLE[c]); res.push(ENCODE_TABLE[d]); cur += 3; } match hex.len() % 3 { 0 => (), 1 => res.push_str(&encode_one_byte(hex[hex.len() - 1])), 2 => res.push_str(&encode_two_bytes(hex[hex.len() - 2], hex[hex.len() - 1])), _ => (), } res } pub fn encode_one_byte(first: u8) -> String { let all = first; let a = all >> 2; let b = (all & 0b11) << 4; format!("{}{}", ENCODE_TABLE[a as usize], ENCODE_TABLE[b as usize]) } pub fn encode_two_bytes(first: u8, second: u8) -> String { let all = ((first as u32) << 8) | (second as u32); let a = all >> 10; let b = (all >> 4) & (0b111111); let c = (all & 0b1111) << 2; format!( "{}{}{}", ENCODE_TABLE[a as usize], ENCODE_TABLE[b as usize], ENCODE_TABLE[c as usize], ) } ``` fixed_xor_test.rs ```use cryptopals::fixed_xor::fixed_xor; use cryptopals::hex_str_to_u8_vec; use cryptopals::u8_vec_to_hex_str; #[test] fn fixed_xor_test() { assert_eq!( u8_vec_to_hex_str(&fixed_xor( &hex_str_to_u8_vec("1c0111001f010100061a024b53535009181c"), &hex_str_to_u8_vec("686974207468652062756c6c277320657965"), )), "746865206b696420646f6e277420706c6179", ); } ``` aes_in_ecb_mode.rs ```use openssl::symm::{decrypt, Cipher}; use std::env; use std::fs; extern crate base64; fn main() { let args: Vec<String> = env::args().collect(); assert_eq!(args.len(), 3); let text: String = fs::read_to_string(&args[1]).unwrap().lines().collect(); let text = base64::decode(text).unwrap(); let key = &args[2]; let cipher = Cipher::aes_128_ecb(); let ciphertext = decrypt(cipher, key.as_bytes(), None, &text).unwrap(); println!("{}", std::str::from_utf8(&ciphertext).unwrap()); } ``` conversion_test.rs ```use cryptopals::u8_vec_to_hex_str; #[test] fn conversion_test() { assert_eq!(u8_vec_to_hex_str(&[0, 1, 16, 17]), "00011011"); assert_eq!(u8_vec_to_hex_str(&[162, 130, 178]), "a282b2"); } ``` solve_single_xor.rs ```use cryptopals::all_single_byte_xors; use cryptopals::best_english_text; use cryptopals::hex_str_to_u8_vec; use std::env; fn main() { assert!(env::args().len() == 2); let args: Vec<String> = env::args().collect(); let all_results = all_single_byte_xors(&(hex_str_to_u8_vec(&args[1]).to_vec())); println!("{}", best_english_text(&all_results)); } ``` repeating_key_xor.rs ```pub fn repeating_key_xor(text: &[u8], cipher: &[u8]) -> Vec<u8> { assert!(cipher.len() != 0); let mut res = Vec::with_capacity(text.len()); let mut counter = 0; for &byte in text { res.push(byte ^ cipher[counter]); counter += 1; if counter >= cipher.len() { counter = 0; } } res } ``` base64_test.rs ```use cryptopals::encode; use cryptopals::hex_str_to_u8_vec; #[test] fn base64_test() { assert_eq!(encode(&vec![48, 48, 48]), String::from("MDAw")); assert_eq!( encode(&hex_str_to_u8_vec("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d")), String::from("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t") ); } ``` pkcs7_test.rs ```use cryptopals::pkcs7; #[test] fn pkcs7_test() { let mut result: Vec<u8> = "YELLOW SUBMARINE".as_bytes().to_vec(); for _ in 0..4 { result.push(4); } assert_eq!(pkcs7("YELLOW SUBMARINE".as_bytes(), 20), result); } ``` pkcs7.rs ```pub fn pkcs7(text: &[u8], block_size: usize) -> Vec<u8> { let len = text.len(); let padding_size = match len % block_size { 0 => block_size, remainder => block_size - remainder, }; let mut res = text.to_vec(); let mut padding = vec![padding_size as u8; padding_size]; res.append(&mut padding); res } ``` conversion.rs ```pub fn single_hex_to_u8(hex: u8) -> u8 { match hex { b'0'..=b'9' => hex - b'0', b'a'..=b'f' => hex - b'a' + 10, b'A'..=b'F' => hex - b'A' + 10, _ => 0, } } pub fn hex_str_to_u8_vec(hex_str: &str) -> Vec<u8> { let hex_str = hex_str.as_bytes(); let mut res = Vec::with_capacity(hex_str.len() / 2); let mut i: usize = 0; while i < hex_str.len() { let mut v: u8 = 0; v += single_hex_to_u8(hex_str[i]) << 4; v += single_hex_to_u8(hex_str[i + 1]); res.push(v); i += 2; } res } pub fn u8_vec_to_hex_str(uvec: &[u8]) -> String { let mut res = String::with_capacity(uvec.len() * 2); for val in uvec { let first_hex = val >> 4; let second_hex = val & 0b1111; let first_hex = match first_hex { 0..=9 => ('0' as u8 + first_hex) as char, 10..=15 => ('a' as u8 + first_hex - 10) as char, _ => 0 as char, }; let second_hex = match second_hex { 0..=9 => ('0' as u8 + second_hex) as char, 10..=15 => ('a' as u8 + second_hex - 10) as char, _ => 0 as char, }; res.push(first_hex); res.push(second_hex); } res } ``` detact_aes_in_ecb_mode.rs ```use std::collections::HashSet; use std::env; use std::fs; fn main() { let args: Vec<String> = env::args().collect(); assert_eq!(args.len(), 2); let file_contents = fs::read_to_string(&args[1]).unwrap(); let lines: Vec<&str> = file_contents.lines().collect(); let mut sets: Vec<HashSet<String>> = vec![HashSet::new(); lines.len()]; for (index, line) in lines.iter().enumerate() { let mut j = 0; while (j + 1) * 16 <= lines.len() { sets[index].insert((&line[j * 16..(j + 1) * 16]).to_string()); j += 1; } } let mut min_size = usize::MAX; let mut line_number = 0; for (index, set) in sets.iter().enumerate() { if set.len() < min_size { min_size = set.len(); line_number = index; } } if min_size != usize::MAX { println!( "line number: {}, number of unique blocks: {}", line_number, min_size ); println!("{}", lines[line_number]); } } ``` break_single_xor.rs ```use ascii_utils::Check; use std::collections::HashMap; /* The hex encoded string: 1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736 has been XOR'd against a single character. Find the key, decrypt the message. You can do this by hand. But don't: write code to do it for you. How? Devise some method for "scoring" a piece of English plaintext. Character frequency is a good metric. Evaluate each output and choose the one with the best score. */ pub fn all_single_byte_xors(ciphertext: &[u8]) -> Vec<String> { let mut res = Vec::new(); for c in 0..=std::u8::MAX { let ciphered = xor_cipher(ciphertext, c); if ciphered .iter() .all(|&byte| byte.is_printable() || byte.is_space()) { res.push(std::str::from_utf8(&ciphered).unwrap().to_string()); } } res } pub fn best_english_text(texts: &[String]) -> String { // http://www.data-compression.com/english.html let character_freq: HashMap<char, f64> = [ ('a', 0.0651738), ('b', 0.0124248), ('c', 0.0217339), ('d', 0.0349835), ('e', 0.1041442), ('f', 0.0197881), ('g', 0.0158610), ('h', 0.0492888), ('i', 0.0558094), ('j', 0.0009033), ('k', 0.0050529), ('l', 0.0331490), ('m', 0.0202124), ('n', 0.0564513), ('o', 0.0596302), ('p', 0.0137645), ('q', 0.0008606), ('r', 0.0497563), ('s', 0.0515760), ('t', 0.0729357), ('u', 0.0225134), ('v', 0.0082903), ('w', 0.0171272), ('x', 0.0013692), ('y', 0.0145984), ('z', 0.0007836), (' ', 0.1918182), ] .iter() .cloned() .collect(); let mut max_score: f64 = 0.0; let mut res = ""; for s in texts { let mut cur_str_score = 0.0; for ch in s.chars() { if let Some(score) = character_freq.get(&ch.to_ascii_lowercase()) { cur_str_score += score; } } if cur_str_score > max_score { max_score = cur_str_score; res = s; } } return res.to_string(); } pub fn xor_cipher(text: &[u8], cipher: u8) -> Vec<u8> { text.iter().map(|x| x ^ cipher).collect() } ``` break_repeating_key_xor_test.rs ```use cryptopals::bitwise_hamming_dis; #[test] fn break_test() { assert_eq!( bitwise_hamming_dis("this is a test".as_bytes(), "wokka wokka!!!".as_bytes()), 37 ); } ``` break_repeating_key_xor.rs ```use cryptopals::all_single_byte_xors; use cryptopals::best_english_text; use cryptopals::bitwise_hamming_dis; use std::env; use std::fs; fn main() { let args: Vec<String> = env::args().collect(); assert_eq!(args.len(), 2); let text: String = fs::read_to_string(&args[1]).unwrap().lines().collect(); let text = base64::decode(text).unwrap(); let mut keysize_and_dis: Vec<(usize, f64)> = Vec::with_capacity(40); for keysize in 2..=40 { keysize_and_dis.push(( keysize, (bitwise_hamming_dis(&text[..keysize], &text[keysize..keysize * 2]) + bitwise_hamming_dis( &text[keysize * 2..keysize * 3], &text[keysize * 3..keysize * 4], )) as f64 / keysize as f64, )); } keysize_and_dis.sort_by(|a, b| a.1.partial_cmp(&b.1).expect("Compared with f64 NaN")); for (keysize, _dis) in keysize_and_dis { let mut blocks: Vec<Vec<u8>> = vec![Vec::new(); keysize]; for (i, &byte) in text.iter().enumerate() { blocks[i % keysize].push(byte); } let snippits: Vec<String> = blocks .iter() .map(|block| best_english_text(&all_single_byte_xors(block))) .collect(); let mut current_res = String::new(); for i in 0..snippits[0].len() { for j in 0..snippits.len() { if i < snippits[j].len() { current_res.push(snippits[j].as_bytes()[i] as char); } else { break; } } } if current_res.len() != 0 { println!("{}", current_res); return; } } } ``` fixed_xor.rs ```// Takes two equal-length buffers and produces their XOR combination. pub fn fixed_xor(buf1: &[u8], buf2: &[u8]) -> Vec<u8> { assert!(buf1.len() == buf2.len()); let len = buf1.len(); let mut res = Vec::with_capacity(len); for i in 0..len { res.push(buf1[i] ^ buf2[i]); } res } ```
zhuqiaowei/spring-boot-shiro
zhuqiaowei/spring-boot-shiro UserInfoService.java ```package com.zqw.service; import com.zqw.entity.UserInfo; public interface UserInfoService { public UserInfo findByUsername(String username); } ``` MyConfigAdapter.java ```package com.zqw.inteceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class MyConfigAdapter extends WebMvcConfigurerAdapter{ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInceptor()).addPathPatterns("/MP/**"); //对来自/user/** 这个链接来的请求进行拦截 } } ``` HomeController.java ```package com.zqw.controller; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.zqw.common.CommonMethod; import com.zqw.common.JsonResult; import com.zqw.common.ReJson; import com.zqw.connecttion.MpConnecttion; import com.zqw.entity.JsonEntity; import com.zqw.entity.UserInfo; import com.zqw.service.UserInfoService; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; import java.util.Random; @Controller public class HomeController { @Resource UserInfoService userInfoService; @RequestMapping({"/","/index"}) @ResponseBody public JsonResult index(HttpServletRequest request){ String sid=""; Random rand=new Random();//生成随机数 for(int a=0;a<12;a++){ sid+=rand.nextInt(10);//生成6位验证码 } Map<String, String> maps=new HashMap<String,String>(); System.out.println("生成Sid:"+sid); request.getSession().setAttribute("sid", sid); System.out.println("保存用户信息到session>>>>>>>>"); UserInfo userInfo = userInfoService.findByUsername("admin"); request.getSession().setAttribute("userInfo", userInfo); //获取卡号并加密MD5 Map<String, String> map=new HashMap<String,String>(); map.put("username", "admin"); String str=MpConnecttion.PostWithParas("BP", "MH0011", map); JsonEntity result=ReJson.reJson(str); System.out.println(result.getData()); String cardNo = null; if(result.getState().equals("1")) { cardNo=ReJson.toJson(result.getData()); System.out.println("对卡号"+cardNo+"进行MD5加密为:574162810e47e71d11dbcceb145da6f1"); cardNo=CommonMethod.tCardNo(cardNo); System.out.println("脱敏为:"+cardNo); } maps.put("sid", sid); maps.put("cardNo", cardNo); maps.put("cardNo_sequence", "574162810e47e71d11dbcceb145da6f1"); maps.put("returnCode", "MP10001"); maps.put("returnMsg", "登录成功"); return new JsonResult(maps); } @RequestMapping("/login") public JsonResult login(HttpServletRequest request, Map<String, Object> map) throws Exception{ System.out.println("用户执行登录>>>>>>>>>>>>>>>"); // 登录失败从request中获取shiro处理的异常信息。 // shiroLoginFailure:就是shiro异常类的全类名. String exception = (String) request.getAttribute("shiroLoginFailure"); System.out.println("exception=" + exception); String msg = ""; if (exception != null) { if (UnknownAccountException.class.getName().equals(exception)) { System.out.println("UnknownAccountException -- > 账号不存在:"); msg = "UnknownAccountException -- > 账号不存在:"; } else if (IncorrectCredentialsException.class.getName().equals(exception)) { System.out.println("IncorrectCredentialsException -- > 密码不正确:"); msg = "IncorrectCredentialsException -- > 密码不正确:"; } else if ("kaptchaValidateFailed".equals(exception)) { System.out.println("kaptchaValidateFailed -- > 验证码错误"); msg = "kaptchaValidateFailed -- > 验证码错误"; } else { msg = "else >> "+exception; System.out.println("else -- >" + exception); } } map.put("msg", msg); // 此方法不处理登录成功,由shiro进行处理 return new JsonResult(); } @RequestMapping("/403") public String unauthorizedRole(){ System.out.println("------没有权限-------"); return "403"; } }``` Test.java ```package com.zqw; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; public class Test { public static void main(String[] args) { System.out.println("日志查询结果:"); System.out.println("日志保存时间:2018.04.25 14:02-2018.04.25 17:00"); System.out.println("MP1001:访问37次,失败次数20,失败率为:55%"); System.out.println("MP1002:访问3次,失败次数0,失败率为:0%"); // try { // sendPhone(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } public static void sendPhone() throws HttpException, IOException { HttpClient client = new HttpClient(); PostMethod post = new PostMethod("http://gbk.api.smschinese.cn"); post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在头文件中设置转码 NameValuePair[] data ={ new NameValuePair("Uid", "zhuqiaowei"),new NameValuePair("Key", "zhuqiaoweidemiyao"), new NameValuePair("smsMob","13711335177"),new NameValuePair("smsText","接口MP1001请求失败率为55%,请及时查看!!")}; post.setRequestBody(data); client.executeMethod(post); Header[] headers = post.getResponseHeaders(); int statusCode = post.getStatusCode(); System.out.println("statusCode:"+statusCode); for(Header h : headers) { System.out.println(h.toString()); } String result = new String(post.getResponseBodyAsString().getBytes("gbk")); System.out.println(result); //打印返回消息状态 post.releaseConnection(); } public static void showMsg() { System.out.println("start request: MP10001:"); System.out.println("该次请求的流水号:flashId=20180424135535321+ea4d"); System.out.println("请求参数为:accountNo=5ds6af5s6das5d9s8f7ds4ad,custumId=123456789"); System.out.println("开始执行前置拦截器getSessionMessage--------->"); System.out.println("accountNo转换成功,622222222222222"); System.out.println("getSessionMessage执行结束------------->"); System.out.println("开始请求:https://localhost:8080/pb/getFirmMobile"); System.out.println("请求参数:accountNo=622222222222222&custumId=123456789"); System.out.println("后台返回参数:tranCode=0,tranMsg=,firmMobile=13711335177"); System.out.println("开始执行后置拦截器setSessionMessage--------->"); System.out.println("firmMobile脱敏成功,137****5177"); System.out.println("setSessionMessage执行结束------------->"); System.out.println("返回结果为:tranCode=MP100001,tranMsg=,firmMobile=137****5177"); } public static void resultMsg() { System.out.println("日志查询结果:"); System.out.println("日志保存时间:2018.04.25 14:02-2018.04.25 17:00"); System.out.println("MP1001:访问37次,失败次数20,失败率为:55%"); System.out.println("MP1002:访问3次,失败次数0,失败率为:0%"); } } ``` UserInfoController.java ```package com.zqw.controller; import java.util.HashMap; import java.util.Map; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.zqw.common.CommonMethod; import com.zqw.common.JsonResult; import com.zqw.common.ReJson; import com.zqw.connecttion.MpConnecttion; import com.zqw.entity.JsonEntity; @Controller @RequestMapping("/MP") public class UserInfoController { /** * 用户查询. * @return */ @RequestMapping("/MP10001") @RequiresPermissions("userInfo:view")//权限管理; public String userInfo(){ return "userInfo"; } /** * 用户添加; * @return */ @RequestMapping("/MP10002") @RequiresPermissions("userInfo:add")//权限管理; public String userInfoAdd(){ return "userInfoAdd"; } /** * 用户删除; * @return */ @RequestMapping("/MP10003") @RequiresPermissions("userInfo:del")//权限管理; public String userDel(){ return "userInfoDel"; } @RequestMapping("/MP10004") @ResponseBody public JsonResult test1() { return new JsonResult("测试成功"); } @RequestMapping("/MP10005") @ResponseBody public JsonResult test2() { Map<String, String> map=new HashMap<String,String>(); map.put("username", "admin"); String str=MpConnecttion.PostWithParas("BP", "MH0011", map); JsonEntity result=ReJson.reJson(str); System.out.println(result.getData()); if(result.getState().equals("1")) { String cardNo=ReJson.toJson(result.getData()); cardNo=CommonMethod.tCardNo(cardNo); Map<String, String> map2=new HashMap<String,String>(); map2.put("cardNo", cardNo); return new JsonResult(map2); }else { return new JsonResult("MP10002",result.getMessage()); } } }``` MyShiroRealm.java ```package com.zqw.config; import javax.annotation.Resource; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import com.zqw.entity.SysPermission; import com.zqw.entity.SysRole; import com.zqw.entity.UserInfo; import com.zqw.service.UserInfoService; public class MyShiroRealm extends AuthorizingRealm { @Resource UserInfoService userInfoService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { System.out.println("权限检测-->MyShiroRealm.doGetAuthorizationInfo()"); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); UserInfo userInfo = (UserInfo)principals.getPrimaryPrincipal(); for(SysRole role:userInfo.getRoleList()){ authorizationInfo.addRole(role.getRole()); for(SysPermission p:role.getPermissions()){ authorizationInfo.addStringPermission(p.getPermission()); } } return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("MyShiroRealm.doGetAuthenticationInfo()"); //获取用户的输入的账号. String username = (String)token.getPrincipal(); System.out.println("登录用户为:"+username); //通过username从数据库中查找 User对象,如果找到,没找到. //实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法 UserInfo userInfo = userInfoService.findByUsername(username); if(userInfo == null){ return null; } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( userInfo, //用户名 userInfo.getPassword(), //密码 ByteSource.Util.bytes(userInfo.getCredentialsSalt()),//salt=username+salt getName() //realm name ); System.out.println(authenticationInfo); return authenticationInfo; } } ``` MyInceptor.java ```package com.zqw.inteceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MyInceptor implements HandlerInterceptor{ /* * 进入方法前执行 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception { System.out.println("前置拦截器执行>>>>>>>>>>>"); HttpSession session=request.getSession(); String s_sid=(String) session.getAttribute("sid"); System.out.println("s_sid:"+s_sid); String sid=(String) request.getParameter("sid"); System.out.println("sid:"+sid); if(s_sid.equals(sid)) { System.out.println("sid匹配成功!"); System.out.println("前置拦截器结束>>>>>>>>>>>"); return true; }else{ System.out.println("sid匹配失败!"); System.out.println("前置拦截器结束>>>>>>>>>>>"); throw new RuntimeException("login time out"); } } /* * 方法执行后 */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView modelAndView) throws Exception { System.out.println("后置1拦截器执行"); if (null != modelAndView && null != modelAndView.getModel()) { Object obj=modelAndView.getModel().get("data"); if (null != obj) { String str=(String) obj; System.out.println(str); } } } /* * 请求结束后 */ @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { System.out.println("后置2拦截器执行"); } } ``` SpringBootShiroApplicationTests.java ```package com.zqw; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.zqw.dao.UserInfoDao; import com.zqw.entity.SysPermission; import com.zqw.entity.SysRole; import com.zqw.entity.UserInfo; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootShiroApplicationTests { @Resource UserInfoDao dao; @Test public void contextLoads() { } } ``` JsonEntity.java ```package com.zqw.entity; public class JsonEntity { private String state; private String message; private String data; public String getState() { return state; } public void setState(String state) { this.state = state; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getData() { return data; } public void setData(String data) { this.data = data; } @Override public String toString() { return "JsonEntity [state=" + state + ", message=" + message + ", data=" + data + "]"; } } ``` CommonMethod.java ```package com.zqw.common; public class CommonMethod { /** * 卡号脱敏 * @param cardNo * @return */ public static String tCardNo(String cardNo){ String str=cardNo.substring(0,5)+"****"+cardNo.substring(cardNo.length()-6, cardNo.length()); return str; } /** * 手机号脱敏 * @param phone * @return */ public static String tPhone(String phone) { String str=phone.substring(0,4)+"****"+phone.substring(phone.length()-4, phone.length()); return str; } } ``` ReJson.java ```package com.zqw.common; import com.zqw.entity.JsonEntity; import net.sf.json.JSONObject; public class ReJson { //将后端的数据解析成JSON对象 public static JsonEntity reJson(String msg) { JSONObject json = JSONObject.fromObject(msg); JsonEntity je=new JsonEntity(); je.setState(json.getString("state")); je.setMessage(json.getString("message")); je.setData(json.getString("data")); return je; } //将data转成JSON对象 测试用 public static String toJson(String msg) { JSONObject json = JSONObject.fromObject(msg); return json.getString("cardNo"); } } ``` MpConnecttion.java ```package com.zqw.connecttion; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import com.zqw.entity.UserInfo; import net.sf.json.JSONObject; public class MpConnecttion { static String url="http://127.0.0.1:8080/"; public static String PostWithParas(String way,String dress,Map<String,String> sendMsg) { HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod("http://127.0.0.1:8088/"+way+"/"+dress); Iterator<String> iter = sendMsg.keySet().iterator(); if(iter.hasNext()) { String key=iter.next(); postMethod.setRequestBody(new NameValuePair[] {new NameValuePair(key,sendMsg.get(key))});//设置参数 } String result=""; try { client.executeMethod(postMethod);//执行请求 result = postMethod.getResponseBodyAsString();//获取返回的Response } catch (IOException e) { e.printStackTrace(); } postMethod.releaseConnection();//释放链接 return result; } public static void main(String[] args) { Map<String, String> map=new HashMap<String,String>(); map.put("cardNo", "6201202012123654"); System.out.println(PostWithParas("BP","MH0011",map)); } } ``` UserInfoServiceImpl.java ```package com.zqw.service.impl; import javax.annotation.Resource; import javax.transaction.Transactional; import org.springframework.stereotype.Service; import com.zqw.dao.UserInfoDao; import com.zqw.entity.UserInfo; import com.zqw.service.UserInfoService; @Service public class UserInfoServiceImpl implements UserInfoService{ @Resource UserInfoDao userDao; @Override @Transactional public UserInfo findByUsername(String username) { System.out.println("UserInfoServiceImpl.findByUsername()"); return userDao.findByUsername(username); } } ``` UserInfoDao.java ```package com.zqw.dao; import org.springframework.data.repository.CrudRepository; import com.zqw.entity.UserInfo; public interface UserInfoDao extends CrudRepository<UserInfo,Long>{ public UserInfo findByUsername(String username); } ```
zhura/binder-dash-proxy
zhura/binder-dash-proxy jupyter_notebook_config.py ```c.ServerProxy.servers = { 'dash': { 'command': ['python3', 'app.py', '{base_url}', '{port}'] } }``` README.md ```# Running a dash server with Binder [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/zhura/binder-dash-proxy/master?urlpath=/dash) This repository demonstrates how to run a Dash server from within Binder. ``` generate_image_name ```#!/usr/bin/env python3 import sys import hashlib import string import escapism def _safe_build_slug(build_slug, limit, hash_length=6): build_slug_hash = hashlib.sha256(build_slug.encode('utf-8')).hexdigest() safe_chars = set(string.ascii_letters + string.digits) def escape(s): return escapism.escape(s, safe=safe_chars, escape_char='-') build_slug = escape(build_slug) return '{name}-{hash}'.format( name=build_slug[:limit - hash_length - 1], hash=build_slug_hash[:hash_length], ).lower() repo_name = sys.argv[1] ref = sys.argv[2] image_prefix = sys.argv[3] build_slug = repo_name.replace('/', '-') safe_build_slug = _safe_build_slug(build_slug, limit=255 - len(image_prefix)) image_name = '{prefix}{build_slug}:{ref}'.format( prefix=image_prefix, build_slug=safe_build_slug, ref=ref ).replace('_', '-').lower() print(image_name)```
zhushuanglou/--
zhushuanglou/-- models.py ```# -*- coding: utf-8 -*- #导入包 from odoo import models, fields, api # 创建一个叫book_manage的类 # 创建一个叫book.manage的模型 class book_manage(models.Model): _name = 'book.manage' #创建四个字段,name与author是必填字段 name = fields.Char(string='名称',required=True) author = fields.Char(string='作者',required=True) price = fields.Float(string='价格') picture = fields.Binary(string='上传图片') # 创建一个叫book_manage的类 # class book_manage(models.Model): # # 创建一个叫book.manage的模型 # _name = 'book.manage' # # name = fields.Char(string='名称',required=True) # author = fields.Char(string='作者',require=True) # # price = fields.Float(string='价格') # picture = fields.Binary(string='上传图片') # # #创建一个叫book_sub的类 # #创建一个叫book.sub的模型 # class book_sub(models.Model): # _name = 'book.sub' # # #创建5个字段,name与author是必填字段 # name = fields.Char(string='名称',required=True) # author = fields.Char(string='作者',required=True) # price = fields.Float(string='价格') # picture = fields.Binary(string='上传图片') # state = fields.Selection([('draft','草稿'),('done','完成')],string="状态",default="draft") # # #定义btn_submit方法,方法的作用是将当前的state的状态变成done # @api.one # def btn_submit(self): # self.state='done' # # #定义btn_ver方法 # @api.multi # def btn_ver(self): # #创建vals,将当前页面的数据传递给vals # vals={ # 'name': self.name, # 'author':self.author, # 'price':self.price, # 'picture':self.picture, # } # #在模型book.manage里创建vals # self.env['book.manage'].create(vals) # #把当前页面的数据删除 # self.unlink() # 名称 作者 价格 上传图品 [('draft','草稿'),('done','完成')],string="状态",default="draft" # class book_manage(models.Model): # # name = fields.Char(string='名称',required=True) # # author = fields.Char(string='作者',required=True) # # price = fields.Char(string='价格') # # picture = fields.Binary(string='上传图片') # # state = fields.Selection([('draft','草稿'),('done','完成')],string='状态',default='draft') class book_sub(models.Model): _name = 'book.sub' name = fields.Char(string='名称',required = True) author = fields.Char(string='作者',required = True) price = fields.Float(string='价格') picture = fields.Binary(string='上传图片') '''state的Selection为多选字段,后面的string和name author一样都有string属性,default = “draft” 默认选中的为draft''' state = fields.Selection([('draft','草稿'),('done','完成')],string='状态',default = "draft") # 该方法将state的状态改为done @api.one def btn_sumit(self): self.state = "done" @api.multi def btn_ver(self): # 创建vals,将当前页面的数据传递给vals vals = {'name':self.name, 'author':self.author, 'price':self.price, 'picture':self.picture, } # 环境储存了模型的缓存记录集,因此我们可以通过环境来获取、增加、修改、删除记录,而触发数据库更改,从而达到操作数据库的目的。 # 例如:新增一条记录 # '''self.env['模型'].create(vals)''' self.evn['book.manage'].create(vals) #把当前页面的数据删除 删除在当前book_sub创建的 vals,这个vals是属于book.manage模型的对象 self.unlink() # @api.multi # def btn_ver(self): # vals = {'name':self.name, # 'author':self.auth, # 'price':self.price, # 'picture':self.picture # } # self.env['book.manage'] = vals # # -*- coding: utf-8 -*- # # # 导入包 # from odoo import models, fields, api # # # # 创建一个叫book_manage的类 # # 创建一个叫book.manage的模型 # class book_manage(models.Model): # _name = 'book.manage' # # # 创建四个字段,name与author是必填字段 # name = fields.Char(string='名称', required=True) # author = fields.Char(string='作者', required=True) # price = fields.Float(string='价格') # picture = fields.Binary(string='上传图片') # # # # 创建一个叫book_sub的类 # # 创建一个叫book.sub的模型 # class book_sub(models.Model): # _name = 'book.sub' # # # 创建5个字段,name与author是必填字段 # name = fields.Char(string='名称', required=True) # author = fields.Char(string='作者', required=True) # price = fields.Float(string='价格') # picture = fields.Binary(string='上传图片') # state = fields.Selection([('draft', '草稿'), ('done', '完成')], string="状态", default="draft") # # # 定义btn_submit方法,方法的作用是将当前的state的状态变成done # @api.one # def btn_submit(self): # self.state = 'done' # # # 定义btn_ver方法 # @api.multi # def btn_ver(self): # # 创建vals,将当前页面的数据传递给vals # vals = { # 'name': self.name, # 'author': self.author, # 'price': self.price, # 'picture': self.picture, # } # # 在模型book.manage里创建vals # self.env['book.manage'].create(vals) # # 把当前页面的数据删除 # self.unlink() # class book_sub(models.Model): # _name = 'book.sub' # name = fields.Char(string='名称',required = True) # auth = fields.Char(string='作者',required = True) # price = fields.Float(string='价格') # picture = fields.Binary(string='上传图片') # '''state的Selection为多选字段,后面的string和name author一样都有string属性,default = “draft” 默认选中的为draft''' # state = fields.Selection([('draft','草稿'),('done','完成')],string='状态',default = "draft") # # 该方法将state的状态改为done # @api.one # def btn_sumit(self): # self.state = "done" # # @api.multi # def btn_ver(self): # # 创建vals,将当前页面的数据传递给vals # vals = {'name':self.name, # 'author':self.author, # 'price':self.price, # 'picture':self.picture, # } # # 环境储存了模型的缓存记录集,因此我们可以通过环境来获取、增加、修改、删除记录,而触发数据库更改,从而达到操作数据库的目的。 # # 例如:新增一条记录 # # '''self.env['模型'].create(vals)''' # self.evn['book.manage'].create(vals) # #把当前页面的数据删除 删除在当前book_sub创建的 vals,这个vals是属于book.manage模型的对象 # self.unlink()```
zhusuqi/zhusuqi.github.com
zhusuqi/zhusuqi.github.com 02.js ```console.log("QS"); console.log("DZ1"); function f1(wow1,wow2){ console.log(wow1); console.log(wow2); }``` gulpfile.js ```'use strict' var gulp = require('gulp'); var less = require('gulp-less'); var cssnano = require('gulp-cssnano'); var cssmin = require('gulp-cssmin'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var imagemin = require('gulp-imagemin'); var clean = require('gulp-clean'); var browserSync=require('browser-sync').create(); gulp.task('wow', function() { console.log("hello wow sb"); }); gulp.task('copy',function(){ gulp.src('src/**/*.html') .pipe(gulp.dest('dist/')); }); gulp.task('less1',function(){ gulp.src('src/**/*.less') .pipe(less()) .pipe(gulp.dest('dist/css/')); }); gulp.task('less2',function(){ gulp.src('src/**/*.less') .pipe(less()) .pipe(cssnano()) .pipe(gulp.dest('dist/css/')); }); gulp.task('less',function(){ gulp.src('src/**/*.less') .pipe(less()) .pipe(cssmin()) .pipe(gulp.dest('dist/css/')); }); gulp.task('js',function(){ gulp.src('src/js/*.js') .pipe(concat('all.js')) .pipe(uglify()) .pipe(gulp.dest('dist/js/')); }); gulp.task('image',function(){ gulp.src('src/images/*') .pipe(imagemin()) .pipe(gulp.dest('dist/images/')); }); gulp.task('clean',function(){ gulp.src('dist/') .pipe(clean()); }); gulp.task('dist',['copy','less','js','image']); gulp.task('watch',function(){ gulp.watch('src/**/*.html',['copy']); gulp.watch('src/**/*.less',['less']); gulp.watch('src/js/*.js',['js']); gulp.watch('src/images/*',['image']); }); gulp.task('server',['copy','less','js','image'],function(){ browserSync.init({ server:{ baseDir:'./dist' }, port:8848 }); }); ``` 01.js ```console.log("wow"); console.log("zs"); console.log("fs");```
zhuxianguo/taro-next-plugin-test
zhuxianguo/taro-next-plugin-test app.config.js ```export default { plugins: { "wxparserPlugin": { "version": "0.3.1", "provider": "wx9d4d4ffa781ff3ac" } }, pages: [ 'pages/index/index' ], window: { backgroundTextStyle: 'light', navigationBarBackgroundColor: '#fff', navigationBarTitleText: 'WeChat', navigationBarTextStyle: 'black' } } ``` README.md ```# taro-next-plugin-test taro-next-plugin-test ``` index.config.js ```export default { navigationBarTitleText: '首页', usingComponents: { "wxparser": "plugin://wxparserPlugin/wxparser" } } ```
zhuxiaoyu1019/google-library-frontend
zhuxiaoyu1019/google-library-frontend README.md ```# Google Library Frontend ![GitHub license](https://img.shields.io/badge/License-MIT-blue.svg) ## Description This is a React-based Google Books Search app built with Node, Express and MongoDB. The application create React components, work with helper/util functions, and utilize React lifecycle methods to query and display books based on user searches. ## Table of Contents - [Deployed Application](#Deployed-Application) - [Usage](#usage) - [Installation](#installation) - [Contributing](#contributing) - [Questions](#questions) - [License](#license) ## Deployed Application [Google Library](https://google-library-frontend.herokuapp.com/) ## Usage ![Google Library demo](./public/google-library.gif) - This application has 2 pages: - Search - User can search for books via the Google Books API and render them here. User has the option to "View" a book, bringing them to the book on Google Books, or "Save" a book, saving it to the Mongo database. - Saved - Renders all books saved to the Mongo database. User has an option to "View" the book, bringing them to the book on Google Books, or "Delete" a book, removing it from the Mongo database. ## Installation - The appliaction is supported by [google-library-backend repository](https://github.com/zhuxiaoyu1019/google-library-frontend.git) - To install necessary dependencies, run the following command: npm i ## Contributing folk / pull ## Questions If you have any questions about the repo, open an issue or contact me directly @[xiaoyz28@uw.edu](xiaoyz28@uw.edu). You can find more of my work at [zhuxiaoyu1019](https://github.com/zhuxiaoyu1019). ## License Copyright (c) Rita Z. All rights reserved. Licensed under the [MIT](https://choosealicense.com/licenses/mit/) license. ``` Header.js ```import React from "react"; import Paper from "@material-ui/core/Paper"; import "./style.css"; export default function Header() { return ( <Paper square className="paper"> <h1>Google Books Search</h1> <h3>Search for and Save Books of Interest.</h3> </Paper> ); } ``` SearchBar.js ```import React, { useState } from "react"; import Paper from "@material-ui/core/Paper"; import Grid from "@material-ui/core/Grid"; import LibraryBooksIcon from "@material-ui/icons/LibraryBooks"; import Input from "@material-ui/core/Input"; import InputLabel from "@material-ui/core/InputLabel"; import Button from "@material-ui/core/Button"; import API from "../../utils/API"; import "./SearchBar.css"; import "../style.css"; export default function SearchBar({ formObject, setFormObject, setSearchBookList, }) { const handleInputChange = (event) => { const { name, value } = event.target; setFormObject({ ...formObject, [name]: value }); }; const handleFormSubmit = (event) => { event.preventDefault(); if (formObject.search) { API.searchBooks(formObject.search) .then((res) => setSearchBookList(res.data.items)) .catch((err) => console.log(err)); } setFormObject({ ...formObject, search: "" }); }; return ( <Paper square className="paper"> <Grid container className="head"> <Grid item> <LibraryBooksIcon /> </Grid> <Grid item className="head-title"> Book Search </Grid> </Grid> <form className="form" onSubmit={handleFormSubmit}> <InputLabel htmlFor="book-search">Book</InputLabel> <Input id="book-search" name="search" onChange={handleInputChange} value={formObject.search || ""} placeholder="A feast for crows" /> <Button className="search-btn" onClick={handleFormSubmit} variant="contained" > Search </Button> </form> </Paper> ); } ``` Book.js ```import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import Paper from "@material-ui/core/Paper"; import Grid from "@material-ui/core/Grid"; import Typography from "@material-ui/core/Typography"; import ButtonBase from "@material-ui/core/ButtonBase"; import Button from "@material-ui/core/Button"; import { useLocation } from "react-router-dom"; import API from "../utils/API"; import "./style.css"; import { useHistory } from "react-router-dom"; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, paper: { padding: theme.spacing(2), margin: "auto", marginTop: "10px", marginBottom: "10px", width: "90%", maxWidth: "none", }, image: { width: 128, height: 128, }, img: { margin: "auto", display: "block", maxWidth: "100%", maxHeight: "100%", }, btnGroup: { margin: "3px", }, })); export default function Book({ id, title, authors, description, image, link, displaySavedBooks, }) { const classes = useStyles(); const location = useLocation(); const history = useHistory(); const handleBookSave = () => { const newBook = { title, authors, description, image, link, }; API.saveBook(newBook) .then(function () { history.push("/saved"); displaySavedBooks(); }) .catch((err) => console.log(err)); }; const handleBookDelete = (id) => { API.deleteBook(id) .then(displaySavedBooks) .catch((err) => console.log(err)); }; return ( <Paper className={classes.paper}> <Grid container> <Grid item> <ButtonBase className={classes.image}> <img className={classes.img} alt={title} src={image} /> </ButtonBase> </Grid> <Grid item xs={12} sm container spacing={2}> <Grid item xs container direction="column" spacing={2}> <Grid item xs> <Typography gutterBottom variant="subtitle1"> {title} </Typography> <Typography variant="body2" gutterBottom> Written by {authors.join(", ")} </Typography> <Typography variant="body2" color="textSecondary"> {description} </Typography> </Grid> </Grid> <Grid item> <Button variant="contained" target="_blank" href={link} className={classes.btnGroup} > View </Button> {location.pathname === "/saved" ? ( <Button variant="contained" color="secondary" className={classes.btnGroup} onClick={() => handleBookDelete(id)} > Delete </Button> ) : ( <Button variant="contained" color="primary" // component={Link} // to="/saved" className={classes.btnGroup} onClick={handleBookSave} > Save </Button> )} </Grid> </Grid> </Grid> </Paper> ); } ``` BookList.js ```import React from "react"; import Paper from "@material-ui/core/Paper"; import Grid from "@material-ui/core/Grid"; import { useLocation } from "react-router-dom"; import SaveAltIcon from "@material-ui/icons/SaveAlt"; import "./style.css"; import Book from "./Book"; export default function BookList({ savedBookList, searchBookList, displaySavedBooks, }) { const location = useLocation(); return ( <div> <Paper square className="paper"> <Grid container className="head"> {location.pathname === "/saved" ? ( <> <Grid item> <SaveAltIcon /> </Grid> <Grid item className="head-title"> Saved Book </Grid> </> ) : ( <Grid item className="head-title"> Results </Grid> )} </Grid> {location.pathname === "/saved" ? savedBookList.map((book) => ( <Book key={book._id} id={book._id} title={book.title} authors={book.authors} description={book.description} image={book.image} link={book.link} displaySavedBooks={displaySavedBooks} /> )) : searchBookList.map((book) => ( <Book key={book.id} id={book.id} title={book.volumeInfo.title} authors={book.volumeInfo.authors} description={book.volumeInfo.description} image={book.volumeInfo.imageLinks.thumbnail} link={book.volumeInfo.previewLink} /> ))} </Paper> </div> ); } ``` API.js ```import axios from "axios"; // const URL_PREFIX = "http://localhost:8080"; const URL_PREFIX = "https://google-library-backend.herokuapp.com"; const API = { searchBooks: (query) => { return axios.get(`https://www.googleapis.com/books/v1/volumes?q=${query}+intitle" `); }, getBooks: () => { return axios.get(`${URL_PREFIX}/api/books`); }, saveBook: (bookInfo) => { return axios.post(`${URL_PREFIX}/api/books`, bookInfo); }, deleteBook: (id) => { return axios.delete(`${URL_PREFIX}/api/books/${id}`); }, }; export default API; ``` Search.js ```import React, { useState } from "react"; import Header from "../components/Header"; import SearchBar from "../components/SeachBar/SearchBar"; import BookList from "../components/BookList"; export default function Search() { const [formObject, setFormObject] = useState({}); const [searchBookList, setSearchBookList] = useState([]); return ( <div> <Header /> <SearchBar formObject={formObject} setFormObject={setFormObject} setSearchBookList={setSearchBookList} /> <BookList searchBookList={searchBookList} /> </div> ); } ``` Saved.js ```import React, { useState, useEffect } from "react"; import BookList from "../components/BookList"; import Header from "../components/Header"; import API from "../utils/API"; export default function Saved() { const [savedBookList, setSavedBookList] = useState([]); useEffect(() => { displaySavedBooks(); }, []); const displaySavedBooks = () => { API.getBooks() .then((res) => { setSavedBookList(res.data); }) .catch((err) => { console.log(err); }); }; return ( <div> <Header /> <BookList savedBookList={savedBookList} displaySavedBooks={displaySavedBooks} /> </div> ); } ```
zhuxinquan/Go
zhuxinquan/Go Login.go ```package main import ( "fmt" "html/template" "net/http" "strings" //"net/url" "log" "os" "io" "crypto/md5" "strconv" "time" ) func upload(w http.ResponseWriter, req * http.Request){ fmt.Println("method:", req.Method) //获取请求的方法 if req.Method == "GET" { crutime := time.Now().Unix() h := md5.New() io.WriteString(h, strconv.FormatInt(crutime, 10)) token := fmt.Sprintf("%x", h.Sum(nil)) t, _ := template.ParseFiles("upload.gtpl") t.Execute(w, token) } else { req.ParseMultipartForm(32 << 20) file, handler, err := req.FormFile("uploadfile") if err != nil { fmt.Println(err) return } defer file.Close() fmt.Fprintf(w, "%v", handler.Header) //fmt.Println(strings.SplitN(handler.Filename, "/", 1)[len(strings.SplitN(handler.Filename, "/", 1)) - 1]) f, err := os.OpenFile("../test/" + strings.Split(handler.Filename, "/")[len(strings.Split(handler.Filename, "/")) - 1], os.O_WRONLY|os.O_CREATE, 0666) if err != nil { fmt.Println(err) return } defer f.Close() io.Copy(f, file) } } func sayhelloName(w http.ResponseWriter, r *http.Request) { r.ParseForm() //解析url传递的参数,对于POST则解析响应包的主体(request body) //注意:如果没有调用ParseForm方法,下面无法获取表单的数据 fmt.Println(r.Form) //这些信息是输出到服务器端的打印信息 fmt.Println("path", r.URL.Path) fmt.Println("scheme", r.URL.Scheme) fmt.Println(r.Form["url_long"]) for k, v := range r.Form { fmt.Println("key:", k) fmt.Println("val:", strings.Join(v, "")) } fmt.Fprintf(w, "Hello astaxie!") //这个写入到w的是输出到客户端的 } //func index(rw http.ResponseWriter, req * http.Request){ // t, _ = template.ParseFiles("index.tpl") // t.Execute(rw, nil) //} func login(w http.ResponseWriter, r *http.Request) { fmt.Println("method:", r.Method) //获取请求的方法 if r.Method == "GET" { t, _ := template.ParseFiles("./index.tpl") t.Execute(w, nil) } else { //请求的是登陆数据,那么执行登陆的逻辑判断 r.ParseForm() if checkPasswd(r.Form["password"][0]) { t, _ := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`) t.ExecuteTemplate(w, "T", "<script>alert('you have been pwned')</script>") //template.HTMLEscape(w, []byte("<script>alert()</script>")) fmt.Println("username:", r.Form["username"]) fmt.Println("password:", r.Form["password"]) } else { fmt.Printf("密码长度不符合") t, _ := template.ParseFiles("/home/zhuxinquan/IdeaProjects/GoLanguage/GoFormManage/main/index.tpl") t.Execute(w, "密码长度不符合") } fmt.Println("username:", r.Form["username"]) fmt.Println("password:", r.Form["password"]) } } func checkPasswd(s string) bool{ if len(s) > 16 || len(s) < 6 { return false } return true } func main() { //v := url.Values{} //v.Set("name", "name") //v.Add("friend", "friend1") //v.Add("friend", "friend2") //fmt.Println(v.Encode()) //fmt.Println(v["friend"][1]) http.HandleFunc("/upload", upload) http.HandleFunc("/", sayhelloName) //设置访问的路由 http.HandleFunc("/login", login) //设置访问的路由 err := http.ListenAndServe(":9090", nil) //设置监听的端口 if err != nil { log.Fatal("ListenAndServe: ", err) } } ``` Note.md ```##源码文件的分类和含义 1. 命令源码文件 2. 库源码文件 3. 测试源码文件 功能测试函数 func TestFind(t *testing.T){ } 基准(性能)测试函数 func BenchmarkFind(b *testing.B){ } ##代码包相关 1. 声明与导入路径的区别 1. 代码包**声明语句**中的包名称只包含代码包导入路径的最右子路径 2. 代码包导入 1. 代码包导入语句中使用的包名称应该与其导入路径一致 2. 带别名的导入: import str "strings" str.HasPrefix("abc", "a") 3. 本地化导入: import . "strings" HasPrefix("abc", "a"),调用代码包中的程序实体如同调用当前代码包的程序实体一样,可以不写任何前缀 4. 仅仅初始化: import _ "strings" 导入了代码包,但并不调用其中的任何程序实体,仅仅执行初始化代码包的动作 3. 代码包初始化函数:无参数声明和结果声明的init函数,init函数可以被声明在任何文件中,且可以有多个 4. init的执行时机 1. 在单一代码包内,当导入某个代码包时,首先对代码包中的全局变量进行求值,求值完成之后,执行所有的init函数,在同一个代码包中init的执行顺序是不定的 2. 不同代码包之间(当前代码包和导入的代码包都包含init函数),被导入的代码包中的init函数先被执行,然后执行导入它的那个代码包的init函数<font color="red">不应在同一个代码包中被导入的多个代码包的init函数的执行顺序作出假设</font> 3. 所有涉及到的代码包,init函数先执行,main函数才会被执行,并且每个init函数只会被执行一次 ##命令基础 1. go run 1. 用于运行命令源码文件 2. 只能接受一个命令源码文件以及若干个库源码文件作为文件参数 3. 内部操作:先编译源码文件再运行,编译结果包括命令源码文件,被编译后生成的可执行文件以及相关库源码文件编译后所生成的归档文件 4. go run常用标记的使用: 1. -a:强制编译相关代码,不论他们的编译结果是否已是最新的 2. -n:打印编译过程中所需运行的命令,但*不是真正执行它们*,最终没有程序的执行结果 3. -p n:并行编译,其中n为并行的数量(建议为CPU逻辑个数(2CPU,2核=》逻辑CPU 为4个)-p 4) 4. -v:列出被编译的代码包的名称 5. -a -v:列出所有被编译的代码包的名称 6. -work:显示编译时创建的临时工作目录的路径,并且在执行完成后不删除(默认删除) 7. -x:打印编译过程中所需运行的命令,_并执行它们_ 2. go build 1. 用于编译源码文件或代码包 2. 编译非命令源码文件不会产生任何结果文件(检查库源码文件的有效性) 3. 编译命令源码文件时会在该命令的执行目录中生成一个可执行文件 4. 执行该命令时不追加任何参数时,它会试图把当前目录作为代码包并编译 5. 执行该命令且以代码包的导入路径作为参数时,该代码包及其依赖会被编译 6. 执行该命令且以若干源码文件作为参数时,只有这些文件会被编译 3. go install 1. 用于编译并安装代码包或源码文件 2. 安装代码包会在当前工作区的pkg/<平台相关目录>下生成归档文件 3. 安装命令源码文件会在当前工作区的bin目录或$GOBIN目录下生成可执行文件 4. 执行该命令时不追加任何参数时,它会试图把当前目录作为代码包并安装 5. 执行该命令且以代码包的导入路径作为参数时,该代码包及其依赖会被安装 6. 执行该命令且以若干源码文件作为参数时,只有这些文件会被编译并安装 4. go get 1. -d:只执行下载动作,而不执行安装动作 2. -fix:在下载代码包后先执行修正动作,而后再进行编译和安装(比如修正版本之间的差异) 3. -u:利用网络来更新已有的代码包及其依赖包(upadte) ``` extcontroller.go ```package controllers import ( "github.com/astaxie/beego" ) // CMS API type CMSController struct { beego.Controller } //func (c *CMSController) URLMapping() { // c.Mapping("StaticBlock", c.StaticBlock) // c.Mapping("AllBlock", c.AllBlock) //} // @router /staticblock/:key [get] func (this *CMSController) StaticBlock() { this.Ctx.Output.Body([]byte(this.Ctx.Input.Param(":key"))) } // @router /all/:key [get] func (this *CMSController) AllBlock() { } ``` sqlorm.go ```package main import ( "database/sql" "github.com/astaxie/beedb" _ "github.com/ziutek/mymysql/godrv" "time" "fmt" "strconv" "reflect" "strings" "unsafe" "util" ) type Userinfo struct { Uid int `PK` //如果表的主键不是id,那么需要加上pk注释,显式的说这个字段是主键 Username string Departname string Created time.Time } func (u Userinfo)String() string{ return strconv.Itoa(u.Uid) } type Tt struct { Id int `PK` Time time.Time } func String(b []byte) (s string) { pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) pstring.Data = pbytes.Data pstring.Len = pbytes.Len return } func main(){ //db, err := sql.Open("mysql", "root:2737353904@tcp(localhost:3306)/test?charset=utf8") db, err := sql.Open("mymysql", "test/root/2737353904") if err != nil { panic(err) } //beedb.OnDebug=true orm := beedb.New(db) var user Tt //var userinfo Userinfo orm.Where("id=?", 1).Find(&user) a, _ := orm.SetTable("userinfo").SetPK("uid").Select("uid,username").FindMap() for _, v := range a { for k, value := range v { if(strings.EqualFold(k, "uid")) { fmt.Println(k, ":", util.ByteToInt(value)) } else { fmt.Println(k, ":", string(value)) } } } }``` fetch.go ```package main import ( "time" "fmt" "net/http" "os" "io/ioutil" ) func main() { for i := 0; i < 5; i++ { start := time.Now() resp, err := http.Get(os.Args[1]) if err != nil { fmt.Println(err) // send to channel ch os.Exit(-1) } b, err := ioutil.ReadAll(resp.Body) resp.Body.Close() fmt.Println(string(b)) fmt.Printf("%.2fs\tbytes: %d\n", time.Since(start).Seconds(), len(b)) } }``` recover.go ```package main import ( "fmt" "os" ) func main() { defer func(){ fmt.Println("recover") if err := recover(); err != nil { fmt.Println("err:", err) } }() fmt.Println("panic") //panic("err") file, err := os.OpenFile("1234", os.O_APPEND|os.O_RDONLY, os.ModeAppend) if err != nil { panic(err) } fmt.Println("before close") file.Close() fmt.Println("after") } ``` router.go ```package routers import ( "quickstart/controllers" "github.com/astaxie/beego" ) func init() { beego.BConfig.RouterCaseSensitive = false beego.Router("/abc", &controllers.MainController{}) beego.Router("/", &controllers.AddController{}) } ``` usesession.go ```package main import ( "net/http" "github.com/astaxie/session" "fmt" ) var globalSessions *session.Manager func init() { globalSessions, _ = session.NewManager("memory","gosessionid",3600) } func getSession(w http.ResponseWriter, r *http.Request) { sess := globalSessions.SessionStart(w, r) session := sess.Get("username") fmt.Fprintf(w, "Get Session Ok, Session is %s", session) } func index(w http.ResponseWriter, r * http.Request) { sess := globalSessions.SessionStart(w, r) sess.Set("username", "set username") fmt.Fprint(w, "Set Session Ok!") } func main() { http.HandleFunc("/", index) http.HandleFunc("/get", getSession) err := http.ListenAndServe(":9090", nil) if err != nil { fmt.Println(err) } } ``` main.go ```package main import ( _ "quickstart/routers" "github.com/astaxie/beego" "quickstart/controllers" ) func main() { beego.Include(&controllers.CMSController{}) beego.Run() }``` conditionmanage.go ```package main import ( "os" "text/template" ) type People struct { Username string Gender string } func (p People)String() string { return "username:" + p.Username + " gender:" + p.Gender } func main() { info := map[string]bool{ "Han Meimei": true, "LiLei": false, } t := template.Must(template.New("test").Parse(`Married: Han Meimei:{{index . "Han Meimei"}}; Li Lei:{{.LiLei}}`)) t.Execute(os.Stdout, info) tEmpty := template.New("hello") tEmpty = template.Must(tEmpty.Parse("{{.}}")) tEmpty.Execute(os.Stdout, People{Username:"username", Gender:"men"}) //tEmpty := template.New("template test") //tEmpty = template.Must(tEmpty.Parse("空 pipeline if demo: {{if ``}} 不会输出. {{end}}\n")) //tEmpty.Execute(os.Stdout, nil) // //tWithValue := template.New("template test") //tWithValue = template.Must(tWithValue.Parse("不为空的 pipeline if demo: {{if `anything`}} 我有内容,我会输出. {{end}}\n")) //tWithValue.Execute(os.Stdout, nil) // //tIfElse := template.New("template test") //tIfElse = template.Must(tIfElse.Parse("if-else demo: {{if `anything`}} if部分 {{else}} else部分.{{end}}\n")) //tIfElse.Execute(os.Stdout, nil) } ``` bytetoint_test.go ```package util import ( "fmt" "testing" ) func TestByteToInt(t *testing.T) { b := []byte{0x11, 0x00, 0x03, 0xe8} fmt.Println(123) fmt.Println(ByteToInt(b)) }``` setcookie.go ```package main import ( "net/http" "fmt" "time" ) func setCookie(w http.ResponseWriter, r *http.Request) { expiration := time.Now() expiration = expiration.AddDate(1, 0, 0) cookie := http.Cookie{Name: "username", Value: "astaxie", Expires: expiration} http.SetCookie(w, &cookie) fmt.Fprintf(w, "Set Cookie Successful") } func getCookie(w http.ResponseWriter, r * http.Request) { cookie, _ := r.Cookie("username") fmt.Fprint(w, "GetCookieIs:", cookie) } func main() { http.HandleFunc("/getcookie", getCookie) http.HandleFunc("/setcookie", setCookie) err := http.ListenAndServe(":8888", nil) if(err != nil) { panic(err) } } ``` bytetoint.go ```package util import ( "strconv" ) func ByteToInt(b []byte) int { x, err := strconv.Atoi(string(b)) if err != nil { panic(err) } return x } ``` comma.go ```package main import ( "strconv" "container/heap" ) type Person struct { name string age int } func (p Person) f1(a int) int { return a } func (p Person) f2(a int) int { return a } //定义了String方法,实现了fmt.Stringer func (p Person) String() string { return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)" } var pp Person type Inter interface { pp.Interface f1() f2() String() }```
zhuysh1988/inspur-dbus-interfaces
zhuysh1988/inspur-dbus-interfaces README.md ```# inspur-dbus-interfaces YAML descriptors of Inspur specific D-Bus interfaces ```
zhuyunsun/FFAppleLogin
zhuyunsun/FFAppleLogin README.md ```# FFAppleLogin Sign in with Apple ```
zhuzhixu/tensorflow-python-java
zhuzhixu/tensorflow-python-java DataUtill.java ```package com.wx.wxdemo.utill; public class DataUtill { public static void close(AutoCloseable autoCloseable){ try { autoCloseable.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` JdbcInstant.java ```package com.wx.wxdemo.dao; import com.wx.wxdemo.entity.User; import com.wx.wxdemo.utill.DataUtill; import java.sql.*; public class JdbcInstant { private static String url = "jdbc:mysql://localhost:3306/wx?serverTimezone=GMT%2B8"; private static String user = "root"; private static String password = "123456"; private static Connection connection = null; static { try{ Class.forName("com.mysql.cj.jdbc.Driver"); }catch (Exception e) { System.out.println("驱动异常"); } } public JdbcInstant(){ try { connection = DriverManager.getConnection(url,user,password); } catch (SQLException e) { e.printStackTrace(); } } public User getUser(int id) { ResultSet resultSet = null; String sql = "select * from t_user"; PreparedStatement statement= null; try { statement = connection.prepareStatement(sql); } catch (SQLException e) { e.printStackTrace(); } try { resultSet = statement.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } User pojo = new User(); while (true){ try { if (!resultSet.next()) break; } catch (SQLException e) { e.printStackTrace(); } String user = null; try { user = resultSet.getString("user"); } catch (SQLException e) { e.printStackTrace(); } String name = null; try { name = resultSet.getString("name"); } catch (SQLException e) { e.printStackTrace(); } String password = null; try { password = resultSet.getString("password"); } catch (SQLException e) { e.printStackTrace(); } pojo.setId(id); pojo.setPassword(password); pojo.setName(name); pojo.setUser(user); } DataUtill.close(resultSet); DataUtill.close(connection); return pojo; } } ``` UserController.java ```package com.wx.wxdemo.controller; import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Controller; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import org.tensorflow.Graph; import org.tensorflow.Session; import org.tensorflow.Tensor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.nio.FloatBuffer; @Controller public class UserController { @RequestMapping(value = "demo",method = RequestMethod.GET) public ModelAndView getUser(){ ModelAndView modelAndView = new ModelAndView("demo"); return modelAndView; } @RequestMapping(value = "demo",method = RequestMethod.POST) @ResponseBody public String re(HttpServletRequest request, HttpServletResponse response){ String data = null; String one = request.getParameter("one"); String two = request.getParameter("two"); try (Graph graph = new Graph()){ Tensor xy = Tensor.create(new long[]{1,2}, FloatBuffer.wrap( new float[]{ Float.parseFloat(one)/10000, Float.parseFloat(two)/10 } )); byte[] graphBytes = IOUtils.toByteArray(new FileInputStream(ResourceUtils.getFile("classpath:model.pb"))); graph.importGraphDef(graphBytes); try(Session session = new Session(graph)){ Tensor<?> out = session.runner() .feed("xy",xy) .fetch("model").run().get(0); float[][] r = new float[1][1]; out.copyTo(r); data = Float.toString(r[0][0]); } }catch (Exception e){ e.printStackTrace(); } return data; } } ``` test.py ```import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import math from tensorflow.python import pywrap_tensorflow #加法器 # log = 'd:/venv/log/add_temple' # a = tf.constant(1.0, name='ta') # b = tf.constant(2.0, name='tb') # c = tf.add(a,b, name='tc') # ss = tf.Session() # xss = ss.run(c) # xsum = tf.summary.FileWriter(log, ss.graph) # ss.close() #乘法器 # log = 'd:/venv/log/log_temp' # a = tf.Variable(1.0, name='ta') # b = tf.constant(1.0, name='tb') # c = tf.multiply(a, b, name='tc') # ss = tf.Session() # xsum = tf.summary.FileWriter(log, ss.graph) # init = tf.global_variables_initializer() # ss.run(init) # xss = ss.run(c) # print('xss',xss) # ss.close() # hello tensorflow # hello = tf.constant('Hello7') # ss = tf.Session() # print(ss.run(hello)) # # a = tf.constant(2) # b = tf.constant(3) # with tf.Session() as sess: # print("a=2 , b = 3") # print('a+b=', ss.run(a+b)) # print('a*b=', ss.run(a*b)) #缺省图运算 contant常量 # gg = tf.get_default_graph() # op1 = gg.get_operations() # print('op,',op1) # print('type(op1),',type(op1)) # init_dat = tf.constant(1.0) # # op2 = gg.get_operations() # # print('init_dat,',init_dat) # # print('type(init_dat)',type(init_dat)) # # print('op2:',op2) # # print('type(op):',type(op2)) # # print('op.node_def,',op2[0].node_def) # # ss = tf.Session() # # xdat = ss.run(init_dat) # # print('xdat',xdat) # # ss.close() # a = tf.constant(1.0, name='input') # b = tf.Variable(0.8, name='weight') # c = tf.multiply(a, b, name='output') # rlog = 'd:/venv/log/log_tem' # ss = tf.Session() # xsum = tf.summary.FileWriter(rlog, ss.graph) # ss.close() # 占位符运算 # rlog = "d:/venv/log/log_tmp" # x = tf.placeholder(tf.float32, name='x') # y = tf.placeholder(tf.float32, name='y') # z = tf.add(x, y, name='z') # ss = tf.Session() # xsum = tf.summary.FileWriter(rlog, ss.graph) # xss = ss.run(z, feed_dict={x:1, y:2.0}) # rlog = 'd:/venv/log/varible_tmp' # a = tf.Variable(1.0, name='a') # b = tf.Variable(1.0, name='b') # c = tf.add(a, b, name='c') # ss = tf.Session() # init = tf.global_variables_initializer() # ss.run(init) # tf.summary.FileWriter(rlog, ss.graph) # xsum = ss.run(c) # print('xsum',xsum) # ss.close() # 变量操作 # rlog = 'd:/venv/log/variable_test_tmp' # cnt = tf.Variable(0, name='cnt') #cnt = 0 # a = tf.constant(1, name='a') #a = 1 # y = tf.add(cnt, a) # y = 1 # y2 = tf.assign(cnt, y) # cnt = 1, y2 = 1 # init = tf.global_variables_initializer() # with tf.Session() as ss: # ss.run(init) # xss = ss.run(cnt) # print('x.cnt,',xss) # for xc in range(3): # ys2 = ss.run(y2) # xs2 = ss.run(cnt) # print('x2.cn2,',xs2) # # xsum = tf.summary.FileWriter(rlog, ss.graph) # feed数据提交 # rlog = 'd:/venv/log/feed_data_tmp' # a = tf.placeholder(tf.float32, name='ta') #占位中没有数据用feed 添加数据 # b = tf.placeholder(tf.float32, name='tb') # c = tf.multiply(a, b, name='tc') # init = tf.global_variables_initializer() # with tf.Session() as ss: # ss.run(init) # xss = ss.run([c], feed_dict={a:[7.0], b:[2.0]}) # print('xss',xss) # xsum = tf.summary.FileWriter(rlog, ss.graph) # feed批量数据提交 # a_dat = [[1., 2., 3.], [4., 5., 6.]] # b_dat = [[2., 3., 4.], [3., 2., 1.]] # xss = ss.run([c], feed_dict={a:a_dat, b:b_dat}) # print('xss',xss) # fetch 获取数据 # rlog = 'd:/venv/log/fetch_data_tmp' # a = tf.constant(3.0, name='ta') # b = tf.constant(2.0, name='tb') # c = tf.constant(5.0, name='tc') # m1 = tf.add(b,c, name='m1') # m2 = tf.multiply(a, m1, name='m2') # with tf.Session() as ss: # xss = ss.run([m2,m1]) # print('xss', xss) # xsum = tf.summary.FileWriter(rlog, ss.graph) #获取fetch多维数据 # a_dat = [[1.,2.,3.],[4.,5.,6.]] # b_dat = [[2.,3.,4.],[3.,2.,1.]] # c_dat = [[3.,2.,1.],[1.,2.,3.]] # a = tf.constant(a_dat, name='ta') # b = tf.constant(b_dat, name='tb') # c = tf.constant(c_dat, name='tc') # m1 = tf.add(b, c, name='m1') # m2 = tf.multiply(a, m1, name='m2') # with tf.Session() as ss: # xss = ss.run([m2, m1]) # print('xss', xss) # xsum = tf.summary.FileWriter(rlog, ss.graph) #单细胞算法 公式: y_model = w*x # #1 # rlog = 'd:/venv/log/danxibao_tmp' # x = tf.constant(2.0, name='input') # w = tf.Variable(0.8, name='weight') # y_model = tf.multiply(w, x, name='output') # #2 # print('\n#2,set.dat #2') # y_ = tf.constant(0.0, name='correct_value') # loss = tf.pow(y_model - y_, 2, name='loss') # #3 # print('\n#3, train_step') # """ 使用梯度下降优化器(Optimizer)作为学习函数,按照误差(loss)导数来调整w权重参数数值。 # 通过学习率(learning rate)调节(moderate)更新权重大小 设置为0.025 # """ # train_step = tf.train.GradientDescentOptimizer(0.025).minimize(loss) # #4 # """ # 添加summary日志数据进行合并优化 # """ # print('\n#4,summary.misc') # for value in [x, w, y_model, y_, loss]: # tf.summary.scalar(value.op.name, value) # summaries = tf.summary.merge_all() # #5 # print('\n#5,Session') # ss = tf.Session() # #6 # print('\n#6,summary, rlog',rlog) # xsum = tf.summary.FileWriter(rlog, ss.graph) # #7 # print('\n#7,Session init') # init = tf.global_variables_initializer() # ss.run(init) # #8 # print('\n#8,Session init') # for i in range(100): # #8.a # xdat =ss.run(summaries) # xsum.add_summary(xdat, i ) # x2 = ss.run(train_step) # #-------- # #8.b # x2, y2, w2 = ss.run(x), ss.run(y_model), ss.run(w) # s2 = ss.run(loss) # print(i, '#,y2,loss:',y2, s2,',x2,w2 ',x2,w2) # print('\n#9,Seesion.close') # # ss.close() # #2-1创建图,启动图(graph) # # 创建常量op # m1 = tf.constant([[3,3]]) # # 创建常量op # m2 = tf.constant([[2],[3]]) # # 创建一个矩阵乘法op, 把m1,m2 传入 # product = tf.matmul(m1, m2) # print(product) # # 定义一个会话,启动默认图 # sess = tf.Session() # #调用sess的run方法来执行矩阵乘法op # # run(product)出发图中3个op # result = sess.run(product) # tf.summary.FileWriter('d:/venv/log/matmui_tmp', sess.graph) # sess.close() # # 2-2变量介绍 # x = tf.Variable([1,2]) # a = tf.constant([3,3]) # #增加一个减法op # sub = tf.subtract(x,a) # #增加一个加法op # add = tf.add(x, sub) # init = tf.global_variables_initializer() # with tf.Session() as sess: # sess.run(init) # result_sub = sess.run(sub) # result_add = sess.run(add) # print(result_sub) # print(result_add) # tf.summary.FileWriter("d:/venv/log/subtracr_tmp", sess.graph) # # 创建一个变量初始化为0 # state = tf.Variable(0, name='counter') # # 创建一个op, 作用是使state加1 # new_value = tf.add(state,1) # # 赋值op # update = tf.assign(state, new_value) # # 变量初始化 # init = tf.global_variables_initializer() # with tf.Session() as sess: # sess.run(init) # print(sess.run(state)) # for _ in range(5): # sess.run(update) # print(sess.run(state)) # 2-3 feed # input1 = tf.placeholder(tf.float32) # input2 = tf.placeholder(tf.float32) # output = tf.multiply(input1, input2) # with tf.Session() as sess: # # feed数据以字典形式传入 # print(sess.run(output,feed_dict={input1:[7.], input2:[2.]})) #使用numpy生成100个随机数 (样本) # x_data = np.random.rand(100) # y_data = x_data*0.1 + 0.2 # # 构造一个线性模型 # b = tf.Variable(0.) # k = tf.Variable(0.) # y = k*x_data + b # # # 二次代价函数 # loss = tf.reduce_mean(tf.square(y_data - y)) # # 定义一个梯度下降法来进行训练的优化器 # optimizer = tf.train.GradientDescentOptimizer(0.2) # # 最小化代价函数 # train = optimizer.minimize(loss) # init = tf.global_variables_initializer() # with tf.Session() as sess: # sess.run(init) # for step in range(201): # sess.run(train) # if step % 2 == 0: # print(step,sess.run([k,b])) # tf.summary.FileWriter("d:/venv/log/test1_tmp", sess.graph) # 线性回归 # x = tf.constant([1,2,3,4,5,6],tf.float32) # y = tf.constant([3,4,7,8,11,14],tf.float32) # k = tf.Variable(1.0,dtype=tf.float32) # b = tf.Variable(1.0,dtype=tf.float32) # # 求loss loss为差值平方 # loss = tf.reduce_sum(tf.square(y - (k*x+b))) # # 初始化变量 # init = tf.global_variables_initializer() # # 创建会话 # with tf.Session() as sess: # sess.run(init) # opti = tf.train.GradientDescentOptimizer(0.005).minimize(loss) # msg = [] # for i in range(500): # sess.run(opti) # msg.append(sess.run(loss)) # if i % 50 ==0: # print((sess.run(k), sess.run(b))) # plt.figure(1) # plt.plot(msg) # plt.show() # # 画出六个点及最后计算出的直线 # plt.figure(2) # x_arry, y_arry = sess.run([x, y]) # plt.plot(x_arry, y_arry, 'o') # xx = np.arange(0, 10, 0.05) # yy = sess.run(k) * xx + sess.run(b) # plt.plot(xx, yy) # plt.show() # 多元线性回归 xy = tf.placeholder(tf.float32, [None, 2], name='xy') z = tf.placeholder(tf.float32, [None, 1], name='z') # 初始化z = w1*x + w2*y + b w = tf.Variable(tf.constant([[1], [1]], tf.float32), dtype=tf.float32, name='w') b = tf.Variable(1.0, dtype=tf.float32, name='b') # 损失函数 loss = tf.reduce_sum(tf.square(z - (tf.matmul(xy, w)+b))) # 初始化变量 init = tf.global_variables_initializer() session = tf.Session() session.run(init) # 梯度下降 opti = tf.train.GradientDescentOptimizer(0.005).minimize(loss) # 记录方差 msg = [] # 训练数据 xy_train = np.array([ [0.1, 0.8], [0.2, 0.3], [0.6, 0.8], [0.8, 0.4] ], np.float32) z_train = np.array([[1080], [2030], [7080], [8040]], np.float32) # 训练模型 循环500次 for i in range(10000): #梯度下降 session.run(opti,feed_dict={xy: xy_train, z: z_train}) #计算每一次迭代损失值 ,追加到列表中保存 msg.append(session.run(loss, feed_dict={xy: xy_train, z: z_train})) #每隔100次打印a b 值 if i % 100 == 0: print("-----------第", i, "次的迭代值----------") print(session.run([w, b])) #建立需要导出的预测模型 model = tf.add(tf.matmul(xy, session.run(w)), session.run(b), name='model') #导出pb预测模型 constant_graph = tf.compat.v1.graph_util.extract_sub_graph(session.graph_def, ['model']) with tf.gfile.GFile("./model/model.pb", "w+") as f: f.write(constant_graph.SerializeToString()) # 画出顺势函数的值 plt.figure(1) plt.plot(msg) plt.show() # 测试数据 print(session.run(model, feed_dict={xy: [[0.8, 0.8]]})) ```
zhuzizhengming/health
zhuzizhengming/health ReadExcel.java ```package com.tao.poi; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.Test; import java.io.IOException; /** * @author:诸子争鸣 * @DATE:2021/1/9 17:27 */ public class ReadExcel { @Test public void readFromExcel() throws IOException { //创建工作簿,构造方法文件路径 Workbook workbook = new XSSFWorkbook("d:\\read.xlsx"); // 获取工作表 Sheet sht = workbook.getSheetAt(0); // sht.getPhysicalNumberOfRows(); // 物理行数 // sht.getLastRowNum(); // 最后一行的下标 // fori遍历时使用getLastrowNum() // 遍历工作表获得行对象 for (Row row : sht) { // 遍布行对象获取单元格 for (Cell cell : row) { // 单元格的类型 int cellType = cell.getCellType(); if(Cell.CELL_TYPE_NUMERIC == cellType){ // 数值类型的单元格 System.out.print(cell.getNumericCellValue() + ","); }else { // 从单元格取值 System.out.print(cell.getStringCellValue() + ","); } } System.out.println(); } // 关闭工作簿 workbook.close(); } } ``` MyJob_Annotation.java ```package com.tao.job; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; /** * @author:诸子争鸣 * @DATE:2021/1/9 16:32 */ @Component public class MyJob_Annotation { private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * Scheduled 指定触发的时机, 代替jobDetail,trigger * 注解所在的对象 targetObject * 注解所在的方法 targetMethod * * cron = "0/2 * * * * ?" 定时 * 错过了时间点不再执行,会等待下一次执行 * * 每间隔多长时间执行,什么时候启动,间隔时间后就执行 * cron CronTrigger */ // @Scheduled(cron = "0/2 * * * * ?") /** * SimpleTrigger * initialDelay 启动后延迟执行,单位为ms 3000 3秒 * fixedDelay: 间隔周期时间 60000 1分钟 6000 6秒 */ @Scheduled(initialDelay = 3000,fixedDelay = 10000) public void abc() { System.out.println("使用普通触发模式:" + sdf.format(new Date())); } } ``` OrderSettingController.java ```package com.tao.health.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.tao.health.constant.MessageConstant; import com.tao.health.entity.Result; import com.tao.health.pojo.OrderSetting; import com.tao.health.service.OrderSettingService; import com.tao.health.utils.POIUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @author:诸子争鸣 * @DATE:2021/1/9 18:04 * */ @RestController @RequestMapping("/ordersetting") public class OrderSettingController { private static final Logger log = LoggerFactory.getLogger(OrderSettingController.class); @Reference private OrderSettingService orderSettingService; /** * 批量导入预约设置 * * @param excelFile * @return */ @PostMapping("/upload") public Result upload(MultipartFile excelFile) { //批量上传:是一个list<string[]>,现在需要将这个转换为javabean //解析excel文件:调用POIUtils解析文件,得到List<string[]>,每一个数组就代表一行记录 try { List<String[]> excelData = POIUtils.readExcel(excelFile); log.debug("导入预约设置读取到了{}条记录", excelData.size()); //转成List<Ordersetting>,再调用service方法做导入,返回给页面 //string[]:中有两个元素:0:日期;1:可预约人数 final SimpleDateFormat sdf = new SimpleDateFormat(POIUtils.DATE_FORMAT); List<OrderSetting> orderSettingList = excelData.stream().map(arr -> { OrderSetting os = new OrderSetting(); try { os.setOrderDate(sdf.parse(arr[0])); os.setNumber(Integer.valueOf(arr[1])); } catch (ParseException e) { } //这步是将设置好的os返回到List<OrderSetting> return os; }).collect(Collectors.toList()); //调用服务 orderSettingService.addBatch(orderSettingList); return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS); } catch (IOException e) { e.printStackTrace(); log.error("导入预约设置失败",e); return new Result(false,MessageConstant.IMPORT_ORDERSETTING_FAIL); } } /** * 查询这个月的预约设置信息 * @return */ @GetMapping("/getOrderSettingByMonth") public Result getOrderSettingByMonth(String month){ List<Map<String,Integer>>data=orderSettingService.getOrderSettingByMonth(month); return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,data); } /** * 通过日期设置可预约的最大数 * @param orderSetting * @return */ @PostMapping("/editNumberByDate") public Result editNumberByDate(@RequestBody OrderSetting orderSetting){ //调用服务,进行更新 orderSettingService.editNumberByDate(orderSetting); return new Result(true,MessageConstant.ORDERSETTING_SUCCESS); } } ``` CheckItemController.java ```package com.tao.health.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.tao.health.constant.MessageConstant; import com.tao.health.entity.PageResult; import com.tao.health.entity.QueryPageBean; import com.tao.health.entity.Result; import com.tao.health.pojo.CheckItem; import com.tao.health.service.CheckItemService; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author:诸子争鸣 * @DATE:2021/1/5 19:34 */ @RestController @RequestMapping("/checkitem") public class CheckItemController { /** * 订阅检查项服务 */ @Reference private CheckItemService checkItemService; /** * 查询所有 * * @return */ @GetMapping("/findAll") public Result findAll() { List<CheckItem> checkItemList = checkItemService.findAll(); //封装到rusult再返回 return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS, checkItemList); } /** * 添加检查项 * * @param checkItem * @return */ @PostMapping("/add") public Result add(@RequestBody CheckItem checkItem) { checkItemService.add(checkItem); return new Result(true, MessageConstant.ADD_CHECKGROUP_SUCCESS); } /** * 分页条件查询 * @param queryPageBean * @return */ @PostMapping("/findPage") public Result findPage(@RequestBody QueryPageBean queryPageBean) { //调用服务进行分页查询 //这个描述当前集合中只能存储CheckItem检查项 PageResult<CheckItem> pageResult = checkItemService.findPage(queryPageBean); //返回给页面,包装到Result对象。 return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS, pageResult); } /** * 编辑检查项根据id回显 * @param id * @return */ @GetMapping("/findById") public Result findById(int id){ //调用服务,根据id查询检查项 CheckItem checkItem= checkItemService.findById(id); return new Result(true,MessageConstant.QUERY_CHECKITEM_SUCCESS,checkItem); } /** * 编辑检查项 * @param checkItem * @return */ @PostMapping("/update") public Result update(@RequestBody CheckItem checkItem){ //调用服务,执行编辑检查项 checkItemService.update(checkItem); return new Result(true,MessageConstant.EDIT_CHECKITEM_SUCCESS); } /** * 根据id删除检查项 * @param id * @return */ @PostMapping("/deleteById") public Result deleteById(int id){ //调用服务,根据id删除检查项 checkItemService.deleteById(id); return new Result(true,MessageConstant.DELETE_CHECKITEM_SUCCESS); } } ``` OrderSettingDao.java ```package com.tao.health.dao; import com.tao.health.pojo.OrderSetting; import java.util.Date; import java.util.List; import java.util.Map; /** * @author:诸子争鸣 * @DATE:2021/1/9 19:42 */ public interface OrderSettingDao { /** * 通过预约的日期来查询预约设置表 * @param orderDate * @return */ OrderSetting findByOrderDate(Date orderDate); /** * 调用dao插入数据 * @param os */ void add(OrderSetting os); /** *更新最大预约数 * @param os */ void updateNumber(OrderSetting os); /** * 查询这个月的预约设置信息 * @param month * @return */ List<Map<String, Integer>> getOrderSettingByMonth(String month); /** * 更新已预约人数 * @param osInDB * @return */ int editReservationsByOrderDate(OrderSetting osInDB); } ``` WriteExcel.java ```package com.tao.poi; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.Test; import java.io.File; import java.io.FileOutputStream; /** * @author:诸子争鸣 * @DATE:2021/1/9 17:36 */ public class WriteExcel { @Test public void createExcel() throws Exception { // 创建工作簿,内存中 Workbook workbook = new XSSFWorkbook(); // 创建工作表 Sheet sht = workbook.createSheet("测试写excel"); // 在工作表下创建行 Row row = sht.createRow(0);// 行的下标是从0开始 // 使用行创建单元格 Cell cell = row.createCell(0);// 单元格的下标也是从0开始, 多个单元格合并后成为1个单元格 // 给单元格赋值 // 表头 cell.setCellValue("姓名"); row.createCell(1).setCellValue("年龄"); row.createCell(2).setCellValue("所在地"); row = sht.createRow(1); row.createCell(0).setCellValue("小明"); row.createCell(1).setCellValue(20); row.createCell(2).setCellValue("北京"); row = sht.createRow(2); row.createCell(0).setCellValue("小李"); row.createCell(1).setCellValue(30); row.createCell(2).setCellValue("南京"); // 保存工作簿,持久化本地硬盘里 workbook.write(new FileOutputStream(new File("d:\\createExcel.xlsx"))); // 关闭工作簿 workbook.close(); } } ``` SetmealService.java ```package com.tao.health.service; import com.tao.health.entity.PageResult; import com.tao.health.entity.QueryPageBean; import com.tao.health.pojo.Setmeal; import java.util.List; /** * @author:诸子争鸣 * @DATE:2021/1/8 19:49 */ public interface SetmealService { /** * 添加套餐 * @param setmeal * @param checkgroupIds * @return */ Integer add(Setmeal setmeal, Integer[] checkgroupIds); /** * 分页条件查询 * @return */ PageResult<Setmeal> findPage(QueryPageBean queryPageBean); /** * 根据id查询套餐 * @param id * @return */ Setmeal findById(int id); /** * 根据套餐id查询选中的检查组id集合 * @param id * @return */ List<Integer> findCheckGroupIdsBySetmealId(int id); /** * 修改套餐 * @param setmeal * @param checkgroupIds */ void update(Setmeal setmeal, Integer[] checkgroupIds); /** * 通过id删除套餐 * @param id */ void deleteById(int id); /** * 查出数据库中的所有图片 * @return */ List<String> findImgs(); /** * 查询所有 * @return */ List<Setmeal> findAll(); /** * 根据套餐id查询套餐详情 * @param id * @return */ Setmeal findDetailById(int id); } ``` MyJob.java ```package com.tao.job; import java.text.SimpleDateFormat; import java.util.Date; /** * @author:诸子争鸣 * @DATE:2021/1/9 16:11 * 自定义任务类 */ public class MyJob { private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public void abc(){ System.out.println(sdf.format(new Date())); } } ``` CheckItemDao.java ```package com.tao.health.dao; import com.github.pagehelper.Page; import com.tao.health.pojo.CheckItem; import java.util.List; /** * @author:诸子争鸣 * @DATE:2021/1/5 20:01 */ public interface CheckItemDao { /** * 查询所有 * @return */ List<CheckItem> findAll(); /** * 添加查询项 * @param checkItem */ void add(CheckItem checkItem); /** * 分页条件查询 * @param queryString * @return */ Page<CheckItem> findByCondition(String queryString); /** * 编辑检查项根据id回显 * @param id * @return */ CheckItem findById(int id); /** * 编辑检查项 * @param checkItem */ void update(CheckItem checkItem); /** * 统计检查项被使用的次数 * @param id * @return */ int findCountByCheckItemId(int id); /** * 根据id删除检查项 * @param id */ void deleteById(int id); } ``` CheckGroupController.java ```package com.tao.health.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.tao.health.constant.MessageConstant; import com.tao.health.entity.PageResult; import com.tao.health.entity.QueryPageBean; import com.tao.health.entity.Result; import com.tao.health.pojo.CheckGroup; import com.tao.health.pojo.CheckItem; import com.tao.health.service.CheckGroupService; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author:诸子争鸣 * @DATE:2021/1/7 14:41 */ @RestController @RequestMapping("/checkgroup") public class CheckGroupController { @Reference private CheckGroupService checkGroupService; /** * 添加检查组信息 * * @param checkGroup 检查组信息 * @param checkitemIds 选中的检查项id数组 */ @PostMapping("/add") public Result add(@RequestBody CheckGroup checkGroup, Integer[] checkitemIds) { checkGroupService.add(checkGroup, checkitemIds); return new Result(true, MessageConstant.ADD_CHECKGROUP_SUCCESS); } /** * 分页条件查询 * * @param queryPageBean * @return */ @PostMapping("/findPage") public Result findPage(@RequestBody QueryPageBean queryPageBean) { //调用服务进行分页查询 //这个描述当前集合中只能存储CheckItem检查项 PageResult<CheckItem> pageResult = checkGroupService.findPage(queryPageBean); //返回给页面,包装到Result对象。 return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS, pageResult); } /** * 编辑检查组根据id回显数据 * * @param id * @return */ @GetMapping("/findById") public Result findById(int id) { CheckGroup checkGroup = checkGroupService.findById(id); return new Result(true, MessageConstant.EDIT_CHECKGROUP_SUCCESS, checkGroup); } /** * 通过检查组id查询绑定检查项id * * @param id * @return */ @GetMapping("/findCheckItemIdsByCheckGroupId") public Result findCheckItemIdsByCheckGroupId(int id) { List<Integer> checkItemIds = checkGroupService.findCheckItemIdsByCheckGroupId(id); return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS, checkItemIds); } /** * 修改检查组 * * @param checkGroup * @param checkitemIds * @return */ @PostMapping("/update") public Result update(@RequestBody CheckGroup checkGroup, Integer[] checkitemIds) { checkGroupService.update(checkGroup, checkitemIds); return new Result(true, MessageConstant.EDIT_CHECKGROUP_SUCCESS); } /** * 根据id删除检查组 * @param id * @return */ @PostMapping("/deleteById") public Result deleteById(int id) { checkGroupService.deleteById(id); return new Result(true,MessageConstant.DELETE_CHECKGROUP_SUCCESS); } /** * 查询所有的检查组 * @return */ @GetMapping("/findAll") public Result findAll(){ List<CheckGroup>list=checkGroupService.findAll(); return new Result(true,MessageConstant.QUERY_CHECKGROUP_SUCCESS,list); } } ``` OrderSettingService.java ```package com.tao.health.service; import com.tao.health.pojo.OrderSetting; import java.util.List; import java.util.Map; /** * @author:诸子争鸣 * @DATE:2021/1/9 19:21 */ public interface OrderSettingService { /** * 批量导入预约设置 * @param orderSettingList */ void addBatch(List<OrderSetting> orderSettingList); /** * 查询这个月的预约设置信息 * @param month * @return */ List<Map<String, Integer>> getOrderSettingByMonth(String month); /** * 通过日期设置可预约的最大数 * @param orderSetting */ void editNumberByDate(OrderSetting orderSetting); } ``` CheckGroupService.java ```package com.tao.health.service; import com.tao.health.entity.PageResult; import com.tao.health.entity.QueryPageBean; import com.tao.health.pojo.CheckGroup; import com.tao.health.pojo.CheckItem; import java.util.List; /** * @author:诸子争鸣 * @DATE:2021/1/7 14:48 */ public interface CheckGroupService { /** * 添加检查组信息 * @param checkGroup 检查组信息 * @param checkitemIds 选中的检查项id */ void add(CheckGroup checkGroup, Integer[] checkitemIds); /** * 分页条件查询 * @param queryPageBean * @return */ PageResult<CheckItem> findPage(QueryPageBean queryPageBean); /** * 编辑检查组根据id回显数据 * @param id * @return */ CheckGroup findById(int id); /** * 编辑检查组 * @param checkGroup * @param checkitemIds */ void update(CheckGroup checkGroup, Integer[] checkitemIds); /** * 通过检查组id查询绑定检查项id * * @param id * @return */ List<Integer> findCheckItemIdsByCheckGroupId(Integer id); /** * 根据id删除检查组 * @param id */ void deleteById(int id); /** * 查询所有检查组 * @return */ List<CheckGroup> findAll(); } ``` CheckGroupServiceImpl.java ```package com.tao.health.service.impl; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.tao.health.dao.CheckGroupDao; import com.tao.health.entity.PageResult; import com.tao.health.entity.QueryPageBean; import com.tao.health.exception.MyException; import com.tao.health.pojo.CheckGroup; import com.tao.health.pojo.CheckItem; import com.tao.health.service.CheckGroupService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @author:诸子争鸣 * @DATE:2021/1/7 14:49 */ @Service(interfaceClass = CheckGroupService.class) public class CheckGroupServiceImpl implements CheckGroupService { @Autowired private CheckGroupDao checkGroupDao; /** * 添加检查组信息 * * @param checkGroup 检查组信息 * @param checkitemIds 选中的检查项id */ @Override //添加事务控制 @Transactional public void add(CheckGroup checkGroup, Integer[] checkitemIds) { //先添加检查组的信息 checkGroupDao.add(checkGroup); //- 获取检查组的id Integer checkgroupId = checkGroup.getId(); //在添加检查项的信息 if (checkitemIds != null) { for (Integer checkitemId : checkitemIds) { //添加检查组的检查项信息 checkGroupDao.addCheckGroupCheckItem(checkgroupId, checkitemId); } } } /** * 分页条件查询 * @param queryPageBean * @return */ @Override public PageResult<CheckItem> findPage(QueryPageBean queryPageBean) { //第二种,Mapper接口方式的调用,推荐这种使用方式。 PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()); //模糊查询 拼接% //判断是否有查询条件--这里使用的这个方法导致耽误了许久。写成了isEmpty if (!StringUtils.isEmpty(queryPageBean.getQueryString())) { //有查询条件,拼接% queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%"); } //查询语句会被分页 Page<CheckItem> page=checkGroupDao.findByCondition(queryPageBean.getQueryString()); PageResult<CheckItem> pageResult = new PageResult<CheckItem>(page.getTotal(), page.getResult()); return pageResult; } /** * 编辑检查组根据id回显数据 * @param id * @return */ @Override public CheckGroup findById(int id) { return checkGroupDao.findById(id); } /** * 编辑检查组 * @param checkGroup * @param checkitemIds */ @Override @Transactional public void update(CheckGroup checkGroup, Integer[] checkitemIds) { //- 先更新检查组 checkGroupDao.update(checkGroup); //- 先删除旧关系 checkGroupDao.deleteCheckGroupCheckItem(checkGroup.getId()); //- 遍历选中的检查项id的数组 if(null != checkitemIds){ for (Integer checkitemId : checkitemIds) { //- 添加检查组与检查项的关系 checkGroupDao.addCheckGroupCheckItem(checkGroup.getId(), checkitemId); } } //- 添加事务控制 } /** * 通过检查组id查询绑定检查项id * @param id * @return */ @Override public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) { return checkGroupDao.findCheckItemIdsByCheckGroupId(id); } /** * 根据id删除检查组 * @param id */ @Override @Transactional public void deleteById(int id) { //查询该检查组是否被套餐使用 int count= checkGroupDao.findCountByCheckGroupId(id); if (count !=0) { //若是有则不能删除,需要抛出自定义异常 throw new MyException("该检查组已被套餐调用,不能删除"); } //若没有使用则可以调用方法进行删除 //先删除检查项与检查组的关系 checkGroupDao.deleteCheckGroupCheckItem(id); //再删除该检查组 checkGroupDao.deleteById(id); } /** * 查询所有检查组 * @return */ @Override public List<CheckGroup> findAll() { return checkGroupDao.findAll(); } } ``` CheckItemServiceImpl.java ```package com.tao.health.service.impl; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.tao.health.dao.CheckItemDao; import com.tao.health.entity.PageResult; import com.tao.health.entity.QueryPageBean; import com.tao.health.exception.MyException; import com.tao.health.pojo.CheckItem; import com.tao.health.service.CheckItemService; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; /** * @author:诸子争鸣 * @DATE:2021/1/5 19:56 */ /** * 检查项服务,发布服务,interfaceClass指定服务的接口类 */ @Service(interfaceClass =CheckItemService.class ) public class CheckItemServiceImpl implements CheckItemService { @Autowired private CheckItemDao checkItemDao; /** * 查询所有 * @return */ @Override public List<CheckItem> findAll() { return checkItemDao.findAll(); } /** * 添加查询项 * @param checkItem */ @Override public void add(CheckItem checkItem) { checkItemDao.add(checkItem); } /** * 分页条件查询 * @param queryPageBean * @return */ @Override public PageResult<CheckItem> findPage(QueryPageBean queryPageBean) { //第二种,Mapper接口方式的调用,推荐这种使用方式。 PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()); //模糊查询 拼接% //判断是否有查询条件--这里使用的这个方法导致耽误了许久。写成了isEmpty if (!StringUtils.isEmpty(queryPageBean.getQueryString())) { //有查询条件,拼接% queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%"); } //查询语句会被分页 Page<CheckItem>page=checkItemDao.findByCondition(queryPageBean.getQueryString()); PageResult<CheckItem> pageResult = new PageResult<CheckItem>(page.getTotal(), page.getResult()); return pageResult; } /** * 编辑检查项根据id回显 * @param id * @return */ @Override public CheckItem findById(int id) { return checkItemDao.findById(id); } /** * 编辑检查项 * @param checkItem */ @Override public void update(CheckItem checkItem) { checkItemDao.update(checkItem); } /** * 根据id删除检查项 * @param id */ @Override public void deleteById(int id) { //调用dao查询 统计这个检查项id被使用的个数 int count=checkItemDao.findCountByCheckItemId(id); if (count>0) { //个数>0 说明被检查组使用了,不能删除,抛出自定义异常。【注意】接口方法要声明抛出异常类型 throw new MyException("该检查项已被使用,不能删除!!"); } //个数=0,则调用dao删除 checkItemDao.deleteById(id); } } ``` CheckGroupDao.java ```package com.tao.health.dao; import com.github.pagehelper.Page; import com.tao.health.pojo.CheckGroup; import com.tao.health.pojo.CheckItem; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author:诸子争鸣 * @DATE:2021/1/7 14:52 */ public interface CheckGroupDao { /** * 添加检查组 * @param checkGroup 检查组信息 * */ void add(CheckGroup checkGroup); /** * 添加检查组中的检查项 * @param checkgroupId * @param checkitemId */ void addCheckGroupCheckItem(@Param("checkgroupId") Integer checkgroupId, @Param("checkitemId") Integer checkitemId); /** * 分页条件查询 * @param queryString * @return */ Page<CheckItem> findByCondition(String queryString); /** * 编辑检查组根据id回显数据 * @param id */ CheckGroup findById(int id); /** * 更新检查组信息 * @param checkGroup */ void update(CheckGroup checkGroup); /** * 删除旧的关系 * @param id */ void deleteCheckGroupCheckItem(Integer id); /** * 通过检查组id查询绑定检查项id * @param id * @return */ List<Integer> findCheckItemIdsByCheckGroupId(Integer id); /** * 查询该检查组是否被套餐使用 * @param id * @return */ int findCountByCheckGroupId(int id); /** * 调用方法进行删除检查组 * @param id */ void deleteById(int id); /** * 查询所有检查组 * @return */ List<CheckGroup> findAll(); } ```
zhw2590582/mini-speed-chart
zhw2590582/mini-speed-chart miniSpeedChart-uncompiled.js ```(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.MiniSpeedChart = factory()); }(this, function () { 'use strict'; function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } var arrayWithoutHoles = _arrayWithoutHoles; function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } var iterableToArray = _iterableToArray; function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } var nonIterableSpread = _nonIterableSpread; function _toConsumableArray(arr) { return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread(); } var toConsumableArray = _toConsumableArray; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var defineProperty = _defineProperty; function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { defineProperty(target, key, source[key]); }); } return target; } var objectSpread = _objectSpread; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var classCallCheck = _classCallCheck; function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var createClass = _createClass; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var detectConnectionSpeed = createCommonjsModule(function (module, exports) { !function(e,t){module.exports=t();}(commonjsGlobal,function(){var o=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e};var n=function(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(e){o(t,e,n[e]);});}return t};var r=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")};function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r);}}var e=function(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e};var t=null;function s(e,a,u){return fetch(e).then(function(e){t=e.body.getReader(),function i(){var s=Date.now();t.read().then(function(e){var t=e.done,n=e.value;if(t)u();else{var r=Date.now()-s,o=new Uint8Array(n).byteLength;a(o,r),i();}}).catch(function(e){throw e});}();}),{destroy:function(){t&&t.cancel();}}}var u=null;function a(e,r,t){(u=new XMLHttpRequest).open("GET",e,!0),u.responseType="moz-chunked-arraybuffer";var o=null,n=function(){var e=Date.now(),t=e-o,n=new Uint8Array(u.response).byteLength;r(n,t),o=e;},i=function(){2===u.readyState&&(o=Date.now());},s=function(){t();},a=function e(){throw e};return u.addEventListener("progress",n),u.addEventListener("readystatechange",i),u.addEventListener("loadend",s),u.addEventListener("error",a),u.send(),{destroy:function(){u&&(u.abort(),u.removeEventListener("progress",n),u.removeEventListener("readystatechange",i),u.removeEventListener("loadend",s),u.removeEventListener("error",a));}}}function c(){if("undefined"!=typeof Response&&Object.prototype.hasOwnProperty.call(Response.prototype,"body")&&"function"==typeof Headers)return s;if(function(e){try{var t=new XMLHttpRequest;return t.responseType=e,t.responseType===e}catch(e){return !1}}("moz-chunked-arraybuffer"))return a;throw new Error("Your browser does not currently support stream factory")}return function(){function t(e){r(this,t),this.option=n({url:"",loop:!0,detectCallback:function(e){return e}},e),this.loopTimer=null,this.stream=null,this.seconds=[],this.calculateSecond=0,this.streamFactory=c(),this.detectStartTime=Date.now(),this.detect();}return e(t,[{key:"detect",value:function(){this.requestUrl=this.option.url+"?time="+Date.now(),this.stream=this.streamFactory(this.requestUrl,this.updateCallback.bind(this),this.doneCallback.bind(this));}},{key:"updateCallback",value:function(e,t){var n={streamSize:e,streamTime:t},r=Math.ceil((Date.now()-this.detectStartTime)/1e3);this.seconds[r]?this.seconds[r].push(n):(this.calculate(),this.seconds[r]=[n]);}},{key:"doneCallback",value:function(){this.option.loop&&(this.stream&&"function"==typeof this.stream.destroy&&this.stream.destroy(),this.detect());}},{key:"calculate",value:function(){var e=this.seconds[this.calculateSecond++]||[],t=this.resultSum(e,"streamTime")||0,n=this.resultSum(e,"streamSize")||0,r=n/t||0,o=r/1024;this.option.detectCallback({downloadTime:t,downloadSize:n,speedKbps:r,speedMbps:o});}},{key:"resultSum",value:function(e,n){return e.reduce(function(e,t){return e+t[n]},0)}},{key:"destroy",value:function(){this.option.loop=!1,this.loopTimer&&clearTimeout(this.loopTimer),this.stream&&"function"==typeof this.stream.destroy&&this.stream.destroy();}}]),t}()}); }); var MiniSpeedChart = /*#__PURE__*/ function () { function MiniSpeedChart(option) { classCallCheck(this, MiniSpeedChart); this.option = objectSpread({ canvas: '', url: '', width: 180, height: 20, backgroundColor: '#000', lineColor: '#4f0', lineWidth: 2, detectCallback: function detectCallback(result) { return result; } }, option); this.speeds = []; this.$canvas = document.querySelector(this.option.canvas); this.ctx = this.$canvas.getContext('2d'); this.style(); this.detect(); } createClass(MiniSpeedChart, [{ key: "style", value: function style() { this.$canvas.width = this.option.width; this.$canvas.height = this.option.height; this.$canvas.style.width = "".concat(this.option.width, "px"); this.$canvas.style.height = "".concat(this.option.height, "px"); this.$canvas.style.backgroundColor = this.option.backgroundColor; } }, { key: "detect", value: function detect() { var _this = this; this.detect = new detectConnectionSpeed({ url: this.option.url, detectCallback: function detectCallback(result) { if (_this.speeds.length * _this.option.lineWidth >= _this.option.width) { _this.speeds.shift(); } _this.speeds.push(Number(result.speedKbps.toFixed(2))); _this.draw(); _this.option.detectCallback(result); } }); } }, { key: "draw", value: function draw() { var _this2 = this; this.ctx.clearRect(0, 0, this.$canvas.width, this.$canvas.height); this.ctx.fillStyle = this.option.lineColor; var min = Math.min.apply(Math, toConsumableArray(this.speeds)); var max = Math.max.apply(Math, toConsumableArray(this.speeds)); var diff = max - min; var scale = diff / this.option.height; this.speeds.forEach(function (item, index) { var y = _this2.option.height - (item - min) / scale; var h = _this2.option.height - y; _this2.ctx.fillRect(index * _this2.option.lineWidth, y, _this2.option.lineWidth, h); }); } }, { key: "destroy", value: function destroy() { this.speeds = []; this.ctx.clearRect(0, 0, this.$canvas.width, this.$canvas.height); if (this.detect) { this.detect.destroy(); } } }]); return MiniSpeedChart; }(); return MiniSpeedChart; })); //# sourceMappingURL=miniSpeedChart-uncompiled.js.map ``` README.md ```# mini-speed-chart Detect connection speed with JavaScript ## Install Install with `npm` ``` $ npm install mini-speed-chart ``` Or install with `yarn` ``` $ yarn add mini-speed-chart ``` ```js import MiniSpeedChart from 'mini-speed-chart'; ``` Or umd builds are also available ```html <script src="path/to/miniSpeedChart.js"></script> ``` Will expose the global variable to `window.MiniSpeedChart`. ## Usage ```js // Init var chart = new MiniSpeedChart({ canvas: '', url: '', width: 180, height: 20, size: 2, backgroundColor: '#000', lineColor: '#4f0', detectCallback: result => result }); // Destroy chart.destroy(); ``` ## License MIT © [Harvey Zack](https://sleepy.im/) ``` miniSpeedChart.js ```!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).MiniSpeedChart=e()}(this,function(){"use strict";var e=function(t){if(Array.isArray(t)){for(var e=0,n=new Array(t.length);e<t.length;e++)n[e]=t[e];return n}};var n=function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)};var o=function(){throw new TypeError("Invalid attempt to spread non-iterable instance")};var t=function(t){return e(t)||n(t)||o()};var r=function(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t};var i=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},o=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(n).filter(function(t){return Object.getOwnPropertyDescriptor(n,t).enumerable}))),o.forEach(function(t){r(e,t,n[t])})}return e};var a=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")};function s(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var c=function(t,e,n){return e&&s(t.prototype,e),n&&s(t,n),t};"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var u,l=(function(t,e){t.exports=function(){function o(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}var e=null;function n(t,s,c){return fetch(t).then(function(t){e=t.body.getReader(),function i(){var a=Date.now();e.read().then(function(t){var e=t.done,n=t.value;if(e)c();else{var o=Date.now()-a,r=new Uint8Array(n).byteLength;s(r,o),i()}}).catch(function(t){throw t})}()}),{destroy:function(){e&&e.cancel()}}}var c=null;function r(t,o,e){(c=new XMLHttpRequest).open("GET",t,!0),c.responseType="moz-chunked-arraybuffer";var r=null,n=function(){var t=Date.now(),e=t-r,n=new Uint8Array(c.response).byteLength;o(n,e),r=t},i=function(){2===c.readyState&&(r=Date.now())},a=function(){e()},s=function t(){throw t};return c.addEventListener("progress",n),c.addEventListener("readystatechange",i),c.addEventListener("loadend",a),c.addEventListener("error",s),c.send(),{destroy:function(){c&&(c.abort(),c.removeEventListener("progress",n),c.removeEventListener("readystatechange",i),c.removeEventListener("loadend",a),c.removeEventListener("error",s))}}}return function(){function e(t){(function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")})(this,e),this.option=function(r){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{},e=Object.keys(i);"function"==typeof Object.getOwnPropertySymbols&&(e=e.concat(Object.getOwnPropertySymbols(i).filter(function(t){return Object.getOwnPropertyDescriptor(i,t).enumerable}))),e.forEach(function(t){var e,n,o;e=r,o=i[n=t],n in e?Object.defineProperty(e,n,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[n]=o})}return r}({url:"",loop:!0,detectCallback:function(t){return t}},t),this.loopTimer=null,this.stream=null,this.seconds=[],this.calculateSecond=0,this.streamFactory=function(){if("undefined"!=typeof Response&&Object.prototype.hasOwnProperty.call(Response.prototype,"body")&&"function"==typeof Headers)return n;if(function(t){try{var e=new XMLHttpRequest;return e.responseType=t,e.responseType===t}catch(t){return!1}}("moz-chunked-arraybuffer"))return r;throw new Error("Your browser does not currently support stream factory")}(),this.detectStartTime=Date.now(),this.detect()}return function(t,e,n){e&&o(t.prototype,e),n&&o(t,n)}(e,[{key:"detect",value:function(){this.requestUrl=this.option.url+"?time="+Date.now(),this.stream=this.streamFactory(this.requestUrl,this.updateCallback.bind(this),this.doneCallback.bind(this))}},{key:"updateCallback",value:function(t,e){var n={streamSize:t,streamTime:e},o=Math.ceil((Date.now()-this.detectStartTime)/1e3);this.seconds[o]?this.seconds[o].push(n):(this.calculate(),this.seconds[o]=[n])}},{key:"doneCallback",value:function(){this.option.loop&&(this.stream&&"function"==typeof this.stream.destroy&&this.stream.destroy(),this.detect())}},{key:"calculate",value:function(){var t=this.seconds[this.calculateSecond++]||[],e=this.resultSum(t,"streamTime")||0,n=this.resultSum(t,"streamSize")||0,o=n/e||0,r=o/1024;this.option.detectCallback({downloadTime:e,downloadSize:n,speedKbps:o,speedMbps:r})}},{key:"resultSum",value:function(t,n){return t.reduce(function(t,e){return t+e[n]},0)}},{key:"destroy",value:function(){this.option.loop=!1,this.loopTimer&&clearTimeout(this.loopTimer),this.stream&&"function"==typeof this.stream.destroy&&this.stream.destroy()}}]),e}()}()}(u={exports:{}},u.exports),u.exports);return function(){function e(t){a(this,e),this.option=i({canvas:"",url:"",width:180,height:20,backgroundColor:"#000",lineColor:"#4f0",lineWidth:2,detectCallback:function(t){return t}},t),this.speeds=[],this.$canvas=document.querySelector(this.option.canvas),this.ctx=this.$canvas.getContext("2d"),this.style(),this.detect()}return c(e,[{key:"style",value:function(){this.$canvas.width=this.option.width,this.$canvas.height=this.option.height,this.$canvas.style.width="".concat(this.option.width,"px"),this.$canvas.style.height="".concat(this.option.height,"px"),this.$canvas.style.backgroundColor=this.option.backgroundColor}},{key:"detect",value:function(){var e=this;this.detect=new l({url:this.option.url,detectCallback:function(t){e.speeds.length*e.option.lineWidth>=e.option.width&&e.speeds.shift(),e.speeds.push(Number(t.speedKbps.toFixed(2))),e.draw(),e.option.detectCallback(t)}})}},{key:"draw",value:function(){var r=this;this.ctx.clearRect(0,0,this.$canvas.width,this.$canvas.height),this.ctx.fillStyle=this.option.lineColor;var i=Math.min.apply(Math,t(this.speeds)),a=(Math.max.apply(Math,t(this.speeds))-i)/this.option.height;this.speeds.forEach(function(t,e){var n=r.option.height-(t-i)/a,o=r.option.height-n;r.ctx.fillRect(e*r.option.lineWidth,n,r.option.lineWidth,o)})}},{key:"destroy",value:function(){this.speeds=[],this.ctx.clearRect(0,0,this.$canvas.width,this.$canvas.height),this.detect&&this.detect.destroy()}}]),e}()}); ``` index.js ```import DetectConnectionSpeed from 'detect-connection-speed'; export default class MiniSpeedChart { constructor(option) { this.option = { canvas: '', url: '', width: 180, height: 20, backgroundColor: '#000', lineColor: '#4f0', lineWidth: 2, detectCallback: result => result, ...option }; this.speeds = []; this.$canvas = document.querySelector(this.option.canvas); this.ctx = this.$canvas.getContext('2d'); this.style(); this.detect(); } style() { this.$canvas.width = this.option.width; this.$canvas.height = this.option.height; this.$canvas.style.width = `${this.option.width}px`; this.$canvas.style.height = `${this.option.height}px`; this.$canvas.style.backgroundColor = this.option.backgroundColor; } detect() { this.detect = new DetectConnectionSpeed({ url: this.option.url, detectCallback: result => { if (this.speeds.length * this.option.lineWidth >= this.option.width) { this.speeds.shift(); } this.speeds.push(Number(result.speedKbps.toFixed(2))); this.draw(); this.option.detectCallback(result); } }); } draw() { this.ctx.clearRect(0, 0, this.$canvas.width, this.$canvas.height); this.ctx.fillStyle = this.option.lineColor; const min = Math.min(...this.speeds); const max = Math.max(...this.speeds); const diff = max - min; const scale = diff / this.option.height; this.speeds.forEach((item, index) => { const y = this.option.height - (item - min) / scale; const h = this.option.height - y; this.ctx.fillRect(index * this.option.lineWidth, y, this.option.lineWidth, h); }); } destroy() { this.speeds = []; this.ctx.clearRect(0, 0, this.$canvas.width, this.$canvas.height); if (this.detect) { this.detect.destroy(); } } } ```
zhxjz/LipstickTest
zhxjz/LipstickTest ok(cy-4-23).py ```# encoding:utf-8 from collections import deque import dlib import numpy as np import cv2 # 4/18 cy: # 将像素遍历范围缩小至嘴唇所在的矩形 # # 下一步:探究bfs(魔棒法)在边缘部分的可行性? def rect_to_bb(rect): # [psy]:获得人脸矩形的坐标信息 x = rect.left() y = rect.top() w = rect.right() - x h = rect.bottom() - y return x, y, w, h def shape_to_np(shape, dtype="int"): # [psy]:将包含68个特征的的shape转换为numpy array格式 coords = np.zeros((68, 2), dtype=dtype) for i in range(0, 68): coords[i] = (shape.part(i).x, shape.part(i).y) return coords def resize(image, width=600): # [psy]:将待检测的image进行resize r = width * 1.0 / image.shape[1] dim = (width, int(image.shape[0] * r)) resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA) return resized def getbgr(image, xx, yy): bb = 0 gg = 0 rr = 0 bgr = image[yy, xx] for ii in range(-1, 1): for jj in range(-1, 1): if ii == 0 and jj == 0: continue tx = xx + ii ty = yy + jj tbgr = image[ty, tx] bb += tbgr[0] gg += tbgr[1] rr += tbgr[2] bb = int(bb / 8 / 3 + bgr[0] / 3 * 2) gg = int(gg / 8 / 3 + bgr[1] / 3 * 2) rr = int(rr / 8 / 3 + bgr[2] / 3 * 2) print(bb, gg, rr) return bgr def bfs(image, edge_list, convex): que = deque() dis = np.zeros((image.shape[0], image.shape[1]), dtype=int) for node in edge_list: que.append((node[0], node[1])) dis[node[0], node[1]] = -10 cc = 0 while que: cc += 1 now = que.popleft() # nbgr = image[now[1], now[0]] if dis[now[0], now[1]] + 1 < 0: for xx in range(-1, 1): for yy in range(-1, 1): ty = yy + now[1] tx = xx + now[0] if cv2.pointPolygonTest(convex, (tx, ty), False) < 0: if dis[tx, ty] > dis[now[0], now[1]] + 1: dis[tx, ty] = dis[now[0], now[1]] + 1 tbgr = image[ty, tx] if tbgr[0] + 40 < 255: image[ty, tx][0] = tbgr[0] + 40 if tbgr[1] - 10 < 255: image[ty, tx][1] = tbgr[1] - 10 if tbgr[2] - 10 < 255: image[ty, tx][2] = tbgr[2] - 10 if (tx, ty) not in que: que.append((tx, ty)) print(cc) return image def outside_edge_judge(x, y, d1, d2, edgelist, threshold, img): # [cy]:边缘点判断函数 a1 = 1 if -threshold <= d1 <= threshold else 0 a2 = 1 if -threshold <= d2 <= threshold else 0 if a1 + a2 == 1: edgelist.append([y, x]) # img[y, x] = [0, 0, 255] return True return False def inside_edge_judge(x, y, d1, edgelist, threshold, img): a = 1 if -threshold <= d1 <= threshold else 0 if a == 1: edgelist.append([y, x]) return True return False def mouth_area_rect(points): # [cy]:获取嘴唇像素的矩形 mins = points.min(axis=0) maxs = points.max(axis=0) return mins[0], maxs[0] + 1, mins[1], maxs[1] + 1 def most_frequently_hsv(img, array): # [cy]:获取嘴唇内部像素出现最多的点坐标 arr = [] for pixel in array: yy = pixel[0] xx = pixel[1] ph = img[yy, xx][0] ps = img[yy, xx][1] pv = img[yy, xx][2] arr.append([ph, ps, pv]) arr = np.array(arr) h = np.argmax(np.bincount(arr[:, 0])) s = np.argmax(np.bincount(arr[:, 1])) v = np.argmax(np.bincount(arr[:, 2])) return int(h), int(s), int(v) def color_delta(c1, c2): c1 = np.array(c1) c2 = np.array(c2) delta = c1 - c2 return np.max(delta) - np.min(delta) def exact_lip_points(img, all_points, color): # [cy]:在给定坐标的像素们中筛选出与color相近的像素的坐标们 color = np.array(color) exact_points = [] delta = 20 for pixel in all_points: pixel_hsv = np.array(img[pixel[0], pixel[1]]) # [cy]:某点的hsv像素值 if color_delta(color, pixel_hsv) < delta: # [cy]:与参考色color的色差 exact_points.append(pixel) return exact_points def side_edge_move(edge_points_array, type, color, min_delta, max_delta, min_e, max_e, img): """嘴唇边缘移动 :param edge_points_array:边缘点 :param type:类型 'outside' 'inside' :param color:参照色 :param min_delta:逃离时的色差阈值(小于就逃离) :param max_delta:靠拢时的色差阈值(大于就靠拢) :param min_e:逃离嘴唇的最大距离 :param max_e:靠拢嘴唇的最大距离 :param img:图像 :return: """ res = {} rgb_color = (154, 107, 113) # color=(rgb_color[0]*180,rgb_color[1]*255,rgb_color[2]*255) if type == 'outside': type = 1 elif type == 'inside': type = -1 else: type = 0 # [cy]:首先找出每一列的两个边界点 [0]是上边界,[1]是下边界 for px in edge_points_array: x = px[1] y = px[0] if x in res.keys(): if y < res[x][0]: res[x][0] = y if y > res[x][1]: res[x][1] = y else: res[x] = [y, y] # [cy]:确保每列都有上下两个边界 for x, yrange in res.items(): if res[x][0] == res[x][1]: if x + 1 in res.keys(): res[x][0] = res[x + 1][0] res[x][1] = res[x + 1][1] else: res[x][0] = res[x - 1][0] res[x][1] = res[x - 1][1] # [cy]:遍历每个边界 if type != 0: for x, yrange in res.items(): direction = 0 if type == 1 else 1 upside_hsv = img[yrange[direction], x] # 外边缘是上边界,内边缘是下边界 e = 0 # 外边缘上边界在嘴唇,则向上逃离 # 内边缘下边界在嘴唇,也向上逃离 while color_delta(color, upside_hsv) - min_delta < 0 and e > -min_e: e -= 1 upside_hsv = img[yrange[direction] + e, x] # 外边缘上边界在外部,则向下靠拢 # 内边缘下边界在外部,也向下靠拢 while color_delta(color, upside_hsv) - max_delta > 0 and e < max_e: e += 1 upside_hsv = img[yrange[direction] + e, x] res[x][direction] = yrange[direction] + e direction = 1 - direction downside_hsv = img[yrange[direction], x] # 外边缘是下边界,内边缘是上边界 e = 0 # 外边缘下边界在嘴唇,则向下逃离 # 内边缘上边界在嘴唇,也向下逃离 while color_delta(color, downside_hsv) - min_delta < 0 and e < min_e: e += 1 downside_hsv = img[yrange[direction] + e, x] # 外边缘下边界在外部,则向上靠拢 # 内边缘上边界在外部,也向上靠拢 while color_delta(color, downside_hsv) - max_delta > 0 and e > -max_e: e += -1 downside_hsv = img[yrange[direction] + e, x] res[x][direction] = yrange[direction] + e return res def outline(res, img, color): for x, yrange in res.items(): img[yrange[0], x] = (0, 0, 0) img[yrange[1], x] = (0, 0, 255) def padding_inside_points(pts, edge_points): # 0,12为左侧两嘴角 # 6,16为右侧两嘴角 left_x1 = pts[0][0] left_x2 = pts[12][0] y = pts[12][1] for x in range(left_x1, left_x2): edge_points.append([y, x]) right_x1 = pts[16][0] right_x2 = pts[6][0] y = pts[16][1] for x in range(right_x1, right_x2): edge_points.append([y, x]) def feature(path, color, outside_tuple=(40, 50, 3, 2), inside_tuple=(90, 100, 3, 1)): (a1, a2, a3, a4) = outside_tuple (b1, b2, b3, b4) = inside_tuple detector = dlib.get_frontal_face_detector() # [cy]:人脸检测仪 predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # [cy]:关键点检测器 image = cv2.imread(path) # [cy]:读取 输入图像.jpg image = resize(image, width=600) # [cy]:缩放 图像,宽为1200 print(image.shape) # [cy]:image尺寸 (高,宽,3) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # [psy]:转为灰度图 # [cy]: # 传入灰度图像,检测出里面的所有脸,某张脸的矩形:rect=[(左上角坐标),(右下角坐标)] # OpenCV坐标 # (0,0) - (100,0) # | | # (0,100) - (100,100) rects = detector(gray, 1) # [psy]:灰度图里定位人脸 shapes = [] # [psy]:shapes存储找到的人脸框,人脸框仅包含四个角数值如frontal_face_detector.png所示。 for (i, rect) in enumerate(rects): # [cy]:遍历所有脸的方框 shape = predictor(gray, rect) # [cy]:用关键点检测器检测出关键点们 shape = shape_to_np(shape) # [cy]:关键点们变成numpy数组 shape = shape[48:] # [cy]:关键点[48-67]是嘴唇区域 shapes.append(shape) # [cy]:把这张脸的嘴唇关键点插入到shapes # [psy]: # 图片转为hsv形式,色调(H),饱和度(S),亮度(V) # H: 0 — 180 # S: 0 — 255 # V: 0 — 255 image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # [cy]: for shape in shapes: # [cy]:遍历每个嘴唇 # [cy]:获取嘴唇像素的矩形 xstart, xend, ystart, yend = mouth_area_rect(shape) # [cy]:图像的高与宽 # sx, sy = image.shape[0], image.shape[1] # [cy]:外嘴唇左半边凸包 hull_left = cv2.convexHull(np.concatenate((shape[0:4], shape[7:12]))) # [cy]:外嘴唇右半边凸包 hull_right = cv2.convexHull(shape[3:8]) # [psy]:内嘴唇凸包 hull_inside = cv2.convexHull(shape[12:]) # [cy]:嘴唇外边缘上的点 outside_edge_points = [] # [cy]:嘴唇内边缘上的点 inside_edge_points = [] # [cy]:嘴唇上的所有点 lip_points = [] for xx in range(xstart, xend): for yy in range(ystart, yend): # [cy]:获得(xx,yy)到左外凸包的距离,正数说明在内部,measureDist:是否返回准确距离 dist_left = cv2.pointPolygonTest(hull_left, (xx, yy), measureDist=True) # [cy]:获得(xx,yy)到右外凸包的距离,正数说明在内部,measureDist:是否返回准确距离 dist_right = cv2.pointPolygonTest(hull_right, (xx, yy), measureDist=True) # [cy]:获得(xx,yy)到内凸包的距离,正数说明在内部,measureDist:是否返回准确距离 dist_inside = cv2.pointPolygonTest(hull_inside, (xx, yy), measureDist=True) # [cy]:判断在外边缘则加入边缘点集 outside_edge_judge(xx, yy, dist_left, dist_right, outside_edge_points, 0.5, image) # [cy]:判断在内边缘则加入边缘点集 inside_edge_judge(xx, yy, dist_inside, inside_edge_points, 1, image) # [cy]:(在外嘴唇左凸包以内或在外嘴唇右凸包以内)且在内嘴唇凸包以外为嘴唇 if dist_left >= -0.5 or dist_right >= -0.5: if dist_inside < 20: lip_points.append([yy, xx]) often_color = most_frequently_hsv(image, lip_points) # [cy]:得到最频繁的颜色组合 outside_edge_points = side_edge_move(outside_edge_points, 'outside', often_color, a1, a2, a3, a4, image) padding_inside_points(shape, inside_edge_points) # [cy]:补齐内边缘点,以内嘴角和外嘴角之间为准 inside_edge_points = side_edge_move(inside_edge_points, 'inside', often_color, b1, b2, b3, b4, image) # cv2.rectangle(image, (xstart, ystart-100), (xend, yend-100), often_color, thickness=2) # [cy]:显示在图像上 for pixel in lip_points: yy = pixel[0] xx = pixel[1] on_lip = False if xx in inside_edge_points.keys(): if outside_edge_points[xx][0] < yy < inside_edge_points[xx][0] or \ inside_edge_points[xx][1] < yy < outside_edge_points[xx][1]: on_lip = True else: if outside_edge_points[xx][0] < yy < outside_edge_points[xx][1]: on_lip = True if on_lip: image[yy, xx][0] = color[0] image[yy, xx][1] = color[1] # image[yy, xx][2] += 10 # outline(outside_edge_points, image, often_color) # outline(inside_edge_points, image, often_color) # for pixel in exact_points: # yy = pixel[0] # xx = pixel[1] # image[yy, xx][0] = color[0] # image[yy, xx][1] = color[1] # image[yy, xx][2] = 255 # for pixel in shape: # xx = pixel[0] # yy = pixel[1] # image[yy, xx][0] = 0 # image[yy, xx][1] = 0 # image[yy, xx][2] = 255 image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR) # [cy]:重新将图像转为BGR格式 # image = cv2.GaussianBlur(image, (7, 7), 0) # [cy]:高斯模糊图像,我认为没有用处 # [cy]:可以查看凹多边形分成2个凸多边形 # shape=shapes[0] # polygon1 = np.concatenate((shape[0:4], shape[7:12])) # 48 49 50 51 55 56 57 58 59 # polygon2 = shape[3:8] # 51 52 53 54 55 # cv2.polylines(image, [polygon1], True, (0, 0, 0), 2) # cv2.polylines(image, [polygon2], True, (0, 0, 250), 2) return image def update(h,s): input_image_path = "test.jpg" # [cy]:输入图像.jpg lipstick_color = [h,s, 0] # [cy]:嘴唇颜色 image_output = feature(input_image_path, lipstick_color) # [cy]:处理图像 cv2.imshow("output", image_output) # [cy]:显示 输出图像2.jpg # cv2.imwrite("process222+" + input_image_path, image_output) # [cy]:保存 输出图像2.jpg # cv2.waitKey(0) def nothing(x): pass if __name__=="__main__": cv2.namedWindow('output') cv2.createTrackbar('H','output',25,50,nothing) cv2.createTrackbar('S', 'output', 150, 255, nothing) cv2.createTrackbar('on', 'output', 0, 1, nothing) while(1): h = cv2.getTrackbarPos('H','output')+155 if(h>180): h-=180 s = cv2.getTrackbarPos('S','output') tag = cv2.getTrackbarPos('on','output') if tag != 0: print(h,s) update(h,s) k = cv2.waitKey(1) & 0xFF4 if k == 27: break cv2.destroyAllWindows()``` Readme.md ```# LipstickTest口红试色项目 对人脸嘴唇区域进行模拟口红试色。 #### 目前实现情况【200426】 根据dlib的人脸关键点,提取出68个关键点,然后嘴唇区域作为凸包; 再判断点是否在嘴唇区域(外嘴唇凸包以内,内嘴唇凸包以外之间区域定义为嘴唇区域), 根据输入的口红hsv值进行嘴唇凸包区域染色。 添加了UI选择H、S界面。 进行了边缘自然化处理,根据出现最多的像素点进行边缘细节处理,将外嘴唇区域细分为左右两个凸包(ok(cy-4-23).py)。 #### 项目陈述: 本科期间的创新创业项目,项目动机是个人对口红的狂热购买欲(尽管做着做着就不那么的热爱了)。最早是想用android做app,但是调试实在是太麻烦,提取关键点后的图像处理总是炸内存。 这几天临近结项,因为我本科毕设一直写python就看了下python的图像处理,发现还挺easy,就写了下,可以基本实现主要功能。 #### 技术路线: python环境下opencv+dlib人脸识别 #### 环境配置: anaconda新建一个python环境,激活环境后: pip install cmake pip install boost (电脑还要确保配置了VS 2017环境) pip install dlib #### 当前效果展示图: 从光妹变超A光姐! <img src="https://github.com/zhxjz/LipstickTest/raw/master/resultShow/1.jpg" height="300"/> 我光妹就是涂死亡色号都好看的自带光环小天使! <img src="https://github.com/zhxjz/LipstickTest/raw/master/resultShow/2.jpg" height="300"/> 简单UI界面: <img src="https://github.com/zhxjz/LipstickTest/raw/master/resultShow/UI.gif" height="600"/> #### 后续组员完善的尝试方向(4.12-4.23时段每天晚上十点check): 1. 口红颜色的调整,多几种配色的选择。(hpf) 14号配置,16号开始每两天汇报进度。 2. ~~rgb转换为hsv空间,尝试调整达到口红效果。内外凸包分离。(hsc)~~ ~~14号配置,16号开始每两天汇报进度。~~ 3. ~~UI添加选择颜色亮度对比度。(wxd)~~ ~~14号配置,16号开始每两天汇报进度。~~ 4. ~~边缘自然化处理。(cy)~~ ~~14号配置,16号开始每两天汇报进度。~~ ``` LipstickTest.py ```# encoding:utf-8 from collections import deque import dlib import numpy as np import cv2 # 获得人脸矩形的坐标信息 def rect_to_bb(rect): x = rect.left() y = rect.top() w = rect.right() - x h = rect.bottom() - y return x, y, w, h # 将包含68个特征的的shape转换为numpy array格式 def shape_to_np(shape, dtype="int"): coords = np.zeros((68, 2), dtype=dtype) for i in range(0, 68): coords[i] = (shape.part(i).x, shape.part(i).y) return coords # 将待检测的image进行resize def resize(image, width=1200): r = width * 1.0 / image.shape[1] dim = (width, int(image.shape[0] * r)) resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA) return resized # 未加入代码部分 # 想借周围rgb值取均值来做边缘处理,但是失败了,明暗中的阴影部分会取极端值变小黑格。 def getbgr(image, xx, yy): bb = 0 gg = 0 rr = 0 bgr = image[yy, xx] for ii in range(-1, 1): for jj in range(-1, 1): if ii == 0 and jj == 0: continue tx = xx + ii ty = yy + jj tbgr = image[ty, tx] bb += tbgr[0] gg += tbgr[1] rr += tbgr[2] bb = int(bb / 8 / 3 + bgr[0] / 3 * 2) gg = int(gg / 8 / 3 + bgr[1] / 3 * 2) rr = int(rr / 8 / 3 + bgr[2] / 3 * 2) print(bb, gg, rr) return bgr # 未加入代码部分 # 想借bfs来拓展嘴唇边缘不自然部分。 def bfs(image, edge_list, convex): que = deque() dis = np.zeros((image.shape[0], image.shape[1]), dtype=int) for node in edge_list: que.append((node[0], node[1])) dis[node[0], node[1]] = -10 cc = 0 while que: cc += 1 now = que.popleft() if dis[now[0], now[1]] + 1 < 0: for xx in range(-1, 1): for yy in range(-1, 1): ty = yy + now[1] tx = xx + now[0] if cv2.pointPolygonTest(convex, (tx, ty), False) < 0: if dis[tx, ty] > dis[now[0], now[1]] + 1: dis[tx, ty] = dis[now[0], now[1]] + 1 tbgr = image[ty, tx] if tbgr[0] + 40 < 255: image[ty, tx][0] = tbgr[0] + 40 if tbgr[1] - 10 < 255: image[ty, tx][1] = tbgr[1] - 10 if tbgr[2] - 10 < 255: image[ty, tx][2] = tbgr[2] - 10 if (tx, ty) not in que: que.append((tx, ty)) return image def feature(image_file, lipstick_color): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") image = cv2.imread(image_file) image = resize(image, width=600) # print(image.shape) # 转为灰度图 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 灰度图里定位人脸 rects = detector(gray, 1) # shapes存储找到的人脸框,人脸框仅包含四个角数值如frontal_face_detector.png所示。 shapes = [] for (i, rect) in enumerate(rects): shape = predictor(gray, rect) shape = shape_to_np(shape) shape = shape[48:] shapes.append(shape) # 图片转为hsv形式,色调(H),饱和度(S),亮度(V) # H: 0 — 180 # S: 0 — 255 # V: 0 — 255 image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) for shape in shapes: sx, sy = image.shape[0], image.shape[1] # 外嘴唇凸包 hull = cv2.convexHull(shape) # 内嘴唇凸包 hull2 = cv2.convexHull(shape[12:]) ## 圈出凸包区域 # cv2.drawContours(image, [hull], -1, (255, 100, 168), -1) # cv2.drawContours(image, [hull2], -1, (168, 100, 168), -1) for xx in range(sx): for yy in range(sy): dist = cv2.pointPolygonTest(hull, (xx, yy), False) dist_inside = cv2.pointPolygonTest(hull2, (xx, yy), False) # 在外嘴唇凸包以内、在内嘴唇凸包以外部分为嘴唇 if (dist >= 0 and dist_inside < 0): image[yy, xx][0] = lipstick_color[0] image[yy, xx][1] = lipstick_color[1] image[yy, xx][2] += 10 image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR) # 高斯滤波是bfs尝试失败来做边缘柔和处理的 # image = cv2.GaussianBlur(image, (7, 7), 0) return image def update(h,s): input_image_path = "test.jpg" # 输入图像.jpg lipstick_color = [h,s, 0] # 嘴唇颜色 image_output = feature(input_image_path, lipstick_color) # 处理图像 cv2.imshow("output", image_output) # 显示 # cv2.imwrite("process2+" + input_image_path, image_output) # 保存 # cv2.waitKey(0) def nothing(x): pass if __name__=="__main__": cv2.namedWindow('output') cv2.createTrackbar('H','output',20,50,nothing) cv2.createTrackbar('S', 'output', 110, 255, nothing) cv2.createTrackbar('on', 'output', 1, 1, nothing) while(1): h = cv2.getTrackbarPos('H','output')+155 if(h>180): h-=180 s = cv2.getTrackbarPos('S','output') tag = cv2.getTrackbarPos('on','output') if s == -1: break if tag != 0: # print(h,s) update(h,s) k = cv2.waitKey(1) & 0xFF4 if k == 27: break cv2.destroyAllWindows()```
zhy0/dmarket_rl
zhy0/dmarket_rl README.md ```# Market RL Fast double auction market engine and Gym training environments. [![Build Status](https://travis-ci.com/zhy0/dmarket_rl.svg?token=6tPXB6jQP6pzcy3JZQHg&branch=master)](https://travis-ci.com/zhy0/dmarket_rl) [![codecov](https://codecov.io/gh/zhy0/dmarket_rl/branch/master/graph/badge.svg?token=N9ZpjbfF1I)](https://codecov.io/gh/zhy0/dmarket_rl) ## Installation Using pip (in virtualenv): ``` bash pip install git+https://github.com/zhy0/dmarket_rl ``` ## Usage See the [example Jupyter notebook](example.ipynb). ``` test_environments.py ```import pytest import numpy as np from dmarket.environments import SingleAgentTrainingEnv, MultiAgentTrainingEnv from dmarket.info_settings import BlackBoxSetting, TimeInformationWrapper from dmarket.agents import ConstantAgent, GymRLAgent, TimeLinearAgent def test_single_env(): rl_agent = GymRLAgent('buyer', 100) fixed_agents = [ ConstantAgent('seller', 80), ConstantAgent('seller', 90), ConstantAgent('seller', 95), ] env = SingleAgentTrainingEnv(rl_agent, fixed_agents, BlackBoxSetting()) # It should have well defined observation space obs = env.reset() assert env.observation_space.contains(obs) # The step function and action_space sampler should work obs, reward, done, _ = env.step(env.action_space.sample()) # It should give positive reward and be done if agent matches env.reset() obs, reward, done, _ = env.step(4) # buy at 90 assert obs == np.array([0.1]) # should be normalized assert reward == 15 assert done def test_multi_env(): rl_agents = [ GymRLAgent('buyer', 110, 'A'), GymRLAgent('seller', 90, 'B'), ] fixed_agents = [ ConstantAgent('buyer', 1, 'B1'), ConstantAgent('buyer', 105, 'B105'), ConstantAgent('seller', 95, 'S95'), ] env = MultiAgentTrainingEnv(rl_agents, fixed_agents, BlackBoxSetting()) # It should have well defined observation space obs = env.reset() assert env.observation_space.contains(obs['A']) assert env.observation_space.contains(obs['B']) # The step function and action_space sampler should work obs, rew, done, _ = env.step({'A': 20, 'B': 1}) assert obs == {'A': np.array([0.5]), 'B': np.array([0.025])} assert rew == {'A': 0, 'B': 8.625} assert done == {'A': False, 'B': True, '__all__': False} obs, rew, done, _ = env.step({'A': 0}) assert obs == {'A': np.array([0.])} assert rew == {'A': 7.5} assert done == {'A': True, '__all__': True} def test_multi_time_env(): rl_agents = [ GymRLAgent('buyer', 130, 'A'), GymRLAgent('seller', 70, 'B'), ] fixed_agents = [ TimeLinearAgent('buyer', 100, max_steps=2, noise=0), TimeLinearAgent('seller', 100, max_steps=2, noise=0), ] env = MultiAgentTrainingEnv(rl_agents, fixed_agents, TimeInformationWrapper(BlackBoxSetting())) # It should have well-defined observation space obs = env.reset() assert env.observation_space.contains(obs['A']) assert env.observation_space.contains(obs['B']) # Seller offers 150, buyer offers 50 obs, rew, done, _ = env.step({'A': 20, 'B': 20}) assert obs == {'A': np.array([0.5]), 'B': np.array([0.5])} assert rew == {'A': 0, 'B': 0} assert done == {'A': False, 'B': False, '__all__': False} # Seller offers 125, buyer offers 75 obs, rew, done, _ = env.step({'A': 20, 'B': 0}) assert obs == {'A': np.array([0.5]), 'B': np.array([0])} assert rew == {'A': 0, 'B': 2.5} assert done == {'A': False, 'B': True, '__all__': False} # Seller offers 100 obs, rew, done, _ = env.step({'A': 0}) print(env.market.offer_history[-1]) assert obs == {'A': np.array([0.])} assert rew == {'A': 15} assert done == {'A': True, '__all__': True} ``` info_settings.py ```import numpy as np from gym.spaces import Discrete, Box, Tuple class InformationSetting: """ Abstract information setting class. Attributes ---------- observation_space: gym.spaces object The specification of the observation space under this setting. """ def __init__(self): pass def get_states(self, agent_ids, market): """ Compute the observations of agents given the market object. Parameters ---------- agent_ids: list A list of agent ids to compute the observations for. market: MarketEngine object The current market object. Returns ------- states: dict A dictionary of observations for each agent id. Each observation should be an element of the ``observation_space``. """ pass def get_state(self, agent_id, market): return self.get_states([agent_id], market)[agent_id] class BlackBoxSetting(InformationSetting): """ The agent is aware of only its own last offer. Attributes ---------- observation_space: Box object Represents the last offer of the agent. Each element is a numpy array with a single entry. If there was no offer, it will be ``[0]``. """ def __init__(self): self.observation_space = Box(low=0, high=np.infty, shape=[1]) def get_states(self, agent_ids, market): if not market.offer_history: return {agent_id: np.array([0]) for agent_id in agent_ids} bids, asks = market.offer_history[-1] # This might be a bit slow bids = {agent_id: val for val, agent_id in bids} asks = {agent_id: val for val, agent_id in asks} result = {} for agent_id in agent_ids: if agent_id in bids: result[agent_id] = np.array([bids[agent_id]]) elif agent_id in asks: result[agent_id] = np.array([asks[agent_id]]) else: result[agent_id] = np.array([0]) return result class OfferInformationSetting(InformationSetting): """ The agent is aware of the best N offers of either side of the last round. Parameters ---------- n_offers: int, optional (default=5) Number of offers to see. For instance, 5 would mean the agents see the best 5 bids and asks. Attributes ---------- observation_space: Box object Each element is a numpy array of shape ``(2, n_offers)``. The first row contains the bids and second row the asks. No offers will be represented by 0. """ def __init__(self, n_offers=5): self.n_offers = n_offers self.observation_space = Box(low=0, high=np.infty, shape=[2, n_offers]) def get_states(self, agent_ids, market): n = self.n_offers offers = np.zeros(shape=(2, n)) if not market.offer_history: return {agent_id: offers for agent_id in agent_ids} bids, asks = market.offer_history[-1] for i, (bid, agent_id) in enumerate(bids[0:n]): offers[0][i] = bid for i, (ask, agent_id) in enumerate(asks[0:n]): offers[1][i] = ask # The information each agent gets is the same return {agent_id: offers for agent_id in agent_ids} class DealInformationSetting(InformationSetting): """ The agent is aware of N deals of the last round. Note: the N deals need not be sorted on deal price. It depends the order the matcher matches deals, see ``MarketEngine.matcher``. Parameters ---------- n_deals: int, optional (default=5) Number of deals to see. Attributes ---------- observation_space: Box object Each element is a numpy array of shape ``(n_offers,)``. No deals will be represented by 0. """ def __init__(self, n_deals=5): self.n_deals = n_deals self.observation_space = Box(low=0, high=np.infty, shape=[n_deals]) def get_states(self, agent_ids, market): n = self.n_deals if market.deal_history: # Here we exploit that deal_history contains the same deal twice # in a row, once for the buyer and once for the seller. Since # Python >= 3.6 dicts preserve the order of insertion, we can # rely on this to obtain the distinct deals that happened. deals = list(market.deal_history[-1].values())[0:2*n:2] deals = np.pad(deals, (0, n-len(deals))) # Pad it with zeros else: deals = np.zeros(n) return {agent_id: deals for agent_id in agent_ids} class TimeInformationWrapper(InformationSetting): """ Wrapper to include the time in the observation. This class takes as input another information setting and adds the time of the market to the observations of that information setting. This allows certain fixed agents to adopt time-dependent strategies. Parameters ---------- base_setting: InformationSetting object The base information setting to add time to. max_steps: int, optional (default=30) This should be the same as the ``max_steps`` parameter in the market engine, as it determines the maximum number of time steps there can be. """ def __init__(self, base_setting, max_steps=30): self.base_setting = base_setting self.max_steps = max_steps self.observation_space = Tuple((base_setting.observation_space, Discrete(max_steps))) def get_states(self, agent_ids, market): base_obs = self.base_setting.get_states(agent_ids, market) result = {} for agent_id, obs in base_obs.items(): result[agent_id] = (obs, market.time) return result ``` test_agents.py ```import pytest from dmarket.agents import * def test_random_agent(): b = UniformRandomAgent('buyer', 100) s = UniformRandomAgent('seller', 100) # Buyers should offer less than their res price # and sellers more than their res price assert b.get_offer(None) < 100 assert s.get_offer(None) > 100 def test_rl_agent_disc(): b = GymRLAgent('buyer', 100) s = GymRLAgent('seller', 100) # action == 0 should mean worst offer, i.e., reservation price assert b.action_to_price(0) == 100 assert s.action_to_price(0) == 100 # Price should be decreasing for buyer and increasing for seller assert b.action_to_price(0) > b.action_to_price(1) assert s.action_to_price(0) < s.action_to_price(1) # Price higher than res_price should be positive for seller and vice versa assert b.normalize(120) < 0 assert s.normalize(120) > 0 # Zero prices (i.e., no offer) should normalize to zero assert b.normalize(0) == 0 assert s.normalize(0) == 0 # Negative prices should also normalize to zero assert b.normalize(-1) == 0 assert s.normalize(-1) == 0 def test_linear_agent(): b = TimeLinearAgent('buyer', 100, noise=0) s = TimeLinearAgent('seller', 100, noise=0) # Buyers should increase and sellers should decrease their price assert b.get_offer((None, 0)) < b.get_offer((None, 1)) assert s.get_offer((None, 0)) > s.get_offer((None, 1)) ``` conftest.py ```import pytest from dmarket.engine import MarketEngine @pytest.fixture() def market(): def create_market(n_buyers, n_sellers): buyer_ids = list(range(n_buyers)) seller_ids = list(range(n_buyers, n_buyers + n_sellers)) return MarketEngine(buyer_ids, seller_ids) return create_market ``` test_engine.py ```import pytest import numpy as np def test_market_step(market): m = market(1,1) m.step({}) assert m.time == 1 assert m.done == set() assert m.offer_history ==[([], [])] assert m.deal_history == [{}] def test_market_bid_ask_sorted(market): m = market(3, 3) offers = { 0: 100, 1: 90, 2: 95, 3: 110, 4: 100, 5: 105 } m.step(offers) assert m.offer_history[-1] == ( [(100, 0), (95, 2), (90, 1)], [(100, 4), (105, 5), (110, 3)], ) def test_market_done(market): m = market(1, 3) # No one should be done in zeroth round assert m.done == set() # Everyone should be done once the only buyer matches m.step({0: 100, 1: 100}) assert m.done == {0, 1, 2, 3} # Everyone should be done after max_steps m.reset() for i in range(m.max_steps): m.step({}) assert m.done == {0, 1, 2, 3} ``` environments.py ```import numpy as np import gym from gym.spaces import Discrete, Box from dmarket.engine import MarketEngine from dmarket.info_settings import TimeInformationWrapper class MultiAgentTrainingEnv(gym.Env): """ OpenAI Gym environment for training multiple agents simultaneously. This environment is designed for training multiple agents at the same time. This environment is compatible with RLlib's ``MultiAgentEnv``. Parameters ---------- rl_agents: list A list of RL agent objects, must be instances of ``GymRLAgent``. fixed_agents: list A list of fixed agents. All instances must implement the ``get_offer`` function. setting: InformationSetting object The information setting of the market environment. max_steps: int, optional (default=30) Maximum number of rounds before a single market game terminates. This is passed on to the market engine. Attributes ---------- observation_space: Box object Derived from ``setting`` parameter. market: MarketEngine object The underlying market engine object. """ def __init__(self, rl_agents, fixed_agents, setting, max_steps=30): self.rl_agents = { rl_agent.name: rl_agent for rl_agent in rl_agents } self.fixed_agents = { fixed_agent.name: fixed_agent for fixed_agent in fixed_agents } self.all_agents = {} self.all_agents.update(self.rl_agents) self.all_agents.update(self.fixed_agents) if isinstance(setting, TimeInformationWrapper): self.observation_space = setting.base_setting.observation_space self.rl_setting = setting.base_setting else: self.observation_space = setting.observation_space self.rl_setting = setting self.setting = setting self.observation_space = Box( low=-np.inf, high=np.inf, shape=self.rl_setting.observation_space.shape ) buyer_ids = [ agent.name for agent in self.all_agents.values() if agent.role == 'buyer' ] seller_ids = [ agent.name for agent in self.all_agents.values() if agent.role == 'seller' ] self.market = MarketEngine(buyer_ids, seller_ids, max_steps) def _get_rewards(self, agent_ids, deals): """ Compute the reward of each agent given the deals in the last round. """ result = {} for agent_id in agent_ids: if agent_id in deals: agent = self.all_agents[agent_id] sign = (-1 if agent.role == 'buyer' else +1) res_price = agent.reservation_price result[agent_id] = (deals[agent_id] - res_price)*sign else: result[agent_id] = 0 return result def reset(self): """ Reset the training market environment. Returns ------- observations: dict Initial observations for all agents. """ self.market.reset() return self.rl_setting.get_states(self.rl_agents.keys(), self.market) def step(self, actions): """ Parameters ---------- actions: dict A dictionary of actions per agent, indexed by agent id. Returns ------- observations: dict Observations per agent. Will only contain those agents found in the passed actions dict. rewards: dict Reward per agent. Will only contain those agents found in the passed actions dict. done: dict Dict of True/False to indicate whether each agent is done or not. Will only contain those agents found in the passed actions dict. Contains additionally a string key ``__all__`` to indicate whether every agent is done. """ # Get dict of fixed agents that aren't yet done other_agents = { agent.name: agent for agent in self.fixed_agents.values() if agent.name not in self.market.done } # First get offers of other fixed agents obs = self.setting.get_states(other_agents.keys(), self.market) offers = { agent.name: agent.get_offer(obs[agent.name]) for agent in other_agents.values() } # Update offers with RL offers from the actions dict rl_agent_ids = set(actions.keys()) for rl_agent_id in rl_agent_ids: offers[rl_agent_id] = self.rl_agents[rl_agent_id].action_to_price( actions[rl_agent_id] ) # Step the market deals = self.market.step(offers) # Obs, done, rewards for RL agents obs = self.rl_setting.get_states(rl_agent_ids, self.market) for rl_agent_id in obs.keys(): # Normalize each observation obs[rl_agent_id] = self.rl_agents[rl_agent_id].normalize( obs[rl_agent_id] ) done = { rl_agent_id: (rl_agent_id in self.market.done) for rl_agent_id in rl_agent_ids } done["__all__"] = (rl_agent_ids.issubset(self.market.done)) rew = self._get_rewards(rl_agent_ids, deals) return obs, rew, done, {} class SingleAgentTrainingEnv(MultiAgentTrainingEnv): """ Gym environment for training single RL agents. This environment is compatible with stable_baselines. Parameters ---------- rl_agent: GymRLAgent object The reinforcement learning agent to be trained. The environment derives action space and observation space from this object. fixed_agents: list A list of fixed agents. All instances must implement the ``get_offer`` function. setting: InformationSetting object The information setting of the market environment. max_steps: int, optional (default=30) Maximum number of rounds before a single market game terminates. This is passed on to the market engine. """ def __init__(self, rl_agent, fixed_agents, setting, max_steps=30): self.rl_agent = rl_agent self.action_space = Discrete(rl_agent.discretization) super().__init__([rl_agent], fixed_agents, setting, max_steps) def reset(self): return super().reset()[self.rl_agent.name] def step(self, action): obs, rew, done, _ = super().step({ self.rl_agent.name: action }) return obs[self.rl_agent.name], \ rew[self.rl_agent.name], \ done[self.rl_agent.name], _ ``` test_info_settings.py ```import pytest from dmarket.info_settings import * def test_blackbox(market): m = market(10, 10) b = BlackBoxSetting() # Initial state should be zeros assert b.get_states([0,1], m) == {0: [0], 1: [0]} # Agents should see their respective offers m.step({0: 100, 1: 150}) assert b.get_states([0,1, 2], m) == {0: [100], 1: [150], 2: [0]} def test_offer_info(market): m = market(10,10) setting = OfferInformationSetting(5) # Initial state should be of shape (2, 5) assert setting.get_states([0], m)[0].shape == (2, 5) # First row should be bids, second should be asks m.step({0: 90, 10: 110}) np.testing.assert_array_equal( setting.get_states([0, 10], m)[0], [ [90, 0, 0, 0, 0], [110, 0, 0, 0, 0] ] ) # It should contain the best deals of both sides, sorted m.reset() m.step({ 0: 90, 1: 91, 2: 92, 3: 93, 4: 94, 5: 105, 10: 100, 11: 101, 12: 102, 13: 103, 14: 104, 15: 95, }) np.testing.assert_array_equal( setting.get_states([0, 10], m)[0], [ [105, 94, 93, 92, 91], [95, 100, 101, 102, 103], ] ) def test_deal_info(market): m = market(10,10) setting = DealInformationSetting(5) # Initial state should be of shape (5,) assert setting.get_states([0], m)[0].shape == (5,) # It should contain deals made, not necessarily sorted on deal price value m.step({0: 110, 1: 96, 10: 90, 11: 94}) np.testing.assert_array_equal( setting.get_states([0, 10], m)[0], [100, 95, 0, 0, 0], ) @pytest.mark.parametrize("base_setting", [ BlackBoxSetting(), OfferInformationSetting(5), DealInformationSetting(5) ]) def test_time_wrapper(market, base_setting): m = market(10,10) setting = TimeInformationWrapper(base_setting) init_state = setting.get_states([0], m)[0] assert type(init_state) == tuple # The first coordinate should be an entry of base_setting assert base_setting.observation_space.contains(init_state[0]) # Second coordinate should be the time assert init_state[1] == 0 # It should increase the time if step is called m.step({0: 100, 1:100}) next_state = setting.get_states([0], m)[0] assert next_state[1] == 1 ``` agents.py ```import numpy as np class MarketAgent: """ Market agent implementation to be used in market environments. Attributes ---------- role: str, 'buyer' or 'seller' reservation_price: float Must be strictly positive. name: str, optional (default=None) Name of the market agent. If not given, a random one will be generated. Note: this will usually not be the agent id used in the market engine. """ def __init__(self, role, reservation_price, name=None): if not role in ['buyer', 'seller']: raise ValueError("Role must be either buyer or seller") if reservation_price <= 0: raise ValueError("Reservation price must be positive") self.role = role self.reservation_price = reservation_price if not name: randstring = "%04x" % np.random.randint(16**4) cls = type(self).__name__[0:4] letter = role[0].upper() name = f"{cls}_{letter}{reservation_price}_{randstring}" self.name = name def get_offer(self, observation): """ Returns offer given an observations. Parameters ---------- observation: array_like An element of some observation space defined by the used information setting. Returns ------- offer: float Offer to made to the market. """ raise NotImplementedError class ConstantAgent(MarketAgent): """Agent that always offers its reservation price.""" def get_offer(self, observation): return self.reservation_price class FactorAgent(MarketAgent): """ Abstract agent class that determines an offer range based on a multiplicative factor. Children of this class will take an argument ``max_factor`` and use this together with its reservation price to determine an interval to offer in. For a seller, the agent will have the range ``[r, (1+max_factor)*r]`` with ``r`` the reservation price. For a buyer, this interval would be ``[(1-max_factor)*r, r]``. Parameters ---------- max_factor: float, optional (default=0.5) Must be between 0 and 1. Attributes ---------- _s: int A sign derived from the role of the agent, +1 means seller, -1 means buyer. _c: float A factor used to compute the interval range. _a: float Lower bound of the offer range. _b: float Upper bound of the offer range. """ def __init__(self, role, reservation_price, name=None, max_factor=0.5): self.max_factor = max_factor super().__init__(role, reservation_price, name) r = reservation_price self._s = (-1 if role == 'buyer' else 1) self._c = (1 + self._s * max_factor) self._a = min(r, self._c*r) # minimum agent can offer self._b = max(r, self._c*r) # maximum agent can offer class UniformRandomAgent(FactorAgent): """ Random agent that offers uniformly random prices. This agent will take an argument ``max_factor`` and use this together with its reservation price to determine the interval to use for sampling offers. For a seller, the agent will make uniform random offers in the range ``[r, (1+max_factor)*r]`` with ``r`` the reservation price. For a buyer, this interval would be ``[(1-max_factor)*r, r]``. Parameters ---------- max_factor: float, optional (default=0.5) Must be between 0 and 1. """ def get_offer(self, observation): return np.random.uniform(self._a, self._b) class TimeDependentAgent(FactorAgent): """ Abstract helper class to create agents that have time-dependent strategies. """ def get_offer(self, observation): if not isinstance(observation, tuple): raise ValueError("Expected tuple observation!") obs = observation[0] time = observation[1] return self.compute_offer(obs, time) def compute_offer(self, observation, time): """ Compute the offer based on observation and time. """ raise NotImplementedError class TimeLinearAgent(TimeDependentAgent): """ Agent that linearly decreases/increases its offer price. This agent starts with a high offer and linearly decreases/increases its price until it reaches its reservation price. Parameters ---------- max_factor: float, optional (default=0.5) Must be between 0 and 1, determines the offer range of the agent. noise: float, optional (default=1.0) The standard deviation of the noise added to the computed price. max_steps: int, optional (default=20) Number of steps until the agent offers its reservation price. This determines how quickly the agent lowers/increases his price. """ def __init__(self, role, reservation_price, name=None, max_factor=0.5, noise=1.0, max_steps=20): super().__init__(role, reservation_price, name, max_factor) self.max_steps = max_steps self.noise = noise self._slope = -self._s * (self._b - self._a)/self.max_steps def compute_offer(self, observation, time): t = min(time, self.max_steps) noise = np.random.normal(scale=self.noise) return self._c*self.reservation_price + t*self._slope + noise class GymRLAgent(FactorAgent): """ A market agent with reinforcement learning model. This class serves as a wrapper for gym RL models and serves two purposes: 1. Standardize action space for RL models; 2. Make trained RL models applicable under different market situations. The second point is achieved through normalization of input observations. This makes it possible for an agent that was trained as a seller to operate as a buyer. It also enables agents to function properly across markets with different price scales. Parameters ---------- model: object, optional (default=None) Trained baselines model to use for predictions. It needs to have the method ``predict(observation) -> (action, state)``. discretization: int, optional (default=20) The number of different offers the agent can make. This determines the action space of the agent. max_factor: int A factor of the reservation price that determines the range of prices the agent can offer. See ``UniformRandomAgent``. """ def __init__(self, role, reservation_price, name=None, model=None, discretization=20, max_factor=0.5): self.model = model self.discretization = discretization self._N = discretization super().__init__(role, reservation_price, name, max_factor) def get_offer(self, observation): if not self.model: raise RuntimeError("Current agent does not have a model") action = self.model.predict(self.normalize(observation))[0] return self.action_to_price(action) def normalize(self, observation): """ Normalize the prices in observations according to reservation price. This function will serve to scale all observations based on the agent's reservation price and role. An observation should contain nonnegative prices. A small value corresponds to prices close to the agent's reservation price, while large values correspond to attractive offers. To preserve symmetry between sellers and buyers, this function is discontinuous in 0, since the information settings represent no offers/no information with zero. Parameters ---------- observation: array_like An element of the observation space determined by the information setting. Returns ------- normalized_observation: array_like Scaled observation based on agent's reservation price and role. """ return np.heaviside(observation, 0) * self._s * \ (observation - self.reservation_price)/self.reservation_price def action_to_price(self, action): """ Convert an action in the action space of the agent to a market price. This function uniformly discretizes the price range of the agent. An action close to zero should yield a conservative offer, i.e., close to the reservation price, while a large value for action gives more aggressive offers. Parameters ---------- action: int The action is an integer ``0 <= action < discretization``. Returns ------- price: float The price corresponding to the action. """ l = action - self._N/2 m = self._N/2 return ((m - l*self._s)*self._a + (m + l*self._s)*self._b)/self._N ``` engine.py ```import numpy as np class MarketEngine: """ Core double auction, single unit market matching enigne Parameters ---------- buyers : array_like List of buyer ids, should be distinct. sellers : array_like List of seller ids, should be distinct. max_steps: int (optional, default=30) Number of maximum market rounds. Attributes ------- time: int The current time step the market is in. Starts at 0. done: set The set of agent ids that are done for this game. If ``max_steps`` is reached, this will contain all agent ids. offer_history: list This is a list of all offers up until the current step. Each entry of this list is a tuple of the form ``(bids, asks)`` which represent the set of bids and asks respectively for that time step. Both ``bids`` and ``asks`` are in the form used by the matcher, i.e., they are lists of tuples of the form ``[(offer1, agent_id1), (offer2, agent_id2), ...]``. deal_history: list A list of all deals up until the current time step. Each entry contains a dict of the form ``{agent_id1: deal_price1, ...}`` for all agents that were matched in that round. """ def __init__(self, buyers, sellers, max_steps=30): self.buyers = set(buyers) self.sellers = set(sellers) self.agents = self.buyers.union(self.sellers) self.max_steps = max_steps self.reset() def reset(self): """Reset the market to its initial unmatched state.""" self.time = 0 self.done = set() self.offer_history = list() self.deal_history = list() def step(self, offers): """ Compute the next market state given a set of offers. This function will update each of the class attributes ``time``, ``done``, ``offer_history`` and ``deal_history``. Parameters ---------- offers: dict A dictionary of offers indexed by agent_id. Returns ------- deals: dict A dictionary indexed by agent_id containing the deal price of each succesfully matched market agent. """ bids = [] asks = [] for agent_id, offer in offers.items(): if agent_id in self.done: continue elif agent_id in self.buyers: bids.append((offer, agent_id)) elif agent_id in self.sellers: asks.append((offer, agent_id)) else: raise RuntimeError(f"Received offer from unkown agent {agent_id}") deals = self.match(bids, asks) self.deal_history.append(deals) self.offer_history.append((bids, asks)) self.time += 1 for agent_id in deals: self.done.add(agent_id) if self.time >= self.max_steps \ or self.buyers.issubset(self.done) \ or self.sellers.issubset(self.done): self.done = self.agents return deals @staticmethod def match(bids, asks): """ Core matching algorithm for market engine. Matching is done as follows: If a bid is higher than an ask, then the buyer will be matched with the seller. If there are multiple bids and asks that could be matched, then matching is determined by the offer placed: the highest bidder will be matched with the lowest asking seller, the second highest bidder will be matched with the second lowest seller and so on. No match will happen if none of the bids exceed the asks. The deal price is determined to be the mid-price of the matched bid and ask. Note: the deal price does not have to be monotone in the offers of either side, i.e., it could happen that the second highest bidder obtains a better deal price than the highest bidder. Parameters ---------- bids: list of tuples A list of the form ``[(bid1, agent_id1), (bid2, agent_id2), ...]``. asks: list of tuples A list of the form ``[(ask1, agent_id1), (ask2, agent_id2), ...]``. Returns ------- deals: dict A dictionary indexed by agent_id containing the deal price. Only agents that were matched will be in this dict. Note: the same deal price will appear twice under the buyer and seller id. """ bids.sort(reverse=True) asks.sort(reverse=False) deals = dict() n = min(len(bids), len(asks)) for (bid, buyer_id), (ask, seller_id) in zip(bids[0:n], asks[0:n]): if bid >= ask: price = (bid + ask)/2 deals[buyer_id] = price deals[seller_id] = price else: break return deals ```
zhy980127/MNIST
zhy980127/MNIST mnist_test.py ```import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' def train_mnist(): """ 训练mnist数字集进行数字识别 :return: None """ #加载mnist数字集 mnist = input_data.read_data_sets("D:/my_test/MNIST/MNIST_data/", one_hot=True) with tf.variable_scope("data"): #1.创建数据 x_data = tf.placeholder(tf.float32,[None,784],"x_data") y_data = tf.placeholder(tf.int32,[None,10],"y_data") with tf.variable_scope("model"): #权重,偏置 weight = tf.Variable(tf.random_normal([784,10],mean=0.0,stddev=1.0),name="weight") bias = tf.Variable(0.0,name="bias") #2.创建模板 y_true = tf.matmul(x_data,weight) + bias with tf.variable_scope("soft_cross"): #3.求平均交叉熵损失(求出所有样本的损失 求均值) loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_data,logits=y_true)) with tf.variable_scope("train_op"): #4.梯度下降损失 train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss) with tf.variable_scope("acc"): #计算准确率 equal_list = tf.equal(tf.arg_max(y_data,1),tf.argmax(y_true,1)) accuracy = tf.reduce_mean(tf.cast(equal_list,tf.float32)) # 收集tensor,收集对于损失函数和准确率等单值变量 tf.summary.scalar("loss", loss) tf.summary.scalar("accuracy",accuracy) # 收集高纬度参数 tf.summary.histogram("weight", weight) tf.summary.histogram("bias", bias) # 合并写入事件文件 merged = tf.summary.merge_all() #初始化op init_op = tf.global_variables_initializer() # 保存模型 saver = tf.train.Saver(max_to_keep=5) #运行程序 with tf.Session() as sess: sess.run(init_op) summary_filr = tf.summary.FileWriter("./test",graph=sess.graph) if os.path.exists("D:\my_test\MNIST\ckpt\checkpoint"): # 加载模型 saver.restore(sess, "D:\my_test\MNIST\ckpt\model") for i in range(100): x_test, y_test = mnist.train.next_batch(1) print("第%d张图片,目标是%d的,预测结果是%d" % (i, tf.argmax(y_test, 1).eval(), tf.argmax(sess.run(y_true, feed_dict={x_data: x_test, y_data: y_test}), 1).eval() )) else: for i in range(5000): mnist_x,mnist_y = mnist.train.next_batch(50) feeds = {x_data: mnist_x, y_data: mnist_y} summary = sess.run(merged,feed_dict=feeds) summary_filr.add_summary(summary,i) sess.run(train_op,feed_dict=feeds) train_acc = sess.run(accuracy,feed_dict=feeds) print("训练第%d步,准确率%f"%(i,train_acc)) saver.save(sess,"D:\my_test\MNIST\ckpt\model") return None if __name__ == "__main__": train_mnist() ```
zhyravelka/js_hw_10
zhyravelka/js_hw_10 task-01.js ```const randomIntegerFromInterval = (min, max) => { return Math.floor(Math.random() * (max - min + 1) + min); }; $(document).ready(function () { $('[data-action="start"]').click(function () { interval = setInterval(() => { const colors = ["red", "green", "violet", "gray", "blue", "yellow"]; const time = randomIntegerFromInterval(0, colors.length-1); $("body").css("background-color", colors[time]); $('[data-action="start"]').attr('disabled', true); }, 1000); }); $('[data-action="stop"]').click(function () { clearInterval(interval); $('[data-action="start"]').attr('disabled', false); }); }); ``` task.js ```let refs = { daysRef: document.querySelector("[data-value='days']"), hoursRef: document.querySelector("[data-value='hours']"), minsRef: document.querySelector("[data-value='mins']"), secsRef: document.querySelector("[data-value='secs']"), }; const finishDay = new Date("September 20, 2021 16:00:00"); class Timer { constructor(finishDay) { this.finishDay = finishDay; } setDate() { let timerID = setInterval(() => { const dateNow = Date.now(); const distance = this.finishDay - dateNow; if (distance < 0) { clearInterval(timerID); return; } let days = Math.floor(distance / (1000 * 60 * 60 * 24)); let hours = Math.floor((distance / (1000 * 60 * 60)) % 24); let minutes = Math.floor((distance / 1000 / 60) % 60); let seconds = Math.floor((distance / 1000) % 60); refs.daysRef.innerHTML = `${days}`, refs.hoursRef.innerHTML = `${hours}`, refs.minsRef.innerHTML = `${minutes}`, refs.secsRef.innerHTML = `${seconds}`; }, 1000); } } let timer = new Timer(finishDay); timer.setDate(); ```
zhzy0077/workflows
zhzy0077/workflows atom.rs ```use crate::{Context, Input, Inputs, Outputs, Workflow}; use anyhow::Result; use atom_syndication::Feed; use chrono::{Duration, Local}; use std::{io::BufReader}; pub struct Atom {} impl Atom { // Input const TEXT: &'static str = "text"; const SCHEDULE_IN_SECS: &'static str = "schedule_in_secs"; const PARAMS: [&'static str; 2] = [Atom::TEXT, Atom::SCHEDULE_IN_SECS]; // Output const TITLE: &'static str = "title"; const LINK: &'static str = "link"; const OUTPUT: [&'static str; 2] = [Atom::TITLE, Atom::LINK]; } impl Workflow for Atom { fn execute(&self, context: &mut Context, input: Inputs) -> Result<()> { let text = input.parameter(Atom::TEXT); let after = input .parameter(Atom::SCHEDULE_IN_SECS) .parse() .map(|secs| Local::now() - Duration::seconds(secs)); let next = match context.next() { Some(next) => next, None => return Ok(()), }; let feed = Feed::read_from(BufReader::new(text.as_bytes()))?; for entry in feed.entries() { if let Ok(after) = after { if entry.updated() < &after { break; } } let mut output = Outputs::new(); output.insert(Atom::TITLE, entry.title().to_string()); output.insert( Atom::LINK, entry .links() .iter() .map(|link| link.href()) .collect::<Vec<_>>() .join(","), ); next.execute(context, output)?; } Ok(()) } fn parameters(&self) -> &'static [&'static str] { return &Atom::PARAMS; } fn outputs(&self) -> &'static [&'static str] { return &Atom::OUTPUT; } } ``` README.md ```# workflows Personal workflow components. See tests/upload_config_to_gist.yml for reference.``` http.rs ```use crate::{Context, Input, Inputs, Workflow}; use anyhow::Result; use reqwest::blocking::{Client, Request}; use std::collections::HashMap; pub struct Http {} impl Http { // Input const URL: &'static str = "url"; const METHOD: &'static str = "method"; const PARAMS: [&'static str; 2] = [Http::URL, Http::METHOD]; // Output const STATUS_CODE: &'static str = "status_code"; const TEXT: &'static str = "text"; const OUTPUT: [&'static str; 2] = [Http::STATUS_CODE, Http::TEXT]; } impl Workflow for Http { fn execute(&self, context: &mut Context, input: Inputs) -> Result<()> { let url = input.parameter(Http::URL); let method = input.parameter(Http::METHOD); reqwest::Proxy::all("http://127.0.0.1:7890")?; let client = Client::new(); let request = Request::new(method.parse()?, url.parse()?); let response = client.execute(request)?; let mut result = HashMap::new(); result.insert(Http::STATUS_CODE, response.status().as_str().to_string()); result.insert(Http::TEXT, response.text()?); if let Some(next) = context.next() { next.execute(context, result)?; } Ok(()) } fn parameters(&self) -> &'static [&'static str] { return &Http::PARAMS; } fn outputs(&self) -> &'static [&'static str] { return &Http::OUTPUT; } } ``` read.rs ```use crate::{Context, Input, Inputs, Outputs, Workflow}; use anyhow::Result; use std::{fs::File, io::Read as _}; pub struct Read {} impl Read { // Input const PATH: &'static str = "path"; const PARAMS: [&'static str; 1] = [Read::PATH]; const TEXT: &'static str = "text"; const OUTPUT: [&'static str; 1] = [Read::TEXT]; } impl Workflow for Read { fn execute(&self, context: &mut Context, input: Inputs) -> Result<()> { let path = input.parameter(Read::PATH); let mut text = String::new(); File::open(path)?.read_to_string(&mut text)?; let mut output = Outputs::new(); output.insert(Read::TEXT, text); if let Some(next) = context.next() { next.execute(context, output)?; } Ok(()) } fn parameters(&self) -> &'static [&'static str] { return &Read::PARAMS; } fn outputs(&self) -> &'static [&'static str] { return &Read::OUTPUT; } } ``` command.rs ```use crate::{Context, Input, Inputs, Workflow}; use anyhow::Result; use std::{ collections::HashMap, process::{Command as StdCommand, Stdio}, }; pub struct Command {} impl Command { // Input const PROGRAM: &'static str = "program"; const DAEMON: &'static str = "daemon"; const INHERIT_IO: &'static str = "inherit_io"; const PARAMS: [&'static str; 3] = [Command::PROGRAM, Command::DAEMON, Command::INHERIT_IO]; const OUTPUT: [&'static str; 0] = []; } impl Workflow for Command { fn execute(&self, context: &mut Context, input: Inputs) -> Result<()> { let program = input.parameter(Command::PROGRAM); let daemon: bool = input.parameter(Command::DAEMON).parse().unwrap_or(false); let inherit_io: bool = input .parameter(Command::INHERIT_IO) .parse() .unwrap_or(false); let mut command = StdCommand::new(program); if !inherit_io { command.stdout(Stdio::null()); command.stderr(Stdio::null()); } let mut handle = command.spawn()?; if !daemon { handle.wait()?; } if let Some(next) = context.next() { next.execute(context, HashMap::new())?; } Ok(()) } fn parameters(&self) -> &'static [&'static str] { return &Command::PARAMS; } fn outputs(&self) -> &'static [&'static str] { return &Command::OUTPUT; } } ``` rss.rs ```use crate::{Context, Input, Inputs, Outputs, Workflow}; use anyhow::Result; use chrono::{DateTime, Duration, Local}; use rss::Channel; use std::io::BufReader; pub struct Rss {} impl Rss { // Input const TEXT: &'static str = "text"; const SCHEDULE_IN_SECS: &'static str = "schedule_in_secs"; const PARAMS: [&'static str; 2] = [Rss::TEXT, Rss::SCHEDULE_IN_SECS]; // Output const TITLE: &'static str = "title"; const LINK: &'static str = "link"; const OUTPUT: [&'static str; 2] = [Rss::TITLE, Rss::LINK]; } impl Workflow for Rss { fn execute(&self, context: &mut Context, input: Inputs) -> Result<()> { let text = input.parameter(Rss::TEXT); let after = input .parameter(Rss::SCHEDULE_IN_SECS) .parse() .map(|secs| Local::now() - Duration::seconds(secs)); let next = match context.next() { Some(next) => next, None => return Ok(()), }; let channel = Channel::read_from(BufReader::new(text.as_bytes()))?; for item in channel.items() { if let (Ok(after), Some(Ok(pub_date))) = ( &after, item.pub_date().map(|s| DateTime::parse_from_rfc2822(s)), ) { if &pub_date < after { break; } } let mut output = Outputs::new(); output.insert( Rss::TITLE, item.title().map(str::to_string).unwrap_or_default(), ); output.insert( Rss::LINK, item.link().map(str::to_string).unwrap_or_default(), ); next.execute(context, output)?; } Ok(()) } fn parameters(&self) -> &'static [&'static str] { return &Rss::PARAMS; } fn outputs(&self) -> &'static [&'static str] { return &Rss::OUTPUT; } } ``` util.rs ```use serde::Serializer; // Serde crate enforces following signature. #[allow(clippy::trivially_copy_pass_by_ref)] pub fn bool_to_int<S>(input: &bool, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_u64(if *input { 1 } else { 0 }) } ``` gist.rs ```use crate::{Context, Input, Inputs, Workflow, USER_AGENT}; use anyhow::Result; use reqwest::blocking::Client; use reqwest::blocking::Response; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use strum::EnumString; pub struct Gist {} #[derive(Debug, EnumString)] enum GistAction { GET, UPDATE, } #[derive(Debug, Serialize, Deserialize)] struct GistPayload<'a> { #[serde(borrow)] files: HashMap<&'a str, GistFile<'a>>, } #[derive(Debug, Serialize, Deserialize)] struct GistFile<'a> { content: &'a str, } impl Gist { pub const TEXT: &'static str = "text"; // Input const ACTION: &'static str = "action"; const GIST_ID: &'static str = "gist_id"; const ACCESS_TOKEN: &'static str = "access_token"; const FILE_NAME: &'static str = "file_name"; const PARAMS: [&'static str; 5] = [ Gist::ACTION, Gist::GIST_ID, Gist::ACCESS_TOKEN, Gist::FILE_NAME, Gist::TEXT, ]; // Output const STATUS_CODE: &'static str = "status_code"; const OUTPUT: [&'static str; 2] = [Gist::STATUS_CODE, Gist::TEXT]; fn update(gist_id: &str, access_token: &str, file_name: &str, text: &str) -> Result<Response> { let url = format!("https://api.github.com/gists/{}", gist_id); let mut files = HashMap::new(); files.insert(file_name, GistFile { content: text }); let gist_payload = GistPayload { files }; let client = Client::new(); Ok(client .patch(&url) .header("Authorization", format!("token {}", access_token)) .header("Accept", "application/vnd.github.v3+json") .header("User-Agent", USER_AGENT) .json(&gist_payload) .send()?) } fn get(gist_id: &str) -> Result<Response> { let url = format!("https://api.github.com/gists/{}", gist_id); let client = Client::new(); Ok(client .get(&url) .header("Accept", "application/vnd.github.v3+json") .header("User-Agent", USER_AGENT) .send()?) } } impl Workflow for Gist { fn execute(&self, context: &mut Context, input: Inputs) -> Result<()> { let action: GistAction = input.parameter(Gist::ACTION).to_uppercase().parse()?; let gist_id = input.parameter(Gist::GIST_ID); let access_token = input.parameter(Gist::ACCESS_TOKEN); let file_name = input.parameter(Gist::FILE_NAME); let text = input.parameter(Gist::TEXT); let response = match action { GistAction::GET => Gist::get(gist_id), GistAction::UPDATE => Gist::update(gist_id, access_token, file_name, text), }?; let mut result = HashMap::new(); result.insert(Gist::STATUS_CODE, response.status().as_str().to_string()); let content: String = response.text()?; let resp: GistPayload = serde_json::from_str(&content)?; result.insert(Gist::TEXT, resp.files[file_name].content.to_string()); if let Some(next) = context.next() { next.execute(context, result)?; } Ok(()) } fn parameters(&self) -> &'static [&'static str] { return &Gist::PARAMS; } fn outputs(&self) -> &'static [&'static str] { return &Gist::OUTPUT; } } ``` decompress.rs ```use crate::{Context, Input, Inputs, Workflow}; use anyhow::Result; use flate2::read::GzDecoder; use std::{collections::HashMap, fs::File}; use tar::Archive; pub struct Decompress {} impl Decompress { // Input const PATH: &'static str = "path"; const DESTINATION: &'static str = "destination"; const PARAMS: [&'static str; 2] = [Decompress::PATH, Decompress::DESTINATION]; const OUTPUT: [&'static str; 0] = []; } impl Workflow for Decompress { fn execute(&self, context: &mut Context, input: Inputs) -> Result<()> { let path = input.parameter(Decompress::PATH); let destination = input.parameter(Decompress::DESTINATION); let tarball = File::open(path)?; let tar = GzDecoder::new(tarball); let mut archive = Archive::new(tar); archive.unpack(destination)?; if let Some(next) = context.next() { next.execute(context, HashMap::new())?; } Ok(()) } fn parameters(&self) -> &'static [&'static str] { return &Decompress::PARAMS; } fn outputs(&self) -> &'static [&'static str] { return &Decompress::OUTPUT; } } ``` main.rs ```mod atom; mod command; mod decompress; mod echo; mod gist; mod http; mod parser; mod read; mod rss; mod save; mod util; mod wechat; use crate::atom::Atom; use crate::command::Command; use crate::decompress::Decompress; use crate::echo::Echo; use crate::gist::Gist; use crate::http::Http; use crate::read::Read; use crate::rss::Rss; use crate::save::Save; use crate::wechat::WeChat; use anyhow::{anyhow, Context as _, Result}; use enum_dispatch::enum_dispatch; use lazy_static::lazy_static; use parser::fulfill; use serde::Deserialize; use std::{collections::HashMap, env, fs}; const USER_AGENT: &'static str = "workflows/1.0"; #[enum_dispatch(SupportedWorkflows)] trait Workflow { fn execute(&self, context: &mut Context, input: Inputs) -> Result<()>; fn parameters(&self) -> &'static [&'static str]; fn outputs(&self) -> &'static [&'static str]; } #[derive(Debug)] pub struct Context { state: usize, config: Config, env: HashMap<String, String>, } impl Context { fn new(config: Config) -> Self { let env: HashMap<String, String> = env::vars().collect(); Self { state: 0, config, env, } } fn next(&mut self) -> Option<WorkflowConfig> { if self.config.workflows.is_empty() { None } else { Some(self.config.workflows.remove(0)) } } } type Outputs = HashMap<&'static str, String>; type Inputs = HashMap<&'static str, String>; trait Input { fn parameter(&self, key: &'static str) -> &str; } impl Input for Inputs { fn parameter(&self, key: &'static str) -> &str { self.get(key).map(|s| &s[..]).unwrap_or_else(|| "") } } #[enum_dispatch] enum SupportedWorkflows { Http, Gist, Echo, WeChat, Command, Save, Decompress, Atom, Read, Rss, } lazy_static! { static ref WORKFLOWS: HashMap<&'static str, SupportedWorkflows> = { let mut m = HashMap::new(); m.insert("http", Http {}.into()); m.insert("echo", Echo {}.into()); m.insert("wechat", WeChat {}.into()); m.insert("gist", Gist {}.into()); m.insert("command", Command {}.into()); m.insert("save", Save {}.into()); m.insert("decompress", Decompress {}.into()); m.insert("atom", Atom {}.into()); m.insert("read", Read {}.into()); m.insert("rss", Rss {}.into()); m }; } #[derive(Debug, Deserialize)] struct Config { workflows: Vec<WorkflowConfig>, } #[derive(Debug, Deserialize)] struct WorkflowConfig { #[serde(rename = "type")] workflow_type: String, parameters: HashMap<String, String>, } impl WorkflowConfig { fn execute(&self, context: &mut Context, output: Outputs) -> Result<()> { let input: HashMap<String, String> = output .into_iter() .map(|(k, v)| (k.to_string(), v)) .collect(); let (workflow, payload) = self.make_workflow(&input, &context)?; workflow.execute(context, payload) } fn make_workflow( &self, input: &HashMap<String, String>, context: &Context, ) -> Result<(&'static SupportedWorkflows, Inputs)> { let workflow = WORKFLOWS .get(&self.workflow_type.to_lowercase()[..]) .context(anyhow!("Workflow {} is not found.", self.workflow_type))?; let mut payload: HashMap<&'static str, String> = HashMap::new(); for key in workflow.parameters() { if let Some(value) = self.parameters.get(*key) { payload.insert(key, fulfill(value, input, &context)?); } } Ok((workflow, payload)) } } fn main() -> Result<()> { let config_path = env::args() .nth(1) .context("No configuration is provided.")?; let config = fs::read_to_string(config_path)?; let config: Config = serde_yaml::from_str(&config)?; let mut context = Context::new(config); if let Some(next) = context.next() { next.execute(&mut context, HashMap::new())?; } Ok(()) } ``` wechat.rs ```use crate::{Context, Input, Inputs, Workflow}; use anyhow::Result; use reqwest::blocking::Client; use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Debug, Deserialize)] pub struct WeChatAccessToken { #[serde(rename = "errcode")] error_code: u64, #[serde(rename = "errmsg")] error_message: String, access_token: String, expires_in: u64, } #[derive(Debug, Serialize)] struct WeChatMessage<'a> { #[serde(rename = "touser")] to_user: &'a str, #[serde(rename = "toparty")] to_party: Option<&'a str>, #[serde(rename = "agentid")] agent_id: i64, #[serde(rename = "msgtype")] message_type: &'a str, text: WeChatMessageText<'a>, #[serde(serialize_with = "crate::util::bool_to_int")] enable_duplicate_check: bool, duplicate_check_interval: u64, } #[derive(Debug, Serialize)] struct WeChatMessageText<'a> { content: &'a str, } #[derive(Debug, Deserialize)] struct WeChatSendResponse { #[serde(rename = "errcode")] error_code: u64, #[serde(rename = "errmsg")] error_message: String, } pub struct WeChat {} impl WeChat { // Input const CORP_ID: &'static str = "corp_id"; const CORP_SECRET: &'static str = "secret"; const AGENT_ID: &'static str = "agent_id"; const TEXT: &'static str = "text"; const PARAMS: [&'static str; 4] = [ WeChat::CORP_ID, WeChat::CORP_SECRET, WeChat::AGENT_ID, WeChat::TEXT, ]; // Output const ERROR_CODE: &'static str = "error_code"; const OUTPUT: [&'static str; 0] = []; } impl Workflow for WeChat { fn execute(&self, context: &mut Context, input: Inputs) -> Result<()> { let corp_id = input.parameter(WeChat::CORP_ID); let secret = input.parameter(WeChat::CORP_SECRET); let agent_id = input.parameter(WeChat::AGENT_ID).parse()?; let text = input.parameter(WeChat::TEXT); let client = Client::new(); let url = format!( "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}", corp_id, secret ); let response = client.get(&url).send()?; let token: WeChatAccessToken = response.json()?; let message = WeChatMessage { to_user: "@all", to_party: None, agent_id: agent_id, message_type: "text", text: WeChatMessageText { content: text }, enable_duplicate_check: false, duplicate_check_interval: 0, }; let url = format!( "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}", token.access_token ); let response: WeChatSendResponse = client.post(&url).json(&message).send()?.json()?; let mut result = HashMap::new(); result.insert(WeChat::ERROR_CODE, response.error_code.to_string()); if let Some(next) = context.next() { next.execute(context, result)?; } Ok(()) } fn parameters(&self) -> &'static [&'static str] { return &WeChat::PARAMS; } fn outputs(&self) -> &'static [&'static str] { return &WeChat::OUTPUT; } } ``` save.rs ```use crate::{Context, Input, Inputs, Workflow}; use anyhow::Result; use std::io::Write; use std::{collections::HashMap, fs::File}; pub struct Save {} impl Save { // Input const TEXT: &'static str = "text"; const DESTINATION: &'static str = "destination"; const PARAMS: [&'static str; 2] = [Save::TEXT, Save::DESTINATION]; const OUTPUT: [&'static str; 0] = []; } impl Workflow for Save { fn execute(&self, context: &mut Context, input: Inputs) -> Result<()> { let text = input.parameter(Save::TEXT); let destination = input.parameter(Save::DESTINATION); let mut file = File::create(destination)?; file.write_all(text.as_bytes())?; if let Some(next) = context.next() { next.execute(context, HashMap::new())?; } Ok(()) } fn parameters(&self) -> &'static [&'static str] { return &Save::PARAMS; } fn outputs(&self) -> &'static [&'static str] { return &Save::OUTPUT; } } ``` parser.rs ```use crate::Context; use anyhow::{anyhow, Context as _, Result}; use nom::{ branch::alt, bytes::complete::{is_not, tag}, character::complete::{char, multispace0}, combinator::map, multi::fold_many1, sequence::{delimited, preceded, separated_pair}, IResult, }; use std::collections::HashMap; pub fn fulfill(raw: &str, input: &HashMap<String, String>, context: &Context) -> Result<String> { let (_, texts) = parse(raw).map_err(|_| anyhow!("Unable to parse expression {}.", raw))?; let mut result = String::new(); for text in texts { result.push_str(match text { Text::Literal(s) => s, Text::Expression(Expression { namespace, field }) if namespace == "env" => context .env .get(field) .with_context(|| format!("Missing {}.", field))?, Text::Expression(Expression { namespace: _, field, }) => input .get(field) .with_context(|| format!("Missing {}.", field))?, }); } Ok(result) } #[derive(Debug, Clone, PartialEq, Eq)] enum Text<'a> { Literal(&'a str), Expression(Expression<'a>), } #[derive(Debug, Clone, PartialEq, Eq)] struct Expression<'a> { namespace: &'a str, field: &'a str, } fn literal(input: &str) -> IResult<&str, Text> { map(is_not("{"), |s: &str| Text::Literal(s))(input) } fn namespace(input: &str) -> IResult<&str, &str> { alt((tag("input"), tag("env")))(input) } fn field(input: &str) -> IResult<&str, &str> { is_not("\t }")(input) } fn expression(input: &str) -> IResult<&str, Expression> { map(separated_pair(namespace, tag("."), field), |(ns, f)| { Expression { namespace: ns, field: f, } })(input) } fn enclosed(input: &str) -> IResult<&str, Text> { map( delimited( char('{'), preceded(multispace0, expression), preceded(multispace0, char('}')), ), |expr| Text::Expression(expr), )(input) } fn parse(input: &str) -> IResult<&str, Vec<Text>> { fold_many1(alt((literal, enclosed)), Vec::new(), |mut acc, t| { acc.push(t); acc })(input) } #[cfg(test)] mod tests { use super::*; #[test] fn test_enclosed_expression() { assert_eq!( enclosed("{ env.gist_secret }"), Ok(( "", Text::Expression(Expression { namespace: "env", field: "gist_secret" }) )) ); assert_eq!( enclosed("{input.status_code}"), Ok(( "", Text::Expression(Expression { namespace: "input", field: "status_code" }) )) ); } #[test] fn test_text() { assert_eq!( parse("hello {env.ttt}"), Ok(( "", vec![ Text::Literal("hello "), Text::Expression(Expression { namespace: "env", field: "ttt" }) ] )) ); assert_eq!( parse("这是 Server 结果 {input.status_code}, 今天天气是 {input.text}。"), Ok(( "", vec![ Text::Literal("这是 Server 结果 "), Text::Expression(Expression { namespace: "input", field: "status_code" }), Text::Literal(", 今天天气是 "), Text::Expression(Expression { namespace: "input", field: "text" }), Text::Literal("。"), ] )) ); } } ``` echo.rs ```use crate::{Context, Input, Inputs, Workflow}; use anyhow::Result; use std::collections::HashMap; pub struct Echo {} impl Echo { // Input const TEXT: &'static str = "text"; const PARAMS: [&'static str; 1] = [Echo::TEXT]; const OUTPUT: [&'static str; 0] = []; } impl Workflow for Echo { fn execute(&self, context: &mut Context, input: Inputs) -> Result<()> { let text = input.parameter(Echo::TEXT); println!("{}", text); if let Some(next) = context.next() { next.execute(context, HashMap::new())?; } Ok(()) } fn parameters(&self) -> &'static [&'static str] { return &Echo::PARAMS; } fn outputs(&self) -> &'static [&'static str] { return &Echo::OUTPUT; } } ```
zi-mo/brim
zi-mo/brim parser.ts ```// This is where we depend on a script buried in a zq // node module in the root directory to parse z. // @ts-ignore import parser from "zq/compiler/parser/parser" // @ts-ignore export const parse = parser.parse ```
ziadaljuhany/node-todo-api
ziadaljuhany/node-todo-api mongoose.js ```var mongoose = require('mongoose'); mongoose.Promise = global.Promise; // Connect to Heroku App // mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true }); // Connect to Local App mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useFindAndModify: false, useCreateIndex: true }); module.exports = {mongoose};```
zidongzhang/api_demo
zidongzhang/api_demo CommentServer.py ```#!/usr/bin/env python import sys import os import time import urllib import urllib2 import json class CommentServer(): def __init__(self, host): self.__host = host return def add_comment(self, username, userid, userpic, usercomment, docid): url = "https://%s/v1/comment/action" % (self.__host) headers = {} headers["Content-Type"] = "application/json; charset=utf-8" headers["Authorization"] = "anonym=%s" % (userid) storge = {} storge["type"] = "inneradd" storge["refId"] = "d-%s" % (docid) storge["name"] = username storge["photo"] = userpic storge["content"] = usercomment data = json.dumps(storge) req = urllib2.Request(url, headers = headers, data = data) try: response = urllib2.urlopen(req) result = response.read() except Exception, ex: result = False print json print ex return result if __name__ == "__main__": comment_server = CommentServer("") test_data_username = "Adam" test_data_userid = "fd8f9136-777d-3a0c-bd73-d6f9ea0655b1" test_data_userpic = "http://profile.egloos.net/f0303947_50.jpg" test_data_usercomment ="That was awesome" test_data_docid = "bd095ac1b7193d2fb662585597465f01" comment_server.add_comment(test_data_username, test_data_userid, test_data_userpic, test_data_usercomment, test_data_docid) ``` UserSelector.py ```#!/usr/bin/python """ Funcion: Select a random user from the user pool while attching him/her with a given comment. Usage: Author: Update: 2016-07-12 20:28:32 """ import sys import os sys.path.append('../conf/') reload(sys) sys.setdefaultencoding('utf8') from config import * import random import time from CommentServer import CommentServer class UserSelector: """ Select a random user from the user pool while attaching his/her information with a given comment. """ def __init__(self, file_name): """ Get information of a random user """ openfile = open(file_name, "r") self.__user_pool = openfile.readlines() openfile.close() self.__comment_server = CommentServer(COMMENT_SERVER) return def random_pick_user(self, commentlist,docid): """ Randomly pick an user and collect his/her information(including username, userid and profile picture). """ for comment in commentlist: user = random.choice(self.__user_pool) user_info = user.split() user_name = user_info[0] user_id = user_info[1] user_picture = user_info[2] self.__comment_server.add_comment(user_name, user_id, user_picture, comment, docid) """ user_info: user's information(including username, userid and profile picture) """ time.sleep(0.1) return if __name__ == "__main__": """ Data testing section (Will not run if using UserSelector as a class). """ user_selector = UserSelector("writefilefinal02.txt") test_commentlist = ["commnet1", "comment2", "comment3"] docid = "bd095ac1b7193d2fb662585597465f01" user_selector.random_pick_user(test_commentlist,docid) ```
zigabe/zigabe
zigabe/zigabe README.md ```- 👋 Hi, I’m @zigabe - 👀 I’m interested in PM - 🌱 I’m currently learning Typescript - 💞️ I’m looking to collaborate on Project management - 📫 How to reach me zigabemg@gmail.com <!--- zigabe/zigabe is a ✨ special ✨ repository because its `README.md` (this file) appears on your GitHub profile. You can click the Preview link to take a look at your changes. ---> ```
ziggyt/tester
ziggyt/tester CarFactory.java ```import java.util.Random; public class CarFactory { private Car currentCar; private String availableCars[] = {"Volvo", "Saab95", "Scania"}; private int randomInt; int getRandomInt() { Random random = new Random(); randomInt = random.nextInt(3); return randomInt; } Car getNewVehicle(String carModel) { carModel = carModel.toLowerCase(); if (carModel.equals("random")) { carModel = availableCars[getRandomInt()]; } switch (carModel) { case "volvo": return new Volvo240(); case "saab95": return new Saab95(); case "scania": return new Scania(); default: return null; } } } ```
zigmars-odins/myappsample
zigmars-odins/myappsample README.md ```#heading This is my app```
zigyxxer/WeatherDemo
zigyxxer/WeatherDemo Constants.java ```package com.zwh.weatherdemo; /** * Created by zwh on 17-9-20. */ public class Constants { public static final int UPDATE_WEATHER = 0; public static final int UPDATE_ERROR = -1; } ``` IconList.java ```package com.zwh.weatherdemo; /** * Created by zwh on 17-9-19. */ public class IconList { } ``` MainActivity.java ```package com.zwh.weatherdemo; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Text; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.net.ssl.HttpsURLConnection; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { private EditText nameCity = null; private Button search = null; private ImageView weather_now_icon = null; private TextView city = null; private TextView description = null; private TextView tempture = null; private TextView quality = null; private TextView wind = null; private TextView humidity = null; private LinearLayout hourForcast = null; private LinearLayout dayForcast = null; private LinearLayout comfortIndex = null; private ProgressDialog progressDialog = null; private ListView mHourListView = null; private ListView mDailyListView = null; private TextView comfortDesc = null; private static final String string_na = "NA"; private static final String TAG = "zhangwenhao"; private HashMap iconList = null; JSONObject nowData = null; private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case Constants.UPDATE_WEATHER: hideProgressDialog(); updateNowWeather(); updateHourWeather(); updateDailyWeather(); updateComfortDescription(); break; case Constants.UPDATE_ERROR: hideProgressDialog(); showErrorMessage("Error occur while getting weather data, please retry!"); break; } super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); initIconList(); } private void init(){ nameCity = (EditText) findViewById(R.id.cityName); search = (Button) findViewById(R.id.search_now); weather_now_icon = (ImageView) findViewById(R.id.weather_icon_now); search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (nameCity != null){ hideSoftKeyBoard(); String cityName = nameCity.getText().toString(); Log.e(TAG,"onclick " + cityName); showProgressDialog("请求中","正在获取数据"); getJSON(cityName); } } }); city = (TextView) findViewById(R.id.city); description = (TextView) findViewById(R.id.description); tempture = (TextView) findViewById(R.id.tempture); quality = (TextView) findViewById(R.id.quality); wind = (TextView) findViewById(R.id.wind); humidity = (TextView) findViewById(R.id.humidity); hourForcast = (LinearLayout) findViewById(R.id.hour_forcast); dayForcast = (LinearLayout) findViewById(R.id.day_forcast); comfortIndex = (LinearLayout) findViewById(R.id.comfort_index); mHourListView = (ListView) findViewById(R.id.hour_list); mDailyListView = (ListView) findViewById(R.id.daily_list); comfortDesc = (TextView) findViewById(R.id.comfort_desc); comfortDesc.setMovementMethod(ScrollingMovementMethod.getInstance()); } public void getJSON(final String city) { String url = "https://free-api.heweather.com/v5/weather?city="+city+"&key=f44ded18a48940e5a45f5cfdb566315b"; OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Call call = okHttpClient.newCall(request); okHttpClient.newBuilder().connectTimeout(60, TimeUnit.SECONDS); okhttp3.Callback callback = new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG,"get weather data error "); Message msg = Message.obtain(); msg.what = Constants.UPDATE_ERROR; mHandler.sendMessage(msg); } @Override public void onResponse(Call call, Response response) throws IOException { try { String json = response.body().string(); Log.e(TAG,json); nowData = new JSONObject(json); if (nowData == null){ Log.e(TAG,"null"); }else { Log.e(TAG,nowData.toString()); } Message msg = Message.obtain(); msg.what = Constants.UPDATE_WEATHER; mHandler.sendMessage(msg); }catch (JSONException e){ e.printStackTrace(); } } }; call.enqueue(callback); } public void showErrorMessage(String msg){ Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show(); } public void initIconList(){ iconList = new HashMap(); iconList.put("100",R.drawable.a100); iconList.put("101",R.drawable.a101); iconList.put("102",R.drawable.a102); iconList.put("103",R.drawable.a103); iconList.put("104",R.drawable.a104); iconList.put("200",R.drawable.a200); iconList.put("201",R.drawable.a201); iconList.put("202",R.drawable.a202); iconList.put("203",R.drawable.a203); iconList.put("204",R.drawable.a204); iconList.put("205",R.drawable.a205); iconList.put("206",R.drawable.a206); iconList.put("207",R.drawable.a207); iconList.put("208",R.drawable.a208); iconList.put("209",R.drawable.a209); iconList.put("210",R.drawable.a210); iconList.put("211",R.drawable.a211); iconList.put("212",R.drawable.a212); iconList.put("213",R.drawable.a213); iconList.put("300",R.drawable.a300); iconList.put("301",R.drawable.a301); iconList.put("302",R.drawable.a302); iconList.put("303",R.drawable.a303); iconList.put("304",R.drawable.a304); iconList.put("305",R.drawable.a305); iconList.put("306",R.drawable.a306); iconList.put("307",R.drawable.a307); iconList.put("308",R.drawable.a308); iconList.put("309",R.drawable.a309); iconList.put("310",R.drawable.a310); iconList.put("311",R.drawable.a311); iconList.put("312",R.drawable.a312); iconList.put("313",R.drawable.a313); iconList.put("400",R.drawable.a400); iconList.put("401",R.drawable.a401); iconList.put("402",R.drawable.a402); iconList.put("403",R.drawable.a403); iconList.put("404",R.drawable.a404); iconList.put("405",R.drawable.a405); iconList.put("406",R.drawable.a406); iconList.put("407",R.drawable.a407); iconList.put("500",R.drawable.a500); iconList.put("501",R.drawable.a501); iconList.put("502",R.drawable.a502); iconList.put("503",R.drawable.a503); iconList.put("504",R.drawable.a504); iconList.put("507",R.drawable.a507); iconList.put("508",R.drawable.a508); iconList.put("900",R.drawable.a900); iconList.put("901",R.drawable.a901); iconList.put("999",R.drawable.a999); } public boolean isStatusOk(JSONObject data){ if (data != null){ try { return "ok".equals(data.getJSONArray("HeWeather5").getJSONObject(0).getString("status")); }catch (JSONException e){ e.printStackTrace(); return false; } } return false; } public class NowWeatherData{ public int iconId ; public String city ; public String description; public String tempture; public String quality; public String wind; public String humidity; public NowWeatherData(int iconId, String city, String description, String tempture, String quality, String wind, String humidity) { this.iconId = iconId; this.city = city; this.description = description; this.tempture = tempture; this.quality = quality; this.wind = wind; this.humidity = humidity; } } public class HourWeatherData{ public int hour_icon; public String hour_time; public String hour_description; public String hour_tempture; public String hour_wind; public HourWeatherData(int hour_icon, String hour_time, String hour_description, String hour_tempture, String hour_wind) { this.hour_icon = hour_icon; this.hour_time = hour_time; this.hour_description = hour_description; this.hour_tempture = hour_tempture; this.hour_wind = hour_wind; } } public class DailyWeatherData{ public String daily_time; public int daily_d_icon; public String daily_d_description; public String daily_tempture; public String daily_hum; public int daily_n_icon; public String daily_n_description; public String daily_wind; public String daily_sun; public DailyWeatherData(String daily_time, int daily_d_icon, String daily_d_description, String daily_tempture, String daily_hum, int daily_n_icon, String daily_n_description, String daily_wind, String daily_sun) { this.daily_time = daily_time; this.daily_d_icon = daily_d_icon; this.daily_d_description = daily_d_description; this.daily_tempture = daily_tempture; this.daily_hum = daily_hum; this.daily_n_icon = daily_n_icon; this.daily_n_description = daily_n_description; this.daily_wind = daily_wind; this.daily_sun = daily_sun; } } public NowWeatherData getNowWeatherData(){ Log.e(TAG,"getNowWeatherData"); if(nowData == null){ Log.e(TAG,"nowData == null"); return null; } try { JSONObject temp = nowData.getJSONArray("HeWeather5").getJSONObject(0); String city = temp.getJSONObject("basic").getString("city"); String icon_string = temp.getJSONObject("now").getJSONObject("cond").getString("code"); int iconId = Integer.parseInt((iconList.get(icon_string)).toString()); String description = temp.getJSONObject("now").getJSONObject("cond").getString("txt"); String tempture = temp.getJSONObject("now").getString("tmp") + "℃"; String quality; if (temp.has("aqi")){ quality = temp.getJSONObject("aqi").getJSONObject("city").getString("qlty"); }else { quality = string_na; } String wind = temp.getJSONObject("now").getJSONObject("wind").getString("dir") + " " + temp.getJSONObject("now").getJSONObject("wind").getString("sc"); String humidity = temp.getJSONObject("now").getString("hum") + "%"; NowWeatherData nowWeatherData = new NowWeatherData(iconId,city,description,tempture,quality,wind,humidity); return nowWeatherData; }catch(JSONException e){ Log.e(TAG,"getNowWeatherData JSONException" + e.getCause().getMessage()); e.printStackTrace(); } return null; } List<Map<String, Object>> getHourData(){ if (nowData == null){ return null; } List<HourWeatherData> hourWeatherDatas = getHourWeatherData(); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map; for (HourWeatherData hourWeatherData:hourWeatherDatas) { map = new HashMap<String, Object>(); map.put("hour_icon", hourWeatherData.hour_icon); map.put("hour_time", hourWeatherData.hour_time); map.put("hour_description", hourWeatherData.hour_description); map.put("hour_tempture",hourWeatherData.hour_tempture); map.put("hour_wind",hourWeatherData.hour_wind); list.add(map); } return list; } List<Map<String, Object>> getDailyData(){ if (nowData == null){ return null; } List<DailyWeatherData> dailyWeatherDatas = getDailyWeatherData(); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map; for (DailyWeatherData dailyWeatherData:dailyWeatherDatas) { map = new HashMap<String, Object>(); map.put("daily_time", dailyWeatherData.daily_time); map.put("daily_d_icon", dailyWeatherData.daily_d_icon); map.put("daily_d_description", dailyWeatherData.daily_d_description); map.put("daily_tempture",dailyWeatherData.daily_tempture); map.put("daily_hum",dailyWeatherData.daily_hum); map.put("daily_n_icon",dailyWeatherData.daily_n_icon); map.put("daily_n_description", dailyWeatherData.daily_n_description); map.put("daily_wind",dailyWeatherData.daily_wind); map.put("daily_sun",dailyWeatherData.daily_sun); list.add(map); } return list; } public List<HourWeatherData> getHourWeatherData(){ List<HourWeatherData> hourWeatherDatas = new ArrayList<>(); try { JSONArray hourly_data = nowData.getJSONArray("HeWeather5").getJSONObject(0).getJSONArray("hourly_forecast"); int hourly_length = hourly_data.length(); for (int i = 0; i < hourly_length; i++){ JSONObject temp = hourly_data.getJSONObject(i); String icon_string = temp.getJSONObject("cond").getString("code"); int hour_icon = Integer.parseInt((iconList.get(icon_string)).toString()); String hour_time = temp.getString("date").split(" ")[1]; String hour_description = temp.getJSONObject("cond").getString("txt"); String hour_tempture = temp.getString("tmp") + "℃"; String hour_wind = temp.getJSONObject("wind").getString("dir"); HourWeatherData hourWeatherData = new HourWeatherData(hour_icon,hour_time,hour_description,hour_tempture,hour_wind); hourWeatherDatas.add(hourWeatherData); } }catch (JSONException e){ e.printStackTrace(); } return hourWeatherDatas; } public List<DailyWeatherData> getDailyWeatherData(){ List<DailyWeatherData> dailyWeatherDatas = new ArrayList<>(); try { JSONArray daily_data = nowData.getJSONArray("HeWeather5").getJSONObject(0).getJSONArray("daily_forecast"); int daily_length = daily_data.length(); for (int i = 0; i < daily_length; i++){ JSONObject temp = daily_data.getJSONObject(i); String daily_time = temp.getString("date"); String icon_d_string = temp.getJSONObject("cond").getString("code_d"); int daily_d_icon = Integer.parseInt((iconList.get(icon_d_string)).toString()); String daily_d_description = temp.getJSONObject("cond").getString("txt_d"); String daily_tempture = temp.getJSONObject("tmp").getString("max") + "℃" + "/" + temp.getJSONObject("tmp").getString("min") + "℃"; String daily_hum = temp.getString("hum") + "%"; String icon_n_string = temp.getJSONObject("cond").getString("code_n"); int daily_n_icon = Integer.parseInt((iconList.get(icon_n_string)).toString()); String daily_n_description = temp.getJSONObject("cond").getString("txt_n"); String daily_wind = temp.getJSONObject("wind").getString("dir"); String daily_sun = temp.getJSONObject("astro").getString("sr") + "/" +temp.getJSONObject("astro").getString("ss"); DailyWeatherData dailyWeatherData =new DailyWeatherData(daily_time,daily_d_icon,daily_d_description, daily_tempture,daily_hum,daily_n_icon,daily_n_description,daily_wind,daily_sun); dailyWeatherDatas.add(dailyWeatherData); } }catch (JSONException e){ e.printStackTrace(); } return dailyWeatherDatas; } public String getComfortDescription(){ try { String desc = nowData.getJSONArray("HeWeather5").getJSONObject(0).getJSONObject("suggestion").getJSONObject("comf").getString("brf") + ":" +nowData.getJSONArray("HeWeather5").getJSONObject(0).getJSONObject("suggestion").getJSONObject("comf").getString("txt"); return desc; }catch (JSONException e){ e.printStackTrace(); } return "no suggestion"; } public void updateNowWeather(){ Log.e(TAG,"updateWeather"); if (nowData == null){ Log.e(TAG,"nul;ss"); return; } NowWeatherData nowWeatherData = getNowWeatherData(); weather_now_icon.setImageResource(nowWeatherData.iconId); city.setText(nowWeatherData.city); description.setText(nowWeatherData.description); tempture.setText(nowWeatherData.tempture); quality.setText(nowWeatherData.quality); wind.setText(nowWeatherData.wind); humidity.setText(nowWeatherData.humidity); } public void updateHourWeather(){ Log.e(TAG,"updateHourWeather"); if (nowData == null){ Log.e(TAG,"nul;ss"); return; } hourForcast.setVisibility(View.VISIBLE); SimpleAdapter simpleAdapter = new SimpleAdapter(this,getHourData(),R.layout.hour_weather_item, new String[]{"hour_icon", "hour_time", "hour_description", "hour_tempture","hour_wind"}, new int[]{R.id.hour_icon, R.id.hour_time, R.id.hour_description, R.id.hour_tempture, R.id.hour_wind}); mHourListView.setAdapter(simpleAdapter); } public void updateDailyWeather(){ Log.e(TAG,"updateDailyWeather"); if (nowData == null){ Log.e(TAG,"nul;ss"); return; } dayForcast.setVisibility(View.VISIBLE); SimpleAdapter simpleAdapter = new SimpleAdapter(this,getDailyData(),R.layout.daily_weather_item, new String[]{"daily_time","daily_d_icon","daily_d_description","daily_tempture","daily_hum","daily_n_icon","daily_n_description","daily_wind","daily_sun"}, new int[]{R.id.daily_time,R.id.daily_d_icon,R.id.daily_d_description,R.id.daily_tempture,R.id.daily_hum,R.id.daily_n_icon,R.id.daily_n_description,R.id.daily_wind,R.id.daily_sun}); mDailyListView.setAdapter(simpleAdapter); } public void updateComfortDescription(){ comfortIndex.setVisibility(View.VISIBLE); comfortDesc.setText(getComfortDescription()); } public void showProgressDialog(String title, String message) { if (progressDialog == null) { progressDialog = ProgressDialog.show(MainActivity.this, title, message, true, false); } else if (progressDialog.isShowing()) { progressDialog.setTitle(title); progressDialog.setMessage(message); } progressDialog.show(); } public void hideProgressDialog(){ if (progressDialog != null && progressDialog.isShowing()){ progressDialog.dismiss(); } } public void hideSoftKeyBoard(){ InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (imm.isActive()) { //imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); imm.hideSoftInputFromWindow(nameCity.getWindowToken(),0); } } } ```
zihanyu/Study-notes-
zihanyu/Study-notes- README.md ```# Study-notes- “学习汪” ```
ziizium/readings-in-web-development
ziizium/readings-in-web-development README.md ```# Readings in web development This repository contains link to __articles that I have read__ in web development. The __objective__ is to read at least __two articles per day__ starting Februrary 2020 for the foreseeable future. The date of the articles are the actually date when I read the articles. ## 18<sup>th</sup> February 2020 * [Why JavaScript is Eating HTML](https://css-tricks.com/why-javascript-is-eating-html/) by Mike Turley on [css-tricks](https://css-tricks.com) * [ARIA labels](https://amberwilson.co.uk/blog/aria-labels/) by [Amber wilson](https://amberwilson.co.uk/) ## 19<sup>th</sup> February 2020 * [A Complete Guide to Links and Buttons](https://css-tricks.com/a-complete-guide-to-links-and-buttons/) on [css-tricks](https://css-tricks.com) * [A Complete Guide to Data Attributes](https://css-tricks.com/a-complete-guide-to-data-attributes/) on [css-tricks](https://css-tricks.com) ## 23<sup>rd</sup> February 2020 * [Accessible unethical technology](https://laurakalbag.com/accessible-unethical-technology/) by [Laura Kalbag](https://laurakalbag.com) * [A decade of heading backwards](https://codepen.io/stevef/post/a-decade-of-heading-backwards) by [Steve faulkner](https://codepen.io/stevef/) * [CSS Can Influence Screenreaders](https://blog.benmyers.dev/css-can-influence-screenreaders/) by [Ben Mayers](https://www.benmyers.dev/) * [Custom Styling Form Inputs With Modern CSS Features](https://css-tricks.com/custom-styling-form-inputs-with-modern-css-features/) by [Aaron Iker](https://aaroniker.me/) ## 24<sup>th</sup> February 2020 * [JavaScript Libraries Are Almost Never Updated Once Installed](https://blog.cloudflare.com/javascript-libraries-are-almost-never-updated/) * [#16 alt, no wait…, aria-label, no wait…, alt](https://www.htmhell.dev/alt-no-aria-label-no-alt/) ## 25<sup>th</sup> February 2020 * [The case for learning sign language as an accessibility engineer](https://developer.paciellogroup.com/blog/2020/02/the-case-for-learning-sign-language-as-an-accessibility-engineer/) * [Squarespace, Wix, & Weebly: Accessibility Review](http://terrillthompson.com/1203) by [Terrill Thompson](http://terrillthompson.com/) ## 26<sup>th</sup> February 2020 * [The JavaScript Thread of Execution, Visually Explained](https://alligator.io/js/thread-of-execution/) by [Paul Ryan](https://www.paulryancodes.com/) * [User experience and cognitive load: when less is more](https://uxdesign.cc/user-experience-and-perception-when-less-is-more-f7939943b2e9) by [Ed Orozco](https://www.edorozco.com/) ## 27<sup>th</sup> February 2020 * [Learn CSS Positioning](https://ishadeed.com/article/learn-css-positioning/) by [Ahmed Shadeed](https://ishadeed.com/) * [Styling the good ol' button](https://ishadeed.com/article/styling-the-good-old-button/) by [Ahmed Shadeed](https://ishadeed.com/) ## 29<sup>th</sup> February 2020 * [Why Supporting Unlabeled UTF-8 in HTML on the Web Would Be Problematic](https://hsivonen.fi/utf-8-detection/) by [Henri Sivonen](https://hsivonen.fi/author/) * [Autofill on Browsers: A Deep Dive](https://tech.ebayinc.com/engineering/autofill-deep-dive/) * [Google’s AMP HTML](https://adrianroselli.com/2015/10/googles-amp-html.html) by [Adrian Roselli](adrianroselli.com) * [Authoring the Authors: Accessibility Best practices for Content authors](https://www.digitala11y.com/authoring-the-authors-accessibility-best-practices-for-content-authors/) by [Raghavendra Satish Peri](https://raghava.in/) * [One of my favourite accessibility testing tools: The Tab Key](https://www.matuzo.at/blog/testing-with-tab/) by [Manuel Matuzovic](https://www.matuzo.at/) ## 1<sup>st</sup> March 2020 * [When CSS Blocks](https://timkadlec.com/remembers/2020-02-13-when-css-blocks/) by [Tim Kadlec](https://timkadlec.com) * [Designing without the packaging](https://gerrymcgovern.com/designing-without-the-packaging/) by [Garry McGovern](https://gerrymcgovern.com) * [Web bloat](https://danluu.com/web-bloat/) by [Dan Luu](https://danluu.com/) ## 2<sup>nd</sup> March 2020 * [Role-up](https://adrianroselli.com/2020/02/role-up.html) by [Adrian Roselli](https://adrianroselli.com) * [Toward Responsive Elements](https://bkardell.com/blog/TowardResponsive.html) by [Brian Kardell](https://bkardell.com/) * [Three Goals of Usability Testing](https://measuringu.com/three-goals/) * [The Guide to Accessible Web Components](https://www.erikkroes.nl/blog/accessibility/the-guide-to-accessible-web-components-draft/) by [Erik Kroes](https://www.erikkroes.nl/) * [Hyphens and dashes](https://readabilityguidelines.co.uk/grammar-points/hyphens-and-dashes/) ## 3<sup>rd</sup> March 2020 * [Select an Element with a Non-Empty Attribute](https://css-tricks.com/select-an-element-with-a-non-empty-attribute/) by [Chris Coyier](https://chriscoyier.net) * [Testing aria-live support](https://moiety.me/research/aria-live/) by [Zoë Bijl](https://moiety.me) * [Hydration](https://adactio.com/journal/16404) by [Jeremy Keith](https://adactio.com/) * [Link Targets and 3.2.5](https://adrianroselli.com/2020/02/link-targets-and-3-2-5.html) by [Adrian Roselli](https://adrianroselli.com/) * [Dropdown Menus 2020: Menus are not menus](http://terrillthompson.com/1226) by [Terril Thompson](http://terrillthompson.com) ## 5<sup>th</sup> March 2020 * [Avoid These 10 UX Design Fails](https://usabilitygeek.com/avoid-these-10-ux-design-fails/) * [How Can We Make URLs Readable?](https://www.lireo.com/make-urls-readable/) * [We need more editors](https://gerrymcgovern.com/we-need-more-editors/) by [Garry McGovern](https://gerrymcgovern.com/) * [5 tips for making your app accessible](https://blogs.intuit.com/blog/2020/01/28/5-tips-for-making-your-app-accessible/) * [Could browsers fix more accessibility problems automatically?](https://hiddedevries.nl/en/blog/2020-02-04-could-browsers-fix-more-accessibility-problems-automatically) by [Hidde de Vries](https://hiddedevries.nl/en/about-me/) * [Here’s what I didn’t know about list-style-type](https://www.matuzo.at/blog/heres-what-i-didnt-know-about-list-style-type/) by [Manuel Matuzovic](https://www.matuzo.at/) ## 8<sup>th</sup> March 2020 * [A very handy guide to moderated and unmoderated testing](https://www.userzoom.com/blog/a-very-handy-guide-to-moderated-and-unmoderated-testing/) * [Accessibility: why you should get on board](https://gds.blog.gov.uk/2020/01/28/accessibility-why-you-should-get-on-board/) * [What does “revert” do in CSS?](https://css-tricks.com/what-does-revert-do-in-css/) by [Chris Coyier](https://chriscoyier.net) * [Dark Mode vs. Light Mode: Which Is Better?](https://www.nngroup.com/articles/dark-mode/) ## 9<sup>th</sup> March 2020 * [What's the value of prototyping in UX design?](https://www.nomensa.com/blog/2020/whats-value-prototyping-ux-design) * [User Research May Be the Most Important Role in Your Company](https://www.uxbooth.com/articles/user-research-may-be-the-most-important-role-in-your-company/) ## 10<sup>th</sup> March 2020 * [Progressive enhancement doesn't have to be hard](https://levimcg.com/posts/progressive-enhancement-doesnt-have-to-be-hard/) * [Understanding Immutability in JavaScript](https://css-tricks.com/understanding-immutability-in-javascript/) * [Why use a form element when submitting fields with JavaScript?](https://gomakethings.com/why-use-a-form-element-when-submitting-fields-with-javascript/) * [Building an accessible autocomplete control](https://adamsilver.io/articles/building-an-accessible-autocomplete-control/) by [Adam Silver](https://adamsilver.io/) ## 11<sup>th</sup> March 2020 * [AI Is Changing Web Development](https://www.enterpriseai.news/2020/01/13/ai-is-changing-web-development/) * [Data expands to fill the space available (Part 2)](https://gerrymcgovern.com/data-expands-to-fill-the-space-available-part-2/) * [Information Scent: How Users Decide Where to Go Next](https://www.nngroup.com/articles/information-scent/) * [placeholder - the piss-take label](https://codepen.io/stevef/post/placeholder-the-piss-take-label) ## 12<sup>th</sup> March 2020 * [Decoding Label and Name for Accessibility](https://webaim.org/articles/label-name/) * [Focus management still matters](https://sarahmhigley.com/writing/focus-navigation-start-point/) ## 13<sup>th</sup> March 2020 * [5 Things You Need to Know About Manual Accessibility Testing with the Keyboard and Screen Readers](https://dev.to/madalynrose/5-things-you-need-to-know-about-manual-accessibility-testing-with-the-keyboard-and-screen-readers-3512) * [Missing Form Label – Site Search example](https://blog.pope.tech/2020/02/28/missing-form-label-search/) ## 15<sup>th</sup> March 2020 * [Why accessibility is an important part of Customer Experience (CX)](https://www.nomensa.com/blog/2020/why-accessibility-important-part-customer-experience-cx) * [PWAC + OZeWAI 2020 conference highlights](https://www.hollier.info/pwac2020/) * [State websites show dozens of accessibility errors, may violate Americans with Disabilities Act](https://www.channel3000.com/state-websites-show-dozens-of-accessibility-errors-may-violate-americans-with-disabilities-act/) * [10 Ways to Hide Elements in CSS](https://www.sitepoint.com/hide-elements-in-css/) ## 17<sup>th</sup> March 2020 * [Responsive Grid Magazine Layout in Just 20 Lines of CSS](https://css-tricks.com/responsive-grid-magazine-layout-in-just-20-lines-of-css/) * [Negative margins in CSS](https://www.quirksmode.org/blog/archives/2020/02/negative_margin.html) by [Peter-Paul Koch](https://twitter.com/ppk) ## 18<sup>th</sup> March 2020 * [Why is CSS Frustrating?](https://css-tricks.com/why-is-css-frustrating/) by [Robin Rendle](https://twitter.com/robinrendle) * [HTML: The Inaccessible Parts](https://daverupert.com/2020/02/html-the-inaccessible-parts/) by [Dave Rupert](https://daverupert.com) ## 04<sup>th</sup> April 2020 * [Web Accessibility Checklist 16 Things to Improve Your Website Accessibility](https://websitesetup.org/web-accessibility-checklist/) by [Bruce Lawson](https://www.brucelawson.co.uk/) * [Create Your Own AHA Moment](https://knowbility.org/blog/2020/create-your-own-aha-moment/) by [Becky Gibson](https://knowbility.org/about/team/becky-gibson/) ## 28<sup>th</sup> April 2020 * [Everything I Know About Positioning Poppers (Tooltips, Popovers, Dropdowns) in UIs](https://dev.to/atomiks/everything-i-know-about-positioning-poppers-tooltips-popovers-dropdowns-in-uis-3nkl) by [atomiks](https://dev.to/atomiks) ## 17<sup>th</sup> May 2020 * [Accessibility 101 for Content Creators](https://jerryjones.dev/2020/05/04/accessibility-101-for-content-creators/) by [Jerry Jones](https://jerryjones.dev/) * [Exciting Things on the Horizon For CSS Layout](https://css-irl.info/exciting-things-on-the-horizon-for-css-layout/) by [Michelle Barker](https://www.michellebarker.co.uk/) * [Bolt-on Accessibility – 5 gears in reverse](https://developer.paciellogroup.com/blog/2020/05/bolt-on-accessibility-5-gears-in-reverse/) * [Micro-Typography: How To Space And Kern Punctuation Marks And Other Symbols](https://www.smashingmagazine.com/2020/05/micro-typography-space-kern-punctuation-marks-symbols/#top) by [Thomas Bohm](https://www.userdesignillustrationandtypesetting.com/) ## 29<sup>th</sup> May 2020 * [Accessible Images For When They Matter Most](https://www.smashingmagazine.com/2020/05/accessible-images/) by [Carie Fisher](https://cariefisher.com/) * [CSS Findings From Twitter Design](https://ishadeed.com/article/twitter-css/) by [Ahmad Shadeed](https://ishadeed.com) * [Thinking About The In-between Design Cases](https://ishadeed.com/article/in-between/) by [Ahmad Shadeed](https://ishadeed.com) ## 30<sup>th</sup> May 2020 * [Image Techniques On The Web](https://ishadeed.com/article/image-techniques/) by [Ahmad Shadeed](https://ishadeed.com) * [ Programming CSS to perform Sass colour functions ](https://dev.to/adactio/programming-css-to-perform-sass-colour-functions-11k9) by [Jeremy Keith](https://adactio.com) ## 11<sup>th</sup> June 2020 * [Grid for layout, Flexbox for components](https://ishadeed.com/article/grid-layout-flexbox-components/#header) by [Ahmad Shadeed](https://ishadeed.com) * [Learn Box Alignment](https://ishadeed.com/article/learn-box-alignment/) by [Ahmad Shadeed](https://ishadeed.com) ## 22<sup>nd</sup> June 2020 * [Building the Woke Web: Web Accessibility, Inclusion & Social Justice](https://alistapart.com/article/building-the-woke-web/) * [Where did the focus go?](https://amberwilson.co.uk/blog/where-did-the-focus-go/) by [Amber Wilson](https://amberwilson.co.uk/) ## 25<sup>th</sup> June 2020 * [Asynchronous JavaScript—How Callbacks, Promises, and Async-Await Work](https://dev.to/nas5w/asynchronous-javascript-how-callbacks-promises-and-async-await-work-1f7p) * [A SOLID framework - Inversion of Control Pt 1](https://dev.to/miketalbot/a-solid-framework-inversion-of-control-pt1-4jg) ## 27<sup>th</sup> June 2020 * [CSS custom properties and the cascade](https://adactio.com/journal/16993) by [Jeremy Keith](https://adactio.com/) * [How CSS Variables Can Improve Efficiency and Consistency](https://speckyboy.com/css-variables-improve-efficiency-consistency/) * [Color Craft & Counterpoint: A Designer’s Life with Color Vision Deficiency](https://alistapart.com/article/a-designers-life-with-color-vision-deficiency/) * [Digital accessibility, What’s beyond Guidelines](https://www.maxability.co.in/2020/06/16/digital-accessibility-whats-beyond-guidelines/) * [Reminder: Accessibility can’t be solved automatically](https://www.joedolson.com/2020/06/reminder-accessibility-cant-be-solved-automatically/) ## 14<sup>th</sup> July 2020 * [Putting design principles into action](https://dev.to/adactio/putting-design-principles-into-action-49hd) by [Jeremy Keith](https://adactio.com) * [How UX writing can help create good design](https://usabilitygeek.com/how-ux-writing-can-help-create-good-design/) * [Uncommon CSS Properties](https://ishadeed.com/article/uncommon-css/) by [Ahmad Shadeed](https://ishadeed.com) * [What's the point of site search?](https://idratherbewriting.com/blog/pointless-to-implement-site-search/) * [Beginners’ Guide To Writing Good HTML](https://websitesetup.org/html-tutorial-beginners/) * [CSS :is() and :where() are coming to browsers](https://webplatform.news/issues/2020-06-04) ## 5<sup>th</sup> September 2020 * [The many ways to write a color in CSS](https://dev.to/alvaromontoro/the-many-ways-to-write-a-color-in-css-2ag8) by [Alvaro Montoro](https://dev.to/alvaromontoro) ## 8<sup>th</sup> September 2020 * [CSS Mistakes While On Autopilot](https://ishadeed.com/article/css-mistakes/) by [Ahmad Shadeed](https://ishadeed.com) * [The New Facebook Login Design](https://ishadeed.com/snippet/facebook-new-login/) by [Ahmad Shadeed](https://ishadeed.com) * [The Just in Case Mindset in CSS](https://ishadeed.com/article/the-just-in-case-mindset-css/) by [Ahmad Shadeed](https://ishadeed.com) ```
zilberbe/micro-focus-hack-tlv
zilberbe/micro-focus-hack-tlv README.md ```# micro-focus-hack-tlv``` admin-common.js ``` console.log('admin-common.js'); registerAdmin = (onServerMsgCallback) => { connectToServer('ADMIN'); socket.on('server-msg', (data) => { onServerMsgCallback(data); }); }; sendAdminMsgToServer = (data) => { socket.emit('admin-msg', data); } ``` admin-games.js ``` console.log('admin-games.js'); onServerMsg = (data) => { console.log(`got message from server: ${data.msg}`); alert(data.msg); }; msgToMobiles = () => { sendAdminMsgToServer({msg: "Hi from admin"}); }; registerAdmin(onServerMsg); ``` mobile-register.js ``` console.log('mobile-register.js'); onServerMsg = (data) => { console.log(`got message from server: ${data.msg}`); alert(data.msg); }; goRegister = () => { registerMobile(document.getElementById('nameInput').value, onServerMsg); }; ``` admin-mime.js ``` console.log('admin-mime.js'); onServerMsg = (data) => { console.log(`got message from server: ${data.msg}`); }; registerAdmin(onServerMsg); ``` common.js ``` const SERVER_ADDRESS = 'localhost'; const SERVER_PORT = 4242; let socket; let userName; connectToServer = (userName) => { userName = userName; if (!socket) { console.log(`connecting to server...`); socket = io.connect(`http://${SERVER_ADDRESS}:${SERVER_PORT}`); socket.on('server-msg-user-registered', (data) => { console.log(`user registered on server`); }); } console.log(`sending username "${userName}" to server...`); socket.emit('client-msg-register-user', { userName: userName }); } ``` mobile-common.js ``` console.log('mobile-common.js'); registerMobile = (userName, onServerMsgCallback) => { connectToServer(userName); socket.on('server-msg', (data) => { onServerMsgCallback(data); }); sendMobileMsgToServer({msg: `Hi from ${userName}`}); }; sendMobileMsgToServer = (data) => { socket.emit('mobile-msg', data); } ``` server.js ``` const _ = require('lodash'); const port = 4242; const express = require('express'); const app = express(); let admin = null; let users = []; app.use(express.static('client')); app.get('/', (req, res) => { res,send('Hi from server'); }); console.log(`--------------------------------------------------------------------------------`); console.log(`server listening on port ${port}...`); server = app.listen(port); const io = require('socket.io')(server); let clientsMgr = require('./server-clients-mgr.js'); sendMsgToAdmin = (data) => { if (clientsMgr.getAdmin() !== null) { console.log(`sending msg "${data.msg}" to admin...`); clientsMgr.getAdmin().socket.emit('server-msg', data); } else { console.log(`No admin`); } } let sendMsgToAllMobiles = (socket, data) => { console.log(`sending msg "${data.msg}" to all mobiles...`); socket.broadcast.emit('server-msg', data); } io.on('connection', (socket) => { console.log(`socket ${socket.id} connected`); socket.on('client-msg-register-user', (data) => { if (data.userName === clientsMgr.ADMIN_USERNAME) { clientsMgr.registerAdmin(socket, data.userName); } else { clientsMgr.registerUser(socket, data.userName); } }); socket.on('disconnect', () => { if (clientsMgr.getAdmin() !== null && socket.id === clientsMgr.getAdmin().socket.id) { clientsMgr.unregsiterAdmin(socket); } else { clientsMgr.unregisterUser(socket); } }); socket.on('admin-msg', (data) => { console.log(`got message "${data.msg}" from admin`); sendMsgToAllMobiles(socket, data); }); socket.on('mobile-msg', (data) => { console.log(`got message "${data.msg}" from mobile`); sendMsgToAdmin(data); }); }); ```
zilchbosons/primality
zilchbosons/primality zilchfactor.py ```from flask import Flask from _primality import * app = Flask(__name__) @app.route("/") def hello(): return "Hellow World!" if __name__ == "__main__": app.run() ``` primality.hpp ```bool isPrime(char* nn); ``` factorize.cpp ```/********************************************************************************* * 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. * **********************************************************************************/ #include <stdio.h> #include <iostream> #include <string> #include <gmp.h> #include <vector> #include <pthread.h> using namespace std; void factorizeByTrialDivision(void* _nn) { char* nn = (char*) _nn; mpz_t nt; mpz_init(nt); mpz_set_str(nt, nn, 10); mpz_t ct; mpz_init(ct); mpz_set_si(ct, 0); mpz_t st; mpz_init(st); mpz_sqrt(st, nt); mpz_set(ct, st); mpz_t rt; mpz_init(rt); while ( mpz_cmp_si(ct, 1) > 0) { mpz_mod(rt, nt, ct); if (mpz_cmp_si(rt, 0)==0) { cout << "\nFactor1:\t"<< strdup(mpz_get_str(0,10,ct))<<"\n"; exit(0); } mpz_sub_ui(ct, ct, 1); } return; } void factorizeByTrialMultiplication(void* _nn) { char* nn = (char*) _nn; mpz_t nt; mpz_init(nt); mpz_set_str(nt, nn, 10); mpz_t st; mpz_init(st); mpz_mul(st, nt, nt); mpz_t ct; mpz_init(ct); mpz_set(ct, nt); mpz_add_ui(ct,ct, 1); mpz_t rt; mpz_init(rt); mpz_t sqt; mpz_init(sqt); mpz_t term; mpz_init(term); mpz_t term2; mpz_init(term2); while (1) { mpz_mul(term, ct,ct); mpz_sub(rt, term, st); mpz_sqrt(sqt, rt); mpz_set(term2, sqt); mpz_mul(sqt, sqt, sqt); mpz_sub(sqt, rt, sqt); mpz_abs(sqt, sqt); if (mpz_cmp_si(sqt, 0)==0) { mpz_sub(ct, ct, nt); mpz_sub(term2, term2, nt); gmp_printf("\n%Zd\t%Zd\n", ct, term2); mpz_add(ct, ct, term2); cout << "\nFactor2:\t"<< strdup((char*) mpz_get_str(0,10, ct))<<"\n"; exit(0); } mpz_add_ui(ct,ct, 1); } return; } int main() { /* Step 1: Reading the Number to be factorized */ FILE* fp = fopen("./input.txt", "r"); std::string num = ""; char n[1024]; int ret = 0; while ((ret=fscanf(fp, "%s", n))!= EOF) { num += n; } cout << "\nNumber read was : \t" << num <<"\n"; char* nn = strdup((char*) num.c_str()); int l = strlen(nn); pthread_t thread1, thread2; pthread_create(&thread1, NULL, (void*(*)(void*) ) &factorizeByTrialDivision, nn); pthread_create(&thread2, NULL, (void*(*)(void*) ) &factorizeByTrialMultiplication, nn); pthread_join(thread1, NULL); pthread_join(thread2, NULL); fclose(fp); free(nn); return 0; } ```
zillesc/Zomato
zillesc/Zomato Dummy.java ```package com.example; /** * Don't use this class; just a dummy file here so that git will include the src directory for you. * Feel free to delete, after you create your own classes. */ public class Dummy { } ``` DummyTest.java ```package com.example; import static org.junit.Assert.*; /** * Also a dummy file. You can delete this (if you want) after you actually create your own test classes. */ public class DummyTest { }```
zillopanda/project1
zillopanda/project1 README.md ```# project1 asdfghjkl ```
zimnyjakub/imgcnvrtr
zimnyjakub/imgcnvrtr service-worker.js ```console.log('elo')```
zimonovn/canban_02
zimonovn/canban_02 Controller.js ```import React, {useState} from 'react'; import 'bootstrap/dist/css/bootstrap.css'; import './App.css'; import {Input, Label, Modal, ModalHeader, ModalBody, Button, ModalFooter} from "reactstrap"; import Row from "reactstrap/es/Row"; import Col from "reactstrap/es/Col"; ; function Controller(props) { const [isModalOpen, setIsModalOpen] = useState(false) const [newTitle, setNewTitle] = useState('') const [newPriority, setNewPriority] = useState(0) const [newStatus, setNewStatus] = useState('') const addButtonHandler = () =>{ props.addNewTask(newTitle, newPriority, newStatus) setIsModalOpen(false) setNewTitle('') } return ( <> <Button onClick={() => setIsModalOpen(true)}>Add new task</Button> <Modal isOpen={isModalOpen}> <ModalHeader>Add new title</ModalHeader> <ModalBody> <Label>New title</Label> <Input type="text" value={newTitle} onChange={(e) => setNewTitle(e.target.value)}/> <Row> <Col> <Label>Priority</Label> <Input type="select" value={newPriority} onChange={(e) => setNewPriority(e.target.value)}> <option value={0}>Low</option> <option value={1}>Med</option> <option value={2}>High</option> </Input> </Col> <Col> <Label>Status</Label> <Input type="select" value={newStatus} onChange={(e) => setNewStatus(e.target.value)}> <option value={'todo'}>To do</option> <option value={'progress'}>Progress</option> <option value={'review'}>Review</option> <option value={'done'}>Done</option> </Input> </Col> </Row> </ModalBody> <ModalFooter> <Button onClick={addButtonHandler}>Add new task</Button> {' '} <Button onClick={() => setIsModalOpen(false)}>Cancel</Button> </ModalFooter> </Modal> </> ); } export default Controller; ``` App.js ```import React, {useState} from 'react'; import 'bootstrap/dist/css/bootstrap.css'; import './App.css'; import {Row, Container} from "reactstrap"; import Column from "./Column"; import Controller from "./Controller"; function App() { const taskList = [ {id: Math.random(), name: 'First', priority: 0, status: 'todo'}, {id: Math.random(), name: 'Second', priority: 1, status: 'todo'}, {id: Math.random(), name: 'Third', priority: 2, status: 'todo'}, {id: Math.random(), name: 'Fourth', priority: 1, status: 'todo'} ] const columnList = [ {id: Math.random(), title: 'To do', status: 'todo'}, {id: Math.random(), title: 'In progress', status: 'progress'}, {id: Math.random(), title: 'Review', status: 'review'}, {id: Math.random(), title: 'Done!', status: 'done'}] const statuses = ['todo', 'progress', 'review', 'done'] const taskPriority = [0,1,2] const [tasks, setTasks] = useState(taskList) const changeTaskStatus = (taskId, direction) => { const newTasks = tasks.map(el => { if (el.id === taskId) { if (direction === 'right') el.status = statuses[statuses.indexOf(el.status) + 1] if (direction === 'left') el.status = statuses[statuses.indexOf(el.status) - 1] if (direction === 'up') el.priority = taskPriority[taskPriority.indexOf(el.priority) + 1] if (direction === 'down') el.priority = taskPriority[taskPriority.indexOf(el.priority) - 1] } return el; }) setTasks(newTasks) } const addNewTask = (newTitle, newPriority, newStatus) => { const newTask = { id: Math.random(), name: newTitle, priority: newPriority, status: newStatus } const newTasks = [...tasks, newTask] setTasks(newTasks) } const deleteTask = (taskId) => { const newTasks = tasks.filter(el => el.id !== taskId) setTasks(newTasks) } return ( <div> <Container> <Row> <Controller addNewTask={addNewTask}/> {columnList.map(el => <Column changeTaskStatus={changeTaskStatus} column={el} tasks={tasks} deleteTask={deleteTask} />)} {/*<Column changeTaskStatus={changeTaskStatus} title={'todo'} tasks={tasks}/>*/} {/*<Column changeTaskStatus={changeTaskStatus} title={'progress'} tasks={tasks}/>*/} {/*<Column changeTaskStatus={changeTaskStatus} title={'review'} tasks={tasks}/>*/} {/*<Column changeTaskStatus={changeTaskStatus} title={'done'} tasks={tasks}/>*/} </Row> </Container> </div> ); } export default App; ```
zimtlabs/zimt-view
zimtlabs/zimt-view README.md ```<div align="center"> <h1 style='border-bottom: 'none'>ZIMT View Example</h1> Minimal example HTML, CSS, JS front-end app to demonstrate displaying assets, events from ZIMT Hub API. </div> ## Getting Started Dependencies - Have a ZIMT account or [register](https://dash.zi.mt/auth/signup) one. - Use/create an API key in your dashboard organization. You can follow the [tutorial in the documentation](https://dev.zi.mt/tutorials/create-viewer-app/getting-started) on how this app works and how to use/customize it. ## Run Open up index.html in your browser. ``` utils.js ```/* * Copyright (c) ZIMT AG - All Rights Reserved 2020 * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Contact: tech@zimt.co */ const copy = data => JSON.parse(JSON.stringify(data)); const getImages = event => { const data = event.data || event; if (data && data.documents) { const images = data.documents.filter(document => document.type.indexOf('image') > -1); return images.length ? images : undefined; } }; const parseEventProperties = event => { const parsed = { simple: {}, complex: {}, }; const IGNORE = ['name', 'type', 'description', 'asset_type']; if (event) { const properties = event.data.properties; if (properties) { Object.keys(properties).forEach(key => { if ( typeof properties[key] === 'string' || typeof properties[key] === 'number' || typeof properties[key] === 'boolean' || !properties[key] ) { if (IGNORE.indexOf(key.toLowerCase()) === -1) parsed.simple[key] = properties[key]; } else { parsed.complex[key] = properties[key]; } }); } } event['parsed'] = parsed; }; const getObject = object => { try { const isAsset = !!object.events; if (isAsset) { const event = object.events.find(e => e.data.type.indexOf('info') > -1); return event; } return object; } catch (error) { return undefined; } }; const getAssetName = asset => { try { if (asset) { const id = asset.id; const infoEvent = asset.info || (asset.events && asset.events.find(event => ['info'].indexOf(event.data.type) > -1)); return (infoEvent && infoEvent.data && infoEvent.data.name) || id; } } catch (error) { console.log('getAssetName: ', error); return 'No name'; } }; const getDocumentURL = document => { const zimt_token = CONFIG.token; let link = document; if (!document) return link; if (typeof document === 'string') return document; if (document.url) link = document.url; if (document.id) link = `${CONFIG.api.core}/documents/${document.id}?zimt_token=${zimt_token}`; return link; }; const cleanKey = value => { return value && value.replace(/\./g, ''); }; const castParam = (_value, options = { number: true }) => { try { let value = JSON.parse(decodeURIComponent(_value)); if (typeof value === 'number' && typeof _value === 'string' && !options.number) value = String(value); if (['undefined', 'null', undefined, null].indexOf(value) > -1) value = undefined; return value; } catch (error) { } return decodeURIComponent(_value); }; function getObjectPropertyValueOne(object, keys) { if (!object || !keys) return object; if (typeof keys === 'string') { const _keys = keys.split('.').filter(Boolean).map(item => castParam(item)); return getObjectPropertyValue(object, _keys); } else if (keys.length === 1) return object[keys[0]]; else if (keys.length > 1 && object[keys[0]]) return getObjectPropertyValue(object[keys[0]], keys.slice(1)); return undefined; } function getObjectPropertyValue(object, ...keys) { if (!object || !keys) return object; let value; for (const key of keys) { value = getObjectPropertyValueOne(object, key); if (value !== undefined) break; } return value; } function setObjectValue(object, keys, value) { if (!object || !keys) return object; if (typeof keys === 'string') { const _keys = keys.split('.').filter(Boolean).map(item => castParam(item)); return setObjectValue(object, _keys, value); } else if (keys.length === 1 && value !== undefined) { if ( (Array.isArray(object) && typeof keys[0] === 'number') || (object instanceof Object && typeof keys[0] === 'string') ) object[typeof keys[0] === 'string' ? cleanKey(keys[0]) : keys[0]] = value; } else if (keys.length > 1) { if (!object[keys[0]]) object[cleanKey(keys[0])] = typeof keys[1] === 'number' ? [] : {}; return setObjectValue(object[keys[0]], keys.slice(1), value); } return object; } function removeObjectValue(object, keys) { if (!object || !keys) return object; if (typeof keys === 'string') { const _keys = keys.split('.').filter(Boolean).map(item => castParam(item)); return removeObjectValue(object, _keys); } else if (keys.length === 1) { if (Array.isArray(object) && typeof keys[0] === 'number') object.splice(keys[0], 1); else if (object instanceof Object && typeof keys[0] === 'string') delete object[keys[0]]; } else if (keys.length > 1) { if (!object[keys[0]]) return object; return removeObjectValue(object[keys[0]], keys.slice(1)); } return object; } ``` main.js ```/* * Copyright (c) ZIMT AG - All Rights Reserved 2020 * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Contact: tech@zimt.co */ async function init() { // Initiate services zimtService = new ZIMTService(); assetService = new AssetService(); eventService = new EventService(); // Get HTML element refs elements['input'] = document.getElementById('input'); elements['button'] = document.getElementById('button'); elements['error'] = document.getElementById('error'); elements['asset'] = document.getElementById('asset'); } // Initiate app dependencies on load window.addEventListener('load', function () { init(); }); function clear() { elements['input'].value = ''; values = {}; } function loading(value = true) { elements['button'].disabled = value; } function setError(text, show = true) { elements.error.innerText = text; elements.error.style.display = show ? 'block' : 'none'; } function setAsset(asset, events) { elements.asset.innerHTML = ''; elements.asset.style.display = 'none'; parseEventProperties(asset); const images = getImages(asset); if (images && images.length) { const image = document.createElement('img'); image.src = getDocumentURL(images[0]); image.alt = 'Asset'; elements.asset.appendChild(image); } const title = document.createElement('h1'); title.innerText = asset.data.name; elements.asset.appendChild(title); const desc = getObjectPropertyValue(asset, 'data.properties.description', 'properties.description', 'description'); if (desc) { const description = document.createElement('p'); description.className = 'description'; description.innerText = desc; elements.asset.appendChild(description); } if (Object.keys(asset.parsed.simple).length) { const properties = document.createElement('div'); properties.className = 'properties'; const subtitle = document.createElement('h3'); subtitle.innerText = 'Properties'; subtitle.style.marginTop = '35px'; subtitle.style.marginBottom = '25px'; properties.appendChild(subtitle); Object.keys(asset.parsed.simple).forEach(key => { const item = document.createElement('p'); item.className = 'property'; item.innerHTML = `<b>${key}</b>: ${asset.parsed.simple[key]}`; properties.appendChild(item); }); elements.asset.appendChild(properties); } if (events && events.response.length) { const timeline = document.createElement('div'); timeline.className = 'timeline'; const subtitle = document.createElement('h2'); subtitle.innerText = 'Events'; subtitle.style.marginBottom = '34px'; subtitle.style.fontWeight = 500; timeline.appendChild(subtitle); const _events = document.createElement('div'); _events.className = 'events'; timeline.appendChild(_events); events.response.forEach(_event => { const data = getObjectPropertyValue(_event, 'object.data', 'data'); const event = document.createElement('div'); event.className = 'event'; const eventType = document.createElement('p'); eventType.className = 'type'; eventType.innerText = data.type; event.appendChild(eventType); const eventTitle = document.createElement('p'); eventTitle.className = 'title'; eventTitle.innerText = data.name; event.appendChild(eventTitle); _events.appendChild(event); }); elements.asset.appendChild(timeline); } elements.asset.style.display = 'flex'; } async function onSubmit(event) { try { event.preventDefault(); const id = values.asset_id; if (id && id.trim()) { loading(); setError('', false); // Get the asset with info event attached const asset = await assetService.get(id); console.log('Asset: ', asset); // Get events const events = await eventService.search(asset.id, {}); console.log('Events: ', events); clear(); loading(false); setAsset(asset, events); } } catch (error) { loading(false); console.error('Search: ', error); setError(error.data.meta.message); } } function onChange(event) { event.preventDefault(); const { value, name } = event.target; values[name] = value; }``` config.js ```/* * Copyright (c) ZIMT AG - All Rights Reserved 2020 * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Contact: tech@zimt.co */ const CONFIG = { api: { // https://hub.test.zi.mt or https://hub.zi.mt core: 'https://hub.test.zi.mt', }, // ENTER YOUR OWN ORGANIZATION API KEY HERE api_key: '', token: '', }; // Global vars let sdk; let values = {}; const elements = {}; let zimtService; let assetService; let eventService; ``` services.js ```/* * Copyright (c) ZIMT AG - All Rights Reserved 2020 * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Contact: tech@zimt.co */ class ZIMTService { sdk; utils; constructor() { this.init(); } init() { const apiKey = CONFIG.api_key; this.sdk = new ZIMTHubSDK({ api_key: apiKey, api: { core: CONFIG.api.core, }, }); console.log('SDK instance: ', this.sdk); this.utils = ZIMTHubSDK.utils; } async ready() { const token = await this.sdk.ready(); CONFIG.token = token; } } class AssetService { cache = {}; clear() { this.cache = {}; } async create(data) { await zimtService.ready(); const asset = await zimtService.sdk.assets.create(data || zimtService.sdk.assets.generateAsset()); return asset.response; } async get(id, options = { info: true }) { await zimtService.ready(); const asset = await zimtService.sdk.assets.get(id, options); return asset.response; } async getMany(pagination, options = { info: true, parse: true }) { await zimtService.ready(); const assets = await zimtService.sdk.assets.getMany(pagination, options); return assets; } async search(query, options = { info: true, parse: true }) { await zimtService.ready(); const assets = await zimtService.sdk.assets.search(query, options); return assets; } } class EventService { cache = {}; clear() { this.cache = {}; } async create(asset_id, data) { await zimtService.ready(); const event = await zimtService.sdk.events.createEvent(asset_id, data); return event.response; } async get(asset_id, event_id, options = { queryParams: { proof: true } }) { await zimtService.ready(); const event = await zimtService.sdk.events.getEvent(asset_id, event_id, options); return event.response; } async getMany(asset_id, pagination) { await zimtService.ready(); const events = await zimtService.sdk.events.getEvents(asset_id, pagination); return events; } async search(asset_id, query) { await zimtService.ready(); const events = await zimtService.sdk.events.searchEvents(asset_id, query); return events; } }```
zinakot0oj/zinakot0oj.github.io
zinakot0oj/zinakot0oj.github.io README.md ```# zinakot0oj.github.io```
zinebOuajjini/MDV2.0
zinebOuajjini/MDV2.0 KitController.java ```package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.dao.KitDAO; import com.sopraMdv.anotherProject.entities.Kit; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; @Controller public class KitController { private KitDAO kitDAO; public KitDAO getKitDAO() { return kitDAO; } @Autowired public void setKitDAO(KitDAO kitDAO) { this.kitDAO = kitDAO; } @FXML private TextField nomKit; @FXML private TextArea descKit; @FXML private Label errorLabel; private Kit kit ; private Session session; public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } private WelcomeController welcomecontroller; @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } @FXML public void initialize() { } @FXML public void createKit(MouseEvent event) throws IOException { kit = new Kit(); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); String nommsg = ""; kit.setNomKit(nomKit.getText().replaceAll(" ", "_")); kit.setScripts(""); kit.setDescriptionKit(descKit.getText()); Set<ConstraintViolation<Kit>> kitViolation = validator.validate(kit); if(kitViolation.isEmpty()) { kitDAO.save(kit); welcomecontroller.FireAnEvent(welcomecontroller.getKitlabel()); }else { for(ConstraintViolation<Kit> kitV : kitViolation) { if (kitV.getPropertyPath().toString().equals("nomKit")) { nommsg = kitV.getMessage(); } } if (!nommsg.isEmpty()) { nomKit.getStyleClass().add("error"); } else { nomKit.getStyleClass().remove("error"); } errorLabel.setText("\t\t\tOuuups!!\nLes champs en rouge sont invalides."); } } @FXML public void cancel(MouseEvent event) throws IOException { welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "Kits de migration"); } } ``` Session.java ```package com.sopraMdv.anotherProject.Controller; import java.sql.Connection; import java.sql.SQLException; import java.util.Scanner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.entities.DataBase; import com.sopraMdv.anotherProject.entities.Kit; @Controller @Scope("singleton") public class Session { private Kit kit; private String queryResult; private Long IdFile; private String fileopenerPath; private Scanner scanner; private ExecuteFileController executefile; private Connection cnx; private Long line,preLine; private int isExePaused;// 0 : not paused |1 : paused | 2 : paused but in initial state. private boolean isFileDone;// True if file has reached end| False if file hasn't reached end yet. public ExecuteFileController getExecutefile() { return executefile; } @Autowired public void setExecutefile(ExecuteFileController executefile) { this.executefile = executefile; } public Long getPreLine() { return preLine; } public void setPreLine(Long preLine) { this.preLine = preLine; } public Connection getCnxNew() throws SQLException { return executefile.connectDB(kit.getDatabase().getId()) ; } public Connection getCnx() throws SQLException { return cnx ; } public void setCnx(Connection cnx) { this.cnx = cnx; } public String getQueryResult() { return queryResult; } public void setQueryResult(String queryResult) { this.queryResult = queryResult; } public Long getIdFile() { return IdFile; } public void setIdFile(Long idFile) { IdFile = idFile; } public Kit getKit() { return kit; } public void setKit(Kit kit) { this.kit = kit; } public Scanner getScanner() { return scanner; } public void setScanner(Scanner scanner) { this.scanner = scanner; } public boolean isFileDone() { return isFileDone; } public void setFileDone(boolean isFileDone) { this.isFileDone = isFileDone; } public int getExePaused() { return isExePaused; } public void setExePaused(int isExePaused) { this.isExePaused = isExePaused; } public Long getLine() { return line; } public void setLine(Long line) { this.line = line; } public String getFileopenerPath() { return fileopenerPath; } public void setFileopenerPath(String fileopenerPath) { this.fileopenerPath = fileopenerPath; } } ``` DataBase.java ```package com.sopraMdv.anotherProject.entities; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; @Entity @Inheritance(strategy = InheritanceType.JOINED) public class DataBase { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long Id; @Column private String TypeDB; @Column private String hote; @Column private int port; @Column private String sid; @Column private String passwordDb; @Column private String schemaDB; // @OneToMany(fetch = FetchType.LAZY, // mappedBy="database",cascade=CascadeType.REMOVE) // private List<FileHistory> files; // @ManyToOne // private Server server; // // public Server getServer() { // return server; // } // // public void setServer(Server server) { // this.server = server; // } public DataBase(String typeDB) { this.TypeDB = typeDB; } // public List<FileHistory> getFiles() { // return files; // } // // public void setFiles(List<FileHistory> files) { // this.files = files; // } // don't show file in tostring or you'll get an error(because it's lazy fetch) @Override public String toString() { return "DataBase [Id=" + Id + ", TypeDB=" + TypeDB + ", hote=" + hote + ", port=" + port + ", sid=" + sid + ", passwordDb=" + passwordDb + ", schemaDB=" + schemaDB + "]"; } public Long getId() { return Id; } public void setId(Long id) { Id = id; } public String getTypeDB() { return TypeDB; } public void setTypeDB(String typeDB) { TypeDB = typeDB; } public String getHote() { return hote; } public void setHote(String hote) { this.hote = hote; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public String getSchemaDB() { return schemaDB; } public void setSchemaDB(String schemaDB) { this.schemaDB = schemaDB; } public String getPasswordDb() { return passwordDb; } public void setPasswordDb(String passwordDb) { this.passwordDb = passwordDb; } public DataBase(Long id, String schemaDB, String typeDB, String hote, int port, String sid, String passwordDb,Kit kit) { super(); Id = id; this.schemaDB = schemaDB; this.TypeDB = typeDB; this.hote = hote; this.port = port; this.sid = sid; this.passwordDb = passwordDb; } public DataBase() { super(); } public DataBase(DataBase database) { Id = database.Id; this.schemaDB = database.schemaDB; this.TypeDB = database.TypeDB; this.hote = database.hote; this.port = database.port; this.sid = database.sid; this.passwordDb = database.passwordDb; } } ``` KitInfoController.java ```package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.dao.DataBaseDAO; import com.sopraMdv.anotherProject.dao.KitDAO; import com.sopraMdv.anotherProject.entities.Kit; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; @Controller public class KitInfoController { @FXML private ImageView img1; @FXML private ImageView img2; @FXML private ImageView img3; @FXML private ImageView img4; @FXML private ImageView deleteDBImg; @FXML private ImageView goBackImg; @FXML private ImageView delete; @FXML private Label nomKit; @FXML private Label descriptionKit; @FXML private Label databaseNom; private Kit kit; @FXML private Label dataBaseBtn; private Session session; @Autowired public void setSession(Session session) { this.session = session; } private WelcomeController welcomecontroller; public WelcomeController getWelcomecontroller() { return welcomecontroller; } @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } private KitDAO kitDAO; public KitDAO getKitDAO() { return kitDAO; } @Autowired public void setKitDAO(KitDAO kitDAO) { this.kitDAO = kitDAO; } private DataBaseDAO dbDAO; public DataBaseDAO getDbDAO() { return dbDAO; } @Autowired public void setDbDAO(DataBaseDAO dbDAO) { this.dbDAO = dbDAO; } @FXML private void initialize() { kit = new Kit(session.getKit()); img1.setImage(new Image("/Resources/progress-arrows.png",false)); img2.setImage(new Image("/Resources/db1.png",false)); img3.setImage(new Image("/Resources/code.png",false)); img4.setImage(new Image("/Resources/code-file.png",false)); goBackImg.setImage(new Image("/Resources/back-arrow.png", false)); delete.setImage(new Image("/Resources/rubbish.png", false)); deleteDBImg.setImage(new Image("/Resources/rubbish.png", false)); nomKit.setText(kit.getNomKit()); descriptionKit.setText(kit.getDescriptionKit()); if(session.getKit().getDatabase() != null) databaseNom.setText(session.getKit().getDatabase().getSid()); if (kitDAO.getDbByKit(session.getKit().getId()) != null) { dataBaseBtn.setText("Modifier"); }else { deleteDBImg.setVisible(false); dataBaseBtn.setText("Créer"); } } @FXML public void showScripts() throws IOException { welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "Historique"); } @FXML public void createDB() throws IOException { // modify DB // DbShooser.setVisible(true); if ( dataBaseBtn.getText().equals("Créer") ) { welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "création_base_de_donnée"); } if (dataBaseBtn.getText().equals("Modifier")) { welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "modification_base_de_donnée"); // System.out.println("before "+session.getKit()); // dbDAO.delete(session.getKit().getDatabase()); // session.setKit(kitDAO.findById(1L).get()); // System.out.println("after "+session.getKit()); } } @FXML public void goBack() throws IOException { welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "Kits de migration"); } @FXML public void delete() throws IOException{ Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Confirmation!!!!"); alert.setHeaderText("Voulez vous Supprimer ce kit ?"); alert.setContentText("tous les données liées vont être supprimées!!!!"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { kitDAO.delete(kit); welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(),"Kits de migration"); } } @FXML public void deleteDB() throws IOException { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Confirmation!!!!"); alert.setHeaderText("Voulez vous Supprimer cette base de données ?"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { Long tmpDBId =session.getKit().getDatabase().getId(); session.getKit().setDatabase(null); kitDAO.save(session.getKit()); dbDAO.deleteById(tmpDBId); System.out.println("after delete "+ session.getKit().getId()); welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(),"kit_info"); } } @FXML public void showDBInfo(MouseEvent t) { welcomecontroller.setAndShowMessage(t,"IP : "+session.getKit().getDatabase().getHote() +"\nSID : "+session.getKit().getDatabase().getSid() +"\nPort : "+session.getKit().getDatabase().getPort() +"\nSchema : "+session.getKit().getDatabase().getSchemaDB() +"\nType : "+session.getKit().getDatabase().getTypeDB(), t.getSceneX() - 150, t.getSceneY() - 70); } public void hideDBInfo(MouseEvent t) { welcomecontroller.hideMessage(t);; } } ``` DataBaseController.java ```package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import java.sql.Connection; import java.util.ArrayList; import java.util.Collection; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.dao.DataBaseDAO; import com.sopraMdv.anotherProject.dao.KitDAO; import com.sopraMdv.anotherProject.dao.ServerDAO; import com.sopraMdv.anotherProject.entities.DataBase; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; @Controller public class DataBaseController { private ObservableList<String> types = FXCollections.observableArrayList("Oracle", "Informix"); private DataBaseDAO databaseDao; private KitDAO kitDAO; private Validator validator; private DataBase db ; private DataBaseConnexion dbconnexion; @FXML private TextField hostDB; @FXML private TextField portDB; @FXML private TextField sidDB; String schemamsg, pwmsg, pnmsg, typemsg, hostmsg, portmsg, sidmsg, dn4umsg; @FXML private VBox DBform; @FXML private Label errorLabel; TextField dbName4Url = new TextField(); HBox hbox = new HBox(dbName4Url); @Autowired DataBaseConnexion dbConnection; public KitDAO getKitDAO() { return kitDAO; } @Autowired public void setKitDAO(KitDAO kitDAO) { this.kitDAO = kitDAO; } Collection<Node> informixCollection = new ArrayList<>(); Collection<Node> oracleCollection = new ArrayList<>(); public DataBaseConnexion getDbconnection() { return dbConnection; } public void setDbconnection(DataBaseConnexion dbConnection) { this.dbConnection = dbConnection; } @FXML private TextField schemaDB; @FXML private PasswordField passwordDB; @FXML private ComboBox<String> typeDB; public DataBaseDAO getDatabaseDao() { return databaseDao; } @Autowired public void setDatabaseDao(DataBaseDAO databaseDao) { this.databaseDao = databaseDao; } public DataBase getDb() { return db; } public void setDb(DataBase db) { this.db = db; } public DataBaseConnexion getDbconnexion() { return dbconnexion; } @Autowired public void setDbconnexion(DataBaseConnexion dbconnexion) { this.dbconnexion = dbconnexion; } private Session session; public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } private WelcomeController welcomecontroller; @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } @FXML private void initialize() { errorLabel.setWrapText(true); dbName4Url.setPromptText("Database Name (for url)"); dbName4Url.setAlignment(Pos.CENTER); dbName4Url.setPrefHeight(40.0); typeDB.getItems().addAll(types); typeDB.getSelectionModel().select(0); // oracle by default typeDB.getSelectionModel().selectedItemProperty().addListener((options, oldValue, newValue) -> { if (newValue.equals("Informix")) { sidDB.setPromptText("Informix Instance"); DBform.getChildren().remove(4, 6); DBform.getChildren().addAll(4, informixCollection); } else if (newValue.equals("Oracle")) { sidDB.setVisible(true); sidDB.setPromptText("Oracle SID"); DBform.getChildren().remove(4, 7); DBform.getChildren().addAll(4, oracleCollection); } }); validator = Validation.buildDefaultValidatorFactory().getValidator(); Platform.runLater(() -> ((VBox) passwordDB.getParent()).requestFocus()); // oracleCollection.add( schemaDB); oracleCollection.add( passwordDB); informixCollection.add(dbName4Url); informixCollection.add( schemaDB); informixCollection.add( passwordDB); } public void createDB(MouseEvent event) throws IOException { sidmsg = schemamsg = hostmsg = portmsg = pwmsg = typemsg = dn4umsg = ""; errorLabel.setText(""); db= new DataBase(); db.setSid(sidDB.getText()); db.setHote(hostDB.getText()); db.setPasswordDb(passwordDB.getText()); db.setTypeDB(typeDB.getValue()); db.setSchemaDB(schemaDB.getText()); System.out.println("hhhhhhhhh"+session.getKit()); // db.setKit(session.getKit()); // db.setServer(serverdao.getServerByEnvid(session.getIdEnv())); if (!portDB.getText().isEmpty()) { db.setPort(Integer.parseInt(portDB.getText())); } else { db.setPort(100000); } Set<ConstraintViolation<DataBase>> DBViolations = validator.validate(db); if (DBViolations.isEmpty()) { try { Connection conn = dbConnection.connectDB(db); if (conn != null) { databaseDao.save(db); System.out.println("database"+db); session.getKit().setDatabase(db); System.out.println(" "+session.getKit()); kitDAO.save(session.getKit()); welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "Kit_info"); //conn.close(); } else { errorLabel.setText("Cannot connect to this Database.\n\tPlease verify this info given."); } } catch (Exception e) { System.out.println("controller problem"+e.getMessage()); } } else { System.out.println("data is Invalid"); System.out.println("------------------------------------"); for (ConstraintViolation<DataBase> DBViolation : DBViolations) { if (DBViolation.getPropertyPath().toString().equals("sid")) { sidDB.getStyleClass().add("error"); sidmsg = DBViolation.getMessage(); } else if (DBViolation.getPropertyPath().toString().equals("TypeDB")) { typeDB.getStyleClass().add("error"); typemsg = DBViolation.getMessage(); } else if (DBViolation.getPropertyPath().toString().equals("hote")) { hostDB.getStyleClass().add("error"); hostmsg = DBViolation.getMessage(); } else if (DBViolation.getPropertyPath().toString().equals("port")) { portDB.getStyleClass().add("error"); portmsg = DBViolation.getMessage(); } else if (DBViolation.getPropertyPath().toString().equals("schemaDB")) { schemaDB.getStyleClass().add("error"); pnmsg = DBViolation.getMessage(); } else if (DBViolation.getPropertyPath().toString().equals("passwordDb")) { passwordDB.getStyleClass().add("error"); pwmsg = DBViolation.getMessage(); } else if (DBViolation.getPropertyPath().toString().equals("dbName4Url")) { dbName4Url.getStyleClass().add("error"); dn4umsg = DBViolation.getMessage(); } else { System.out.println( "LOGINFO : " + DBViolation.getPropertyPath() + " " + DBViolation.getMessageTemplate()); } } if (!sidmsg.isEmpty()) { sidDB.getStyleClass().add("error"); } else { sidDB.getStyleClass().removeAll("error"); } if (!typemsg.isEmpty()) { typeDB.getStyleClass().add("error"); } else { typeDB.getStyleClass().removeAll("error"); } if (!hostmsg.isEmpty()) { hostDB.getStyleClass().add("error"); } else { hostDB.getStyleClass().removeAll("error"); } if (!portmsg.isEmpty()) { portDB.getStyleClass().add("error"); } else { portDB.getStyleClass().removeAll("error"); } if (!schemamsg.isEmpty()) { schemaDB.getStyleClass().add("error"); } else { schemaDB.getStyleClass().removeAll("error"); } if (!pwmsg.isEmpty()) { passwordDB.getStyleClass().add("error"); } else { passwordDB.getStyleClass().removeAll("error"); } if (!dn4umsg.isEmpty()) { dbName4Url.getStyleClass().add("error"); } else { dbName4Url.getStyleClass().removeAll("error"); } errorLabel.setText("Ouuups!! les champs en rouge sont invalides."); } } @FXML public void cancel(MouseEvent event) throws IOException { welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "kit_info"); } } ``` FileHistory.java ```package com.sopraMdv.anotherProject.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class FileHistory { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long Id; @ManyToOne private Kit kit; // @ManyToOne // private DataBase database; @Column private String fileName; @Column private String path; @Column private String logpath; @Column private Long currentline; @Column private Long lines; @Column private String dateDebut; @Column private String dateFin; public Long getId() { return Id; } public void setId(Long id) { Id = id; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getLogpath() { return logpath; } public void setLogpath(String logpath) { this.logpath = logpath; } public Long getCurrentline() { return currentline; } public void setCurrentline(Long currentline) { this.currentline = currentline; } public Long getLines() { return lines; } public void setLines(Long lines) { this.lines = lines; } public String getDateDebut() { return dateDebut; } public void setDateDebut(String dateDebut) { this.dateDebut = dateDebut; } public String getDateFin() { return dateFin; } public void setDateFin(String dateFin) { this.dateFin = dateFin; } public Kit getKit() { return kit; } public void setKit(Kit kit) { this.kit = kit; } public FileHistory(Long id, Kit kit, DataBase database, String fileName, String path, String logpath, Long currentline, Long lines, String dateDebut, String dateFin) { super(); Id = id; this.kit = kit; this.fileName = fileName; this.path = path; this.logpath = logpath; this.currentline = currentline; this.lines = lines; this.dateDebut = dateDebut; this.dateFin = dateFin; } public FileHistory(FileHistory file) { super(); Id = file.Id; this.fileName = file.fileName; this.path = file.path; this.logpath = file.logpath; this.currentline = file.currentline; this.lines = file.lines; this.dateDebut = file.dateDebut; this.dateFin = file.dateFin; this.kit = file.kit; } public FileHistory() { super(); } @Override public String toString() { return "File [Id=" + Id + ", fileName=" + fileName + ", path=" + path + ", logpath=" + logpath + ", currentline=" + currentline + ", lines=" + lines + ", dateDebut=" + dateDebut + ", dateFin=" + dateFin + "]"; } } ``` ExecuteFileController.java ```package com.sopraMdv.anotherProject.Controller; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.sql.Connection; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.dao.DataBaseDAO; import com.sopraMdv.anotherProject.dao.FileHistoryDAO; import com.sopraMdv.anotherProject.dao.KitDAO; import com.sopraMdv.anotherProject.entities.DataBase; import com.sopraMdv.anotherProject.entities.FileHistory; import com.sopraMdv.anotherProject.entities.Server; import com.sopraMdv.anotherProject.util.DBService; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.image.Image; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.stage.WindowEvent; @Controller public class ExecuteFileController { @FXML private AnchorPane ViewPane; private DataBaseDAO dbDAO; private ExecuteFileController executefile; private ScriptManagerController scriptMangerController; private DataBaseConnexion dbconnexion; private MainController mainController; private SplitFileController splitfile; @FXML private TextArea consoleLog; @FXML private Pane executionPane; public Pane getExecutionPane() { return executionPane; } public void setExecutionPane(Pane executionPane) { this.executionPane = executionPane; } @FXML private TextArea queryProblem; private int i = 0; @FXML private Label addLabel; @FXML private Label editLabel; @FXML private Label commentLabel; @FXML private Label cancelLabel; private HistoriqueController historiqueController; public HistoriqueController getHistoriqueController() { return historiqueController; } @Autowired public void setHistoriqueController(HistoriqueController historiqueController) { this.historiqueController = historiqueController; } public ScriptManagerController getScriptMangerController() { return scriptMangerController; } @Autowired public void setScriptMangerController(ScriptManagerController scriptMangerController) { this.scriptMangerController = scriptMangerController; } public ExecuteFileController getExecutefile() { return executefile; } @Autowired public void setExecutefile(ExecuteFileController executefile) { this.executefile = executefile; } private DBService service; public DBService getService() { return service; } @Autowired public void setService(DBService service) { this.service = service; } public TextArea getQueryProblem() { return queryProblem; } public void setQueryProblem(TextArea queryProblem) { this.queryProblem = queryProblem; } public TextArea getConsoleLog() { return consoleLog; } public void setConsoleLog(TextArea consoleLog) { this.consoleLog = consoleLog; } public SplitFileController getSplitfile() { return splitfile; } @Autowired public void setSplitfile(SplitFileController splitfile) { this.splitfile = splitfile; } public MainController getMainController() { return mainController; } @Autowired public void setMainController(MainController mainController) { this.mainController = mainController; } @Autowired public void setDbconnexion(DataBaseConnexion dbconnexion) { this.dbconnexion = dbconnexion; } public DataBaseDAO getDbDAO() { return dbDAO; } @Autowired public void setDbDAO(DataBaseDAO dbDAO) { this.dbDAO = dbDAO; } private KitDAO kitDAO; public KitDAO getKitDAO() { return kitDAO; } @Autowired public void setKitDAO(KitDAO kitDAO) { this.kitDAO = kitDAO; } private FileHistoryDAO fileDao; public FileHistoryDAO getFileDao() { return fileDao; } @Autowired public void setFileDao(FileHistoryDAO fileDao) { this.fileDao = fileDao; } private WelcomeController welcomecontroller; @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } private Session session; public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } @FXML private void initialize() { consoleLog.setOnMouseClicked((MouseEvent t) -> { if (t.getButton().equals(MouseButton.PRIMARY)) { if (t.getClickCount() == 2) { try { openFilewith(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); } public void openFilewith() throws IOException { String filePath = ""; if (session.getFileopenerPath() == null) { FileChooser chooser = new FileChooser(); File fileopener = chooser.showOpenDialog(consoleLog.getScene().getWindow()); filePath = fileopener.getCanonicalPath(); session.setFileopenerPath(filePath); } else { filePath = session.getFileopenerPath(); } FileHistory fh = new FileHistory(fileDao.getFileById(session.getIdFile())); try { if (filePath != null) { String cmd = "\"" + filePath + "\" " + fh.getPath() + " -n" + fh.getCurrentline(); Runtime.getRuntime().exec(cmd); } } catch (IOException e) { Alert alert = new Alert(AlertType.WARNING); alert.setTitle("Problème!!"); alert.setHeaderText("Problème d'ouverture du fichier"); alert.setContentText("programme non valide!"); alert.showAndWait(); } } public void startdbThread(Scanner sc, Connection cnx) { System.out.println("jhjkhjkhjkhjkhjkhjkhjkhk"); session.setScanner(sc); session.setFileDone(false); welcomecontroller.getOnTopProgressLabel().textProperty().bind(service.messageProperty()); welcomecontroller.getOnTopProgressbar().progressProperty().bind(service.progressProperty()); service.messageProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { System.out.println("changer messageProperty :: " + oldValue + "|" + newValue); } }); service.runningProperty().addListener(e -> { if (session.isFileDone()) { System.out.println("exiting file"); try { System.out.println("starting next file"); historiqueController.executeKit(); } catch (IOException | SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } System.out.println("changing stat : " + service.isRunning()); }); service.setOnFailed(e -> { System.out.println("failed"); welcomecontroller.getOnTopProgressLabel().textProperty().unbind(); welcomecontroller.getOnTopProgressbar().progressProperty().unbind(); }); service.setOnSucceeded(e -> { System.out.println("succeded"); welcomecontroller.getOnTopProgressLabel().textProperty().unbind(); welcomecontroller.getOnTopProgressbar().progressProperty().unbind(); }); service.setOnCancelled(e -> { System.out.println("cancelled"); welcomecontroller.getOnTopProgressLabel().textProperty().unbind(); welcomecontroller.getOnTopProgressbar().progressProperty().unbind(); }); if (!service.isRunning()) {// run service(test if its already running, in this case we do noting) service.reset(); service.start(); } } public void executeScript() throws IOException, SQLException { i++; DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); Date date = new Date(); Scanner sc1 = new Scanner(new FileReader(mainController.getSelectedFile())); Long lines = 0L; while (sc1.hasNext()) { sc1.nextLine(); lines++; } String fileName = null; String fileInCashpath = System.getProperty("user.dir") + "\\src\\main\\java\\Cache\\"; String dateDebut = dateFormat.format(date); String cmd = "CMD /C COPY /Y " + "\"" + mainController.getSelectedFile().getCanonicalPath() + "\" \"" + fileInCashpath + dateDebut + "_" + mainController.getSelectedFile().getName() + "\""; DirectoryChooser chooser = new DirectoryChooser(); chooser.setTitle("choisir votre repertoire des Logs"); File ff = chooser.showDialog(consoleLog.getScene().getWindow()); if (ff != null) { fileName = mainController.getSelectedFile().getName(); String cleanFile = ff.getCanonicalPath() + "\\" + dateDebut + "_" + fileName.substring(0, fileName.length() - 4) + "_Corr.txt"; File f = new File(cleanFile); String logFile = ff.getCanonicalPath() + "\\" + dateDebut + "_" + fileName.substring(0, fileName.length() - 4) + "_Log.txt"; File f1 = new File(logFile); f.createNewFile(); f1.createNewFile(); System.out.println(cmd + "||" + Runtime.getRuntime().exec(cmd)); com.sopraMdv.anotherProject.entities.FileHistory fichier = new com.sopraMdv.anotherProject.entities.FileHistory(); fichier.setCurrentline(0L); fichier.setDateDebut(dateDebut); fichier.setFileName(fileName.substring(0, fileName.length() - 4)); fichier.setLines(lines); fichier.setPath(fileInCashpath + dateDebut + "_" + mainController.getSelectedFile().getName()); fichier.setLogpath(ff.getCanonicalPath()); // fichier.setDatabase(dbDAO.getDatabaseById(session.getKit().getDatabase().getId())); session.setIdFile(fileDao.save(fichier).getId()); System.out.println(session.getIdFile()); FileReader file = new FileReader(mainController.getSelectedFile().getCanonicalPath()); Scanner sc = new Scanner(file); // Connection cnx = connectDB(session.getIdDB()); welcomecontroller.getExecutebtn().setImage(new Image("/Resources/pause.png", false)); session.setExePaused(0); welcomecontroller.getExecutebtn().setImage(new Image("/Resources/pause.png", false)); welcomecontroller.getConnectstate().setStyle("-fx-Fill : #2ffc69"); welcomecontroller.getTitre().setText("En execution"); splitfile.ExtractQuery(sc, session.getCnx()); } sc1.close(); } public void continueScript() throws FileNotFoundException, SQLException { System.out.println(session.getScanner()); // Connection cnx = connectDB(session.getIdDB()); if (session.getCnx() == null || session.getCnx().isClosed()) { session.setCnx(session.getCnxNew()); } /// mise à jour de la table File (currentLine) com.sopraMdv.anotherProject.entities.FileHistory fichier = new com.sopraMdv.anotherProject.entities.FileHistory( fileDao.getFileById(session.getIdFile())); fichier.setCurrentline(session.getLine()); fileDao.save(fichier); ///////////////////// fin mise à jour welcomecontroller.getExecutebtn().setImage(new Image("/Resources/pause.png", false)); welcomecontroller.getConnectstate().setStyle("-fx-Fill : #2ffc69"); welcomecontroller.getTitre().setText("En execution"); executefile.getQueryProblem().setText(""); executefile.getConsoleLog().setText(""); session.setExePaused(0); // splitfile.ExtractQuery(session.getScanner(), session.getCnx()); startdbThread(session.getScanner(), session.getCnx()); } public void executeScript_Sequential(File scriptfile) throws IOException, SQLException { i++; DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); Date date = new Date(); String dateDebut = dateFormat.format(date); Scanner sc1 = new Scanner(new FileReader(scriptfile)); Long lines = 0L; while (sc1.hasNext()) { sc1.nextLine(); lines++; } String fileName = null; String Cashpath = welcomecontroller.getCachePath() + "\\MDVApp\\Cache\\"; String filesInCashpath = Cashpath + session.getKit().getNomKit() + "\\" + "scripts\\"; String logPath = Cashpath + session.getKit().getNomKit() + "\\" + "logs\\"; String resPath = Cashpath + session.getKit().getNomKit() + "\\" + "resultats\\"; fileName = scriptfile.getName(); String cleanFile = resPath + fileName; File f = new File(cleanFile); String logFile = logPath + "\\" + fileName.substring(0, fileName.length() - 4) + "_Log.txt"; File f1 = new File(logFile); f.createNewFile(); f1.createNewFile(); com.sopraMdv.anotherProject.entities.FileHistory fichier = new com.sopraMdv.anotherProject.entities.FileHistory(); fichier.setKit(session.getKit()); fichier.setCurrentline(0L); fichier.setDateDebut(dateDebut); fichier.setFileName(fileName); fichier.setLines(lines); fichier.setPath(filesInCashpath + fileName); fichier.setLogpath(logPath); // fichier.setDatabase(session.getKit().getDatabase()); session.setIdFile(fileDao.save(fichier).getId()); // remove the script from field'kit.scripts) String str = session.getKit().getScripts(); str = str.replace(scriptfile.getName(), ""); str = str.replaceAll(";;", ";"); session.getKit().setScripts(str); kitDAO.save(session.getKit()); ////////////////////////// // System.out.println(session.getIdFile()); FileReader file = new FileReader(scriptfile.getCanonicalFile()); Scanner sc = new Scanner(file); // Connection cnx = connectDB(session.getIdDB()); session.setExePaused(0); welcomecontroller.getExecutebtn().setImage(new Image("/Resources/pause.png", false)); welcomecontroller.getConnectstate().setStyle("-fx-Fill : #2ffc69"); welcomecontroller.getTitre().setText("En execution"); // load executeInterface welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "Scripts"); welcomecontroller.loadInMainPane(mainController.getViewPane(), "ExecuteInterface"); mainController.showDialog(); if (session.getCnx() == null) { session.setCnx(session.getCnxNew()); } // splitfile.ExtractQuery(sc, session.getCnx()); startdbThread(sc, session.getCnx()); sc1.close(); } public void continueScript_Sequential() throws SQLException, IOException { // Connection cnx = connectDB(session.getIdDB()); if (session.getCnx() == null || session.getCnx().isClosed()) { session.setCnx(session.getCnxNew()); } /// mise à jour de la table File (currentLine) // com.sopraMdv.anotherProject.entities.FileHistory fichier = new // com.sopraMdv.anotherProject.entities.FileHistory( // fileDao.getFileById(session.getIdFile())); // fichier.setCurrentline(session.getLine()); // fileDao.save(fichier); ///////////////////// fin mise à jour welcomecontroller.getExecutebtn().setImage(new Image("/Resources/pause.png", false)); welcomecontroller.getConnectstate().setStyle("-fx-Fill : #2ffc69"); welcomecontroller.getTitre().setText("En execution"); session.setExePaused(0); // load executeInterface welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "Scripts"); welcomecontroller.loadInMainPane(mainController.getViewPane(), "ExecuteInterface"); mainController.showDialog(); executefile.getQueryProblem().setText(""); executefile.getConsoleLog().setText(""); // splitfile.ExtractQuery(session.getScanner(), session.getCnx()); startdbThread(session.getScanner(), session.getCnx()); } public Connection connectDB(Long id) throws SQLException { DataBase database = dbDAO.getDatabaseById(id); return dbconnexion.connectDB(database); } /* OnMouseClicked Handlers */ @FXML public void addScript() throws SQLException, IOException { String str = queryProblem.getText(); if (session.getCnx().isClosed()) { session.setCnx(session.getCnxNew()); } // if (str.endsWith(";")) { // str = str.replace(str.substring(str.length() - 1), ""); // } try { dbconnexion.executeQuery(str, session.getCnx()); continueScript_Sequential(); /// mise à jour de la table File (currentLine) com.sopraMdv.anotherProject.entities.FileHistory fichier = new com.sopraMdv.anotherProject.entities.FileHistory( fileDao.getFileById(session.getIdFile())); fichier.setCurrentline(session.getLine()); fileDao.save(fichier); ///////////////////// fin mise à jour welcomecontroller.getExecutebtn().setVisible(false); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); //PopUp.errorPopUp("Echec", "ok"); } } public void editScript() { System.out.println("Editing script loading ... "); } @FXML public void IgnoreScript() throws IOException, SQLException, InterruptedException { ///// Showing movingGears welcomecontroller.getMovingGears().setVisible(true); welcomecontroller.getOnTopPane().setVisible(true); ///// String joinString1 = "/* ****************** ignoré !!!!! *****************\n" + queryProblem.getText() + "\n***********************!!!!!********************* */\n"; // System.out.println(joinString1); com.sopraMdv.anotherProject.entities.FileHistory fichier = new com.sopraMdv.anotherProject.entities.FileHistory( fileDao.getFileById(session.getIdFile())); String Cashpath = welcomecontroller.getCachePath() + "\\MDVApp\\Cache\\"; String resPath = Cashpath + fichier.getKit().getNomKit() + "\\" + "resultats\\"; String cleanFile = resPath + fichier.getFileName(); String logFile = fichier.getLogpath() + "\\" + fichier.getFileName().substring(0, fichier.getFileName().length() - 4) + "_Log.txt"; Files.write(Paths.get(cleanFile), joinString1.getBytes(), StandardOpenOption.APPEND); Files.write(Paths.get(logFile), joinString1.getBytes(), StandardOpenOption.APPEND); continueScript(); } public void cancel() { System.out.println("Closing the PopUp."); Stage stage = (Stage) queryProblem.getScene().getWindow(); stage.close(); } // public void ContinueScript() throws SQLException { // welcomecontroller.getExecutebtn().setVisible(false); // // TODO Auto-generated method stub // Connection cnx = connectDB(session.getIdDB()); // /// mise à jour de la table File (currentLine) // com.sopraMdv.anotherProject.entities.File fichier = new // com.sopraMdv.anotherProject.entities.File( // fileDao.getFileById(session.getIdFile())); // fichier.setCurrentline((long) splitfile.getA()); // fileDao.save(fichier); // ///////////////////// fin mise à jour // splitfile.ExtractQuery(session.getScanner(), cnx); // } @FXML public void stopScript() throws SQLException, IOException { welcomecontroller.getExecutebtn().setVisible(false); welcomecontroller.stopScript(0); } @FXML public void launchPopUp() throws IOException { Stage popUp = PopUp.ScriptManagerPopUp(); popUp.show(); popUp.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { scriptMangerController.setPopUpActive(false); } }); } } ``` Server.java ```package com.sopraMdv.anotherProject.entities; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; @Entity public class Server { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long Id; @Column @Pattern(regexp="(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",message="Doesn't match an ip address") private String hote; @Column @NotBlank private String nomServer; @Column //@Size(min = 5,message="too short for username") private String userName; @Column //@Pattern(regexp="(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}",message="Your password is very weak") private String password; @Column @NotNull(message="Can't be null") private String platformOS; @Column //@Size(min = 5,message="too short for username") private String userNameAmp; @Column //@Pattern(regexp="(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}",message="Your password is very weak") private String passwordAmp; @Column //@Size(min = 5,message="too short for username") private String userNameGener; @Column //@Pattern(regexp="(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}",message="Your password is very weak") private String passwordGener; @Column //@Pattern(regexp="^(.*/)([^/]*)$",message="This is not a valid path") private String pathAmp; @Column private String pathGener; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { //warning: if you try to display the hole envi object it will rise an invokationExeption(because the class Environnement has an object "Server" too ), //so we only display Envi.id !!!!!!! return "Server [Id=" + Id + ", hote=" + hote + ", nomServer=" + nomServer + ", userName=" + userName + ", password=" + password + ", platformOS=" + platformOS + ", userNameAmp=" + userNameAmp + ", passwordAmp=" + passwordAmp + ", userNameGener=" + userNameGener + ", passwordGener=" + passwordGener + ", pathAmp=" + pathAmp + ", pathGener=" + pathGener + "]"; } public Long getId() { return Id; } public void setId(Long id) { Id = id; } public String getHote() { return hote; } public void setHote(String hote) { this.hote = hote; } public String getNomServer() { return nomServer; } public void setNomServer(String nomServer) { this.nomServer = nomServer; } public String getPlatformOS() { return platformOS; } public void setPlatformOS(String platformOS) { this.platformOS = platformOS; } public String getUserNameAmp() { return userNameAmp; } public void setUserNameAmp(String userNameAmp) { this.userNameAmp = userNameAmp; } public String getPasswordAmp() { return passwordAmp; } public void setPasswordAmp(String passwordAmp) { this.passwordAmp = passwordAmp; } public String getUserNameGener() { return userNameGener; } public void setUserNameGener(String userNameGener) { this.userNameGener = userNameGener; } public String getPasswordGener() { return passwordGener; } public void setPasswordGener(String passwordGener) { this.passwordGener = passwordGener; } public String getPathAmp() { return pathAmp; } public void setPathAmp(String pathAmp) { this.pathAmp = pathAmp; } public String getPathGener() { return pathGener; } public void setPathGener(String pathGener) { this.pathGener = pathGener; } public Server(Long id, String hote, String nomServer, String userName, String password, String platformOS, String typeServer, String protocole, int port, String userNameAmp, String passwordAmp, String userNameGener, String passwordGener, String pathAmp, String pathGener) { super(); Id = id; this.hote = hote; this.nomServer = nomServer; this.userName = userName; this.password = password; this.platformOS = platformOS; this.userNameAmp = userNameAmp; this.passwordAmp = passwordAmp; this.userNameGener = userNameGener; this.passwordGener = passwordGener; this.pathAmp = pathAmp; this.pathGener = pathGener; } public Server() { super(); } public Server(Server server) { super(); Id = server.Id; this.hote = server.hote; this.nomServer = server.nomServer; this.platformOS = server.platformOS; this.userNameAmp = server.userNameAmp; this.passwordAmp = server.passwordAmp; this.userNameGener = server.userNameGener; this.passwordGener = server.passwordGener; this.pathAmp = server.pathAmp; this.pathGener = server.pathGener; this.userName=server.userName; this.password=server.password; } } ``` Server_modifierController.java ```package com.sopraMdv.anotherProject.Controller; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.jcraft.jsch.JSchException; import com.sopraMdv.anotherProject.dao.ServerDAO; import com.sopraMdv.anotherProject.entities.Server; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; @Controller public class Server_modifierController { private Validator validator; @FXML private TextField nameServ; private ObservableList<String> platforms = FXCollections.observableArrayList("RedHat", "AIX"); @FXML private TextField hostServ; @FXML private TextField portServ; @FXML private TextField userNameAmpServ; @FXML private TextField pathAmp; @FXML private TextField userNameGenerServ; @FXML private TextField pathGener; @FXML private ComboBox<String> platformOSServ; @FXML private PasswordField passwordAmp; @FXML private PasswordField passwordGener; @FXML private Label errorLabel; String nommsg,hostmsg,osmsg,cbaamsg,pw1msg,cbrdmsg,gaamsg,pw2msg,grdmsg,usermsg,pwmsg; private Session session; private DataBaseConnexion dbconnexion; @FXML private TextField usernameEdit; @FXML private PasswordField passwordEdit; public DataBaseConnexion getDbconnexion() { return dbconnexion; } @Autowired public void setDbconnexion(DataBaseConnexion dbconnexion) { this.dbconnexion = dbconnexion; } public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } private WelcomeController welcomecontroller; @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } private ServerDAO serverDao; private Server server; public ServerDAO getServerDao() { return serverDao; } @Autowired public void setServerDao(ServerDAO serverDao) { this.serverDao = serverDao; } public Server getServer() { return server; } public void setServer(Server server) { this.server = server; } @FXML private void initialize() { validator = Validation.buildDefaultValidatorFactory().getValidator(); platforms = FXCollections.observableArrayList("RedHat", "AIX"); System.out.println("3"+this.session); platformOSServ.getItems().addAll(platforms); // server = new Server(serverDao.getServerByEnvid(session.getIdEnv())); // hostServ.setText(server.getHote()); // nameServ.setText(server.getNomServer()); // platformOSServ.getSelectionModel().select(server.getPlatformOS()); // userNameAmpServ.setText(server.getUserNameAmp()); // passwordAmp.setText(server.getPasswordAmp()); // userNameGenerServ.setText(server.getUserNameGener()); // passwordGener.setText(server.getPasswordGener()); // pathAmp.setText(server.getPathAmp()); // pathGener.setText(server.getPathGener()); // usernameEdit.setText(server.getUserName()); // passwordEdit.setText(server.getPassword()); } public void editserver() throws JSchException { nommsg=hostmsg=osmsg=cbaamsg=pw1msg=cbrdmsg=gaamsg=pw2msg=grdmsg=""; server.setHote(hostServ.getText()); server.setNomServer(nameServ.getText()); server.setPlatformOS(platformOSServ.getValue()); server.setUserNameAmp(userNameAmpServ.getText()); server.setPasswordAmp(passwordAmp.getText()); server.setUserNameGener(userNameGenerServ.getText()); server.setPasswordGener(passwordGener.getText()); server.setPathAmp(pathAmp.getText()); server.setPathGener(pathGener.getText()); server.setUserName(usernameEdit.getText()); server.setPassword(passwordEdit.getText()); // server.setId(serverDao.getServerByEnvid(session.getIdEnv()).getId()); // System.out.println(server); Set<ConstraintViolation<Server>> serverViolations = validator.validate(server); if (serverViolations.isEmpty()) { com.jcraft.jsch.Session session=dbconnexion.connectServer(server); dbconnexion.getSession().disconnect(); dbconnexion.setSession(null); if (session!=null) { System.out.println("save server "); serverDao.save(server); server.setId(null); session.disconnect(); //welcomecontroller.FireAnEvent(welcomecontroller.getServerlabel()); } } else { System.out.println("data is Invalid"); System.out.println("------------------------------------"); for (ConstraintViolation<Server> serverViolation : serverViolations) { if(serverViolation.getPropertyPath().toString().equals("nomServer")) { nommsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("hote")) { hostmsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("platformOS")) { osmsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("userNameAmp")) { cbaamsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("passwordAmp")) { pw1msg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("pathAmp")) { cbrdmsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("userNameGener")) { gaamsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("passwordGener")) { pw2msg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("pathGener")) { grdmsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("userName")) { usermsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("password")) { pwmsg = serverViolation.getMessage(); }else { System.out.println( "LOGINFO : " + serverViolation.getPropertyPath() + " " + serverViolation.getMessage()); } } if (!nommsg.isEmpty()) { nameServ.getStyleClass().add("error"); }else { nameServ.getStyleClass().removeAll("error"); } if (!hostmsg.isEmpty()) { hostServ.getStyleClass().add("error"); }else { hostServ.getStyleClass().removeAll("error"); } if (!osmsg.isEmpty()) { platformOSServ.getStyleClass().add("error"); }else { platformOSServ.getStyleClass().removeAll("error"); } if (!cbaamsg.isEmpty()) { userNameAmpServ.getStyleClass().add("error"); }else { userNameAmpServ.getStyleClass().removeAll("error"); } if (!pw1msg.isEmpty()) { passwordAmp.getStyleClass().add("error"); }else { passwordAmp.getStyleClass().removeAll("error"); } if (!cbrdmsg.isEmpty()) { pathAmp.getStyleClass().add("error"); }else { pathAmp.getStyleClass().removeAll("error"); } if (!gaamsg.isEmpty()) { userNameGenerServ.getStyleClass().add("error"); }else { userNameGenerServ.getStyleClass().removeAll("error"); } if (!pw2msg.isEmpty()) { passwordGener.getStyleClass().add("error"); }else { passwordGener.getStyleClass().removeAll("error"); } if (!grdmsg.isEmpty()) { pathGener.getStyleClass().add("error"); }else { pathGener.getStyleClass().removeAll("error"); } errorLabel.setText("Ouuups!! les champs en rouge sont invalides."); } } public void cancel() { server = null; //welcomecontroller.FireAnEvent(welcomecontroller.getServerlabel()); } } ``` DB_modifierController.java ```package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import java.sql.Connection; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.dao.DataBaseDAO; import com.sopraMdv.anotherProject.dao.ServerDAO; import com.sopraMdv.anotherProject.entities.DataBase; import com.sopraMdv.anotherProject.entities.Oracle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; @Controller public class DB_modifierController { Validator validator; private ObservableList<String> types = FXCollections.observableArrayList("Oracle"); private DataBaseDAO databaseDao; @Autowired DataBaseConnexion dbConnection; private DataBase db; @FXML private TextField schemaDB; @FXML private TextField hostDB; @FXML private TextField portDB; @FXML private TextField sidDB; @FXML private PasswordField passwordDB; @FXML private ComboBox<String> typeDB; @FXML private Label errorLabel; String schemamsg, pwmsg, typemsg, hostmsg, portmsg, sidmsg, dn4umsg; TextField dbName4Url = new TextField(); private DataBaseConnexion dbconnexion; public DataBaseConnexion getDbconnexion() { return dbconnexion; } @Autowired public void setDbconnexion(DataBaseConnexion dbconnexion) { this.dbconnexion = dbconnexion; } public DataBaseDAO getDtaabaseDao() { return databaseDao; } @Autowired public void setDtaabaseDao(DataBaseDAO dtaabaseDao) { this.databaseDao = dtaabaseDao; } public DataBase getDb() { return db; } public void setDb(DataBase db) { this.db = db; } private ServerDAO serverdao; public ServerDAO getServerdao() { return serverdao; } @Autowired public void setServerdao(ServerDAO serverdao) { this.serverdao = serverdao; } private Session session; public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } private WelcomeController welcomecontroller; @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } public DataBaseConnexion getDbconnection() { return dbConnection; } public void setDbconnection(DataBaseConnexion dbConnection) { this.dbConnection = dbConnection; } @FXML private void initialize() { validator = Validation.buildDefaultValidatorFactory().getValidator(); db = databaseDao.getDatabaseById(session.getKit().getDatabase().getId()); hostDB.setText(db.getHote()); hostDB.setDisable(true); passwordDB.setText(db.getPasswordDb()); portDB.setText("" + db.getPort()); typeDB.getSelectionModel().select(db.getTypeDB()); schemaDB.setText(db.getSchemaDB()); sidDB.setText(db.getSid()); typeDB.setDisable(true); errorLabel.setWrapText(true); } public void editDB(MouseEvent event) throws IOException { schemamsg = sidmsg = hostmsg = portmsg = pwmsg = typemsg = dn4umsg = ""; db.setHote(hostDB.getText()); db.setPasswordDb(passwordDB.getText()); db.setPort(Integer.parseInt(portDB.getText())); db.setSid(sidDB.getText()); db.setTypeDB(typeDB.getValue()); db.setSchemaDB(schemaDB.getText()); db.setId(session.getKit().getDatabase().getId()); // db.setServer(serverdao.getServerByEnvid(session.getIdEnv())); Set<ConstraintViolation<DataBase>> DBViolations = validator.validate(db); if (DBViolations.isEmpty()) { try { Connection conn = dbConnection.connectDB(db); if (conn != null) { databaseDao.save(db); db.setId(null); //welcomecontroller.FireAnEvent(welcomecontroller.getDblabel()); } else { errorLabel.setText("Cannot connect to this Database.\n please verify this info given."); } } catch (Exception e) { System.out.println("controller problem"); } } else { System.out.println("data is Invalid"); System.out.println("------------------------------------"); for (ConstraintViolation<DataBase> DBViolation : DBViolations) { if (DBViolation.getPropertyPath().toString().equals("sid")) { sidDB.getStyleClass().add("error"); sidmsg = DBViolation.getMessage(); } else if (DBViolation.getPropertyPath().toString().equals("TypeDB")) { typeDB.getStyleClass().add("error"); typemsg = DBViolation.getMessage(); } else if (DBViolation.getPropertyPath().toString().equals("hote")) { hostDB.getStyleClass().add("error"); hostmsg = DBViolation.getMessage(); } else if (DBViolation.getPropertyPath().toString().equals("port")) { portDB.getStyleClass().add("error"); portmsg = DBViolation.getMessage(); } else if (DBViolation.getPropertyPath().toString().equals("schemaDB")) { schemaDB.getStyleClass().add("error"); schemamsg = DBViolation.getMessage(); } else if (DBViolation.getPropertyPath().toString().equals("passwordDb")) { passwordDB.getStyleClass().add("error"); pwmsg = DBViolation.getMessage(); } else if (DBViolation.getPropertyPath().toString().equals("dbName4Url")) { dbName4Url.getStyleClass().add("error"); dn4umsg = DBViolation.getMessage(); } else if (DBViolation.getPropertyPath().toString().equals("instance")) { sidDB.getStyleClass().add("error"); sidmsg = DBViolation.getMessage(); } else { System.out.println( "LOGINFO : " + DBViolation.getPropertyPath() + " " + DBViolation.getMessageTemplate()); } } if (!sidmsg.isEmpty()) { sidDB.getStyleClass().add("error"); } else { sidDB.getStyleClass().removeAll("error"); } if (!typemsg.isEmpty()) { typeDB.getStyleClass().add("error"); } else { typeDB.getStyleClass().removeAll("error"); } if (!hostmsg.isEmpty()) { hostDB.getStyleClass().add("error"); } else { hostDB.getStyleClass().removeAll("error"); } if (!portmsg.isEmpty()) { portDB.getStyleClass().add("error"); } else { portDB.getStyleClass().removeAll("error"); } if (!sidmsg.isEmpty()) { sidDB.getStyleClass().add("error"); } else { sidDB.getStyleClass().removeAll("error"); } if (!sidmsg.isEmpty()) { sidDB.getStyleClass().add("error"); } else { sidDB.getStyleClass().removeAll("error"); } if (!schemamsg.isEmpty()) { schemaDB.getStyleClass().add("error"); } else { schemaDB.getStyleClass().removeAll("error"); } if (!pwmsg.isEmpty()) { passwordDB.getStyleClass().add("error"); } else { passwordDB.getStyleClass().removeAll("error"); } if (!dn4umsg.isEmpty()) { dbName4Url.getStyleClass().add("error"); } else { dbName4Url.getStyleClass().removeAll("error"); } errorLabel.setText("Ouuups!! les champs en rouge sont invalides."); } } @FXML public void cancel(MouseEvent event) throws IOException { welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "kit_info"); } } ``` PopUp.java ```package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import com.sopraMdv.anotherProject.AnotherProjectApplication; import javafx.fxml.FXMLLoader; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; public class PopUp { public static void errorPopUp(String msg,String btnMsg) { Stage popupwindow = new Stage(); popupwindow.initModality(Modality.APPLICATION_MODAL); popupwindow.setTitle("Erreur !!"); Label label1= new Label(msg); label1.getStyleClass().add("erreur"); Button button1= new Button(btnMsg); button1.setOnAction(e -> popupwindow.close()); VBox layout= new VBox(10); layout.getChildren().addAll(label1, button1); layout.setAlignment(Pos.CENTER); Scene scene1= new Scene(layout, 200, 200); popupwindow.setScene(scene1); popupwindow.show(); } public void popup(String label,String button) { Stage popupwindow=new Stage(); popupwindow.initModality(Modality.APPLICATION_MODAL); popupwindow.setTitle("Nouvelle fenêtre"); Label label1= new Label(label); Button button1= new Button(button); button1.setOnAction(e -> popupwindow.close()); VBox layout= new VBox(10); layout.getChildren().addAll(label1, button1); layout.setAlignment(Pos.CENTER); Scene scene1= new Scene(layout, 300, 250); popupwindow.setScene(scene1); popupwindow.show(); } public static Stage ScriptManagerPopUp() throws IOException { Stage window=new Stage(); window.initModality(Modality.APPLICATION_MODAL); window.setTitle("Nouvelle requête."); FXMLLoader fxmlLoader = new FXMLLoader(PopUp.class.getResource("/com/sopraMdv/anotherProject/view/ScriptPopUp.fxml")); fxmlLoader.setControllerFactory(AnotherProjectApplication.springContext::getBean); AnchorPane layout = fxmlLoader.load(); Scene scene= new Scene(layout, 744, 427); window.setScene(scene); return window; } } ``` DBListElementController.java ```package com.sopraMdv.anotherProject.Controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.dao.DataBaseDAO; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; @Controller public class DBListElementController { @FXML private ImageView deletebtn; @FXML private Label chosebtn; @FXML private ImageView envimg; @FXML private Label idlabel; @FXML private Label editbutton; private Session session; public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } private DataBaseDAO dbDAO; @FXML private Label nomDBLabel; public DataBaseDAO getDbDAO() { return dbDAO; } @Autowired public void setDbDAO(DataBaseDAO dbDAO) { this.dbDAO = dbDAO; } @FXML private void initialize() { deletebtn.setImage(new Image("/Resources/delete.png",false)); envimg.setImage(new Image("/Resources/database.png",false)); } // @FXML // public void connectdb() throws SQLException { // // // DataBase database=dbDAO.getDatabaseById(storebdId.getId()); // // Server server=database.getServer(); // // dbconnexion.connectDB(database,server); // // } // } ``` KitListController.java ```package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.dao.DataBaseDAO; import com.sopraMdv.anotherProject.dao.KitDAO; import com.sopraMdv.anotherProject.entities.Kit; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; @Controller public class KitListController { @FXML private Pane listelements; private DataBaseDAO dbDAO; public DataBaseDAO getDbDAO() { return dbDAO; } @Autowired public void setDbDAO(DataBaseDAO dbDAO) { this.dbDAO = dbDAO; } private Session session; private KitDAO kitDao; public KitDAO getKitDao() { return kitDao; } @Autowired public void setKitDao(KitDAO kitDao) { this.kitDao = kitDao; } private WelcomeController welcomecontroller; @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } public Session getSession() { return session; } private MainController mainController; public MainController getMainController() { return mainController; } @Autowired public void setMainController(MainController mainController) { this.mainController = mainController; } private ExecuteFileController executefile; public ExecuteFileController getExecutefile() { return executefile; } @Autowired public void setExecutefile(ExecuteFileController executefile) { this.executefile = executefile; } @Autowired public void setSession(Session session) { this.session = session; } @FXML private void initialize() { welcomecontroller.getStopBtn().setVisible(false); welcomecontroller.getExecutebtn().setVisible(false); try { for (Kit element : kitDao.findAll()) { System.out.println(element); AddElemnt(element); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void AddElemnt(Kit kit) throws IOException { AnchorPane element = new AnchorPane(); element.setPrefHeight(227); element.setPrefWidth(230); welcomecontroller.loadInMainPane(element, "kit_element"); Label nom = (Label) element.lookup("#nomKit"); nom.setText(kit.getNomKit()); Label idk = (Label) element.lookup("#idlabel"); idk.setText(kit.getId().toString()); Label chosebtn = (Label) element.lookup("#chosebtn"); ImageView img = (ImageView) element.lookup("#img"); chosebtn.setOnMouseClicked((MouseEvent t) -> { try { session.setKit(kit); welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "kit_info"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }); listelements.getChildren().add(element); } @FXML public void createKit() throws IOException { welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "Kit"); } } ``` HistoriqueController.java ```package com.sopraMdv.anotherProject.Controller; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.nio.file.Paths; import java.sql.SQLException; import java.text.DecimalFormat; import java.util.HashSet; import java.util.Optional; import java.util.Scanner; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.dao.DataBaseDAO; import com.sopraMdv.anotherProject.dao.FileHistoryDAO; import com.sopraMdv.anotherProject.dao.KitDAO; import com.sopraMdv.anotherProject.entities.FileHistory; import antlr.debug.Event; import ch.qos.logback.core.net.SyslogOutputStream; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.stage.DirectoryChooser; @Controller public class HistoriqueController { private File directory = Paths.get(System.getProperty("user.home") + "\\Desktop").toFile(); @FXML private Pane listelements; @FXML private ImageView img; @FXML private ImageView goBackImg; @FXML private ImageView startImg; @FXML private Label nomdbLabel; @FXML private Label nomKitLabel; private DataBaseDAO dbDAO; public DataBaseDAO getDbDAO() { return dbDAO; } @Autowired public void setDbDAO(DataBaseDAO dbDAO) { this.dbDAO = dbDAO; } private Session session; private FileHistoryDAO fileDao; public FileHistoryDAO getFileDao() { return fileDao; } @Autowired public void setFileDao(FileHistoryDAO fileDao) { this.fileDao = fileDao; } private KitDAO kitdao; public KitDAO getKitdao() { return kitdao; } @Autowired public void setKitdao(KitDAO kitdao) { this.kitdao = kitdao; } private WelcomeController welcomecontroller; @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } public Session getSession() { return session; } private MainController mainController; public MainController getMainController() { return mainController; } @Autowired public void setMainController(MainController mainController) { this.mainController = mainController; } private ExecuteFileController executefile; public ExecuteFileController getExecutefile() { return executefile; } @Autowired public void setExecutefile(ExecuteFileController executefile) { this.executefile = executefile; } @Autowired public void setSession(Session session) { this.session = session; } @FXML private void initialize() { img.setImage(new Image("/Resources/gear1.png", false)); goBackImg.setImage(new Image("/Resources/back-arrow.png", false)); startImg.setImage(new Image("/Resources/fa-play.png", false)); nomKitLabel.setText(session.getKit().getNomKit()); if (session.getKit().getDatabase() != null) nomdbLabel.setText("Base de données : " + session.getKit().getDatabase().getSid()); loadScripts(); } public void loadScripts() { try { for (FileHistory element : fileDao.getAllFiles(session.getKit().getId())) { AddElemnt(element); } String[] scriptsUnExecuted = session.getKit().getScripts().split(";"); FileHistory tmpFile = new FileHistory(); for (String element : scriptsUnExecuted) { if (!element.equals("")) { tmpFile.setFileName(element); AddElemnt(tmpFile); System.out.println(element); } } } catch (IOException e) { e.printStackTrace(); } } public void AddElemnt(FileHistory file) throws IOException { double progressVal; AnchorPane element = new AnchorPane(); element.setPrefHeight(50); element.setPrefWidth(880); welcomecontroller.loadInMainPane(element, "Historique_element"); Label nom = (Label) element.lookup("#nomLabel"); Label idh = (Label) element.lookup("#idlabel"); Label statusLabel = (Label) element.lookup("#label"); Label chosebtn = (Label) element.lookup("#chosebtn"); ImageView deletebtn = (ImageView) element.lookup("#deletebtn"); ImageView fileimg = (ImageView) element.lookup("#img"); ProgressBar progress = (ProgressBar) element.lookup("#progress"); Label progressLabel = (Label) element.lookup("#progressLabel"); if (file.getId() != null) { nom.setText(file.getFileName()); idh.setText(file.getId().toString()); if(session.getKit().getDatabase() != null) statusLabel.setText(session.getKit().getDatabase().getSid()); progress.setProgress((float) file.getCurrentline() / file.getLines()); progressVal = ((double) file.getCurrentline() / file.getLines()) * 100; if(progressVal>100) progressVal = 100; progressLabel.setText( (new DecimalFormat("##.##")).format(progressVal) + "%"); if (file.getCurrentline() >= file.getLines()) { fileimg.setImage(new Image("/Resources/check-mark.png", false)); statusLabel.setText("Terminé"); chosebtn.setVisible(false); } else { fileimg.setImage(new Image("/Resources/working.png", false)); statusLabel.setText("En cours"); } fileimg.setOnMousePressed((MouseEvent t) -> { String dateFin = ""; if (file.getDateFin() != null) { dateFin = "\nDate Fin : " + file.getDateFin(); } // String envnom = dbDAO.getDatabaseById(file.getDatabase().getId()).getServer().getEnvi().getNomEnv(); welcomecontroller.setAndShowMessage(t, "Fichier : " + file.getFileName() + "\nLog path : " + file.getLogpath() + "\nnombre de lignes : " + file.getLines() + "\nligne atteinte : " + file.getCurrentline() + "\nDate debut : " + file.getDateDebut() + dateFin, t.getSceneX() - 150, t.getSceneY() - 70); }); fileimg.setOnMouseReleased((MouseEvent t) -> { welcomecontroller.hideMessage(t); }); chosebtn.setOnMouseClicked((MouseEvent t) -> { // continue executing file try { // session.getKit().setDatabase(file.getDatabase()); session.setCnx(session.getCnxNew()); if (session.getCnx() != null) { session.setIdFile(Long.parseLong(idh.getText())); session.setExePaused(0); mainController.setSelectedFile(new java.io.File(file.getPath())); System.out.println(mainController.getSelectedFile().getCanonicalPath()); session.setScanner(getScanner(file)); session.setLine(file.getCurrentline()); welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "Scripts"); welcomecontroller.loadInMainPane(mainController.getViewPane(), "ExecuteInterface"); mainController.showDialog(); ////////////// ///// Showing movingGears welcomecontroller.getMovingGears().setVisible(true); welcomecontroller.getOnTopPane().setVisible(true); ///// welcomecontroller.getOnTopScriptName().setText(file.getFileName()); executefile.continueScript(); }else System.out.println("connexion nuuuuuuuuuuuuuuuuuuuuuul"); //////////////// } catch (IOException | NumberFormatException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }); deletebtn.setVisible(false); deletebtn.setOnMouseClicked((MouseEvent t) -> { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Confirmation!!!!"); alert.setHeaderText("Voulez vous Supprimer ce fichier ?"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { com.sopraMdv.anotherProject.entities.FileHistory fichier = new com.sopraMdv.anotherProject.entities.FileHistory( fileDao.getFileById(Long.parseLong(idh.getText()))); fileDao.delete(fichier); //// delete fichier from kit(filesexecutes) Set<FileHistory> tmp = new HashSet<FileHistory>(); for (FileHistory tmpelement : session.getKit().getFilesExecutes()) { System.out.println("|" + tmpelement.getId() + "||" + fichier.getId() + "|"); if (!tmpelement.getId().equals(fichier.getId())) { tmp.add(tmpelement); } } session.getKit().setFilesExecutes(tmp); ////////////////////// try { welcomecontroller.getMessagePane().setVisible(false); welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "Historique"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); deletebtn.setOnMouseEntered((MouseEvent t) -> { welcomecontroller.setAndShowMessage(t, "supprimer", t.getSceneX() - 180, t.getSceneY() - 70); }); deletebtn.setOnMouseExited((MouseEvent t) -> { welcomecontroller.hideMessage(t); }); statusLabel.setOnMouseClicked((MouseEvent e) -> { if (e.getClickCount() == 3) { if (deletebtn.isVisible()) deletebtn.setVisible(false); else deletebtn.setVisible(true); } }); } else { chosebtn.setVisible(false); deletebtn.setVisible(false); progress.setVisible(false); progressLabel.setVisible(false); nom.setText(file.getFileName()); fileimg.setImage(new Image("/Resources/progress-arrows.png", false)); } listelements.getChildren().add(element); } public Scanner getScanner(FileHistory fichier) throws FileNotFoundException, IOException { int a = 0; FileReader file = new FileReader(mainController.getSelectedFile().getCanonicalPath()); Scanner sc = new Scanner(file); if (fichier.getCurrentline() == 0) return sc; while (sc.hasNext()) { sc.nextLine(); a++; if (a == fichier.getCurrentline()) break; } return sc; } @FXML public void executeKit() throws IOException, SQLException { session.setFileDone(false); for (FileHistory element : fileDao.getAllFiles(session.getKit().getId())) { File file; // System.out.println(element); if (element.getCurrentline() < element.getLines()) { file = new File(element.getPath()); session.setExePaused(0); session.setIdFile(element.getId()); session.setLine(element.getCurrentline()); mainController.setSelectedFile(file); welcomecontroller.getOnTopScriptName().setText(element.getFileName()); ///// Showing movingGears welcomecontroller.getMovingGears().setVisible(true); welcomecontroller.getOnTopPane().setVisible(true); ///// session.setScanner(getScanner(element)); executefile.continueScript_Sequential(); return; } } String[] scriptsUnExecuted = session.getKit().getScripts().split(";"); File file; String Cashpath = welcomecontroller.getCachePath() + "\\MDVApp\\Cache\\"; System.out.println(scriptsUnExecuted); if (session.getKit().getDatabase() == null) { Alert alert = new Alert(AlertType.ERROR); alert.setContentText("vous avez oublié de choisir une base de données!!"); alert.showAndWait(); } else { for (String element : scriptsUnExecuted) { if (!element.equals("")) { session.setExePaused(0); session.setLine(0L); file = new File(Cashpath + "\\" + session.getKit().getNomKit() + "\\" + "scripts\\" + element); mainController.setSelectedFile(file); welcomecontroller.getOnTopScriptName().setText(element); ///// Showing movingGears welcomecontroller.getMovingGears().setVisible(true); welcomecontroller.getOnTopPane().setVisible(true); ///// executefile.executeScript_Sequential(file); return; } } } welcomecontroller.stopScript(1); welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "Historique"); } @FXML public void getDirectory() throws IOException { String Cashpath = welcomecontroller.getCachePath() + "\\MDVApp\\Cache\\"; String cmd = "CMD /C mkdir " + Cashpath + "\\" + session.getKit().getNomKit(); Runtime.getRuntime().exec(cmd); cmd = "CMD /C mkdir " + Cashpath + "\\" + session.getKit().getNomKit() + "\\" + "scripts"; Runtime.getRuntime().exec(cmd); cmd = "CMD /C mkdir " + Cashpath + "\\" + session.getKit().getNomKit() + "\\" + "logs"; Runtime.getRuntime().exec(cmd); cmd = "CMD /C mkdir " + Cashpath + "\\" + session.getKit().getNomKit() + "\\" + "resultats"; Runtime.getRuntime().exec(cmd); DirectoryChooser chooser = new DirectoryChooser(); directory = chooser.showDialog(null); // System.out.println("1 |"+directory); if (directory != null) { session.getKit().setScripts(""); // System.out.println("2 |"+directory); for (File element : directory.listFiles()) { if (element.isFile() && element.getName().endsWith(".sql")) { session.getKit().setScripts(session.getKit().getScripts() + ";" + element.getName()); kitdao.save(session.getKit()); cmd = "CMD /C COPY /Y " + "\"" + element.getCanonicalPath() + "\" \"" + Cashpath + "\\" + session.getKit().getNomKit() + "\\scripts\\" + element.getName() + "\""; Runtime.getRuntime().exec(cmd); } } listelements.getChildren().setAll(); loadScripts(); if (session.getKit().getScripts().startsWith(";")) { // System.out.println("3 |"+directory); session.getKit().setScripts(session.getKit().getScripts().substring(1)); kitdao.save(session.getKit()); } } } @FXML public void goBack() throws IOException { welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "kit_info"); } } ``` DBService.java ```package com.sopraMdv.anotherProject.util; import java.sql.Connection; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.time.temporal.IsoFields; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Scanner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sopraMdv.anotherProject.Controller.DataBaseConnexion; import com.sopraMdv.anotherProject.Controller.HistoriqueController; import com.sopraMdv.anotherProject.Controller.Session; import com.sopraMdv.anotherProject.Controller.WelcomeController; import com.sopraMdv.anotherProject.dao.FileHistoryDAO; import com.sopraMdv.anotherProject.entities.FileHistory; import javafx.application.Platform; import javafx.concurrent.Task; @Service public class DBService extends javafx.concurrent.Service<Object> { private int counter, stop; List<String> listMulti; private FileHistoryDAO fileDao; private boolean checkMulti; private boolean isPackage,isDeclareBlock; public FileHistoryDAO getFileDao() { return fileDao; } @Autowired public void setFileHistoryDao(FileHistoryDAO fileDao) { this.fileDao = fileDao; } private WelcomeController welcomecontroller; @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } private Session session; public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } private DataBaseConnexion dbConnexion; public DataBaseConnexion getDbConnexion() { return dbConnexion; } @Autowired public void setDbConnexion(DataBaseConnexion dbConnexion) { this.dbConnexion = dbConnexion; } private HistoriqueController historiqueController; public HistoriqueController getHistoriqueController() { return historiqueController; } @Autowired public void setHistoriqueController(HistoriqueController historiqueController) { this.historiqueController = historiqueController; } @Override protected Task createTask() { // SplitFileTask task = new SplitFileTask(dbConnexion, session, // welcomecontroller, // fileDao, historiqueController); return new Task() { @Override protected Void call() throws Exception { Scanner sc = session.getScanner(); Connection cnx = session.getCnx(); String s1 = "", s2 = "", s3 = ""; FileHistory file = fileDao.getFileById(session.getIdFile()); listMulti = new ArrayList<String>(FillListMulti()); try { int querytype = 0; // 0 : single line query -- 1 : multi-line query while (sc.hasNext()) { if (session.getExePaused() == 1) { // is paused ? break; } checkMulti = true;// set to check if there is a multiline inside another multiline s1 = sc.nextLine(); session.setLine(session.getLine() + 1); s1 = eliminateComments(s1, sc); // System.out.println("--" + IsMultiline2(s1, sc)); //s3 = IsMultiline2(s1, sc); // querytype = IsMultiLine(s1, listMulti); s2 = ""; //if (!sc.hasNext()) { s2 += "\n" + s1; //} // while (sc.hasNext()) { // if (!s1.equals("")) { // s2 += "\n" + s1 + " "; // } // // if (s1.contains(";")) // break; // // s1 = sc.nextLine(); // session.setLine(session.getLine() + 1); // // if (!sc.hasNext()) { // s2 += "\n" + s1; // } // } if (querytype == 0) { session.setPreLine(session.getLine()); session.setScanner(sc); // if (s2.replaceAll(" ", "").endsWith(";")) { // s2 = s2.replaceAll(" +$", "").replaceAll("\n"," "); // if(s2.toLowerCase().matches(".*( |;)end *[^ ]* *\\;")) { // s2 = s2.replaceAll(";$", ""); // } // } // if (s2.replaceAll(" ", "").endsWith(";")) { // s2 = s2.replaceAll(" +$", "").replaceAll(";$", ""); // } if (s2.replaceAll("\n", "").isEmpty()) { break; } else { double progressVal = ((double) session.getLine() / file.getLines()) * 100; if(progressVal>100) progressVal = 100; try { dbConnexion.executeQuery(s2.trim(), cnx); } catch (Exception e) { if(session.getCnx().isClosed()) { return null; } System.out.println("a warning occurred;"); } this.updateMessage((new DecimalFormat("##.##")).format(progressVal) + "%"); this.updateProgress((float) session.getLine() / file.getLines(), 1); } } } // -------end of file FileHistory fichier = new FileHistory(fileDao.getFileById(session.getIdFile())); /// mise à jour de la table File (currentLine) fichier.setCurrentline(session.getLine()); /// mise à jour de la table File (dateFin) DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); Date date = new Date(); String dateFin = dateFormat.format(date); fichier.setDateFin(dateFin); //////////////////// enregistrement fileDao.save(fichier); ///////////////////// fin mise à jour Platform.runLater(() -> welcomecontroller.getMovingGears().setVisible(false)); // historiqueController.executeKit(); session.setFileDone(true); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }; } // @Override // protected Task createTask() { // // // SplitFileTask task = new SplitFileTask(dbConnexion, session, // // welcomecontroller, // // fileDao, historiqueController); // // return new Task() { // // @Override // protected Void call() throws Exception { // // Scanner sc = session.getScanner(); // Connection cnx = session.getCnx(); // String s1 = "", s2 = "", s3 = ""; // FileHistory file = fileDao.getFileById(session.getIdFile()); // // listMulti = new ArrayList<String>(FillListMulti()); // // try { // // int querytype = 0; // 0 : single line query -- 1 : multi-line query // // while (sc.hasNext()) { // // if (session.getExePaused() == 1) { // is paused ? // break; // } // checkMulti = true;// set to check if there is a multiline inside another multiline // s1 = sc.nextLine(); // session.setLine(session.getLine() + 1); // s1 = eliminateComments(s1, sc); // // System.out.println("--" + IsMultiline2(s1, sc)); // s3 = IsMultiline2(s1, sc); // // querytype = IsMultiLine(s1, listMulti); // if (!s3.isEmpty()) { // // s2 = MultiLine(s1, sc).trim().replaceAll("\n+", "\n"); // s2 = s3; // System.out.println("--" + s2); // session.setPreLine(session.getLine()); // session.setScanner(sc); // // dbConnexion.executeQuery(s2, cnx); // double progressVal = ((double) session.getLine() / file.getLines()) * 100; // if(progressVal>100) // progressVal = 100; // dbConnexion.executeQuery(s2.trim(), cnx); // this.updateMessage((new DecimalFormat("##.##")).format(progressVal) + "%"); // this.updateProgress((float) session.getLine() / file.getLines(), 1); // } else { // s2 = ""; // if (!sc.hasNext()) { // s2 += "\n" + s1; // } // while (sc.hasNext()) { // if (!s1.equals("")) { // s2 += "\n" + s1 + " "; // } // // if (s1.contains(";")) // break; // // s1 = sc.nextLine(); // session.setLine(session.getLine() + 1); // // if (!sc.hasNext()) { // s2 += "\n" + s1; // } // } // if (querytype == 0) { // session.setPreLine(session.getLine()); // session.setScanner(sc); // if (s2.replaceAll(" ", "").endsWith(";")) { // s2 = s2.replaceAll(" +$", "").replaceAll(";$", ""); // } // if (s2.replaceAll("\n", "").isEmpty()) { // break; // } else { // double progressVal = ((double) session.getLine() / file.getLines()) * 100; // if(progressVal>100) // progressVal = 100; // dbConnexion.executeQuery(s2.trim(), cnx); // this.updateMessage((new DecimalFormat("##.##")).format(progressVal) + "%"); // this.updateProgress((float) session.getLine() / file.getLines(), 1); // } // } // // } // } // // -------end of file // FileHistory fichier = new FileHistory(fileDao.getFileById(session.getIdFile())); // /// mise à jour de la table File (currentLine) // fichier.setCurrentline(session.getLine()); // /// mise à jour de la table File (dateFin) // DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); // Date date = new Date(); // String dateFin = dateFormat.format(date); // fichier.setDateFin(dateFin); // //////////////////// enregistrement // fileDao.save(fichier); // ///////////////////// fin mise à jour // Platform.runLater(() -> welcomecontroller.getMovingGears().setVisible(false)); // // historiqueController.executeKit(); // session.setFileDone(true); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // return null; // } // }; // } public String IsMultiline2(String s1, Scanner sc) { String s2 = ""; int linecount = 0; isPackage = false; isDeclareBlock = false; String tmpStrNoSpaces = s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" ", "").toLowerCase(); String tmpStr = s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" +", " ").trim().toLowerCase(); String[] words = tmpStr.split(" "); int wordCounter = 0; if (words[0].matches("create")) { while (sc.hasNext()) { if (Arrays.stream(words).anyMatch("package"::equals) || isPackage) { isPackage = true; if (Arrays.stream(words).anyMatch("body"::equals)) { return s2 + MultiLine(s1, sc); } else if ((Arrays.stream(words).anyMatch("as"::equals)) && !Arrays.stream(words).anyMatch("body"::equals)) { checkMulti = false; return s2 + MultiLine(s1, sc); } else { s2 += s1 + "\n"; s1 = sc.nextLine(); session.setLine(session.getLine() + 1); tmpStrNoSpaces = s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" ", "").toLowerCase(); tmpStr = s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" ", " ").trim().toLowerCase(); words = tmpStr.split(" "); } } else if (Arrays.stream(words).anyMatch("type"::equals)) { return s2 + MultilineIsType(s1, sc); } else if (Arrays.stream(words).anyMatch("function"::equals) || Arrays.stream(words).anyMatch("procedure"::equals) || Arrays.stream(words).anyMatch("trigger"::equals)) { return s2 + MultiLine(s1, sc); } else if (linecount == 0 && !(tmpStrNoSpaces.endsWith("create") || tmpStrNoSpaces.endsWith("createorreplace") || tmpStrNoSpaces.endsWith("createor"))) { return ""; } else { if (!s1.isEmpty()) { linecount++; } if (linecount >= 4) { return ""; } s2 += s1 + "\n"; s1 = sc.nextLine(); session.setLine(session.getLine() + 1); s1 = eliminateComments(s1, sc); tmpStrNoSpaces = s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" ", "").toLowerCase(); tmpStr = s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" +", " ").toLowerCase(); words = tmpStr.split(" "); } } } else if (tmpStr.startsWith("declare")) { isDeclareBlock = true; return s2 + MultiLine(s1, sc); } else if (tmpStr.startsWith("begin")) return s2 + MultiLine(s1, sc); return ""; } public String IsMultiline3(String s1, Scanner sc) { String s2 = ""; int linecount = 0; isPackage = false; isDeclareBlock = false; String tmpStrNoSpaces = s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" ", "").toLowerCase(); String tmpStr = s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" ", " ").toLowerCase(); if (tmpStrNoSpaces.startsWith("create")) { while (sc.hasNext()) { if (tmpStr.contains("package") || isPackage) { isPackage = true; if (tmpStr.matches(".*( body | body).*")) { return s2 + MultiLine(s1, sc); } else if ((tmpStr.matches(".*( as | as).*") || tmpStr.matches("as")) && !tmpStr.contains(" body ")) { checkMulti = false; return s2 + MultiLine(s1, sc); } else { s2 += s1 + "\n"; s1 = sc.nextLine(); session.setLine(session.getLine() + 1); tmpStrNoSpaces = s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" ", "").toLowerCase(); tmpStr = s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" ", " ").toLowerCase(); } } else if (tmpStr.matches(".*( type | type\n).*")) { return s2 + MultilineIsType(s1, sc); } else if (tmpStr.contains("function") || tmpStr.contains("procedure") || tmpStr.contains("trigger")) { return s2 + MultiLine(s1, sc); } else if (linecount == 0 && !(tmpStrNoSpaces.endsWith("create") || tmpStrNoSpaces.endsWith("createorreplace") || tmpStrNoSpaces.endsWith("createor"))) { return ""; } else { if (!s1.isEmpty()) { linecount++; } if (linecount >= 4) return ""; s2 += s1 + "\n"; s1 = sc.nextLine(); session.setLine(session.getLine() + 1); tmpStrNoSpaces = s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" ", "").toLowerCase(); tmpStr = s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" ", " ").toLowerCase(); } } } else if (tmpStr.startsWith("declare")) { isDeclareBlock = true; return s2 + MultiLine(s1, sc); } else if (tmpStr.startsWith("begin")) return s2 + MultiLine(s1, sc); return ""; } public String MultilineIsType(String s1, Scanner sc) { String s2 = ""; while (sc.hasNext()) { // s1 = eliminateComments(s1, sc); // // querytype = IsMultiLine(s2 + s1, listMulti); // if (querytype == 1) { // s2 += MultiLine(s1, sc).trim(); // System.out.println("-----------------------------"); // System.out.println(s2); // System.out.println("-----------------------------"); // session.setPreLine(session.getLine()); // session.setScanner(sc); // // // dbConnexion.executeQuery(s2, cnx); // this.updateMessage(session.getLine().toString()); // // break; // } if (!s1.equals("")) { s2 += "\n" + s1 + " "; } if (s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" ", "").toLowerCase().matches("/")) break; s1 = sc.nextLine(); session.setLine(session.getLine() + 1); if (!sc.hasNext()) { s2 += "\n" + s1; } } return s2; } public int IsMultiLineInsideMultiline(String s1, List<String> list) { String tmpStr = s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" ", "").toLowerCase(); for (String str : list) { if (tmpStr.startsWith(str) && !tmpStr.endsWith(";")) return 1; } return 0; } public List<String> FillListMulti() { List<String> list = new ArrayList<String>(); list.add("function"); list.add("trigger"); // list.add("sequence"); list.add("procedure"); list.add("package"); return list; } public int IsMultiLine(String s1, List<String> list) { for (String str : list) { if (s1.replaceAll("\t", " ").replaceAll(" +", " ").toLowerCase().contains("create " + str)) return 1; if (s1.replaceAll("\t", " ").replaceAll(" +", " ").toLowerCase().contains("create or replace " + str)) return 1; if (s1.replaceAll("\t", " ").replaceAll(" ", "").toLowerCase().startsWith("declare")) return 1; if (s1.replaceAll("\t", " ").replaceAll(" ", "").toLowerCase().startsWith("begin")) return 1; } return 0; } public String MultiLine(String s1, Scanner sc) { stop = 0; counter = 0; String s2 = ""; // if (s1.toLowerCase().contains("declare")) // counterForDeclare++; // // if (s1.toLowerCase().contains("package")) // stop = -1; while (sc.hasNext()) { s1 = eliminateComments(s1, sc); if (IsMultiLineInsideMultiline(s1, listMulti) == 1 && checkMulti) { s2 += "\n" + s1; s1 = sc.nextLine(); session.setLine(session.getLine() + 1); s2 += MultiLine(s1, sc); if (sc.hasNext() && (isPackage || isDeclareBlock)) { s1 = sc.nextLine(); session.setLine(session.getLine() + 1); continue; } else break; } if (!s1.equals("")) { s2 += "\n" + s1 + " "; } System.out.println(counter + " || " + s1); //////////////////// if (s1.toLowerCase().contains("begin")) counter++; if (s1.replaceAll(" ", "").toLowerCase().contains("end;")) { counter--; if (counter <= stop) { break; } s1 = sc.nextLine(); // System.out.println(counter+"---"+s1); session.setLine(session.getLine() + 1); continue; } if (s1.toLowerCase().replaceAll("\t", " ").replaceAll(" +", " ").contains(" end ") || s1.toLowerCase().replaceAll("\t", " ").replaceAll(" +", " ").startsWith("end ")) { if (s1.replaceAll(" ", "").toLowerCase().contains("endif") || s1.replaceAll(" ", "").toLowerCase().contains("endloop") || s1.replaceAll(" ", "").toLowerCase().contains("endcase") || s1.replaceAll(" ", "").toLowerCase().contains("endquery")) { } else if (s1.replaceAll(" +", " ").replaceAll("\t", " ").toLowerCase().startsWith("end ") || s1.replaceAll(" +", " ").replaceAll("\t", " ").toLowerCase().contains(" end ")) { counter--; if (counter <= stop) { // System.out.println(counter+"--exiting--"+s1); break; } } } s1 = sc.nextLine(); session.setLine(session.getLine() + 1); if (!sc.hasNext()) { s2 += "\n" + s1; } } return s2; } public String eliminateComments(String s1, Scanner sc) { String s3 = ""; // s1 = s1.replaceAll("\t", " "); if ((s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" +", "").isEmpty()) && sc.hasNext()) { // if line is emty or has second end after a multiline // query(somtimes the query has "end NAME-PROCEDUR" and a second "end;"). s1 = sc.nextLine(); session.setLine(session.getLine() + 1); s1 = eliminateComments(s1, sc); } if (s1.replaceAll(" ", "").equals("/")) { // if line has only the character '/' . if (sc.hasNextLine()) { s1 = sc.nextLine(); session.setLine(session.getLine() + 1); } else s1 = ""; } else if (s1.contains("/*") && !s1.contains("*/")) { // if comment starts and doesn't end in the same line. s3 = s1.replaceAll("/\\*.*", " "); while (sc.hasNext()) { if (s1.contains("*/")) {// if comment ends. s1 = s1.replaceAll("/\\*.*?\\*/", " "); s3 += s1.replaceAll(".*?\\*/", " "); break; } else { s1 = sc.nextLine(); session.setLine(session.getLine() + 1); } } s1 = s3; } else if (s1.contains("/*") && s1.contains("*/")) {// if line has entire comment(/**/) . s1 = s1.replaceAll("/\\*.*?\\*/", " "); } if (s1.contains("--")) {// if line has comment(--). // System.out.println("found one line"); String[] str = s1.split("--"); if (str.length > 1) { if (s1.contains("'")) { // if -- inside a single quotes like ( val = '--ERROR--' ) String[] str1 = s1.split("'"); String str2 = ""; boolean var = true; // is inside single quotes for (int i = 0; i < s1.length(); i++) { if (s1.charAt(i) == '\'') { var = !var; } if (var == true && i < s1.length() - 1 && s1.charAt(i) == '-' && s1.charAt(i + 1) == '-') { s1 = s1.substring(0, i); break; } } } else { s1 = str[0]; } } else { s1 = ""; } } if (s1.replaceAll("\n", "").replaceAll("\t", "").replaceAll(" +", "").isEmpty()) { // if line has only spaces,"\t" or "\n". // this happens when there is only comments in a line or for a long set of lines // and the line only contains spaces,"\t" or "\n" // so this bloc is important !!!! if (sc.hasNext()) { s1 = sc.nextLine(); session.setLine(session.getLine() + 1); s1 = eliminateComments(s1, sc); } else s1 = ""; } return s1; } } ``` MainController.java ```package com.sopraMdv.anotherProject.Controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Paths; import java.sql.SQLException; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.dao.DataBaseDAO; import com.sopraMdv.anotherProject.entities.DataBase; import com.sopraMdv.anotherProject.util.FilePathTreeItem; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.TabPane; import javafx.scene.control.TreeCell; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; @Controller public class MainController { String initFolder = System.getProperty("user.home") + "\\Desktop"; private File directory = Paths.get(initFolder).toFile(); private FileOutputStream fos = null; private String data; @FXML private Label filenameLabel; @FXML private Label directoryLabel; @FXML private AnchorPane ViewPane; @FXML private TabPane tabPane; @FXML private VBox dirArchitecture; private ArrayList<String> openedfiles = new ArrayList<>(); // private TabPane openedTabPane; Queue<Integer> findedNumberLine = new PriorityQueue<>(); private Session session; private final ContextMenu contextMenu = new ContextMenu(); public AnchorPane getViewPane() { return ViewPane; } public void setViewPane(AnchorPane viewPane) { ViewPane = viewPane; } public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } public File getDirectory() { return directory; } public void setDirectory(File directory) { this.directory = directory; } private DataBaseConnexion dbconnexion; private WelcomeController welcomecontroller; KeyCodeCombination saveKcc = new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN); KeyCodeCombination findKcc = new KeyCodeCombination(KeyCode.F, KeyCombination.CONTROL_DOWN); Scanner scanner = null; private String log = null, error = null; public String getLog() { return log; } public void setLog(String log) { this.log = log; } public String getError() { return error; } public void setError(String error) { this.error = error; } private TreeView<String> treeView = null; public TreeView<String> getTreeView() { return treeView; } public void setTreeView(TreeView<String> treeView) { this.treeView = treeView; } private ExecuteFileController executefile; public ExecuteFileController getExecutefile() { return executefile; } @Autowired public void setExecutefile(ExecuteFileController executefile) { this.executefile = executefile; } @FXML private ComboBox<DataBase> DBs; @FXML private Label errorLabel; @FXML private Pane EnvPopUp; public Pane getEnvPopUp() { return EnvPopUp; } public void setEnvPopUp(Pane envPopUp) { EnvPopUp = envPopUp; } private TabPane openedTabPane; private File selectedFile; public File getSelectedFile() { return selectedFile; } public void setSelectedFile(File selectedFile) { this.selectedFile = selectedFile; } @Autowired public void setDbconnexion(DataBaseConnexion dbconnexion) { this.dbconnexion = dbconnexion; } private DataBaseDAO dbDAO; public DataBaseDAO getDbDAO() { return dbDAO; } @Autowired public void setDbDAO(DataBaseDAO dbDAO) { this.dbDAO = dbDAO; } public void setOpenedfiles(ArrayList<String> openedfiles) { this.openedfiles = openedfiles; } public ArrayList<String> getOpenedfiles() { return openedfiles; } @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } @FXML private void initialize() throws IOException, SQLException { // if (session.getKit().getDatabase() != null) { // EnvPopUp.setVisible(false); // } // welcomecontroller.loadInMainPane(ViewPane, "home"); if (session.getExePaused() != 1) { welcomecontroller.getExecutebtn().setVisible(true); } // welcomecontroller.getBtnChooser().setVisible(true); welcomecontroller.getStopBtn().setVisible(true); //welcomecontroller.getDbChooser().setVisible(true); /////////////// ouvrir un fichier if (contextMenu.getItems().isEmpty()) { MenuItem open = new MenuItem("Ouvrir"); MenuItem openwith = new MenuItem("Ouvrir avec ..."); contextMenu.getItems().addAll(open); contextMenu.getItems().addAll(openwith); open.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { openFile(); } }); openwith.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { openFilewith(); } }); } /////////////////////////////////// openedfiles.clear(); if (log != null && error != null) { executeFile(); executefile.getConsoleLog().setText(error); executefile.getQueryProblem().setText(log); } if (treeView != null) { dirArchitecture.getChildren().clear(); dirArchitecture.getChildren().addAll(directoryLabel, treeView); } } @FXML private void EnvOk(MouseEvent e) throws IOException { DataBase selectedDB = DBs.getValue(); if (selectedDB != null) { session.getKit().setDatabase(selectedDB); EnvPopUp.setVisible(false); } else { errorLabel.setText("Aucune Base de données selectionnée !!!!"); } } @FXML private void EnvCancel(MouseEvent e) throws IOException { EnvPopUp.setVisible(false); // welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "home"); } @FXML public void showDialog() throws IOException { if (session.getExePaused() == 0) { directory = selectedFile.getParentFile(); } else { DirectoryChooser chooser = new DirectoryChooser(); chooser.setInitialDirectory(new File(initFolder)); directory = chooser.showDialog(null); } if (directory != null) { TreeItem<String> treeItem = new TreeItem<String>(directory.getName(), new ImageView(new Image(getClass().getResource("/Resources/computer.png").toExternalForm()))); for (File name : directory.listFiles()) { if (name.exists()) { listChildren(name, treeItem); } else { System.out.println("Alert : Le dossier n'existe pas!!"); } } treeView = new TreeView<String>(treeItem); treeView.setPrefHeight(1500); treeItem.setExpanded(true); EventHandler<MouseEvent> mouseEventHandle = (MouseEvent event) -> { if (event.getButton() == MouseButton.SECONDARY) { handleMouseClicked(event); } if (event.getButton().equals(MouseButton.PRIMARY)) { contextMenu.hide(); if (event.getClickCount() == 2 && selectedFile != null && selectedFile.isFile()) { openFile(); } } }; treeView.addEventHandler(MouseEvent.MOUSE_CLICKED, mouseEventHandle); treeView.setStyle("-fx-border-color: #048FD8;-fx-border-width : 0 0 0 1;"); treeView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { if (newValue instanceof FilePathTreeItem) { // handle((FilePathTreeItem) newValue); selectedFile = new File(((FilePathTreeItem) newValue).getFullPath()); } else selectedFile = null; }); dirArchitecture.getChildren().clear(); dirArchitecture.getChildren().addAll(directoryLabel, treeView); } } public void openFile() { try { if (System.getProperty("os.name").toLowerCase().contains("windows")) { String cmd = "rundll32 url.dll,FileProtocolHandler " + selectedFile.getCanonicalPath(); Runtime.getRuntime().exec(cmd); } else { java.awt.Desktop.getDesktop().edit(selectedFile); } } catch (Exception e) { e.printStackTrace(); } } public void openFilewith() { FileChooser chooser = new FileChooser(); File fileopener = chooser.showOpenDialog(contextMenu); try { if (fileopener != null) { String cmd = "\"" + fileopener.getCanonicalPath() + "\" " + selectedFile.getCanonicalPath() + " -n76"; Runtime.getRuntime().exec(cmd); } } catch (IOException e) { Alert alert = new Alert(AlertType.WARNING); alert.setTitle("Problème!!"); alert.setHeaderText("Problème d'ouverture du fichier"); alert.setContentText("programme non valide!"); alert.showAndWait(); } } private void handleMouseClicked(MouseEvent event) { contextMenu.hide(); Node node = event.getPickResult().getIntersectedNode(); // Accept clicks only on node cells, and not on empty spaces of the TreeView if (node instanceof Text || (node instanceof TreeCell && ((TreeCell) node).getText() != null)) { if (selectedFile != null && selectedFile.isFile()) contextMenu.show(treeView, event.getScreenX(), event.getScreenY()); else setSelectedFile(null); } } // close button creator function private Button createTabButton() { Button button = new Button(); button.setStyle("-fx-background-color: transparent"); ImageView imageView = new ImageView( new Image(getClass().getResource("/Resources/close2.png").toExternalForm(), 16, 16, false, true)); button.setGraphic(imageView); button.getStyleClass().add("tab-button"); return button; } /// help to dir architecture private void listChildren(File file, TreeItem<String> treeItem) { FilePathTreeItem treeNode = new FilePathTreeItem(file.toPath()); if (file.isDirectory()) { treeItem.getChildren().add(treeNode); for (File file1 : file.listFiles()) { listChildren(file1, treeNode); } } else { // Adding event Filter treeNode.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { System.out.println("ensa"); } }); treeItem.getChildren().add(treeNode); } } @FXML private void executeFile() throws IOException, SQLException { welcomecontroller.loadInMainPane(ViewPane, "ExecuteInterface"); } @FXML private void modify() throws IOException, SQLException { ViewPane.getChildren().clear(); ViewPane.getChildren().addAll(tabPane); } } ``` DBListController.java ``` package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.dao.DataBaseDAO; import com.sopraMdv.anotherProject.dao.ServerDAO; import com.sopraMdv.anotherProject.entities.DataBase; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; @Controller public class DBListController { private DataBaseDAO dbDAO; private DataBaseConnexion dbconnexion; private SplitFileController splitfilecontroller; public DataBaseConnexion getDbconnexion() { return dbconnexion; } public SplitFileController getSplitfilecontroller() { return splitfilecontroller; } @Autowired public void setSplitfilecontroller(SplitFileController splitfilecontroller) { this.splitfilecontroller = splitfilecontroller; } @Autowired public void setDbconnexion(DataBaseConnexion dbconnexion) { this.dbconnexion = dbconnexion; } public DataBaseDAO getDbDAO() { return dbDAO; } @Autowired public void setDbDAO(DataBaseDAO dbDAO) { this.dbDAO = dbDAO; } private ServerDAO serverdao; public ServerDAO getServerdao() { return serverdao; } @Autowired public void setServerdao(ServerDAO serverdao) { this.serverdao = serverdao; } @FXML private Pane listelements; private WelcomeController welcomecontroller; @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } private Session session; public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } @FXML private void initialize() { // try { // for (DataBase element : dbDAO.getAllDatabases(serverdao.getServerByEnvid(session.getIdEnv()).getId())) { // // AddElemnt(element); // } // // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } public void AddElemnt(DataBase db) throws IOException { AnchorPane element = new AnchorPane(); element.setPrefHeight(50); element.setPrefWidth(880); welcomecontroller.loadInMainPane(element, "DB_list_element"); Label nom = (Label) element.lookup("#nomDBLabel"); nom.setText(db.getSid()); Label iddb = (Label) element.lookup("#idlabel"); iddb.setText(db.getId().toString()); Label editbtn = (Label) element.lookup("#editbutton"); Label chosebtn = (Label) element.lookup("#chosebtn"); ImageView deletebtn = (ImageView) element.lookup("#deletebtn"); ImageView envimg = (ImageView) element.lookup("#envimg"); DataBase TmpDatabase = new DataBase(dbDAO.getDatabaseById(Long.parseLong(iddb.getText()))); envimg.setOnMousePressed((MouseEvent t) -> { welcomecontroller.setAndShowMessage(t, "Schema : " + db.getSchemaDB() + "\nHôte : " + db.getHote() + "\nType : " + db.getTypeDB() + "\nPort : " + db.getPort() + "\nSID : " + db.getSid(), t.getSceneX() - 150, t.getSceneY() - 70); }); envimg.setOnMouseReleased((MouseEvent t) -> { welcomecontroller.hideMessage(t); }); editbtn.setOnMouseClicked((MouseEvent t) -> { session.getKit().setDatabase(TmpDatabase); try { welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "DB_modifier"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }); // chosebtn.setOnMouseClicked((MouseEvent t) -> { // session.setIdDB(Long.parseLong(iddb.getText())); // System.out.println("connect database:" + session.getIdDB()); // try { // welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "TapPane"); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // }); deletebtn.setOnMouseClicked((MouseEvent t) -> { session.getKit().setDatabase(TmpDatabase); try { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Attention!!!!"); alert.setHeaderText("Voulez vous supprimer cette Base de données?"); alert.setContentText("Tout l'historique des fichiers exécutés va être supprimé!!!!"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK){ deleteDB(); } else { // ... user chose CANCEL or closed the dialog } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //welcomecontroller.FireAnEvent(welcomecontroller.getDblabel()); }); deletebtn.setOnMouseEntered((MouseEvent t) -> { welcomecontroller.setAndShowMessage(t, "supprimer", t.getSceneX() - 180, t.getSceneY() - 70); }); deletebtn.setOnMouseExited((MouseEvent t) -> { welcomecontroller.hideMessage(t); }); listelements.getChildren().add(element); } @FXML public void createDB() throws IOException { welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "Base de donnée"); } public void deleteDB() throws IOException { dbDAO.deleteById(session.getKit().getDatabase().getId()); } } ``` ServerConnexion.java ```package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import java.io.InputStream; import org.springframework.stereotype.Controller; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.sopraMdv.anotherProject.entities.Server; import javafx.fxml.FXML; @Controller public class ServerConnexion { private Server server = new Server(); public Server getServer() { return server; } public void setServer(Server server) { this.server = server; } @FXML public void connectServer() throws JSchException { JSch jsch = new JSch(); // Session session = jsch.getSession(server.getUserName(), server.getHote(), // server.getPort()); Session session = jsch.getSession("amplitude", "10.240.164.11", 22); // session.setPassword(server.getPassword()); session.setPassword("amplitude"); session.setConfig("StrictHostKeyChecking", "no"); System.out.println("Establishing Connection..."); session.connect(); System.out.println("Connection established."); System.out.println(sendCommand("ls")); } public String sendCommand(String command) throws JSchException { JSch jsch = new JSch(); // Session session = jsch.getSession(server.getUserName(), server.getHote(), // server.getPort()); Session session = jsch.getSession("amplitude", "10.240.164.11", 22); // session.setPassword(server.getPassword()); session.setPassword("amplitude"); session.setConfig("StrictHostKeyChecking", "no"); System.out.println("Establishing Connection..."); session.connect(); System.out.println("Connection established."); StringBuilder outputBuffer = new StringBuilder(); try { Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); InputStream commandOutput = channel.getInputStream(); channel.connect(); int readByte = commandOutput.read(); while (readByte != 0xffffffff) { outputBuffer.append((char) readByte); readByte = commandOutput.read(); } channel.disconnect(); } catch (IOException ioX) { return "IOE warning"; } catch (JSchException jschX) { return "JSch warning"; } System.out.println(outputBuffer.toString()); return outputBuffer.toString(); } } ``` AuthentificationController.java ```package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.AnotherProjectApplication; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; @Controller public class AuthentificationController { @FXML private ImageView exit; @FXML private ImageView minimize; @FXML private ImageView logoSopra; @FXML private HBox controlPane; double x, y; @FXML private AnchorPane mainpane; public AnchorPane getMainpane() { return mainpane; } @FXML private void initialize() { logoSopra.setImage(new Image("/Resources/logo.png", false)); minimize.setImage(new Image("/Resources/mini.png", false)); exit.setImage(new Image("/Resources/close.png", false)); System.out.println("before"); FXMLLoader fxmlLoader= new FXMLLoader(getClass().getResource("/com/sopraMdv/anotherProject/view/login.fxml")); fxmlLoader.setControllerFactory(AnotherProjectApplication.springContext::getBean); try { mainpane.getChildren().setAll((Node)fxmlLoader.load()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void exit() { Stage stage = (Stage) exit.getScene().getWindow(); stage.close(); System.exit(1); } public void minimize() { // get a handle to the stage Stage stage = (Stage) minimize.getScene().getWindow(); stage.setIconified(true); } public void moving(MouseEvent mouseEvent) { controlPane.getScene().getWindow().setX(mouseEvent.getScreenX() + x); controlPane.getScene().getWindow().setY(mouseEvent.getScreenY() + y); } public void premoving(MouseEvent mouseEvent) { // record a delta distance for the drag and drop operation. x = (double) (controlPane.getScene().getWindow().getX() - mouseEvent.getScreenX()); y = (double) (controlPane.getScene().getWindow().getY() - mouseEvent.getScreenY()); } } ``` DataBaseDAO.java ```package com.sopraMdv.anotherProject.dao; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.sopraMdv.anotherProject.entities.DataBase; @Repository public interface DataBaseDAO extends CrudRepository<DataBase, Long> { // @Query("SELECT D FROM DataBase D WHERE D.server.id = :id") // public List<DataBase> getAllDatabases(@Param("id")Long long1); // @Query("SELECT D FROM DataBase D WHERE D.id = :id") public DataBase getDatabaseById(@Param("id")Long long1); @Query("SELECT D FROM DataBase D WHERE D.schemaDB = :nomdb") public DataBase getDbbyName(@Param("nomdb")String nomdb); } ``` DataBaseConnexion.java ```package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.sql.Connection; import java.util.Date; import java.text.DateFormat; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.sopraMdv.anotherProject.dao.FileHistoryDAO; import com.sopraMdv.anotherProject.entities.DataBase; import com.sopraMdv.anotherProject.entities.Server; import javafx.scene.control.Alert.AlertType; @Controller public class DataBaseConnexion { private Connection connection = null; private Session session = null; private String driverName = "oracle.jdbc.driver.OracleDriver"; private com.sopraMdv.anotherProject.Controller.Session sessionController; public void setSession(Session session) { this.session = session; } public Session getSession() { return session; } private MainController mainController; public com.sopraMdv.anotherProject.Controller.Session getSessionController() { return sessionController; } @Autowired public void setSessionController(com.sopraMdv.anotherProject.Controller.Session sessionController) { this.sessionController = sessionController; } public MainController getMainController() { return mainController; } @Autowired public void setMainController(MainController mainController) { this.mainController = mainController; } private FileHistoryDAO fileDao; public FileHistoryDAO getFileDao() { return fileDao; } @Autowired public void setFileDao(FileHistoryDAO fileDao) { this.fileDao = fileDao; } private SplitFileController splitfile; public SplitFileController getSplitfile() { return splitfile; } @Autowired public void setSplitfile(SplitFileController splitfile) { this.splitfile = splitfile; } private WelcomeController welcomecontroller; @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } public Connection connectDB(DataBase db) throws SQLException { try { if (session == null) { // cnx au serveur // connectServer(server); } Class.forName(driverName); connection = DriverManager.getConnection( "jdbc:oracle:thin:@" + db.getHote() + ":" + db.getPort() + ":" + db.getSid(), db.getSchemaDB(), db.getPasswordDb()); System.out.println("Connection to database established!"); } catch (Exception e) { e.printStackTrace(); // session.disconnect(); welcomecontroller.MyAlert(AlertType.ERROR, "Erreur de connexion", null, "echec de connexion au BD "); return null; } return connection; } public Session connectServer(Server server) throws JSchException { JSch jsch = new JSch(); // Get SSH session session = jsch.getSession(server.getUserName(), server.getHote(), 22); session.setPassword(server.getPassword()); java.util.Properties config = new java.util.Properties(); // Never automatically add new host keys to the host file config.put("StrictHostKeyChecking", "no"); session.setConfig(config); // Connect to remote server session.connect(); // Apply the port forwarding session.setPortForwardingL(1521, server.getHote(), 22); return session; } @Transactional public void executeQuery(String sql, Connection connection) throws SQLException, IOException { Statement cs = null; if (connection == null) { welcomecontroller.MyAlert(AlertType.ERROR, "Erreur de connexion", null, "echec de connexion au BD "); } else { com.sopraMdv.anotherProject.entities.FileHistory fichier = new com.sopraMdv.anotherProject.entities.FileHistory( fileDao.getFileById(sessionController.getIdFile())); String Cashpath = welcomecontroller.getCachePath() + "\\MDVApp\\Cache\\"; String resPath = Cashpath + fichier.getKit().getNomKit() + "\\" + "resultats\\"; String cleanFile = resPath + fichier.getFileName(); String logFile = fichier.getLogpath() + "\\" + fichier.getFileName().substring(0, fichier.getFileName().length() - 4) + "_Log.txt"; Statement ps = connection.createStatement(); System.out.println("NOM DE KIT" + fichier.getKit().getNomKit()); System.out.println(sessionController.getLine()); System.out.println(sql); DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss"); Date start = new Date(); System.out.println(df.format(start)); //insert into MigrationProcessLog cs = connection.createStatement(); String sql1 = "insert into MIGRATIONPROCESSLOG"+ "(starttime,"+ "SCRIPTNAME,"+ "STEPNAME,)"+ "values ("+ df.format(start)+","+ fichier.getFileName()+","+ sessionController.getLine()+","+ sql+")"; ps.execute(sql1); ps.execute(sql); //update sur migrationprocess et migrationprocesslog Date stop = new Date(); System.out.println(df.format(stop)); String sql2 = "UPDATE MIGRATIONPROCESS"+ " SET DATEEXEC = "+ df.format(stop)+ " SCRIPTNAME = "+fichier.getFileName()+","+ " LINENUMBER = "+sessionController.getLine()+","+ "WHERE nomKit = "+fichier.getKit().getNomKit(); String sql3 = "update MIGRATIONPROCESSLOG set "+ "stoptime = "+df.format(stop)+ "SQLERRCODE = "+0+ "SQLERRMESS = "+ null+" where "+ sql +"=REQUETE" ; ps.execute(sql2); ps.execute(sql3); System.out.println(sessionController.getLine()); /// mise à jour de la table File (currentLine) fichier.setCurrentline(sessionController.getLine()); fileDao.save(fichier); ///////////////////// fin mise à jour if (!sql.replaceAll(" ", "").endsWith(";")) { sql = sql + ";"; } Files.write(Paths.get(cleanFile), (sql + "\n").getBytes(), StandardOpenOption.APPEND); Files.write(Paths.get(logFile), ("/* ------------------------------ Succés ------------------------------- \n\n" + sql + "\n ------------------------------------------------------------------------- */\n") .getBytes(), StandardOpenOption.APPEND); // ******this block is for testing the split algo***** // Files.write(Paths.get(logFile), // (" ------------------------------ line : " + fichier.getCurrentline() + " ------------------------------- \n\n" + sql // + "\n\n ------------------------------------------------------------------------- \n\n") // .getBytes(), // StandardOpenOption.APPEND); // ************************* ps.close(); } } public void executeNewQuery(String sql, Connection connection, boolean savingStatus) throws SQLException, IOException { if (connection == null) { welcomecontroller.MyAlert(AlertType.ERROR, "Erreur de connexion", null, "echec de connexion au BD "); } else { com.sopraMdv.anotherProject.entities.FileHistory fichier = new com.sopraMdv.anotherProject.entities.FileHistory( fileDao.getFileById(sessionController.getIdFile())); String Cashpath = welcomecontroller.getCachePath() + "\\MDVApp\\Cache\\"; String resPath = Cashpath + fichier.getKit().getNomKit() + "\\" + "resultats\\"; String cleanFile = resPath + fichier.getFileName(); String logFile = fichier.getLogpath() + "\\" + fichier.getFileName().substring(0, fichier.getFileName().length() - 4) + "_Log.txt"; Statement ps = connection.createStatement(); ps.execute(sql); // ResultSet rs = ps.executeQuery(sql); // // String row = ""; // ResultSetMetaData metadata = rs.getMetaData(); // int columnCount = metadata.getColumnCount(); // while (rs.next()) { // row += "\n"; // if (row.equals("\n")) { // for (int i = 1; i <= columnCount; i++) { // row += metadata.getColumnName(i) + " " + metadata.getColumnTypeName(i) + " | "; // } // } // row += "\n"; // for (int i = 1; i <= columnCount; i++) { // row += rs.getString(i) + " | "; // } // } // sessionController.setQueryResult(row); if (!sql.replaceAll(" ", "").endsWith(";")) { sql = sql + ";"; } if (savingStatus) { Files.write(Paths.get(cleanFile), (sql + "\n").getBytes(), StandardOpenOption.APPEND); Files.write(Paths.get(logFile), ("/* ------------------------------ Succés ------------------------------- \n\n" + sql + "\n\n ------------------------------------------------------------------------- */\n\n") .getBytes(), StandardOpenOption.APPEND); } ps.close(); } } public void executeCommand() throws JSchException, IOException { StringBuilder outputBuffer = new StringBuilder(); Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(""); InputStream commandOutput = channel.getInputStream(); channel.connect(); int readByte = commandOutput.read(); while (readByte != 0xffffffff) { outputBuffer.append((char) readByte); readByte = commandOutput.read(); } channel.disconnect(); } } ``` AnotherProjectApplication.java ```package com.sopraMdv.anotherProject; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; import javafx.stage.StageStyle; @EnableJpaRepositories("com.sopraMdv.anotherProject.dao") @SpringBootApplication public class AnotherProjectApplication extends Application{ // private static final SpringFxmlLoader loader = new SpringFxmlLoader(); public static ConfigurableApplicationContext springContext; private Parent rootNode; public static void main(String[] args) { //SpringApplication.run(MdvApplication.class, args); Application.launch(args); } @Override public void init() throws Exception { springContext = SpringApplication.run(AnotherProjectApplication.class); FXMLLoader fxmlLoader= new FXMLLoader(getClass().getResource("/com/sopraMdv/anotherProject/view/Welcome.fxml")); springContext.getAutowireCapableBeanFactory().autowireBean(this); fxmlLoader.setControllerFactory(AnotherProjectApplication.springContext::getBean); rootNode=fxmlLoader.load(); } @Override public void start(Stage stage) throws Exception { Scene scene = new Scene(rootNode, 1068, 700); stage.setTitle("Bienvenue Sur MDV APP"); stage.setScene(scene); scene.getStylesheets().add("/Resources/login.css"); stage.getIcons().add(new Image("/Resources/favicon-32x32.ico")); stage.requestFocus(); stage.setResizable(false); stage.initStyle(StageStyle.UNDECORATED); stage.show(); } @Override public void stop() throws Exception { springContext.close(); } // public void setContext() { // // // // } // } ``` ScriptManagerController.java ```package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; @Component public class ScriptManagerController { private SplitFileController splitfile; private boolean isPopUpActive = false; private ExecuteFileController executefile; @Autowired private DataBaseConnexion dbConnexion; private Session session; /* FXML Components */ @FXML private TextArea resultat; @FXML private HBox footer; @FXML private Label addLabel; @FXML private ImageView savingSwitch; private boolean savingstaus; @FXML private Label editLabel; @FXML private Label commentLabel; @FXML private Label cancelLabel; @FXML private TextArea scriptEditor; @FXML private Label correctQuery; public boolean isPopUpActive() { return isPopUpActive; } public void setPopUpActive(boolean isPopUpActive) { this.isPopUpActive = isPopUpActive; } public SplitFileController getSplitfile() { return splitfile; } @Autowired public void setSplitfile(SplitFileController splitfile) { this.splitfile = splitfile; } public ExecuteFileController getExecutefile() { return executefile; } @Autowired public void setExecutefile(ExecuteFileController executefile) { this.executefile = executefile; } public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } public TextArea getScriptEditor() { return scriptEditor; } public void setScriptEditor(TextArea scriptEditor) { this.scriptEditor = scriptEditor; } @FXML private void initialize() { savingstaus = false; savingSwitch.setImage(new Image("/Resources/switch-off.png", false)); } public void runNewQuery() throws SQLException, IOException { resultat.setText(""); isPopUpActive = true; // Connection cnx = executefile.connectDB(session.getIdDB()); if (session.getCnx().isClosed()) { session.setCnx(session.getCnxNew()); } String str = scriptEditor.getText(); if (!str.toUpperCase().replaceAll("\n"," ").replaceAll("\t", "").replaceAll(" +", " ").matches("^ *\t*CREATE OR REPLACE PROCEDURE.*|^ *\\t*DECLARE.*" + "|^ *\t*BEGIN.*|^ *\t*CREATE TRIGGER.*|^ *\t*CREATE OR REPLACE FUNCTION.*|^ *\t*CREATE TRIGGER.*" + "|^ *\t*CREATE OR REPLACE TRIGGER.*|^ *\t*CREATE OR REPLACE PACKAGE.*")) { str = str.replaceAll("; *$", ""); } if (!str.isEmpty()) { try { dbConnexion.executeNewQuery(str, session.getCnx(),savingstaus); correctQuery.setStyle("-fx-text-inner-color : green;"); correctQuery.setText("requette exécutée"); //resultat.setText(session.getQueryResult()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); resultat.setText(e.getMessage()); correctQuery.setStyle("-fx-text-inner-color : red;"); correctQuery.setText("erreur"); } } else { resultat.setText("L'instruction SQL ne peut pas être vide!!"); } } @FXML public void switchSaving() { if (savingstaus) { savingstaus = false; savingSwitch.setImage(new Image("/Resources/switch-off.png", false)); } else { savingstaus = true; savingSwitch.setImage(new Image("/Resources/switch-on.png", false)); } } } ``` Kit.java ```package com.sopraMdv.anotherProject.entities; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.validation.constraints.NotEmpty; @Entity public class Kit { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; @Column(unique=true) @NotEmpty private String nomKit; private String descriptionKit; @OneToMany(fetch=FetchType.EAGER,mappedBy="kit") private Set<ProgrammeDeReprise> progReprises; @OneToMany(fetch=FetchType.EAGER,mappedBy="kit") private Set<FileHistory> filesExecuted; private String scripts; private String scriptsPath; @OneToOne(cascade=CascadeType.ALL) private DataBase database; public Kit() { super(); } public Kit(Long id, @NotEmpty String nomKit, String descriptionKit, Set<ProgrammeDeReprise> progReprises, Set<FileHistory> filesExecutes, String scripts, DataBase database, String scriptsPath) { super(); this.id = id; this.nomKit = nomKit; this.descriptionKit = descriptionKit; this.progReprises = progReprises; this.filesExecuted = filesExecutes; this.scripts = scripts; this.database = database; this.scriptsPath = scriptsPath; } public Kit(Kit kit) { this.id = kit.id; this.nomKit = kit.nomKit; this.descriptionKit = kit.descriptionKit; this.progReprises = kit.progReprises; this.filesExecuted = kit.filesExecuted; this.scripts = kit.scripts; this.database = kit.database; this.scriptsPath = kit.scriptsPath; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNomKit() { return nomKit; } public void setNomKit(String nomKit) { this.nomKit = nomKit; } public String getDescriptionKit() { return descriptionKit; } public void setDescriptionKit(String descriptionKit) { this.descriptionKit = descriptionKit; } public Set<ProgrammeDeReprise> getProgReprises() { return progReprises; } public void setProgReprises(Set<ProgrammeDeReprise> progReprises) { this.progReprises = progReprises; } public Set<FileHistory> getFilesExecutes() { return filesExecuted; } public void setFilesExecutes(Set<FileHistory> filesExecutes) { this.filesExecuted = filesExecutes; } public String getScripts() { return scripts; } public void setScripts(String scripts) { this.scripts = scripts; } public DataBase getDatabase() { return database; } public void setDatabase(DataBase database) { this.database = database; } public String getScriptsPath() { return scriptsPath; } public void setScriptsPath(String scriptsPath) { this.scriptsPath = scriptsPath; } @Override public String toString() { return "Kit [id=" + id + ", nomKit=" + nomKit + ", descriptionKit=" + descriptionKit + ", progReprises=" + progReprises + ", filesExecutes=" + filesExecuted + ", scripts=" + scripts + ", scriptsPath=" + scriptsPath + ", database=" + database + "]"; } } ``` ExceptionLoggerPointCut.java ```package com.sopraMdv.anotherProject.util; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import com.sopraMdv.anotherProject.Controller.ExecuteFileController; import com.sopraMdv.anotherProject.Controller.MainController; import com.sopraMdv.anotherProject.Controller.ScriptManagerController; import com.sopraMdv.anotherProject.Controller.Session; import com.sopraMdv.anotherProject.Controller.SplitFileController; import com.sopraMdv.anotherProject.Controller.WelcomeController; import com.sopraMdv.anotherProject.dao.FileHistoryDAO; import com.sopraMdv.anotherProject.entities.FileHistory; import javafx.application.Platform; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; @Configuration @Aspect public class ExceptionLoggerPointCut { private ExecuteFileController executefile; private WelcomeController welcomeController; private ScriptManagerController scriptmanagercontroller; private Session session; private SplitFileController splitfile; private FileHistoryDAO fileDao; public FileHistoryDAO getFileDao() { return fileDao; } @Autowired public void setFileDao(FileHistoryDAO fileDao) { this.fileDao = fileDao; } public WelcomeController getWelcomeController() { return welcomeController; } @Autowired public void setWelcomeController(WelcomeController welcomeController) { this.welcomeController = welcomeController; } public ScriptManagerController getScriptmanagercontroller() { return scriptmanagercontroller; } @Autowired public void setScriptmanagercontroller(ScriptManagerController scriptmanagercontroller) { this.scriptmanagercontroller = scriptmanagercontroller; } private MainController mainController; public MainController getMainController() { return mainController; } @Autowired public void setMainController(MainController mainController) { this.mainController = mainController; } public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } public SplitFileController getSplitfile() { return splitfile; } @Autowired public void setSplitfile(SplitFileController splitfile) { this.splitfile = splitfile; } public ExecuteFileController getExecutefile() { return executefile; } @Autowired public void setExecutefile(ExecuteFileController executefile) { this.executefile = executefile; } @AfterThrowing(pointcut = "execution(* com.sopraMdv.anotherProject.Controller.DataBaseConnexion.*(..)) && args(sql,connection)", throwing = "ex") public void logError(Exception ex, String sql, Connection connection) throws IOException, SQLException { // i had to use Platform.runLater because of the conflict between the main FX // Thread and the threads created for DataBase access. // If the DB thread use the FX interface an error will rise . Statement cs = null; if (ex.toString().contains("java.sql.SQLRecoverableException: Erreur d'E/S: Socket read timed out")) { connection.commit(); connection.close(); session.setCnx(session.getCnxNew()); } else { //// stopping movingGears Platform.runLater(() -> welcomeController.getMovingGears().setVisible(false)); Platform.runLater(() -> welcomeController.getOnTopPane().setVisible(false)); ///// Boolean iswarning = false; String warningnum = ""; List<String> listwarnings = new ArrayList<String>(); // listwarnings.add("-01418:"); // listwarnings.add("-00001:"); // listwarnings.add("-01430:"); // listwarnings.add("-02443:"); // listwarnings.add("-01442:"); // listwarnings.add("-24344:"); listwarnings.add("-02291"); listwarnings.add("-0955"); listwarnings.add("-04080"); listwarnings.add("-01430"); listwarnings.add("-01408"); listwarnings.add("-02260"); listwarnings.add("-01418"); listwarnings.add("-02275"); listwarnings.add("-04043"); listwarnings.add("-0957"); listwarnings.add("-0942"); listwarnings.add("-02443"); listwarnings.add("-02289"); listwarnings.add("-24344:"); // listwarnings.add("-02291:"); // listwarnings.add("-04080:"); // listwarnings.add("-02260:"); // listwarnings.add("-02275:"); // listwarnings.add("-04043:"); // listwarnings.add("-00957:"); // listwarnings.add("-00942:"); // listwarnings.add("-02443:"); // listwarnings.add("-02289:"); for (String str : listwarnings) { if (ex.toString().contains(str)) { iswarning = true; warningnum = str; //trace de l'erreur sur migrationprocesslog DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss"); Date stop = new Date(); cs = connection.createStatement(); String sqlErr = "update MIGRATIONPROCESSLOG set "+ "stoptime = "+df.format(stop)+ "SQLERRCODE = "+str+ "SQLERRMESS = "+ ex.toString() +" where "+ sql +"=REQUETE" ; cs.execute(sqlErr); break; } } // if (!sql.replaceAll(" ", "").endsWith(";")) { // sql = sql + ";"; // } if (!scriptmanagercontroller.isPopUpActive()) { com.sopraMdv.anotherProject.entities.FileHistory fichier = new com.sopraMdv.anotherProject.entities.FileHistory( fileDao.getFileById(session.getIdFile())); String Cashpath = welcomeController.getCachePath() + "\\MDVApp\\Cache\\"; String resPath = Cashpath + fichier.getKit().getNomKit() + "\\" + "resultats\\"; String cleanFile = resPath + fichier.getFileName(); String logFile = fichier.getLogpath() + "\\" + fichier.getFileName().substring(0, fichier.getFileName().length() - 4) + "_Log.txt"; if (iswarning) { Files.write(Paths.get(logFile), ("/* -------------------------- warning !!!!!!!!! --------------------------*/" + "\n Num : " + warningnum + sql + "\n " + " -------------------------- End Warning -------------------------- */\n\n") .getBytes(), StandardOpenOption.APPEND); Files.write(Paths.get(cleanFile), ("/* -------------------------- warning !!!!!!!!! --------------------------" + "\n Num : " + warningnum + sql + "\n " + " -------------------------- End Warning -------------------------- */\n\n") .getBytes(), StandardOpenOption.APPEND); /// mise à jour de la table File (currentLine) System.out.println(fichier); fichier.setCurrentline(session.getLine()); fileDao.save(fichier); ///////////////////// fin mise à jour ///////////////////// fin mise à jour // Mise à jour du kit Set tmpFiles = new HashSet<FileHistory>(session.getKit().getFilesExecutes()); for (FileHistory element : session.getKit().getFilesExecutes()) { if (element.getId() == fichier.getId()) { tmpFiles.remove(element); tmpFiles.add(fichier); session.getKit().setFilesExecutes(tmpFiles); break; } } ///////////////////// fin mise à jour // executefile.continueScript(); } else { Platform.runLater(() -> welcomeController.getExecutebtn().setVisible(false)); Platform.runLater(() -> welcomeController.getConnectstate().setStyle("-fx-Fill : #F28400")); Platform.runLater(() -> welcomeController.getTitre().setText("En attente")); Platform.runLater(() -> welcomeController.getTitre().setPrefWidth(200)); session.setExePaused(1); Files.write(Paths.get(logFile), ("/* -------------------------- Erreur !!!!!!!!! --------------------------" + "\n Exception : " + ex + " ------------------------------ \n" + sql + "\n" + "-------------------------- End Erreur -------------------------- */\n\n") .getBytes(), StandardOpenOption.APPEND); executefile.getConsoleLog().setText("Numero de ligne : " + session.getLine() + "\n" + ex); // PopUp.ScriptManagerPopUp(); // scriptmanagercontroller.getScriptEditor().setText(""+sql); executefile.getQueryProblem().setText(sql); mainController.setLog(new String(sql)); mainController.setError(new String("Numero de ligne ss : " + session.getLine() + "\n" + ex)); connection.close(); } } } } }``` WelcomeController.java ```package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.AnotherProjectApplication; import com.sopraMdv.anotherProject.dao.DataBaseDAO; import com.sopraMdv.anotherProject.dao.FileHistoryDAO; import com.sopraMdv.anotherProject.dao.ServerDAO; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.shape.Circle; import javafx.stage.Stage; @Controller public class WelcomeController { @FXML private ImageView exit; @FXML private ImageView minimize; @FXML private ImageView logoSopra; @FXML private ImageView executebtn; @FXML private Pane imageChanger; @FXML private ImageView imageChangerIcon; // @FXML // private ImageView btnChooser; @FXML private ImageView stopBtn; @FXML private ImageView movingGears; // @FXML // private ImageView dbChooser; @FXML private AnchorPane ViewPane; @FXML private Circle profilePic; @FXML private Circle connectstate; @FXML private HBox controlPane; @FXML private Pane messagePane; @FXML private Label messageLabel; @FXML private Label kitlabel; @FXML private Pane onTopPane; @FXML private Label onTopScriptName; @FXML private ProgressBar onTopProgressbar; @FXML private Label onTopProgressLabel; @FXML private Label parametrage; @FXML private Label IdServ; @FXML private Label IdDB; private Session session; @FXML private AnchorPane mainpane; private double x, y; private boolean dbShow;// pour tester si il faut afficher dbLabel. private ExecuteFileController executefile; private ServerDAO serverdao; private DataBaseDAO dbDAO; @FXML private Label titre; private MainController mainController; public MainController getMainController() { return mainController; } @Autowired public void setMainController(MainController mainController) { this.mainController = mainController; } public boolean isDbShow() { return dbShow; } public void setDbShow(boolean dbShow) { this.dbShow = dbShow; } private SplitFileController splitfile; public SplitFileController getSplitfile() { return splitfile; } @Autowired public void setSplitfile(SplitFileController splitfile) { this.splitfile = splitfile; } private FileHistoryDAO fileDao; public FileHistoryDAO getFileDao() { return fileDao; } @Autowired public void setFileDao(FileHistoryDAO fileDao) { this.fileDao = fileDao; } public Label getTitre() { return titre; } public ImageView getStopBtn() { return stopBtn; } public void setStopBtn(ImageView stopBtn) { this.stopBtn = stopBtn; } public Pane getOnTopPane() { return onTopPane; } public void setOnTopPane(Pane onTopPane) { this.onTopPane = onTopPane; } public Label getOnTopScriptName() { return onTopScriptName; } public void setOnTopScriptName(Label onTopScriptName) { this.onTopScriptName = onTopScriptName; } public ProgressBar getOnTopProgressbar() { return onTopProgressbar; } public void setOnTopProgressbar(ProgressBar onTopProgressbar) { this.onTopProgressbar = onTopProgressbar; } public Label getOnTopProgressLabel() { return onTopProgressLabel; } public void setOnTopProgressLabel(Label onTopProgressLabel) { this.onTopProgressLabel = onTopProgressLabel; } public ImageView getMovingGears() { return movingGears; } public void setMovingGears(ImageView movingGears) { this.movingGears = movingGears; } public ExecuteFileController getExecutefile() { return executefile; } @Autowired public void setExecutefile(ExecuteFileController executefile) { this.executefile = executefile; } public Circle getConnectstate() { return connectstate; } public ImageView getExecutebtn() { return executebtn; } public void setExecutebtn(ImageView executebtn) { this.executebtn = executebtn; } public Pane getMessagePane() { return messagePane; } public Label getMessageLabel() { return messageLabel; } public Label getKitlabel() { return kitlabel; } public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } public AnchorPane getMainpane() { return mainpane; } public ServerDAO getServerdao() { return serverdao; } @Autowired public void setServerdao(ServerDAO serverdao) { this.serverdao = serverdao; } public DataBaseDAO getDbDAO() { return dbDAO; } @Autowired public void setDbDAO(DataBaseDAO dbDAO) { this.dbDAO = dbDAO; } private int transitionDirection; @FXML private void initialize() { onTopPane.setVisible(false); executebtn.setVisible(false); // btnChooser.setVisible(false); stopBtn.setVisible(false); // dbChooser.setVisible(false); System.out.println(movingGears.isVisible()); imageChanger.setVisible(false); session.setExePaused(2); executebtn.setImage(new Image("/Resources/fa-play.png", false)); // btnChooser.setImage(new Image("/Resources/folder.png", false)); stopBtn.setImage(new Image("/Resources/fa-stop.png", false)); // dbChooser.setImage(new Image("/Resources/Choosedatabase.png", false)); movingGears.setImage(new Image("/Resources/movingGears.gif", false)); imageChangerIcon.setImage(new Image("/Resources/photo-camera.png", false)); logoSopra.setImage(new Image("/Resources/logo.png", false)); minimize.setImage(new Image("/Resources/mini.png", false)); exit.setImage(new Image("/Resources/close.png", false)); connectstate.setStyle("-fx-Fill : #ff0400"); messagePane.setVisible(false); movingGears.setVisible(false); dbShow = false; transitionDirection = 0; session.setLine(0L); // if (user.getImageUrl() == null) { // profilePic.setFill(new ImagePattern(new Image("/Resources/profile.png", false))); // } else { // try { // profilePic.setFill(new ImagePattern(new Image(new File(user.getImageUrl()).toURI().toString(), false))); // } catch (Exception e) { // // TODO Auto-generated catch block // System.out.println("erreur d'image"); // profilePic.setFill(new ImagePattern(new Image("/Resources/profile.png", false))); // } // } // fire kitlabel OnMouseClick***************** FireAnEvent(kitlabel); // ************************************ } public void exit() { if (session.getExePaused() == 2) { Optional<ButtonType> result = MyAlert(AlertType.CONFIRMATION, "Confirmation!!!!", "Voulez-vous sortire de l'application ?", null); if (result.get() == ButtonType.OK) { Stage stage = (Stage) exit.getScene().getWindow(); stage.close(); System.exit(1); } } else { MyAlert(AlertType.WARNING, "Attention!!!!", "Il faut arrêter le script !!", "Vous ne pouvez pas sortir parce qu'un fichier est en execution !!!"); } } public void minimize() { // get a handle to the stage Stage stage = (Stage) minimize.getScene().getWindow(); stage.setIconified(true); } public void moving(MouseEvent mouseEvent) { // move the stage controlPane.getScene().getWindow().setX(mouseEvent.getScreenX() + x); controlPane.getScene().getWindow().setY(mouseEvent.getScreenY() + y); } public void premoving(MouseEvent mouseEvent) { // record a delta distance for the drag and drop operation. x = (double) (controlPane.getScene().getWindow().getX() - mouseEvent.getScreenX()); y = (double) (controlPane.getScene().getWindow().getY() - mouseEvent.getScreenY()); } @FXML public void press(MouseEvent event) throws IOException { // String name = ((Label) event.getSource()).getText(); mainpane.setPadding(new Insets(1000, 201.0, 0, 0)); // if (name.equals("Serveur")) { // name = verifyServer(); // } else if (name.equals("Base de données")) { // name = verifyDB(); // } // // if (name.equals("Scripts")) { // // } else { // executebtn.setVisible(false); // btnChooser.setVisible(false); // stopBtn.setVisible(false); // dbChooser.setVisible(false); // // } loadInMainPane(mainpane, name); } // @FXML // public void paramClicked(MouseEvent event) { // int i = 5; // AnimationTimer timer = new AnimationTimer() { // @Override // public void handle(long now) { // if (transitionDirection == 0) { // // if (envlabel.getLayoutY() < 377) // envlabel.setLayoutY(envlabel.getLayoutY() + i - 2); // if (serverlabel.getLayoutY() < 430) // serverlabel.setLayoutY(serverlabel.getLayoutY() + i - 1); // // dblabel.setLayoutY(dblabel.getLayoutY() + i); // if (session.getIdEnv() != null) // serverlabel.setVisible(true); // if (dbShow) // dblabel.setVisible(true); // // envlabel.setVisible(true); // // if (dblabel.getLayoutY() >= 483) { // transitionDirection = 1; // this.stop(); // } // } else { // if (dblabel.getLayoutY() < 350) // dblabel.setVisible(false); // if (envlabel.getLayoutY() < 350) // envlabel.setVisible(false); // if (serverlabel.getLayoutY() < 350) // serverlabel.setVisible(false); // dblabel.setLayoutY(dblabel.getLayoutY() - i); // if (envlabel.getLayoutY() > 324) // envlabel.setLayoutY(envlabel.getLayoutY() - i + 2); // if (serverlabel.getLayoutY() > 324) // serverlabel.setLayoutY(serverlabel.getLayoutY() - i + 1); // if (dblabel.getLayoutY() <= 324) { // transitionDirection = 0; // this.stop(); // } // } // } // }; // timer.start(); // } public void loadInMainPane(AnchorPane Apane, String minipane) throws IOException { FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource("/com/sopraMdv/anotherProject/view/" + minipane + ".fxml")); fxmlLoader.setControllerFactory(AnotherProjectApplication.springContext::getBean); Node node = (Node) fxmlLoader.load(); Apane.getChildren().setAll(node); } public void FireAnEvent(Node node) { // fire OnMouseClick***************** node.fireEvent(new MouseEvent(MouseEvent.MOUSE_CLICKED, node.getLayoutX(), node.getLayoutY(), node.getLayoutX(), node.getLayoutY(), MouseButton.PRIMARY, 1, true, true, true, true, true, true, true, true, true, true, null)); // *********************** } @FXML public void showMessageScriptState(MouseEvent e) { if (session.getIdFile() != null) setAndShowMessage(e, "Script : " + fileDao.getFileById(session.getIdFile()).getFileName(), e.getX() + 40, e.getY() + 40); else { setAndShowMessage(e, "Aucun script selectionné", e.getX() + 40, e.getY() + 40); connectstate.setStyle("-fx-Fill : red"); } } @FXML public void showMessageStart(MouseEvent e) { setAndShowMessage(e, "Executer", e.getX() + 470, e.getY() + 40); } @FXML public void showMessageStop(MouseEvent e) { setAndShowMessage(e, "Arrêter", e.getX() + 520, e.getY() + 40); } @FXML public void changeImage() { } @FXML public void hideMessage(MouseEvent event) { messagePane.setVisible(false); } public void setAndShowMessage(MouseEvent evn, String message, Double x, Double y) { messagePane.setLayoutX(x); messagePane.setLayoutY(y); messagePane.setVisible(true); messageLabel.setVisible(true); messageLabel.setText(message); } @FXML public void browse() throws IOException { mainController.showDialog(); } @FXML public void runScript() throws IOException, SQLException { if (session.getKit().getDatabase().getId() != null) { if (session.getExePaused() == 2) { if (mainController.getSelectedFile() != null) { if (mainController.getSelectedFile().getName().endsWith(".sql")) { Optional<ButtonType> result = MyAlert(AlertType.CONFIRMATION, "Confirmation!!!!", "Voulez vous executer ce script(" + mainController.getSelectedFile().getName() + ")?", "Dans la BD : " + dbDAO.getDatabaseById(session.getKit().getDatabase().getId()).getSid()); if (result.get() == ButtonType.OK) { session.setLine(0L); session.setCnx(session.getCnxNew()); if (session.getCnx() != null) { loadInMainPane(mainController.getViewPane(), "ExecuteInterface"); executefile.executeScript(); } } } else { MyAlert(AlertType.WARNING, "Attention!!!!", null, "Script non valide (~_~) !!!"); } } else { MyAlert(AlertType.WARNING, "Attention!!!!", "Ouuuups", "vous avez oubiez de selectionner le Script (°o°) !!!"); } } else if (session.getExePaused() == 1) { session.setExePaused(0); executebtn.setImage(new Image("/Resources/pause.png", false)); connectstate.setStyle("-fx-Fill : #2ffc69"); titre.setText("En execution"); executefile.continueScript(); } else { executebtn.setImage(new Image("/Resources/fa-play.png", false)); connectstate.setStyle("-fx-Fill : #F28400"); titre.setText("En attante"); session.setExePaused(1); } } else { MyAlert(AlertType.WARNING, "Attention!!!!", "Ouuuups", "vous avez oubiez de selectionner la DB (°o°) !!!"); } } public void stopScript(int indecator) throws IOException, SQLException { if (session.getIdFile() != null) { Optional<ButtonType> result = null; if (indecator != 1) { result = MyAlert(AlertType.CONFIRMATION, "Confirmation!!!!", "Voulez vous arrêtter l'execution ?", null); } if (indecator == 1 || result.get() == ButtonType.OK) { ////stopping movingGears movingGears.setVisible(false); onTopPane.setVisible(false); //// loadInMainPane(mainController.getViewPane(), "home"); session.setExePaused(2); mainController.setSelectedFile(null); mainController.setError(null); mainController.setLog(null); executebtn.setImage(new Image("/Resources/fa-play.png", false)); executebtn.setVisible(true); connectstate.setStyle("-fx-Fill : #ff0400"); titre.setText("Bienvenue"); executebtn.setVisible(true); // mainController.getViewPane().getChildren().clear(); session.setScanner(null); session.setIdFile(null); session.setCnx(null); session.setLine(0L); if (mainController.getDirectory().getName().equals("Cache")) { mainController.setDirectory(null); mainController.getTreeView().setRoot(null); } // btnChooser.setVisible(false); stopBtn.setVisible(false); // dbChooser.setVisible(false); executebtn.setVisible(false); loadInMainPane(mainpane, "Historique"); } } } @FXML public void stopScriptFxml() throws IOException, SQLException { stopScript(0); } public Optional<ButtonType> MyAlert(AlertType aType, String title, String header, String message) { Alert alert = new Alert(aType); alert.setTitle(title); alert.setHeaderText(header); alert.setContentText(message); return alert.showAndWait(); } @FXML public void showImageChanger() throws IOException, SQLException { imageChanger.setVisible(true); imageChangerIcon.setVisible(true); } @FXML public void hideImageChanger() throws IOException, SQLException { imageChanger.setVisible(false); imageChangerIcon.setVisible(false); } // @FXML // public void changeImage(MouseEvent e) throws IOException, SQLException { // FileChooser chooser = new FileChooser(); // FileChooser.ExtensionFilter imageFilter = new FileChooser.ExtensionFilter("Fichier Image", "*.jpg", "*.png", // "*.jpge"); // chooser.setTitle("choisir votre Image."); // chooser.getExtensionFilters().add(imageFilter); // File ff = chooser.showOpenDialog(mainpane.getScene().getWindow()); // // if (ff != null) { // User uti = new User(userDao.getUserById(session.getIdUser())); // uti.setImageUrl(ff.getCanonicalPath()); // userDao.save(uti); // // try { // profilePic.setFill(new ImagePattern(new Image(ff.toURI().toString(), false))); // } catch (Exception ex) { // // // System.out.println(ex.getMessage() + " \n ||erreur d'image"); // } // // } // // } public String getCachePath() { String myDocuments = null; try { Process p = Runtime.getRuntime().exec( "reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v personal"); p.waitFor(); InputStream in = p.getInputStream(); byte[] b = new byte[in.available()]; in.read(b); in.close(); myDocuments = new String(b); myDocuments = myDocuments.split("\\s\\s+")[4]; } catch (Throwable t) { t.printStackTrace(); } return myDocuments; } } ``` ServerListController.java ```package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.dao.ServerDAO; import com.sopraMdv.anotherProject.entities.Server; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.control.Alert.AlertType; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; @Controller public class ServerListController { @FXML private ImageView serverimg; @FXML private Label nomenv; @FXML private Label label1; @FXML private Label label2; @FXML private Label label3; @FXML private Label label4; @FXML private Label label5; @FXML private Label label6; @FXML private Label label7; @FXML private Label label8; @FXML private Label label9; @FXML private Label label10; private Server serv; private WelcomeController welcomecontroller; private ServerDAO serverdao; public ServerDAO getServerdao() { return serverdao; } @Autowired public void setServerdao(ServerDAO serverdao) { this.serverdao = serverdao; } private Session session; public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } @FXML private void initialize() throws IOException { serverimg.setImage(new Image("/Resources/server.png", false)); // serv = serverdao.getServerByEnvid(session.getIdEnv()); FillLabels(); } public void FillLabels() { System.out.println(serv); if (serv != null) { label1.setText(serv.getNomServer()); label2.setText(serv.getHote()); label3.setText(serv.getPlatformOS()); label7.setText(serv.getUserNameAmp()); label8.setText(serv.getPathAmp()); label9.setText(serv.getUserNameGener()); label10.setText(serv.getPathGener()); } } @FXML public void editserver(MouseEvent event) throws IOException { welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "Server_modifier"); } @FXML public void deleteserver(MouseEvent event) throws IOException { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Attention!!!!"); alert.setHeaderText("Voulez vous supprimer ce serveur?"); alert.setContentText("L'historique et les bases de données liées vont êtres supprimées!!!!"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK){ serverdao.deleteById(serv.getId()); } else { // ... user chose CANCEL or closed the dialog } } @FXML public void connectserver(MouseEvent event) throws IOException { welcomecontroller.setDbShow(true); //welcomecontroller.FireAnEvent(welcomecontroller.getDblabel()); } } ``` FileHistoryDAO.java ```package com.sopraMdv.anotherProject.dao; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.sopraMdv.anotherProject.entities.DataBase; import com.sopraMdv.anotherProject.entities.FileHistory; @Repository public interface FileHistoryDAO extends CrudRepository<FileHistory, Long> { @Query("SELECT F FROM FileHistory F WHERE F.kit.id = :id") public List<FileHistory> getAllFiles(@Param("id")Long long1); @Query("SELECT F FROM FileHistory F WHERE F.id = :id") public FileHistory getFileById(@Param("id")Long long1); } ``` migration.sql ```--creation de migratinprocess create table MIGRATIONPROCESS ( DATEEXEC TIMESTAMP not null, SCRIPTNAME varchar2(64) null, LINENUMBER varchar2(20) null, KITNAME varchar2(200) null ); --insert into migrationprocess INSERT INTO MIGRATIONPROCESS (DATEEXEC) VALUES ( sysdate ); --creation de migrationprocesslog create table MIGRATIONPROCESSLOG ( starttime timestamp null, stoptime timestamp null, SCRIPTNAME varchar2(100) null, STEPNAME varchar2(100) null, SQLERRCODE varchar2(10) null, SQLERRMESS varchar2(400) null, REQUETE varchar2(255) ); ``` SplitFileController.java ```package com.sopraMdv.anotherProject.Controller; import java.sql.Connection; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Scanner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.sopraMdv.anotherProject.dao.FileHistoryDAO; import com.sopraMdv.anotherProject.entities.FileHistory; @Controller public class SplitFileController { private DataBaseConnexion dbConnexion; private Session session; private int counter; private HistoriqueController historiqueController; public HistoriqueController getHistoriqueController() { return historiqueController; } @Autowired public void setHistoriqueController(HistoriqueController historiqueController) { this.historiqueController = historiqueController; } public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } public DataBaseConnexion getDbConnexion() { return dbConnexion; } @Autowired public void setDbConnexion(DataBaseConnexion dbConnexion) { this.dbConnexion = dbConnexion; } private FileHistoryDAO fileDao; public FileHistoryDAO getFileDao() { return fileDao; } @Autowired public void setFileDao(FileHistoryDAO fileDao) { this.fileDao = fileDao; } private WelcomeController welcomecontroller; @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } public void ExtractQuery(Scanner sc, Connection cnx) { String s1 = "", s2 = ""; List<String> listMulti = new ArrayList<String>(FillListMulti()); /* * FileReader file; FileOutputStream file2 = null; try { file = new FileReader( * "D:\\Profiles\\saqaoui\\Documents\\testScript\\mig_V09.1.312_ora.sql"); file2 * = new * FileOutputStream("D:\\Profiles\\saqaoui\\Documents\\testScript\\out.txt"); sc * = new Scanner(file); } catch (FileNotFoundException e1) { // TODO * Auto-generated catch block e1.printStackTrace(); * * } */ try { int querytype = 0; // 0 : single line query -- 1 : multi-line query while (sc.hasNext()) { if (session.getExePaused() == 1) { // is paused ? break; } s1 = sc.nextLine(); // a++; session.setLine(session.getLine() + 1); /* * s1 = eliminateComments(s1, sc); String ll = session.getLine() + " ||"; * file2.write(ll.getBytes()); file2.write(s1.getBytes()); * file2.write("\n".getBytes()); */ s1 = eliminateComments(s1, sc); s2 = ""; if (!sc.hasNext()) { s2 += "\n" + s1; } while (sc.hasNext()) { if (!s1.equals("")) { s2 += "\n" + s1 + " "; } if (s1.contains(";")) break; s1 = sc.nextLine(); session.setLine(session.getLine() + 1); if (!sc.hasNext()) { s2 += "\n" + s1; } } // System.out.println(session.getLine() + "--------;---------" // + s2.trim().replaceAll("\n", "").replaceAll(" +", " ") + // "----------;-------"); if (querytype == 0) { session.setPreLine(session.getLine()); session.setScanner(sc); if (s2.replaceAll(" ", "").endsWith(";")) { s2 = s2.replaceAll(" +$", "").replaceAll(";$", ""); } if (s2.replaceAll("\n", "").isEmpty()) { break; } else dbConnexion.executeQuery(s2.trim(), cnx); } } // -------end of file FileHistory fichier = new FileHistory(fileDao.getFileById(session.getIdFile())); /// mise à jour de la table File (currentLine) fichier.setCurrentline(session.getLine()); /// mise à jour de la table File (dateFin) DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); Date date = new Date(); String dateFin = dateFormat.format(date); fichier.setDateFin(dateFin); //////////////////// enregistrement fileDao.save(fichier); ///////////////////// fin mise à jour historiqueController.executeKit(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // public void ExtractQuery(Scanner sc, Connection cnx) { // // String s1 = "", s2 = ""; // // List<String> listMulti = new ArrayList<String>(FillListMulti()); // // /* // * FileReader file; FileOutputStream file2 = null; try { file = new FileReader( // * "D:\\Profiles\\saqaoui\\Documents\\testScript\\mig_V09.1.312_ora.sql"); file2 // * = new // * FileOutputStream("D:\\Profiles\\saqaoui\\Documents\\testScript\\out.txt"); sc // * = new Scanner(file); } catch (FileNotFoundException e1) { // TODO // * Auto-generated catch block e1.printStackTrace(); // * // * } // */ // // try { // // int querytype = 0; // 0 : single line query -- 1 : multi-line query // // while (sc.hasNext()) { // // if (session.getExePaused() == 1) { // is paused ? // break; // } // // s1 = sc.nextLine(); // // // a++; // session.setLine(session.getLine() + 1); // // /* // * s1 = eliminateComments(s1, sc); String ll = session.getLine() + " ||"; // * file2.write(ll.getBytes()); file2.write(s1.getBytes()); // * file2.write("\n".getBytes()); // */ // // s1 = eliminateComments(s1, sc); // querytype = IsMultiLine(s1, listMulti); // if (querytype == 1) { // s2 = MultiLine(s1, sc).trim().replaceAll("\n+", "\n"); // // System.out.println(session.getLine() + " ---------1multiLine--------" // // + s2.replaceAll("\n", "").replaceAll(" +", " ") + // // "---------1multiLine--------"); // /* // * String ll = session.getLine() + " ||"; file2.write(ll.getBytes()); // * file2.write("-----m---------".getBytes()); file2.write(s2.getBytes()); // * file2.write("\n".getBytes()); // */ // session.setPreLine(session.getLine()); // session.setScanner(sc); // // dbConnexion.executeQuery(s2, cnx); // // } else { // s2 = ""; // if (!sc.hasNext()) { // s2 += "\n" + s1; // } // while (sc.hasNext()) { // s1 = eliminateComments(s1, sc); // querytype = IsMultiLine(s2 + s1, listMulti); // if (querytype == 1) { // s2 += MultiLine(s1, sc).trim(); // // System.out.println(session.getLine() + " ---------2multiLine--------" // // + s2.replaceAll("\n", "").replaceAll(" +", " ") + // // "---------2multiLine--------"); // // session.setPreLine(session.getLine()); // session.setScanner(sc); // // dbConnexion.executeQuery(s2, cnx); // // break; // } // if (!s1.equals("")) { // s2 += "\n" + s1 + " "; // } // // if (s1.contains(";")) // break; // // s1 = sc.nextLine(); // session.setLine(session.getLine() + 1); // // if (!sc.hasNext()) { // s2 += "\n" + s1; // } // // } // // System.out.println(session.getLine() + "--------;---------" // // + s2.trim().replaceAll("\n", "").replaceAll(" +", " ") + // // "----------;-------"); // if (querytype == 0) { // session.setPreLine(session.getLine()); // session.setScanner(sc); // if (s2.replaceAll(" ", "").endsWith(";")) { // s2 = s2.replaceAll(" +$", "").replaceAll(";$", ""); // } // if (s2.replaceAll("\n", "").isEmpty()) { // break; // } else // dbConnexion.executeQuery(s2.trim(), cnx); // } // // } // } // // -------end of file // FileHistory fichier = new FileHistory(fileDao.getFileById(session.getIdFile())); // /// mise à jour de la table File (currentLine) // fichier.setCurrentline(session.getLine()); // /// mise à jour de la table File (dateFin) // DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); // Date date = new Date(); // String dateFin = dateFormat.format(date); // fichier.setDateFin(dateFin); // //////////////////// enregistrement // fileDao.save(fichier); // ///////////////////// fin mise à jour // historiqueController.executeKit(); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } public List<String> FillListMulti() { List<String> list = new ArrayList<String>(); list.add("function"); list.add("trigger"); // list.add("sequence"); list.add("procedure"); list.add("package"); return list; } public int IsMultiLine(String s1, List<String> list) { for (String str : list) { if (s1.replaceAll(" +", " ").toLowerCase().contains("create " + str)) return 1; if (s1.replaceAll(" +", " ").toLowerCase().contains("create or replace " + str)) return 1; if (s1.replaceAll(" ", "").toLowerCase().startsWith("declare")) return 1; if (s1.replaceAll(" ", "").toLowerCase().startsWith("begin")) return 1; } return 0; } public String MultiLine(String s1, Scanner sc) { int stop = 0; counter = 0; String s2 = ""; if (s1.toLowerCase().contains("package")) stop = -1; while (sc.hasNext()) { s1 = eliminateComments(s1, sc); if (!s1.equals("")) { s2 += "\n" + s1 + " "; } // System.out.println(counter + " || " + s1); //////////////////// if (s1.toLowerCase().contains("begin")) counter++; if (s1.replaceAll(" ", "").toLowerCase().contains("end;")) { counter--; // System.out.println(counter+"--before ending--"+s1); if (counter <= stop) { break; } s1 = sc.nextLine(); // System.out.println(counter+"---"+s1); session.setLine(session.getLine() + 1); continue; } if (s1.toLowerCase().replaceAll(" +", " ").contains(" end ") || s1.toLowerCase().replaceAll(" +", " ").startsWith("end ")) { if (s1.replaceAll(" ", "").toLowerCase().contains("endif") || s1.replaceAll(" ", "").toLowerCase().contains("endloop") || s1.replaceAll(" ", "").toLowerCase().contains("endcase") || s1.replaceAll(" ", "").toLowerCase().contains("endquery")) { } else if (s1.replaceAll(" +", " ").toLowerCase().startsWith("end ") || s1.replaceAll(" +", " ").toLowerCase().contains(" end ")) { counter--; if (counter <= stop) { // System.out.println(counter+"--exiting--"+s1); break; } } } s1 = sc.nextLine(); session.setLine(session.getLine() + 1); if (!sc.hasNext()) { s2 += "\n" + s1; } } return s2; } public String eliminateComments(String s1, Scanner sc) { String s3 = ""; // s1 = s1.replaceAll("\t", " "); if ((s1.isEmpty() || (counter == 0 && (s1.toLowerCase().startsWith("end ") || s1.toLowerCase().startsWith(" *end ")))) && sc.hasNext()) { // if line is emty or has second end after a multiline query(somtimes the query // has // "end NAME-PROCEDUR" and a second "end;"). s1 = sc.nextLine(); session.setLine(session.getLine() + 1); } if (s1.replaceAll(" ", "").equals("/")) { // if line has only the character '/' . if (sc.hasNextLine()) { s1 = sc.nextLine(); session.setLine(session.getLine() + 1); } else s1 = ""; } else if (s1.contains("/*") && !s1.contains("*/")) { // if comment starts and doesn't end in the same line. s3 = s1.replaceAll("/\\*.*", " "); while (sc.hasNext()) { if (s1.contains("*/")) {// if comment ends. s1 = s1.replaceAll("/\\*.*?\\*/", " "); s3 += s1.replaceAll(".*?\\*/", " "); break; } else { s1 = sc.nextLine(); session.setLine(session.getLine() + 1); } } s1 = s3; } else if (s1.contains("/*") && s1.contains("*/")) {// if line has entire comment(/**/) . s1 = s1.replaceAll("/\\*.*?\\*/", " "); } if (s1.contains("--")) {// if line has comment(--). // System.out.println("found one line"); String[] str = s1.split("--"); if (str.length > 1) { if (s1.contains("'")) { // if -- inside a single quotes like ( val = '--ERROR--' ) String[] str1 = s1.split("'"); String str2 = ""; boolean var = true; // is inside single quotes for (int i = 0; i < s1.length(); i++) { if (s1.charAt(i) == '\'') { var = !var; } if (var == true && i < s1.length() - 1 && s1.charAt(i) == '-' && s1.charAt(i + 1) == '-') { s1 = s1.substring(0, i); break; } } } else { s1 = str[0]; } } else { s1 = ""; } } // if (s1.contains("--")) {// if line has comment(--). // String[] str = s1.split("--"); // if (str.length > 1) { // s1 = str[0]; // } else // s1 = ""; // } if (s1.replaceAll(" +", " ").equals(" ")) {// if line has only spaces(empty). s1 = ""; } return s1; } }``` 2018_07_10_11_14_28_mig_V11.1.4_ora.sql ```-- ------------ -- DIMmon_BDK170831-01_01_STR_ora.sql -- ------------ -- ======================================================================== -- Modification de bkiso8583in -- ======================================================================== ALTER TABLE bkiso8583in MODIFY ( fi003 CHAR(64), fi039 CHAR(64) ); -- ======================================================================== -- Modification de bkiso8583out -- ======================================================================== ALTER TABLE bkiso8583out MODIFY ( fi003 CHAR(64), fi039 CHAR(64) ); -- ------------ -- EVOmcn_EUROPE-17-E013_01_STR_ora.sql -- ------------ --ANTIDOTE --DROP TABLE bkdosmcn_001; --DROP TABLE bkdosmcn_audit_001; CREATE TABLE bkdosmcn_001( modu CHAR(3) ,age CHAR(5) ,typ CHAR(3) ,ndos CHAR(11) ,nbjgra NUMBER(2,0) ); CREATE UNIQUE INDEX PK_BKDOSMCN_001 on bkdosmcn_001(modu,age,typ,ndos); ALTER TABLE bkdosmcn_001 ADD CONSTRAINT PK_BKDOSMCN_001 PRIMARY KEY (modu,age,typ,ndos); CREATE TABLE bkdosmcn_audit_001( numaudit NUMBER(10,0) ,modu CHAR(3) ,age CHAR(5) ,typ CHAR(3) ,ndos CHAR(11) ,nbjgra NUMBER(2,0) ); CREATE UNIQUE INDEX PK_BKDOSMCN_AUDIT_001 on bkdosmcn_audit_001(numaudit,modu,age,typ,ndos); ALTER TABLE bkdosmcn_audit_001 ADD CONSTRAINT PK_BKDOSMCN_AUDIT_001 PRIMARY KEY (numaudit,modu,age,typ,ndos) ; -- ------------ -- DEF_9374_01_MAJ_ora.sql -- ------------ --UPDATE bkitfrejcat SET lib7="ON", typcsp7="624129", typcsp6="624130" -- WHERE itf="SEPA" AND version="1" AND cat="SDD"; UPDATE bkitfrejcat SET lib7='624129', typcsp7='ON', lib6='624130', typcsp6='ON' WHERE itf='SEPA' AND version='1' AND cat='SDD'; UPDATE bkitfrej SET csp7=csp6 WHERE itf='SEPA' AND version='1' and cat='SDD'; -- ------------ -- EVOmcn_BGFIEUROPE-17-E006_01_STR_ora.sql -- ------------ -- DOSSIERS DE MOBILISATIONS SUR CREANCES NEES (MCNE) bkdosmcn_001 + bkdosmcn_audit_001 ------------------------------------------------------------- --Antidote -- ALTER TABLE bkdosmcn_001 DROP (cclit); -- ALTER TABLE bkdosmcn_audit_001 DROP (cclit); ------------------------------------------------------------- -- bkdosmcn_001 = ajout d'un champ ALTER TABLE bkdosmcn_001 ADD ( cclit CHAR(15) ); -- bkdosmcn_audit_001 = ajout d'un champ ALTER TABLE bkdosmcn_audit_001 ADD ( cclit CHAR(15) ); -- ------------ -- DEF_9942_01_STR_ora.sql -- ------------ declare v_sql LONG; begin v_sql:='DROP TRIGGER BKCONDVAL_WDD'; execute immediate v_sql; EXCEPTION WHEN OTHERS THEN IF SQLCODE = -4080 THEN NULL; ELSE RAISE; END IF; END; / declare v_sql LONG; begin v_sql:='DROP TABLE BKCONDVAL_WATCHDOG'; execute immediate v_sql; EXCEPTION WHEN OTHERS THEN IF SQLCODE = -942 THEN NULL; ELSE RAISE; END IF; END; / -- ------------ -- DIMmon_SGBS171025-01_01_MAJ_ora.sql -- ------------ -- Ajout de champs dans motrxtpost pour audit et décalage des mises à jour dans un traitement -- annexe parallélisé --ALTER TABLE motrxtpost DROP ( --, traite_age_eve --, trace_id --, mcc --, rappro1 --, rappro2 --, rappro3 --, traite_age_cnp --, maj_bkeve_cnp_tmp --, maj_bkeve_cnp_matching --, age_cnp --, ope_cnp --, eve_cnp --, mon1_cnp --, traite_age_prdcli --, maj_bkstopcli --, age_prdcli --, per --, cli --, ope_stopcli --, annee --, mois --, traite_age_serv --, maj_mcpdvforf --, age_serv --, id_pdv --, id_serv --, version --, id_ccom --, traite_age_pdv --, maj_mctpe --, age_pdv --, id_term --, traite_age_carte --, maj_mocarte_data --, age_carte --, refcar --) ; ALTER TABLE motrxtpost ADD ( traite_age_eve CHAR(1) , trace_id CHAR(36) , mcc CHAR(4) , rappro1 CHAR(200) , rappro2 CHAR(200) , rappro3 CHAR(200) , traite_age_cnp CHAR(1) , maj_bkeve_cnp_tmp NUMBER(5) , maj_bkeve_cnp_matching NUMBER(5) , age_cnp CHAR(5) , ope_cnp CHAR(3) , eve_cnp CHAR(6) , mon1_cnp NUMBER(19,4) , traite_age_prdcli CHAR(1) , maj_bkstopcli NUMBER(5) , age_prdcli CHAR(5) , per CHAR(1) , cli CHAR(15) , ope_stopcli CHAR(3) , annee NUMBER(5) , mois NUMBER(5) , traite_age_serv CHAR(1) , maj_mcpdvforf NUMBER(5) , age_serv CHAR(5) , id_pdv CHAR(10) , id_serv CHAR(10) , version NUMBER(5) , id_ccom CHAR(10) , traite_age_pdv CHAR(1) , maj_mctpe NUMBER(5) , age_pdv CHAR(5) , id_term CHAR(10) , traite_age_carte CHAR(1) , maj_mocarte_data NUMBER(5) , age_carte CHAR(5) , refcar NUMBER(10,0) ) ; -- ------------ -- DIM_MON_SGBS171107-04_01_STR_ora.sql -- ------------ ALTER TABLE motranf DROP CONSTRAINT fk_motranf$refcar; -- ------------ -- DEF_8074_01_MAJ_ora.sql -- ------------ -- Script de correction du defect 8074 pour corriger le script mig_kyc_nouv_DIMAD_cli_ora.sql DELETE from abdomad where refdo = '379' or refdo ='380'; INSERT INTO abdomad(refdo,origine,typcli,reffct,valparefct,numaff,utilscen,nomlab,dou,dmo,uti) VALUES ('379','2','T',NULL,' ','379','N',NULL,TO_CHAR(SYSDATE,'DD/MM/YYYY'),NULL,'DELT'); INSERT INTO abdomad(refdo,origine,typcli,reffct,valparefct,numaff,utilscen,nomlab,dou,dmo,uti) VALUES ('380','2','T',NULL,' ','380','N',NULL,TO_CHAR(SYSDATE,'DD/MM/YYYY'),NULL,'DELT'); -- ------------ -- DIM_TMAIBFS171031-04_01_STR_ora.sql -- ------------ --Antidote --ALTER TABLE bkrecapfra DROP CONSTRAINT CK_BKRECAPFRA$orig; --ALTER TABLE bkrecapfra ADD CONSTRAINT CK_BKRECAPFRA$orig CHECK (orig IN ('Q' /* Traitement quotidien */, 'R' /* reprise de l'historique */)); ALTER TABLE bkrecapfra DROP CONSTRAINT CK_BKRECAPFRA$orig; ALTER TABLE bkrecapfra ADD CONSTRAINT CK_BKRECAPFRA$orig CHECK (orig IN ('Q' /* Traitement quotidien */, 'R' /* reprise de l'historique */, 'M' /* traitement manuel */)); -- ------------ -- DIMtreso_SGTOS171206-01_01_STR_ora.sql -- ------------ /* -- Script ORACLE -- Modification des contraintes ck_tft_fxope_mod_hist_10, ck_tft_fxope_mod_hist_13 et ck_tft_fxope_mod_hist_37 sur la table TFT_FXOPE_MOD_HIST -- ANTIDOTE : ALTER TABLE TFT_FXOPE_MOD_HIST DROP CONSTRAINT CK_FXOPE_MOD$OPERATION_SIDE; ALTER TABLE TFT_FXOPE_MOD_HIST ADD CONSTRAINT ck_tft_fxope_mod_hist_10 CHECK (operation_side IN ('A', 'V')); ALTER TABLE TFT_FXOPE_MOD_HIST DROP CONSTRAINT CK_FXOPE_MOD$FORWARD_SPOT_CODE; ALTER TABLE TFT_FXOPE_MOD_HIST ADD CONSTRAINT ck_tft_fxope_mod_hist_13 CHECK (forward_spot_code IN ('C', 'T')); ALTER TABLE TFT_FXOPE_MOD_HIST DROP CONSTRAINT CK_FXOPE_MOD$TRANS_SUB_TYPE; ALTER TABLE TFT_FXOPE_MOD_HIST ADD CONSTRAINT ck_tft_fxope_mod_hist_37 CHECK (transaction_sub_type IN ('TERME' ,'COMPTANT')); */ --/* ALTER TABLE TFT_FXOPE_MOD_HIST DROP CONSTRAINT ck_tft_fxope_mod_hist_10; ALTER TABLE TFT_FXOPE_MOD_HIST ADD CONSTRAINT CK_FXOPE_MOD$OPERATION_SIDE CHECK (operation_side IN (' ', 'A', 'V')); ALTER TABLE TFT_FXOPE_MOD_HIST DROP CONSTRAINT ck_tft_fxope_mod_hist_13; ALTER TABLE TFT_FXOPE_MOD_HIST ADD CONSTRAINT CK_FXOPE_MOD$FORWARD_SPOT_CODE CHECK (forward_spot_code IN (' ', 'C', 'T')); ALTER TABLE TFT_FXOPE_MOD_HIST DROP CONSTRAINT ck_tft_fxope_mod_hist_37; ALTER TABLE TFT_FXOPE_MOD_HIST ADD CONSTRAINT CK_FXOPE_MOD$TRANS_SUB_TYPE CHECK (transaction_sub_type IN (' ', 'TERME' ,'COMPTANT')); --*/ -- ------------ -- DIM_SGA170405-01_01_MAJ_ora.sql -- ------------ -- V101-ARR-001 : en montee de version, migration, obligation d'initialiser le -- poids des conditions d'arretes car a partir de cette version le calcul du -- poids est obligtaoirement different (ajout du niveau dans la valeur du poids). CREATE OR REPLACE FUNCTION V101_ARR_01_calcul_poids(p_niveau IN NUMBER,p_age IN CHAR,p_dev IN CHAR,p_cprod IN CHAR,p_cpack IN CHAR,p_site IN VARCHAR) RETURN NUMBER IS f_poids NUMBER(7,0); BEGIN f_poids := p_niveau * 10000; IF p_dev = '*' THEN f_poids := f_poids + 1000; END IF; IF p_cprod = '*' THEN f_poids := f_poids + 100; END IF; IF p_cpack = '*' THEN f_poids := f_poids + 10; END IF; IF p_cpack = ' ' THEN f_poids := f_poids + 20; END IF; IF p_age = p_site THEN f_poids := f_poids + 1; END IF; RETURN f_poids; END; / UPDATE bkacodeb SET poids = V101_ARR_01_calcul_poids(bkacodeb.niveau,bkacodeb.age,bkacodeb.dev,bkacodeb.cprod,bkacodeb.cpack,(SELECT age FROM bknom WHERE ctab = '098' AND cacc = 'BANQUE')) WHERE 1=1; UPDATE bkacocre SET poids = V101_ARR_01_calcul_poids(bkacocre.niveau,bkacocre.age,bkacocre.dev,bkacocre.cprod,bkacocre.cpack,(SELECT age FROM bknom WHERE ctab = '098' AND cacc = 'BANQUE')) WHERE 1=1; UPDATE bkacoprl SET poids = V101_ARR_01_calcul_poids(bkacoprl.niveau,bkacoprl.age,bkacoprl.dev,bkacoprl.cprod,bkacoprl.cpack,(SELECT age FROM bknom WHERE ctab = '098' AND cacc = 'BANQUE')) WHERE 1=1; UPDATE bkacofra SET poids = V101_ARR_01_calcul_poids(bkacofra.niveau,bkacofra.age,bkacofra.dev,bkacofra.cprod,bkacofra.cpack,(SELECT age FROM bknom WHERE ctab = '098' AND cacc = 'BANQUE')) WHERE 1=1; UPDATE bkacocmo SET poids = V101_ARR_01_calcul_poids(bkacocmo.niveau,bkacocmo.age,bkacocmo.dev,bkacocmo.cprod,bkacocmo.cpack,(SELECT age FROM bknom WHERE ctab = '098' AND cacc = 'BANQUE')) WHERE 1=1; UPDATE bkacocde SET poids = V101_ARR_01_calcul_poids(bkacocde.niveau,bkacocde.age,bkacocde.dev,bkacocde.cprod,bkacocde.cpack,(SELECT age FROM bknom WHERE ctab = '098' AND cacc = 'BANQUE')) WHERE 1=1; UPDATE bkacoteg SET poids = V101_ARR_01_calcul_poids(bkacoteg.niveau,bkacoteg.age,bkacoteg.dev,bkacoteg.cprod,bkacoteg.cpack,(SELECT age FROM bknom WHERE ctab = '098' AND cacc = 'BANQUE')) WHERE 1=1; DROP FUNCTION V101_ARR_01_calcul_poids; -- ------------ -- DEF_10072_01_MAJ_ora.sql -- ------------ UPDATE bketebac SET formatext = '0' WHERE formatext IS NULL or formatext =' '; -- ------------ -- DIM_mdp_TMAIBFS171211-02_01_MAJ_ora.sql -- ------------ DELETE FROM bkmoperror_code; DELETE FROM bkmoperror_cat; INSERT INTO bkmoperror_cat VALUES('PAIN','0','TOUT'); INSERT INTO bkmoperror_cat VALUES('TYPE','001','Parametrage'); INSERT INTO bkmoperror_cat VALUES('TYPE','002','XSD'); INSERT INTO bkmoperror_cat VALUES('TYPE','003','Identification'); INSERT INTO bkmoperror_cat VALUES('TYPE','004','MD5'); INSERT INTO bkmoperror_cat VALUES('TYPE','005','ISO'); INSERT INTO bkmoperror_cat VALUES('TYPE','006','Canal'); INSERT INTO bkmoperror_cat VALUES('TYPE','007','Flux'); INSERT INTO bkmoperror_cat VALUES('TYPE','008','Compte'); INSERT INTO bkmoperror_cat VALUES('TYPE','009','Transaction'); INSERT INTO bkmoperror_cat VALUES('PROG','01','gumoprec'); INSERT INTO bkmoperror_cat VALUES('TYPE','010','Traitement transfert'); INSERT INTO bkmoperror_cat VALUES('TYPE','011','Traitement prélèvement'); INSERT INTO bkmoperror_cat VALUES('TYPE','013','Requêtes'); INSERT INTO bkmoperror_cat VALUES('FONC','014','fct_tm_mop_genere_vir'); INSERT INTO bkmoperror_cat VALUES('FONC','015','fct_tm_mop_genere_prlaut'); INSERT INTO bkmoperror_cat VALUES('FONC','016','fct_tm_mop_genere_prlabq'); INSERT INTO bkmoperror_cat VALUES('FONC','017','fct_trf_mop_genere'); INSERT INTO bkmoperror_cat VALUES('TYPE','018','TOUT'); INSERT INTO bkmoperror_cat VALUES('TYPE','019','Emission de PSR'); INSERT INTO bkmoperror_cat VALUES('PROG','02','gumoptrt'); INSERT INTO bkmoperror_cat VALUES('TYPE','020','LOT'); INSERT INTO bkmoperror_cat VALUES('TYPE','021','routage'); INSERT INTO bkmoperror_cat VALUES('FONC','022','fct_tm_mop_sepa'); INSERT INTO bkmoperror_cat VALUES('FONC','023','CBSNOTINIT'); INSERT INTO bkmoperror_cat VALUES('FONC','024','CBSNOTPSR'); INSERT INTO bkmoperror_cat VALUES('FONC','025','CBMAJSTNOT'); INSERT INTO bkmoperror_cat VALUES('FONC','026','GUMOPREP'); INSERT INTO bkmoperror_cat VALUES('FONC','027','FCT_TM_MOP'); INSERT INTO bkmoperror_cat VALUES('FONC','028','FCT_TM_CLIENT'); INSERT INTO bkmoperror_cat VALUES('FONC','029','FCT_TM_MOP_TRT'); INSERT INTO bkmoperror_cat VALUES('PROG','03','gumoprep'); INSERT INTO bkmoperror_cat VALUES('FONC','030','FCT_TM_ABO'); INSERT INTO bkmoperror_cat VALUES('FONC','031','FCT_TM_STSNOT'); INSERT INTO bkmoperror_cat VALUES('FONC','032','FCT_TM_PSR'); INSERT INTO bkmoperror_cat VALUES('TYPE','033','GUMOPTRT'); INSERT INTO bkmoperror_cat VALUES('FONC','034','CRE_PRLAUT'); INSERT INTO bkmoperror_cat VALUES('FONC','035','CRE_PRLABQ'); INSERT INTO bkmoperror_cat VALUES('TYPE','036','CBSNOTCAMT'); INSERT INTO bkmoperror_cat VALUES('TYPE','037','???'); INSERT INTO bkmoperror_cat VALUES('TYPE','038','CBSNOTDCAM'); INSERT INTO bkmoperror_cat VALUES('FONC','039','GUMOPREC'); INSERT INTO bkmoperror_cat VALUES('PROG','04','gumopmtrf'); INSERT INTO bkmoperror_cat VALUES('FONC','040','FCT_TM_SDD'); INSERT INTO bkmoperror_cat VALUES('FONC','041','GUSEPAREC'); INSERT INTO bkmoperror_cat VALUES('FONC','042','FCT_TM_GEN_VIRSCT'); INSERT INTO bkmoperror_cat VALUES('FONC','043','GUGENSEPA'); INSERT INTO bkmoperror_cat VALUES('FONC','044','GUPRESEPA'); INSERT INTO bkmoperror_cat VALUES('FONC','045','gusepaeve'); INSERT INTO bkmoperror_cat VALUES('TYPE','046','FCT_TM_MOP_MAJ'); INSERT INTO bkmoperror_cat VALUES('TYPE','047','GUMOPLREP'); INSERT INTO bkmoperror_cat VALUES('FONC','048','CBCRSEQOPE'); INSERT INTO bkmoperror_cat VALUES('TYPE','049','gu_bl_cmp_dao'); INSERT INTO bkmoperror_cat VALUES('PROG','05','gumopmdd'); INSERT INTO bkmoperror_cat VALUES('FONC','050','gu_bl_cmp_spec_maurice'); INSERT INTO bkmoperror_cat VALUES('FONC','051','gucmppre'); INSERT INTO bkmoperror_cat VALUES('FONC','052','gu_bl_cmp'); INSERT INTO bkmoperror_cat VALUES('FONC','053','gucmpenv'); INSERT INTO bkmoperror_cat VALUES('FONC','054','GUCMPREC'); INSERT INTO bkmoperror_cat VALUES('FONC','055','GU_BL_CMPREC_SPEC_MAURIC'); INSERT INTO bkmoperror_cat VALUES('FONC','056','gu_bl_cmpenv_spec_mauric'); INSERT INTO bkmoperror_cat VALUES('TYPE','057','GU_BL_CMPMONI_PPREP'); INSERT INTO bkmoperror_cat VALUES('FONC','058','GU_BL_CMPMONI_PREC'); INSERT INTO bkmoperror_cat VALUES('FONC','059','GU_BL_CMPMONI_PSUIVI'); INSERT INTO bkmoperror_cat VALUES('TYPE','060','GU_BL_CMPMONI_PERR'); INSERT INTO bkmoperror_cat VALUES('FONC','061','GU_BL_CMPMONI_PCONS'); INSERT INTO bkmoperror_cat VALUES('FONC','062','fc_bl_tm_ctrlvisu'); INSERT INTO bkmoperror_cat VALUES('FONC','063','fc_bl_signature'); INSERT INTO bkmoperror_cat VALUES('FONC','064','cbdmsigdes'); INSERT INTO bkmoperror_cat VALUES('FONC','065','GU_BL_CMPMONI_PENV'); INSERT INTO bkmoperror_cat VALUES('FONC','066','gucmpcvisu'); INSERT INTO bkmoperror_cat VALUES('FONC','067','FCT_BKEVE'); INSERT INTO bkmoperror_cat VALUES('FONC','068','FCT_GESEVE'); INSERT INTO bkmoperror_cat VALUES('FONC','069','API_GU_CMP'); INSERT INTO bkmoperror_cat VALUES('FONC','070','API_CMP_SCREEN'); INSERT INTO bkmoperror_cat VALUES('FONC','071','GU_BL_CMPMONI_PANN'); INSERT INTO bkmoperror_cat VALUES('FONC','072','GU_BL_CMPMONI_PSAIREJ'); INSERT INTO bkmoperror_cat VALUES('FONC','073','gu_bl_ctrl_visu'); INSERT INTO bkmoperror_cat VALUES('FONC','074','gu_ctrl_visu'); INSERT INTO bkmoperror_cat VALUES('FONC','075','GU_BL_CHQ_CTRL'); INSERT INTO bkmoperror_cat VALUES('FONC','076','GUCMPEVE'); INSERT INTO bkmoperror_cat VALUES('FONC','077','API_GU_GENCHQ'); INSERT INTO bkmoperror_cat VALUES('TYPE','078','GU_BL_CMPMONI_PGESREJ'); INSERT INTO bkmoperror_cat VALUES('FONC','079','GU_BL_CMPMONI_PCOR'); INSERT INTO bkmoperror_cat VALUES('FONC','080','fc_bl_postmsg'); INSERT INTO bkmoperror_cat VALUES('FONC','081','GUCMPHISTO'); INSERT INTO bkmoperror_cat VALUES('FONC','082','API_GU_MOP'); INSERT INTO bkmoperror_cat VALUES('FONC','083','FC_BL_SEQ'); INSERT INTO bkmoperror_cat VALUES('FONC','084','fct_ope'); INSERT INTO bkmoperror_cat VALUES('FONC','085','CRE_AGEVIR'); INSERT INTO bkmoperror_cat VALUES('FONC','086','CBMAJ060'); INSERT INTO bkmoperror_cat VALUES('FONC','087','guconvxslt'); INSERT INTO bkmoperror_cat VALUES('FONC','088','API_CONVERSION_FIC'); INSERT INTO bkmoperror_cat VALUES('FONC','089','FC_BL_ITFCODE'); INSERT INTO bkmoperror_cat VALUES('FONC','090','API_GU_GENVIR'); INSERT INTO bkmoperror_cat VALUES('FONC','091','GUCMPFORC'); INSERT INTO bkmoperror_cat VALUES('TYPE','092','GUMOPMVAL'); INSERT INTO bkmoperror_cat VALUES('TYPE','093','GU_BL_CMPENV_SPEC_VIET'); INSERT INTO bkmoperror_cat VALUES('FONC','094','fc_bl_ampxml'); INSERT INTO bkmoperror_cat VALUES('TYPE','095','GU_BL_CMPREC_SPEC_VIET'); INSERT INTO bkmoperror_cat VALUES('FONC','096','API_CMP_REG'); INSERT INTO bkmoperror_cat VALUES('FONC','097','GU_CMP_REG'); INSERT INTO bkmoperror_cat VALUES('FONC','098','api_chqfac'); INSERT INTO bkmoperror_cat VALUES('FONC','099','API_GU_CHQFAC'); INSERT INTO bkmoperror_cat VALUES('PAIN','1','PAIN.001'); INSERT INTO bkmoperror_cat VALUES('FONC','100','API_GU_CHQ'); INSERT INTO bkmoperror_cat VALUES('TYPE','101','GU_BL_CMPMONI_PEXC'); INSERT INTO bkmoperror_cat VALUES('TYPE','102','gurdccvisu'); INSERT INTO bkmoperror_cat VALUES('FONC','103','API_GU_GENRES'); INSERT INTO bkmoperror_cat VALUES('FONC','104','fct_tm_mop_ebc'); INSERT INTO bkmoperror_cat VALUES('PAIN','2','PAIN.002'); INSERT INTO bkmoperror_cat VALUES('PAIN','8','PAIN.008'); --Langue : 001 INSERT INTO bkmoperror_code VALUES('T','001','0001','001','Le type de base est incorrect. Il doit être soit PROD, soit PRE-PROD soit HOMOLOGATION.','Corriger la configuration du paramètre "TYPE_BASE" en nomenclature "098"'); INSERT INTO bkmoperror_code VALUES('T','001','0002','001','Paramètre mal renseigne.',' Le paramètre cité dans le message d''erreur n''est pas correctement renseigné. Corriger la configuration du paramètre via la gestion des paramètres "cbitfparam"'); INSERT INTO bkmoperror_code VALUES('T','001','0003','001','Paramètre manquant.','Le paramètre cité n''est pas défini, cela signifie que le référentiel des paramètres n''est probablement pas à jour. Contacter la maintenance Delta-Bank'); INSERT INTO bkmoperror_code VALUES('T','001','0004','001','Problème lors de l''initialisation des interfaces.',''); INSERT INTO bkmoperror_code VALUES('T','001','0005','001','Problème lors du traitement des interfaces.',''); INSERT INTO bkmoperror_code VALUES('T','001','0006','001','problème lors de la fermeture de l''interface.',''); INSERT INTO bkmoperror_code VALUES('T','001','0007','001','Code erreur absent du référentiel!','Le référentiel des codes erreur (tables bkmoperror_cat et bkmoperror_code) n''est pas à jour. Contacter la maintenance Delta-Bank'); INSERT INTO bkmoperror_code VALUES('T','001','0008','001','Dossier temporaire de travail non trouve.',''); INSERT INTO bkmoperror_code VALUES('T','001','0009','001','Compta par défaut des transfert non renseignée',''); INSERT INTO bkmoperror_code VALUES('T','001','0010','001','Compta par défaut des prélèvements non renseignée',''); INSERT INTO bkmoperror_code VALUES('T','001','0011','001','Code BIC incorrect dans la fiche banque du site central','Corriger la fiche banque du site central'); INSERT INTO bkmoperror_code VALUES('T','001','0012','001','Longueur de l''IBAN locale mal parametree',''); INSERT INTO bkmoperror_code VALUES('T','002','0001','001','Validation XSD échouée.','Vérifier le flux, vérifier la XSD.'); INSERT INTO bkmoperror_code VALUES('T','003','0001','001','Flux de simulation intégré sur une base de production.',''); INSERT INTO bkmoperror_code VALUES('T','003','0002','001','Flux de production intégré sur une base de test (pré-prod ou homologation).',''); INSERT INTO bkmoperror_code VALUES('T','003','0003','001','Flux de pré-production intégré sur une base d''homologation.',''); INSERT INTO bkmoperror_code VALUES('T','003','0004','001','Flux d''homologation intégré sur une base de pré-production.',''); INSERT INTO bkmoperror_code VALUES('T','003','0005','001','Flux de pré-production intégré sur une base de production.',''); INSERT INTO bkmoperror_code VALUES('T','003','0006','001','Flux d''homologation intégré sur une base de production.',''); INSERT INTO bkmoperror_code VALUES('T','003','0007','001','Réception d''un flux généré par le simulateur Delta-Bank du SIOP, sur un environnement n''étant pas un environnement de test','Vérifier l''environnement et le routage des flux, si le routage des flux est correct et l''environnement est bien un environnement de test alors définir la variable d''environnement TEST_CONNECTOR à 1'); INSERT INTO bkmoperror_code VALUES('T','003','0008','001','Identification du flux non indiquée.',''); INSERT INTO bkmoperror_code VALUES('T','004','0001','001','Impossible de calculer le MD5 du flux.',''); INSERT INTO bkmoperror_code VALUES('T','004','0002','001','MD5 duplique : potentielle duplication de flux',''); INSERT INTO bkmoperror_code VALUES('T','004','0003','001','Transaction potentiellement dupliquée.',''); INSERT INTO bkmoperror_code VALUES('T','004','0004','001','Toutes les transactions du lot sont en anomalies.',''); INSERT INTO bkmoperror_code VALUES('T','005','0001','001','La règle ISO ''PaymentTypeInformationRule'' n''est pas respectée.','Le type de paiement doit être indiqué soit globalement, soit unitairement pour chaque crédit, ou être absent.'); INSERT INTO bkmoperror_code VALUES('T','005','0002','001','La règle ISO ''ChequeInstructionRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0003','001','La règle ISO ''ChargesAccountRule'' n''est pas respectée.','Le compte de frais est manquant ou l''intitution de frais doit être absente.'); INSERT INTO bkmoperror_code VALUES('T','005','0004','001','La règle ISO ''ChargesAccountAgentRule'' n''est pas respectée.','L''agence de l''institution de frais ne correspond pas a une agence de l''institution du donneur d''ordre.'); INSERT INTO bkmoperror_code VALUES('T','005','0005','001','La règle ISO ''ChargeBearerRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0006','001','La règle ISO ''UltimateDebtorRule'' n''est pas respectée.','Le débiteur ultime doit être indiqué soit globalement, soit unitairement pour chaque crédit, ou être absent.'); INSERT INTO bkmoperror_code VALUES('T','005','0007','001','La règle ISO ''ChequeAndCreditorAccountRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0008','001','La règle ISO ''ChequeDeliveryAndCreditorAgentRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0009','001','La règle ISO ''ChequeDeliveryAndNoCreditorAgentRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0010','001','La règle ISO ''NonChequePaymentMethodRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0011','001','La règle ISO ''ChequeNoDeliveryAndNoCreditorAgentRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0012','001','La règle ISO ''IntermediaryAgent2Rule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0013','001','La règle ISO ''IntermediaryAgent3Rule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0014','001','La règle ISO ''InstructionForCreditorAgentRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0015','001','La règle ISO ''IntermediaryAgent1AccountRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0016','001','La règle ISO ''IntermediaryAgent2AccountRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0017','001','La règle ISO ''IntermediaryAgent3AccountRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0018','001','La règle ISO ''ChequeMaturityDateRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0019','001','La règle ISO ''CreditorSchemeIdentificationRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0020','001','La règle ISO ''UltimateCreditorRule'' n''est pas respectée.','Le creancier ultime doit être indiqué soit globalement, soit unitairement pour chaque crédit, ou être absent.'); INSERT INTO bkmoperror_code VALUES('T','005','0021','001','La règle ISO ''AmendmentIndicatorTrueRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0022','001','La règle ISO ''AmendmentIndicatorFalseRule'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0023','001','La règle ISO ''PaymentInformationStatus'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0024','001','La règle ISO ''AccountServicerReference'' n''est pas respectée.',''); INSERT INTO bkmoperror_code VALUES('T','005','0025','001','La règle ISO ''UltimateDebtor'' n''est pas respectée',''); INSERT INTO bkmoperror_code VALUES('T','005','0026','001','La règle ISO ''Debtor'' n''est pas respectée',''); INSERT INTO bkmoperror_code VALUES('T','005','0027','001','La règle ISO ''DebtorAccount'' n''est pas respectée',''); INSERT INTO bkmoperror_code VALUES('T','005','0028','001','La règle ISO ''DebtorAgent'' n''est pas respectée',''); INSERT INTO bkmoperror_code VALUES('T','005','0029','001','La règle ISO ''DebtorAgentAccount'' n''est pas respectée',''); INSERT INTO bkmoperror_code VALUES('T','005','0030','001','La règle ISO ''CreditorAgent'' n''est pas respectée',''); INSERT INTO bkmoperror_code VALUES('T','005','0031','001','La règle ISO ''CreditorAgentAccount'' n''est pas respectée',''); INSERT INTO bkmoperror_code VALUES('T','005','0032','001','La règle ISO ''Creditor'' n''est pas respectée',''); INSERT INTO bkmoperror_code VALUES('T','005','0033','001','La règle ISO ''CreditorAccount'' n''est pas respectée',''); INSERT INTO bkmoperror_code VALUES('T','005','0034','001','La règle ISO ''UltimateCreditor'' n''est pas respectée',''); INSERT INTO bkmoperror_code VALUES('T','006','0001','001','Le canal n''est pas actif',''); INSERT INTO bkmoperror_code VALUES('T','006','0002','001','La canal indique dans le flux ne correspond pas au canal en cours.',''); INSERT INTO bkmoperror_code VALUES('T','006','0003','001','Le canal ne reçoit pas de transfert.',''); INSERT INTO bkmoperror_code VALUES('T','006','0004','001','Le canal ne reçoit pas de prélèvement.',''); INSERT INTO bkmoperror_code VALUES('T','006','0005','001','Plusieurs canaux pour cette interface.',''); INSERT INTO bkmoperror_code VALUES('T','007','0001','001','Impossible de lire le flux.',''); INSERT INTO bkmoperror_code VALUES('T','007','0002','001','Flux non valide.',''); INSERT INTO bkmoperror_code VALUES('T','007','0003','001','Il y a des données privatives en double dans le flux.',''); INSERT INTO bkmoperror_code VALUES('T','008','0001','001','Compte du donneur d''ordre inexistant',''); INSERT INTO bkmoperror_code VALUES('T','008','0002','001','Compte de frais du donneur d''ordre inexistant.',''); INSERT INTO bkmoperror_code VALUES('T','008','0003','001','Compte de la transaction inexistant.',''); INSERT INTO bkmoperror_code VALUES('T','008','0004','001','Compte de frais n''appartient pas au donneur d''ordre.',''); INSERT INTO bkmoperror_code VALUES('T','008','0005','001','Compte de frais n''appartient pas à la banque.',''); INSERT INTO bkmoperror_code VALUES('T','008','0006','001','Au moins un comptes (niveau ordre ou transaction) doit être dans la devise de transaction.',''); INSERT INTO bkmoperror_code VALUES('T','008','0007','001','Format du compte du donneur d''ordre incorrect.',''); INSERT INTO bkmoperror_code VALUES('T','008','0008','001','Format du compte de frais incorrect.',''); INSERT INTO bkmoperror_code VALUES('T','008','0009','001','Format du compte de la transaction incorrect.',''); INSERT INTO bkmoperror_code VALUES('T','008','0010','001','Le code BIC de la transaction est inconnu',''); INSERT INTO bkmoperror_code VALUES('T','008','0011','001','Compte non en faveur de la TGR',''); INSERT INTO bkmoperror_code VALUES('T','008','0012','001','Virement permanent international non autorisé',''); INSERT INTO bkmoperror_code VALUES('T','008','0013','001','Date de début du virement permanent incorrecte',''); INSERT INTO bkmoperror_code VALUES('T','009','0001','001','Montant de la transaction à 0.',''); INSERT INTO bkmoperror_code VALUES('T','009','0002','001','Montant de la transaction négatif.',''); INSERT INTO bkmoperror_code VALUES('T','009','0003','001','Code virement SICA incorrect',''); INSERT INTO bkmoperror_code VALUES('T','009','0004','001','Code economique en doublon dans la transaction',''); INSERT INTO bkmoperror_code VALUES('T','009','0005','001','Au moins une des références locales est erronée',''); INSERT INTO bkmoperror_code VALUES('T','009','0006','001','Reference avis imposition incorrecte',''); INSERT INTO bkmoperror_code VALUES('T','010','0001','001','Erreur numéro évènement',''); INSERT INTO bkmoperror_code VALUES('T','010','0002','001','Erreur lecture banque bénéficiaire',''); INSERT INTO bkmoperror_code VALUES('T','010','0003','001','Incident insert bkeve',''); INSERT INTO bkmoperror_code VALUES('T','010','0004','001','Devise transaction inconnue',''); INSERT INTO bkmoperror_code VALUES('T','010','0005','001','Le type de virement ne gère pas de traitement multiple',''); INSERT INTO bkmoperror_code VALUES('T','010','0006','001','Le type de virement ne gère pas de traitement unitaire',''); INSERT INTO bkmoperror_code VALUES('T','010','0007','001','Type de virement inconnu',''); INSERT INTO bkmoperror_code VALUES('T','010','0008','001','Compte donneur d''ordre inexistant',''); INSERT INTO bkmoperror_code VALUES('T','010','0009','001','Compte de frais inexistant',''); INSERT INTO bkmoperror_code VALUES('T','010','0010','001','Compte bénéficiaire inexistant',''); INSERT INTO bkmoperror_code VALUES('T','010','0011','001','Code économique non renseigné pour la transaction','correction via le moniteur transfert'); INSERT INTO bkmoperror_code VALUES('T','010','0012','001','Code économique incorrect','correction via le moniteur transfert'); INSERT INTO bkmoperror_code VALUES('T','011','0001','001','Devise transaction inconnue',''); INSERT INTO bkmoperror_code VALUES('T','012','0001','001','Erreur lors de la sélection du message',''); INSERT INTO bkmoperror_code VALUES('T','012','0002','001','Erreur lors de la sélection du lot',''); INSERT INTO bkmoperror_code VALUES('T','012','0003','001','Erreur lors de la sélection de la transaction',''); INSERT INTO bkmoperror_code VALUES('T','012','0004','001','Erreur lors de la sélection de env pour le canal',''); INSERT INTO bkmoperror_code VALUES('T','012','0005','001','Incident insert bkmoplot_rep.eta',''); INSERT INTO bkmoperror_code VALUES('T','012','0006','001','Incident insert bkmoptx_rep.eta',''); INSERT INTO bkmoperror_code VALUES('T','012','0007','001','Incident update bkmopmsg_rep',''); INSERT INTO bkmoperror_code VALUES('T','012','0008','001','Incident update bkmoplot_rep',''); INSERT INTO bkmoperror_code VALUES('T','012','0009','001','Incident update bkmoptx_rep',''); INSERT INTO bkmoperror_code VALUES('T','013','0001','001','Erreur d''intégration du message.',''); INSERT INTO bkmoperror_code VALUES('T','013','0002','001','Erreur d''intégration du lot.',''); INSERT INTO bkmoperror_code VALUES('T','013','0003','001','Erreur d''intégration de la transaction.',''); INSERT INTO bkmoperror_code VALUES('T','013','0004','001','Erreur lors de l''alimentation de bkmopmsg_md5',''); INSERT INTO bkmoperror_code VALUES('T','013','0005','001','Erreur lors de l''alimentation de bkmoptx_md5',''); INSERT INTO bkmoperror_code VALUES('T','013','0006','001','Impossible d''insérer une réponse.',''); INSERT INTO bkmoperror_code VALUES('T','013','0007','001','Valeur non autorisée dans la donnée privative PtcInf_Sgt','Le flux est rejeté.'); INSERT INTO bkmoperror_code VALUES('T','013','0008','001','EU n''est pas une valeur autorisée pour l''élément FlwInd','Le flux est rejeté.'); INSERT INTO bkmoperror_code VALUES('T','013','0009','001','Erreur lors de la sélection du statut du message',''); INSERT INTO bkmoperror_code VALUES('T','013','0010','001','HU n''est pas une valeur autorisée pour l''élément FlwInd','Le flux est rejeté.'); INSERT INTO bkmoperror_code VALUES('T','013','0011','001','Erreur lors de la selection du code economique',''); INSERT INTO bkmoperror_code VALUES('T','013','0012','001','Erreur lors de la selection du code de la donnée privative du PSR',''); INSERT INTO bkmoperror_code VALUES('T','013','0013','001','Erreur lors de la selection du type d''opération.',''); INSERT INTO bkmoperror_code VALUES('T','013','0014','001','Erreur lors de l''insertion de bkmoplot_rev',''); INSERT INTO bkmoperror_code VALUES('T','013','0015','001','Erreur de comptage des motifs structurés ou non structurés',''); INSERT INTO bkmoperror_code VALUES('F','014','0001','001','Devise du virement inconnue.',''); INSERT INTO bkmoperror_code VALUES('F','014','0002','001','Le type de virement n''est pas autorisé.',''); INSERT INTO bkmoperror_code VALUES('F','014','0003','001','Type de virement inconnu.',''); INSERT INTO bkmoperror_code VALUES('F','014','0004','001','Agence de traitement inconnue.',''); INSERT INTO bkmoperror_code VALUES('F','014','0005','001','Erreur lors du chargement des chapitres comptable.',''); INSERT INTO bkmoperror_code VALUES('F','014','0006','001','Compte du donneur d''ordre inexistant.',''); INSERT INTO bkmoperror_code VALUES('F','014','0007','001','Compte de frais inexistant.',''); INSERT INTO bkmoperror_code VALUES('F','014','0008','001','Compte du bénéficiaire inexistant.',''); INSERT INTO bkmoperror_code VALUES('F','014','0009','001','Chapitre comptable du compte du donneur d''ordre non autorise pour l''opération.',''); INSERT INTO bkmoperror_code VALUES('F','014','0010','001','Chapitre comptable du compte du bénéficiaire non autorise pour l''opération.',''); INSERT INTO bkmoperror_code VALUES('F','014','0011','001','Numéro d''évènement non trouve.',''); INSERT INTO bkmoperror_code VALUES('F','014','0012','001','Banque du bénéficiaires inconnue.',''); INSERT INTO bkmoperror_code VALUES('F','014','0013','001','Incident lors de l''insertion.',''); INSERT INTO bkmoperror_code VALUES('F','014','0014','001','Le type de virement est mal paramétré.',''); INSERT INTO bkmoperror_code VALUES('F','014','0015','001','Montant au débit à zéro interdit',''); INSERT INTO bkmoperror_code VALUES('F','014','0016','001','Impossible de modifier le VIRMUL.',''); INSERT INTO bkmoperror_code VALUES('F','014','0017','001','Impossible de modifier les évènements liés au VIRMUL.',''); INSERT INTO bkmoperror_code VALUES('F','014','0018','001','Erreur lors du calcul du numéro d''événement du VIRMUL',''); INSERT INTO bkmoperror_code VALUES('F','014','0019','001','Erreur lors du calcul du numéro de l''événement',''); INSERT INTO bkmoperror_code VALUES('F','014','0020','001','Erreur lors du calcul des frais au beneficiaire',''); INSERT INTO bkmoperror_code VALUES('F','014','0021','001','Erreur lors du calcul du numéro de dossier du VRTPER',''); INSERT INTO bkmoperror_code VALUES('F','014','0022','001','Erreur lors du calcul du numéro d''événement du VRTPER',''); INSERT INTO bkmoperror_code VALUES('F','014','0023','001','Erreur lors du calcul du numéro d''événement du VRMPER',''); INSERT INTO bkmoperror_code VALUES('F','014','0024','001','Erreur lors du calcul du numéro d''événement du VRTANU',''); INSERT INTO bkmoperror_code VALUES('F','014','0025','001','Code agence non renseigné en nomenclature 310',''); INSERT INTO bkmoperror_code VALUES('F','014','0026','001','Mauvais paramétrage pour la nomenclature 310',''); INSERT INTO bkmoperror_code VALUES('F','014','0027','001','Erreur lors de la mise à jour de l''évènement',''); INSERT INTO bkmoperror_code VALUES('F','014','0028','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0029','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0030','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0031','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0032','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0033','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0034','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0035','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0036','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0037','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0038','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0039','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0040','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0041','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0042','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0043','001','..',''); INSERT INTO bkmoperror_code VALUES('F','014','0044','001','Le montant des frais au bénéficiaire sont plus élevés que le montant du virement',''); INSERT INTO bkmoperror_code VALUES('F','014','0045','001','Le montant des frais au bénéficiaire sont plus élevés que le montant du virement',''); INSERT INTO bkmoperror_code VALUES('F','015','0001','001','Devise du virement inconnue.',''); INSERT INTO bkmoperror_code VALUES('F','015','0002','001','Compte du donneur d''ordre inexistant.',''); INSERT INTO bkmoperror_code VALUES('F','015','0003','001','Compte de frais inexistant.',''); INSERT INTO bkmoperror_code VALUES('F','015','0004','001','Compte du bénéficiaire inexistant.',''); INSERT INTO bkmoperror_code VALUES('F','015','0005','001','Chapitre comptable du compte du donneur d''ordre non autorise pour l''opération.',''); INSERT INTO bkmoperror_code VALUES('F','015','0006','001','Chapitre comptable du compte du bénéficiaire non autorise pour l''opération.',''); INSERT INTO bkmoperror_code VALUES('F','015','0007','001','Numéro d''évènement non trouve.',''); INSERT INTO bkmoperror_code VALUES('F','015','0008','001','Incident lors de l''insertion.',''); INSERT INTO bkmoperror_code VALUES('F','015','0009','001','Le type de virement est mal paramétré.',''); INSERT INTO bkmoperror_code VALUES('T','015','0010','001','Paramètre mal renseigné.',''); INSERT INTO bkmoperror_code VALUES('T','015','0011','001','Organisme inconnu.',''); INSERT INTO bkmoperror_code VALUES('T','015','0012','001','Le compte du créancier ne correspond pas au compte de l''organisme renseigné.',''); INSERT INTO bkmoperror_code VALUES('T','015','0013','001','Pas de code operation associe au PRLAUT (Entre parenthèses sont indiqués les champs vides pouvant être à l''origine de l''erreur)',''); INSERT INTO bkmoperror_code VALUES('T','015','0014','001','PRLAUT non autorisé',''); INSERT INTO bkmoperror_code VALUES('F','015','0015','001','Montant au débit à zéro interdit',''); INSERT INTO bkmoperror_code VALUES('F','015','0016','001','Montant au crédit à zéro interdit',''); INSERT INTO bkmoperror_code VALUES('F','016','0001','001','Devise du virement inconnue.',''); INSERT INTO bkmoperror_code VALUES('F','016','0002','001','Compte du donneur d''ordre inexistant.',''); INSERT INTO bkmoperror_code VALUES('F','016','0003','001','Compte de frais inexistant.',''); INSERT INTO bkmoperror_code VALUES('F','016','0004','001','Chapitre comptable du compte du donneur d''ordre non autorise pour l''opération.',''); INSERT INTO bkmoperror_code VALUES('F','016','0005','001','Numéro d''évènement non trouve.',''); INSERT INTO bkmoperror_code VALUES('F','016','0006','001','Incident lors de l''insertion.',''); INSERT INTO bkmoperror_code VALUES('F','016','0007','001','Incident sélection de banque.',''); INSERT INTO bkmoperror_code VALUES('F','016','0008','001','Le type de virement est mal paramétré.',''); INSERT INTO bkmoperror_code VALUES('T','016','0009','001','Paramètre mal renseigné.',''); INSERT INTO bkmoperror_code VALUES('T','016','0010','001','Organisme inconnu.',''); INSERT INTO bkmoperror_code VALUES('T','016','0011','001','Le compte du créancier ne correspond pas au compte de l''organisme renseigné.',''); INSERT INTO bkmoperror_code VALUES('T','016','0012','001','Pas de code operation associe au PRLABQ (Entre parenthèses sont indiqués les champs vides pouvant être à l''origine de l''erreur)',''); INSERT INTO bkmoperror_code VALUES('T','016','0013','001','PRLABQ non autorisé',''); INSERT INTO bkmoperror_code VALUES('F','016','0014','001','Montant au crédit à zéro interdit',''); INSERT INTO bkmoperror_code VALUES('F','017','0001','001','Correspondant incorrect',''); INSERT INTO bkmoperror_code VALUES('F','017','0002','001','Devise du transfert inconnue',''); INSERT INTO bkmoperror_code VALUES('F','017','0003','001','Code opération transfert inexistant',''); INSERT INTO bkmoperror_code VALUES('F','017','0004','001','Devise du compte donneur d''ordre inexistante',''); INSERT INTO bkmoperror_code VALUES('F','017','0005','001','Devise du compte de frais inexistante',''); INSERT INTO bkmoperror_code VALUES('F','017','0006','001','Incident compte de frais',''); INSERT INTO bkmoperror_code VALUES('F','017','0007','001','Paramétrage compte de passage incorrect',''); INSERT INTO bkmoperror_code VALUES('F','017','0008','001','Compte de passage incorrect',''); INSERT INTO bkmoperror_code VALUES('F','017','0009','001','Paramétrage compte de passage frais incorrect',''); INSERT INTO bkmoperror_code VALUES('F','017','0010','001','Compte de passage frais incorrect',''); INSERT INTO bkmoperror_code VALUES('F','017','0011','001','Type de transfert inconnu',''); INSERT INTO bkmoperror_code VALUES('F','017','0012','001','Compte de banque non client incorrect',''); INSERT INTO bkmoperror_code VALUES('F','017','0013','001','Registre inexistant',''); INSERT INTO bkmoperror_code VALUES('F','017','0014','001','Compte de banque transfert multiple non client incorrect',''); INSERT INTO bkmoperror_code VALUES('F','017','0015','001','Nature ORDMIX non Définie',''); INSERT INTO bkmoperror_code VALUES('F','017','0016','001','Code opération ordre mixte inexistant',''); INSERT INTO bkmoperror_code VALUES('F','017','0017','001','Correspondant pas en relation de compte',''); INSERT INTO bkmoperror_code VALUES('F','017','0018','001','BIC et IBAN bénéficiaire incohérent',''); INSERT INTO bkmoperror_code VALUES('F','017','0019','001','Correspondant inconnu',''); INSERT INTO bkmoperror_code VALUES('F','017','0020','001','Informations donneur d''ordre incorrectes',''); INSERT INTO bkmoperror_code VALUES('F','017','0021','001','Problème lors de la génération de transfert multiple',''); INSERT INTO bkmoperror_code VALUES('F','017','0022','001','Problème lors de la génération de l''évenement mixte',''); INSERT INTO bkmoperror_code VALUES('T','018','0001','001','Programme déjà lancé',''); INSERT INTO bkmoperror_code VALUES('T','018','0002','001','Crash du programme de traitement',''); INSERT INTO bkmoperror_code VALUES('T','018','0003','001','Erreurs trouvées lors de la génération du PSR.',''); INSERT INTO bkmoperror_code VALUES('F','019','0001','001','Lot valide, changement de l''état a NC',''); INSERT INTO bkmoperror_code VALUES('F','019','0002','001','Transaction valide, changement de l''état a NC',''); INSERT INTO bkmoperror_code VALUES('F','019','0003','001','La version du flux d''entré est incorrecte',''); INSERT INTO bkmoperror_code VALUES('F','019','0004','001','La version du PSR d''entré est incorrecte',''); INSERT INTO bkmoperror_code VALUES('F','019','0005','001','L''origine du message est incorrect',''); INSERT INTO bkmoperror_code VALUES('T','020','0001','001','La somme totale des transactions ne correspond pas au montant du lot.',''); INSERT INTO bkmoperror_code VALUES('T','020','0002','001','Le nombre de transaction ne correspond pas à celui indiqué au niveau lot.',''); INSERT INTO bkmoperror_code VALUES('T','020','0003','001','Les transactions ne sont pas toutes de la même devise.',''); INSERT INTO bkmoperror_code VALUES('T','020','0004','001','Le compte du créancier ne correspond pas au compte de l''organisme renseigné.',''); INSERT INTO bkmoperror_code VALUES('T','021','0001','001','Cohérence entre le service détermine et le service reçu',''); INSERT INTO bkmoperror_code VALUES('T','021','0002','001','Banque bénéficiaire non reliée à SEPA',''); INSERT INTO bkmoperror_code VALUES('F','022','0001','001','Catégorie inexistante.',''); INSERT INTO bkmoperror_code VALUES('F','022','0002','001','La banque du bénéficiaire doit être au format BIC.',''); INSERT INTO bkmoperror_code VALUES('F','022','0003','001','Le compte du bénéficiaire doit être au format IBAN.',''); INSERT INTO bkmoperror_code VALUES('F','022','0004','001','Incohérence entre le code BIC et l''IBAN du bénéficiaire.',''); INSERT INTO bkmoperror_code VALUES('F','022','0005','001','Incident SQL.',''); INSERT INTO bkmoperror_code VALUES('F','022','0006','001','Le contrôle de cohérence entre le code BIC et l''IBAN n''est pas définit pour le paramétre SEPA.',''); INSERT INTO bkmoperror_code VALUES('F','022','0007','001','Paramétre SEPA non trouvé.',''); INSERT INTO bkmoperror_code VALUES('F','022','0008','001','Le nombre de motif structuré et le nombre de motif non structuré sont différent de 0',''); INSERT INTO bkmoperror_code VALUES('F','022','0009','001','Le nombre de motif non structuré est strictement supérieur à 1',''); INSERT INTO bkmoperror_code VALUES('F','022','0010','001','Le nombre de motif structuré est strictement supérieur à 1',''); INSERT INTO bkmoperror_code VALUES('F','022','0011','001','La longueur des informations sur la transaction est supérieur à 140 caractères',''); INSERT INTO bkmoperror_code VALUES('F','022','0012','001','Les frais peuvent uniquement être partagés ou selon le servie level',''); INSERT INTO bkmoperror_code VALUES('F','022','0013','001','Virement uniquement',''); INSERT INTO bkmoperror_code VALUES('F','023','0001','001','La version du flux d''entrée est incorrecte',''); INSERT INTO bkmoperror_code VALUES('F','023','0002','001','Flux d''entrée inconnu bkmopmsg.typmsg',''); INSERT INTO bkmoperror_code VALUES('F','024','0001','001','Anomalie lors de la lecture du mode debug au niveau de la définition du canal abonnement','Contacter la maintenance'); INSERT INTO bkmoperror_code VALUES('F','024','0002','001','Génération des PSR en cours pour le canal','Relancer le traitement ultérieurement'); INSERT INTO bkmoperror_code VALUES('F','024','0003','001','Anomalie lors de la lecture du canal abonnement','Contacter la maintenance'); INSERT INTO bkmoperror_code VALUES('F','024','0004','001','Anomalie bloquante lors du traitement des PSR','Contacter la maintenance'); INSERT INTO bkmoperror_code VALUES('F','024','0005','001','Anomalie bloquante lors de la génération des flux PSR','Contacter la maintenance'); INSERT INTO bkmoperror_code VALUES('F','024','0006','001','Anomalie de configuration de l''interface ABO : aucune version de PSR/CAMT autorisée','Corriger la configuration'); INSERT INTO bkmoperror_code VALUES('F','024','0007','001','Anomalie bloquante au niveau base de donnée','Contacter la maintenance'); INSERT INTO bkmoperror_code VALUES('F','027','0001','001','Anomalie lors de l''enregistrement sur le module de restitution "ABO" d''un statut niveau LOT','Contacter la hotline'); INSERT INTO bkmoperror_code VALUES('F','027','0002','001','Anomalie lors de l''enregistrement sur le module de restitution "ABO" d''un statut niveau Transaction','Contacter la hotline'); INSERT INTO bkmoperror_code VALUES('F','027','0003','001','Le service n''est pas activé',''); INSERT INTO bkmoperror_code VALUES('F','027','0004','001','Impossible de détérminer le code BIC de la banque',''); INSERT INTO bkmoperror_code VALUES('F','027','0005','001','Absence de type de transfert défini au niveau de la définition du canal (gumopcanal) pour un service','Corriger la définition du canal'); INSERT INTO bkmoperror_code VALUES('F','027','0006','001','Impossible de mettre le statut du lot en annulé',''); INSERT INTO bkmoperror_code VALUES('F','027','0007','001','Données manquantes pour généré le PSR d''annulation niveau lot',''); INSERT INTO bkmoperror_code VALUES('F','027','0008','001','Erreur lors de la génération du PSR d''annulation niveau lot',''); INSERT INTO bkmoperror_code VALUES('F','028','0001','001','Erreur lors de la lecture du client',''); INSERT INTO bkmoperror_code VALUES('F','029','0001','001','Un désaccord n''est pas défini en nomenclature "058"','Créer le désaccord en nomencalture 058'); INSERT INTO bkmoperror_code VALUES('F','029','0002','001','Paramètre LTRF_RFND_OPE mal renseigné','Modifier le paramètre via cbitfparam'); INSERT INTO bkmoperror_code VALUES('F','029','0003','001','Impossible de calculer le numéro d''évènement pour la réservation de fond',''); INSERT INTO bkmoperror_code VALUES('F','029','0004','001','Anomalie lors de la création d''une réservation de fond',''); INSERT INTO bkmoperror_code VALUES('F','029','0005','001','Paramètre TIME_WAIT mal renseigné','Modifier le paramètre via cbitfparam'); INSERT INTO bkmoperror_code VALUES('F','029','0006','001','Anomalie lors de la création des codes de paiement',''); INSERT INTO bkmoperror_code VALUES('F','029','0007','001','Le compte de la transaction n''est pas renseigné','Corriger le compte de la transaction via le moniteur métier'); INSERT INTO bkmoperror_code VALUES('F','029','0008','001','Impossible de déterminer la comptabilisation',''); INSERT INTO bkmoperror_code VALUES('F','029','0009','001','Impossible de retrouver le canal',''); INSERT INTO bkmoperror_code VALUES('F','029','0010','001','Impossible de retrouver le message',''); INSERT INTO bkmoperror_code VALUES('F','029','0011','001','Le code BIC de la transaction est incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0012','001','Toutes les transactions du lot sont en erreur',''); INSERT INTO bkmoperror_code VALUES('F','029','0013','001','Au moins une des transactions du lot est en erreur',''); INSERT INTO bkmoperror_code VALUES('F','029','0014','001','Impossible de déterminer l''opération pour un PRLAUT',''); INSERT INTO bkmoperror_code VALUES('F','029','0015','001','Impossible de déterminer l''opération pour un PRLABQ',''); INSERT INTO bkmoperror_code VALUES('F','029','0016','001','Impossible de déterminer le numéro d''événement pour un PRLAUT',''); INSERT INTO bkmoperror_code VALUES('F','029','0017','001','Impossible de déterminer le numéro d''événement pour un PRLABQ',''); INSERT INTO bkmoperror_code VALUES('F','029','0018','001','Impossible de déterminer le mode d''encaissement','Déterminer un mode d''encaissement par défault via le paramétre DEFAULT_INCOMING_COLLECTION_MODE'); INSERT INTO bkmoperror_code VALUES('F','029','0019','001','Impossible de déterminer l''agence de compensation pour les prélèvements',''); INSERT INTO bkmoperror_code VALUES('F','029','0020','001','Référence(s) locale(s) incorrecte(s) :',''); INSERT INTO bkmoperror_code VALUES('F','029','0021','001','Anomalie lors de la recherche de la transaction d''origine',''); INSERT INTO bkmoperror_code VALUES('F','029','0022','001','Anomalie lors de la recherche de la transaction d''origine',''); INSERT INTO bkmoperror_code VALUES('F','029','0023','001','Anomalie lors de la recherche de la transaction d''origine',''); INSERT INTO bkmoperror_code VALUES('F','029','0024','001','Anomalie lors de la recherche de la transaction d''origine',''); INSERT INTO bkmoperror_code VALUES('F','029','0025','001','Anomalie de parametrage',''); INSERT INTO bkmoperror_code VALUES('F','029','0026','001','Anomalie sur la date de règlement',''); INSERT INTO bkmoperror_code VALUES('F','029','0027','001','Anomalie sur le blocage des enregistrements',''); INSERT INTO bkmoperror_code VALUES('F','029','0028','001','Anomalie sur le blocage des enregistrements',''); INSERT INTO bkmoperror_code VALUES('F','029','0029','001','Anomalie sur la génération de l''évènement d''annulation',''); INSERT INTO bkmoperror_code VALUES('F','029','0030','001','Anomalie sur la génération de l''évènement d''annulation',''); INSERT INTO bkmoperror_code VALUES('F','029','0031','001','Anomalie sur la génération de l''évènement d''annulation',''); INSERT INTO bkmoperror_code VALUES('F','029','0032','001','Anomalie sur la génération de l''évènement de réception du prélèvement',''); INSERT INTO bkmoperror_code VALUES('F','029','0033','001','Anomalie sur la génération de l''évènement de réception du prélèvement',''); INSERT INTO bkmoperror_code VALUES('F','029','0034','001','Montant de l''ordre incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0035','001','Compte noscaisse incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0036','001','Compte autre banque (RIB_FR) incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0037','001','Compte autre banque (RIB_SICA) incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0038','001','Compte NBS incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0039','001','Impossible de trouver le référentiel du pays du compte NBS',''); INSERT INTO bkmoperror_code VALUES('F','029','0040','001','Compte IBAN non valide',''); INSERT INTO bkmoperror_code VALUES('F','029','0041','001','Compte IBAN non cohérent avec le code BIC',''); INSERT INTO bkmoperror_code VALUES('F','029','0042','001','Compte autre banque (RIB_MA) incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0043','001','Etablissement non renseigné',''); INSERT INTO bkmoperror_code VALUES('F','029','0044','001','Etablissement du donneur d''ordre différent de celui de la banque',''); INSERT INTO bkmoperror_code VALUES('F','029','0045','001','Code BIC du donneur d''ordre différent de celui de la banque',''); INSERT INTO bkmoperror_code VALUES('F','029','0046','001','Erreur au niveau du virement TGR',''); INSERT INTO bkmoperror_code VALUES('F','029','0047','001','Erreur lors de l''insertion d''un VIRMUL',''); INSERT INTO bkmoperror_code VALUES('F','029','0048','001','Erreur lors de la mise à jour d''un VIMxxx',''); INSERT INTO bkmoperror_code VALUES('F','029','0049','001','Erreur lors de la mise en desaccord d''une transaction d''un lot en compta cumulée.',''); INSERT INTO bkmoperror_code VALUES('F','029','0050','001','Code peach non renseigné pour le paramètre SEPA2',''); INSERT INTO bkmoperror_code VALUES('F','029','0051','001','Impossible de retrouver le BIC correspondant à l''IBAN de la tranaction',''); INSERT INTO bkmoperror_code VALUES('F','029','0052','001','Erreur survenue lors de la mise à jour du compte',''); INSERT INTO bkmoperror_code VALUES('F','029','0053','001','Nom du bénéficiaire non renseigné',''); INSERT INTO bkmoperror_code VALUES('F','029','0054','001','Motif non renseigné',''); INSERT INTO bkmoperror_code VALUES('F','029','0055','001','Impossible de mettre à jour les VIMxxx du VIRMUL',''); INSERT INTO bkmoperror_code VALUES('F','029','0056','001','Impossible de mettre à jour les soldes indicatifs des comptes',''); INSERT INTO bkmoperror_code VALUES('F','029','0057','001','Impossible de mettre à jour les soldes indicatifs des comptes pour les virements multiple',''); INSERT INTO bkmoperror_code VALUES('F','029','0058','001','Impossible de supprimer les frais d''un AGEVIR pour les virements multiple',''); INSERT INTO bkmoperror_code VALUES('F','029','0059','001','Impossible de supprimer l''AGEVIR pour les virements multiple',''); INSERT INTO bkmoperror_code VALUES('F','029','0060','001','Erreur lors de la recherche du client donneur d''ordre pour le contrôle du chapitre comptable',''); INSERT INTO bkmoperror_code VALUES('F','029','0061','001','Erreur lors de la recherche du profil du client donneur d''ordre pour le contrôle du chapitre comptable',''); INSERT INTO bkmoperror_code VALUES('F','029','0062','001','Transaction dupliquée',''); INSERT INTO bkmoperror_code VALUES('F','029','0063','001','Erreur lors du contrôle de duplicuté d''une transaction',''); INSERT INTO bkmoperror_code VALUES('F','029','0064','001','Impossible de déterminer le format du compte de la transaction.',''); INSERT INTO bkmoperror_code VALUES('F','029','0065','001','Format du compte donneur d''ordre non autorisé',''); INSERT INTO bkmoperror_code VALUES('F','029','0066','001','Format du compte de frais non autorisé',''); INSERT INTO bkmoperror_code VALUES('F','029','0067','001','Le format ''BBAN'' n''est pas autorisé pour le compte donneur d''ordre',''); INSERT INTO bkmoperror_code VALUES('F','029','0068','001','Le format ''BBAN'' n''est pas autorisé pour le compte de frais',''); INSERT INTO bkmoperror_code VALUES('F','029','0069','001','Le compte du donneur d''ordre est incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0070','001','Le compte de frais est incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0071','001','Le compte de frais n''appartient pas au donneur d''ordre.',''); INSERT INTO bkmoperror_code VALUES('F','029','0072','001','Le compte de frais n''appartient pas à l''agence du compte du donneur d''ordre.',''); INSERT INTO bkmoperror_code VALUES('F','029','0073','001','Impossible de mettre à jour le lot',''); INSERT INTO bkmoperror_code VALUES('F','029','0074','001','Impossible de mettre à jour le lot, suite à une erreur detectée sur une transaction',''); INSERT INTO bkmoperror_code VALUES('F','029','0075','001','Impossible de trouver le numéro de dossier pour un PRLABQ',''); INSERT INTO bkmoperror_code VALUES('F','029','0076','001','Impossible de trouver le numéro de dossier pour un PRLAUT',''); INSERT INTO bkmoperror_code VALUES('F','029','0077','001','Aucun organisme n''a été renseigné dans le flux',''); INSERT INTO bkmoperror_code VALUES('F','029','0078','001','Le type de virement ne gére pas la périodicité recue',''); INSERT INTO bkmoperror_code VALUES('F','029','0079','001','Unicitée de la référence de l''ordre incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0080','001','Identifiant créancier invalide',''); INSERT INTO bkmoperror_code VALUES('F','029','0081','001','Type de frais non autorisé',''); INSERT INTO bkmoperror_code VALUES('F','029','0082','001','Format de la reference Amplitude de reservation de fond incorrecte','Hors scope Amplitude, l''ordre est rejeté'); INSERT INTO bkmoperror_code VALUES('F','029','0083','001','Format de la reference Amplitude de reservation de fond incorrecte','Hors scope Amplitude, l''ordre est rejeté'); INSERT INTO bkmoperror_code VALUES('F','029','0084','001','Anomalie lors de la levée d''une reservation de fond (à partir d''une référence externe)','Hors scope Amplitude, l''ordre est rejeté'); INSERT INTO bkmoperror_code VALUES('F','029','0085','001','Anomalie lors de la levée d''une reservation de fond (à partir d''une référence Amplitude)','Hors scope Amplitude, l''ordre est rejeté'); INSERT INTO bkmoperror_code VALUES('F','029','0086','001','Anomalie lors du contrôle d''une reservation de fond (à partir d''une référence Amplitude)','Hors scope Amplitude, l''ordre est rejeté'); INSERT INTO bkmoperror_code VALUES('F','029','0087','001','Anomalie lors du contrôle d''une reservation de fond (à partir d''une référence externe)','Hors scope Amplitude, l''ordre est rejeté'); INSERT INTO bkmoperror_code VALUES('F','029','0088','001','Incohérence des références externes et Amplitude d''une réservation de fond','Hors scope Amplitude, l''ordre est rejeté'); INSERT INTO bkmoperror_code VALUES('F','029','0089','001','Reservation de fond non valide','Hors scope Amplitude, l''ordre est rejeté'); INSERT INTO bkmoperror_code VALUES('F','029','0090','001','Incoherence du numéro de compte entre la reservation de fond et l''ordre reçu par SIOP','Hors scope Amplitude, l''ordre est rejeté'); INSERT INTO bkmoperror_code VALUES('F','029','0091','001','Incohérence de devise : la devise du compte débité est différente de la devise de transaction','Hors scope Amplitude, l''ordre est rejeté'); INSERT INTO bkmoperror_code VALUES('F','029','0092','001','Devise non définie','Hors scope Amplitude, l''ordre est rejeté'); INSERT INTO bkmoperror_code VALUES('F','029','0093','001','anomalie lors de la lecture du profil d''un client','contacter le support'); INSERT INTO bkmoperror_code VALUES('F','029','0094','001','Desaccord PLAF non defini en nomenclature 058','Verifier le paramétrage'); INSERT INTO bkmoperror_code VALUES('F','029','0095','001','Desaccord PMIN non defini en nomenclature 058','Verifier le paramétrage'); INSERT INTO bkmoperror_code VALUES('F','029','0096','001','Type d''opération non autorisée',''); INSERT INTO bkmoperror_code VALUES('F','029','0097','001','Code Profil inexistant','Créer le profil du client'); INSERT INTO bkmoperror_code VALUES('F','029','0098','001','Compte autre banque (RIB_ALG) incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0099','001','Le compte doit être un compte autre banque',''); INSERT INTO bkmoperror_code VALUES('F','029','0100','001','Le format du compte est incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0101','001','Anomalie lors de la recherche du profil client',''); INSERT INTO bkmoperror_code VALUES('F','029','0102','001','Montant du virement suppérieur au plafond PMAVIM',''); INSERT INTO bkmoperror_code VALUES('F','029','0103','001','Le montant du virement fait dépasser la limite MAXLIV pour le compte à créditer',''); INSERT INTO bkmoperror_code VALUES('F','029','0104','001','Une erreur est survenue lors du calcul des frais au donneur d''ordre',''); INSERT INTO bkmoperror_code VALUES('F','029','0105','001','Erreur lors de l''insertion de données privatives pour un virement unitaire',''); INSERT INTO bkmoperror_code VALUES('F','029','0106','001','Erreur lors de l''insertion de données privatives pour un virement cumulé',''); INSERT INTO bkmoperror_code VALUES('F','029','0107','001','Le code BIC de la transaction est inconnu',''); INSERT INTO bkmoperror_code VALUES('F','029','0108','001','Format du compte de la transaction incorrect.',''); INSERT INTO bkmoperror_code VALUES('F','029','0109','001','Compte autre banque (RIB_MG) incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0110','001','Compte de la transaction inexistant.',''); INSERT INTO bkmoperror_code VALUES('F','029','0111','001','Compte de la transaction inexistant.',''); INSERT INTO bkmoperror_code VALUES('F','029','0112','001','Au moins un comptes (niveau ordre ou transaction) doit être dans la devise de transaction.',''); INSERT INTO bkmoperror_code VALUES('F','029','0113','001','Devise incorrecte',''); INSERT INTO bkmoperror_code VALUES('F','029','0114','001','Devise incorrecte',''); INSERT INTO bkmoperror_code VALUES('F','030','0001','001','.',''); INSERT INTO bkmoperror_code VALUES('F','030','0002','001','.',''); INSERT INTO bkmoperror_code VALUES('F','030','0003','001','.',''); INSERT INTO bkmoperror_code VALUES('F','030','0004','001','.',''); INSERT INTO bkmoperror_code VALUES('F','030','0005','001','.',''); INSERT INTO bkmoperror_code VALUES('F','030','0006','001','.',''); INSERT INTO bkmoperror_code VALUES('F','030','0007','001','.',''); INSERT INTO bkmoperror_code VALUES('F','030','0008','001','.',''); INSERT INTO bkmoperror_code VALUES('F','030','0009','001','.',''); INSERT INTO bkmoperror_code VALUES('F','030','0010','001','.',''); INSERT INTO bkmoperror_code VALUES('F','030','0011','001','.',''); INSERT INTO bkmoperror_code VALUES('F','030','0012','001','.',''); INSERT INTO bkmoperror_code VALUES('F','030','0013','001','Erreur PREPARE calcul identifiant "stsnot"','Appeler la hotline'); INSERT INTO bkmoperror_code VALUES('F','032','0001','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0002','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0003','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0004','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0005','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0006','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0007','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0008','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0009','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0010','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0011','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0012','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0013','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0014','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0015','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0016','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0017','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0018','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0019','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0020','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0021','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0022','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0023','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0024','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0025','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0026','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0027','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0028','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0029','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0030','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0031','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0032','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0033','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0034','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0035','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0036','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0037','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0038','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0039','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0040','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0041','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0042','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0043','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0044','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0045','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0046','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0047','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0048','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0049','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0050','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0051','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0052','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0053','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0054','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0055','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0056','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0057','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0058','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0059','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0060','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0061','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0062','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0063','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0064','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0065','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0066','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0067','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0068','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0069','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0070','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0071','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0072','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0073','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0074','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0075','001',',',''); INSERT INTO bkmoperror_code VALUES('F','032','0076','001','Incident lors de la mise a jour de la table bkmoptx_rep',''); INSERT INTO bkmoperror_code VALUES('T','033','0001','001','BIC de l''implantation mal configuré sur la fiche banque du site central','Corriger la configuration de la fiche banque du site central via le cbgesbanq'); INSERT INTO bkmoperror_code VALUES('T','033','0002','001','Virement permanent international non autorisé',''); INSERT INTO bkmoperror_code VALUES('T','033','0003','001','Date de début du virement permanent incorrecte',''); INSERT INTO bkmoperror_code VALUES('F','034','0001','001','La condition DVACAI n''existe pas.',''); INSERT INTO bkmoperror_code VALUES('F','034','0002','001','La condition DVAAGE n''existe pas.',''); INSERT INTO bkmoperror_code VALUES('F','034','0003','001','La condition DINCAI n''existe pas.',''); INSERT INTO bkmoperror_code VALUES('F','034','0004','001','La condition DINAGE n''existe pas.',''); INSERT INTO bkmoperror_code VALUES('F','034','0005','001','La condition DATVAL n''existe pas.',''); INSERT INTO bkmoperror_code VALUES('F','034','0006','001','La condition EXOCOM n''existe pas.',''); INSERT INTO bkmoperror_code VALUES('F','034','0007','001','Compte incorrect',''); INSERT INTO bkmoperror_code VALUES('F','034','0008','001','Insertion dans bkeve echouée',''); INSERT INTO bkmoperror_code VALUES('F','034','0009','001','Selection du compte echouée 1',''); INSERT INTO bkmoperror_code VALUES('F','034','0010','001','Selection du compte echouée 2',''); INSERT INTO bkmoperror_code VALUES('F','034','0011','001','Selection du compte echouée 3',''); INSERT INTO bkmoperror_code VALUES('F','034','0012','001','Selection du compte echouée 4',''); INSERT INTO bkmoperror_code VALUES('F','034','0013','001','Selection du compte echouée 5',''); INSERT INTO bkmoperror_code VALUES('F','034','0014','001','Selection du compte echouée 6',''); INSERT INTO bkmoperror_code VALUES('F','034','0015','001','Selection du compte echouée 7',''); INSERT INTO bkmoperror_code VALUES('F','034','0016','001','Selection du compte echouée 8',''); INSERT INTO bkmoperror_code VALUES('F','034','0017','001','Selection du compte echouée 9',''); INSERT INTO bkmoperror_code VALUES('F','034','0018','001','Selection du compte echouée 10',''); INSERT INTO bkmoperror_code VALUES('F','034','0019','001','Selection du compte echouée 11',''); INSERT INTO bkmoperror_code VALUES('F','034','0020','001','Selection du compte echouée 12',''); INSERT INTO bkmoperror_code VALUES('F','034','0021','001','Selection bkicprl echouée',''); INSERT INTO bkmoperror_code VALUES('F','034','0022','001','Mise a jour bkicprl echouée (MAJ4)',''); INSERT INTO bkmoperror_code VALUES('F','034','0023','001','Mise a jour bkicprld echouée (MAJ4)',''); INSERT INTO bkmoperror_code VALUES('F','034','0024','001','Mise a jour bkicprl echouée 1 (MAJ2)',''); INSERT INTO bkmoperror_code VALUES('F','034','0025','001','Mise a jour bkicprld echouée 1 (MAJ2)',''); INSERT INTO bkmoperror_code VALUES('F','034','0026','001','Mise a jour bkicprl echouée 2 (MAJ2)',''); INSERT INTO bkmoperror_code VALUES('F','034','0027','001','Mise a jour bkicprld echouée 2 (MAJ2)',''); INSERT INTO bkmoperror_code VALUES('F','034','0028','001','Insertion bkicprl echouée (MAJ1)',''); INSERT INTO bkmoperror_code VALUES('F','034','0029','001','Insertion bkicprld echouée (MAJ1)',''); INSERT INTO bkmoperror_code VALUES('F','034','0030','001','Devise inexistante.',''); INSERT INTO bkmoperror_code VALUES('F','034','0031','001','Insertion bkevec échouée',''); INSERT INTO bkmoperror_code VALUES('F','034','0032','001','Mise à jour des soldes échouée (crédit org)',''); INSERT INTO bkmoperror_code VALUES('F','034','0033','001','Mise à jour des soldes échouée (débit client)',''); INSERT INTO bkmoperror_code VALUES('F','034','0034','001','Insertion bkeve échouée (SIOP)',''); INSERT INTO bkmoperror_code VALUES('F','034','0035','001','Insertion bkevec échouée (SIOP)',''); INSERT INTO bkmoperror_code VALUES('F','035','0001','001','La condition DATVAL n''existe pas.',''); INSERT INTO bkmoperror_code VALUES('F','035','0002','001','Selection de la banque 1',''); INSERT INTO bkmoperror_code VALUES('F','035','0003','001','Selection de la banque 2',''); INSERT INTO bkmoperror_code VALUES('F','035','0004','001','Date de valeur nulle',''); INSERT INTO bkmoperror_code VALUES('F','035','0005','001','Compte non trouvé',''); INSERT INTO bkmoperror_code VALUES('F','035','0006','001','Selection du compte',''); INSERT INTO bkmoperror_code VALUES('F','035','0007','001','Devise inexistante',''); INSERT INTO bkmoperror_code VALUES('F','035','0008','001','Insertion bkevec échouée',''); INSERT INTO bkmoperror_code VALUES('F','035','0009','001','Insertion bkevec échouée (SIOP)',''); INSERT INTO bkmoperror_code VALUES('F','035','0010','001','Mise à jour des soldes échouée (crédit org)',''); INSERT INTO bkmoperror_code VALUES('F','035','0011','001','Insertion bkeve échouée',''); INSERT INTO bkmoperror_code VALUES('F','035','0012','001','Insertion bkeve échouée (SIOP)',''); INSERT INTO bkmoperror_code VALUES('T','036','0001','001','???',''); INSERT INTO bkmoperror_code VALUES('T','037','0001','001','Evenement inexistant',''); INSERT INTO bkmoperror_code VALUES('T','037','0002','001','??',''); INSERT INTO bkmoperror_code VALUES('T','037','0003','001','??',''); INSERT INTO bkmoperror_code VALUES('T','037','0004','001','??',''); INSERT INTO bkmoperror_code VALUES('T','037','0005','001','??',''); INSERT INTO bkmoperror_code VALUES('T','037','0006','001','??',''); INSERT INTO bkmoperror_code VALUES('T','037','0007','001','??',''); INSERT INTO bkmoperror_code VALUES('T','037','0008','001','??',''); INSERT INTO bkmoperror_code VALUES('T','037','0009','001','??',''); INSERT INTO bkmoperror_code VALUES('T','037','0010','001','Erreur SQL',''); INSERT INTO bkmoperror_code VALUES('T','037','0011','001','??',''); INSERT INTO bkmoperror_code VALUES('T','037','0012','001','Erreur init flux',''); INSERT INTO bkmoperror_code VALUES('T','037','0013','001','Erreur flux bloc compte',''); INSERT INTO bkmoperror_code VALUES('T','038','0001','001','Le programme est deja en cours de traitement.','Interruption du programme.'); INSERT INTO bkmoperror_code VALUES('T','038','0002','001','Interface ABO inexistante','Interruption du programme.'); INSERT INTO bkmoperror_code VALUES('T','038','0003','001','Interface ABO inactive en version @','Interruption du programme.'); INSERT INTO bkmoperror_code VALUES('T','038','0004','001','Fonction de tm_itfparam_get(...)','Interruption du programme.'); INSERT INTO bkmoperror_code VALUES('T','038','0005','001','Fonction de tm_itfparam_get(...)','Interruption du programme.'); INSERT INTO bkmoperror_code VALUES('T','038','0006','001','Fonction de tm_itfparam_get(...)','Interruption du programme.'); INSERT INTO bkmoperror_code VALUES('T','038','0007','001','Fonction de tm_itfparam_get(...)','Interruption du programme.'); INSERT INTO bkmoperror_code VALUES('T','038','0008','001','Fonction de tm_itfparam_get(...)','Interruption du programme.'); INSERT INTO bkmoperror_code VALUES('T','038','0009','001','Incident @ Table @ Status @','Interruption du programme.'); INSERT INTO bkmoperror_code VALUES('T','038','0010','001','Incident @ Table @ Status @','Interruption du programme.'); INSERT INTO bkmoperror_code VALUES('T','038','0011','001','Fonction de tm_abo_insert_bkstsnot(...)','Poursuite du programme.'); INSERT INTO bkmoperror_code VALUES('T','038','0012','001','Incident @ Table @ Status @','Poursuite du programme.'); INSERT INTO bkmoperror_code VALUES('F','039','0001','001','Erreur au niveau du virement TGR','veuillez corriger via les moniteurs métiers'); INSERT INTO bkmoperror_code VALUES('F','039','0002','001','Erreur lors d''un virement NANTI','Veuillez corriger via les moniteurs métiers'); INSERT INTO bkmoperror_code VALUES('F','039','0003','001','Erreur sur la lecture d''un canal non actif','Contacter la hotline'); INSERT INTO bkmoperror_code VALUES('F','039','0004','001','Erreur ModifyCancelModeRule',''); INSERT INTO bkmoperror_code VALUES('F','039','0005','001','Erreur ChangeReasonInformationRule',''); INSERT INTO bkmoperror_code VALUES('F','039','0006','001','Erreur StandingOrderInformationRule',''); INSERT INTO bkmoperror_code VALUES('F','039','0007','001','Erreur StandingOrderNbCdtRule',''); INSERT INTO bkmoperror_code VALUES('F','039','0008','001','DBMONEY mal ou non positionné','Positionner DBMONEY dans le script de mise en place du profile'); INSERT INTO bkmoperror_code VALUES('F','039','0009','001','Règles ISO Amplitude non respectées',''); INSERT INTO bkmoperror_code VALUES('F','039','0010','001','Probléme d''écriture fichier',''); INSERT INTO bkmoperror_code VALUES('F','039','0011','001','Canal non autorisé',''); INSERT INTO bkmoperror_code VALUES('F','039','0012','001','Valeur non autorisée pour la donnée privative VALIDATION','Rejet du flux'); INSERT INTO bkmoperror_code VALUES('F','039','0013','001','Valeur non autorisée pour la donnée privative COMPLETION','Rejet du flux'); INSERT INTO bkmoperror_code VALUES('F','040','0001','001','Le type du compte débiteur est incorrect',''); INSERT INTO bkmoperror_code VALUES('F','040','0002','001','Type de prélèvement incorrect',''); INSERT INTO bkmoperror_code VALUES('F','040','0003','001','Devise de transaction incorrecte',''); INSERT INTO bkmoperror_code VALUES('F','040','0004','001','Identifiant du créancier non renseigné',''); INSERT INTO bkmoperror_code VALUES('F','040','0005','001','Identifiant du mandat non renseigné',''); INSERT INTO bkmoperror_code VALUES('F','040','0006','001','Etiquette comptable ENCAISSDD0 inexistante',''); INSERT INTO bkmoperror_code VALUES('F','040','0007','001','Paramétre SEPA-SDD- inexistant',''); INSERT INTO bkmoperror_code VALUES('F','040','0008','001','Date de réglement incorrect',''); INSERT INTO bkmoperror_code VALUES('F','040','0009','001','Agence de compensation pour SEPA mal renseignée',''); INSERT INTO bkmoperror_code VALUES('F','040','0010','001','Paramétre SEPA inexistant',''); INSERT INTO bkmoperror_code VALUES('F','040','0011','001','Paramétre SEPA2 inexistant',''); INSERT INTO bkmoperror_code VALUES('F','040','0012','001','Nature de transaction PAISDD inexistant',''); INSERT INTO bkmoperror_code VALUES('F','040','0013','001','Incident lors de la mise a jour de la table des oppositions SDD',''); INSERT INTO bkmoperror_code VALUES('F','040','0014','001','Une opposition existe déjà',''); INSERT INTO bkmoperror_code VALUES('F','040','0015','001','Desaccord présent pour le compte à créditer',''); INSERT INTO bkmoperror_code VALUES('F','040','0016','001','Impossible de récuperer la devise numérique de la transaction',''); INSERT INTO bkmoperror_code VALUES('F','040','0017','001','Impossible d''identifier le client du compte à créditer',''); INSERT INTO bkmoperror_code VALUES('F','040','0018','001','Compte d''encaissement inexistant',''); INSERT INTO bkmoperror_code VALUES('F','040','0019','001','Erreur lors de la génération de l''événement REASDD',''); INSERT INTO bkmoperror_code VALUES('F','040','0020','001','Erreur lors de la génération de l''événement REISDD',''); INSERT INTO bkmoperror_code VALUES('F','040','0021','001','Erreur lors de la génération de l''événement REPSDD',''); INSERT INTO bkmoperror_code VALUES('F','040','0022','001','Impossible de selectionner le mandat',''); INSERT INTO bkmoperror_code VALUES('F','040','0023','001','Incident lors de la mise a jour de la table des mandats',''); INSERT INTO bkmoperror_code VALUES('F','040','0024','001','Incident lors de l''insertion dans la table des mandats',''); INSERT INTO bkmoperror_code VALUES('F','040','0025','001','Incident lors de la selection du mandat',''); INSERT INTO bkmoperror_code VALUES('F','040','0026','001','Incident lors de l''insertion dans la table bksepacreancier',''); INSERT INTO bkmoperror_code VALUES('F','040','0027','001','Incident lors de l''insertion dans la table bksepacreancier',''); INSERT INTO bkmoperror_code VALUES('F','040','0028','001','Probléme lors de la lecture des paramétres',''); INSERT INTO bkmoperror_code VALUES('F','040','0029','001','Probléme lors des contrôles',''); INSERT INTO bkmoperror_code VALUES('F','040','0030','001','Incident lors de la selection du créancier',''); INSERT INTO bkmoperror_code VALUES('F','040','0031','001','Incident lors de l''insertion dans la table bksepasdd',''); INSERT INTO bkmoperror_code VALUES('F','040','0032','001','Incident lors de l''insertion dans la table bksepacplsdd',''); INSERT INTO bkmoperror_code VALUES('F','040','0033','001','Incident lors de l''insertion du prélèvement',''); INSERT INTO bkmoperror_code VALUES('F','041','0001','001','Programme déjà lancé',''); INSERT INTO bkmoperror_code VALUES('F','041','0002','001','Agence de compensation incorrecte',''); INSERT INTO bkmoperror_code VALUES('F','041','0003','001','Paramétre SEPA inexistant',''); INSERT INTO bkmoperror_code VALUES('F','041','0004','001','Paramétre BANQUE inexistant',''); INSERT INTO bkmoperror_code VALUES('F','041','0005','001','Agence du site centrale fermée',''); INSERT INTO bkmoperror_code VALUES('F','041','0006','001','Agence du site centrale inexistante',''); INSERT INTO bkmoperror_code VALUES('F','041','0007','001','Devise EUR inexistante en nomenclature 002',''); INSERT INTO bkmoperror_code VALUES('F','041','0008','001','Repertoire mal configuré',''); INSERT INTO bkmoperror_code VALUES('F','041','0009','001','Paramétre SEPAINCXML non défini dans bkintfic',''); INSERT INTO bkmoperror_code VALUES('F','041','0010','001','Erreur lors de la lecture des répertoires',''); INSERT INTO bkmoperror_code VALUES('F','041','0011','001','Incident de requete',''); INSERT INTO bkmoperror_code VALUES('F','041','0012','001','Erreur lors de la lecture du flux',''); INSERT INTO bkmoperror_code VALUES('F','041','0013','001','Montant de contrôle différent du montant total des transactions (pacs 004)',''); INSERT INTO bkmoperror_code VALUES('F','041','0014','001','Erreur lors de l''éxecution du shell TraiteFichierRecu',''); INSERT INTO bkmoperror_code VALUES('F','041','0015','001','Devise de la balise IntrBkSttlmAmt mal renseignée',''); INSERT INTO bkmoperror_code VALUES('F','041','0016','001','Devise de la balise RtrdIntrBkSttlmAmt mal renseignée',''); INSERT INTO bkmoperror_code VALUES('F','041','0017','001','Devise de la balise OrgnlIntrBkSttlmAmt mal renseignée',''); INSERT INTO bkmoperror_code VALUES('F','041','0018','001','Devise différente de EUR',''); INSERT INTO bkmoperror_code VALUES('F','041','0019','001','BIC destinataire erroné',''); INSERT INTO bkmoperror_code VALUES('F','041','0020','001','Erreur lors de la recherche du PEACH',''); INSERT INTO bkmoperror_code VALUES('F','041','0021','001','Incident FLUSH bkseparv',''); INSERT INTO bkmoperror_code VALUES('F','041','0022','001','Incident UPDATE bksepahav',''); INSERT INTO bkmoperror_code VALUES('F','041','0023','001','Incident PUT bksepaavmrejet',''); INSERT INTO bkmoperror_code VALUES('F','041','0024','001','Donnée déjà en cours de traitement',''); INSERT INTO bkmoperror_code VALUES('F','041','0025','001','Incident SELECT bksepahav',''); INSERT INTO bkmoperror_code VALUES('F','041','0026','001','Donnée déjà en cours de traitement',''); INSERT INTO bkmoperror_code VALUES('F','041','0027','001','Incident SELECT bksepahav',''); INSERT INTO bkmoperror_code VALUES('F','041','0028','001','Incident PUT bkseparv',''); INSERT INTO bkmoperror_code VALUES('F','041','0029','001','Incident PUT bksepacpltr',''); INSERT INTO bkmoperror_code VALUES('F','041','0030','001','Erreur lorsqe l''on verifie si le fichier a déjà été intégré',''); INSERT INTO bkmoperror_code VALUES('F','041','0031','001','Fichier déjà integré',''); INSERT INTO bkmoperror_code VALUES('F','041','0032','001','Montant de contrôle différent du montant total des transactions (pacs 008)',''); INSERT INTO bkmoperror_code VALUES('F','041','0033','001','Nombre du contrôle de transaction différent du nombre de transaction (pacs 008)',''); INSERT INTO bkmoperror_code VALUES('F','041','0034','001','Libellé 2 de la devise EUR mal renseignée',''); INSERT INTO bkmoperror_code VALUES('F','041','0035','001','Devise de la balise RvsdIntrBkSttlmAmt mal renseignée',''); INSERT INTO bkmoperror_code VALUES('F','041','0036','001','Devise de la balise CtrlSum mal renseignée',''); INSERT INTO bkmoperror_code VALUES('F','041','0037','001','Valeur d''origine déjà en cours de traitement',''); INSERT INTO bkmoperror_code VALUES('F','041','0038','001','Incident SELECT valeur d''origine',''); INSERT INTO bkmoperror_code VALUES('F','041','0039','001','Valeur d''origine déjà en cours de traitement',''); INSERT INTO bkmoperror_code VALUES('F','041','0040','001','Incident SELECT valeur d''origine',''); INSERT INTO bkmoperror_code VALUES('F','041','0041','001','Incident lors de la recherche de la valeur d''origine pour un camt029',''); INSERT INTO bkmoperror_code VALUES('F','041','0042','001','Mandat déjà en cousr de traitement',''); INSERT INTO bkmoperror_code VALUES('F','041','0043','001','Incident lors de l''insertion du mandat',''); INSERT INTO bkmoperror_code VALUES('F','041','0044','001','Incident lors de la validation de l''insertion du mandat',''); INSERT INTO bkmoperror_code VALUES('F','041','0045','001','Incident SELECT sur le mandat',''); INSERT INTO bkmoperror_code VALUES('F','041','0046','001','Mandat déjà en cousr de traitement',''); INSERT INTO bkmoperror_code VALUES('F','041','0047','001','Incident SELECT sur le mandat',''); INSERT INTO bkmoperror_code VALUES('F','041','0048','001','Incident lors de l''insertion du motif de l''annulation',''); INSERT INTO bkmoperror_code VALUES('F','041','0049','001','Incident lors de la validation de l''insertion du motif de l''annulation',''); INSERT INTO bkmoperror_code VALUES('F','041','0050','001','Le fichier contient des epaces dans son nom',''); INSERT INTO bkmoperror_code VALUES('F','041','0051','001','Nombre du contrôle de transaction différent du nombre de transaction (pacs 004)',''); INSERT INTO bkmoperror_code VALUES('F','041','0052','001','Incident lors de l''insertion du créancier',''); INSERT INTO bkmoperror_code VALUES('F','041','0053','001','Incident lors de la validation de l''insertion du créancier',''); INSERT INTO bkmoperror_code VALUES('F','041','0054','001','Incident lors de la mise à jour de la valeur d''origine',''); INSERT INTO bkmoperror_code VALUES('F','041','0055','001','Montant de contrôle différent du montant total des transactions (pacs 003 - pacs 006 - camt 56)',''); INSERT INTO bkmoperror_code VALUES('F','041','0056','001','Nombre du contrôle de transaction différent du nombre de transaction (pacs 003 - pacs 006 - camt 56)',''); INSERT INTO bkmoperror_code VALUES('F','041','0057','001','Montant de contrôle différent du montant total des transactions (pacs 003 - pacs 007)',''); INSERT INTO bkmoperror_code VALUES('F','041','0058','001','Nombre du contrôle de transaction différent du nombre de transaction (pacs 003 - pacs 007)',''); INSERT INTO bkmoperror_code VALUES('F','041','0059','001','Valeur d''origine pour un camt029 non trouvée',''); INSERT INTO bkmoperror_code VALUES('F','041','0060','001','Incident lors de la mise à jour du mandat',''); INSERT INTO bkmoperror_code VALUES('F','041','0061','001','Incident lors de la recherche du créancier',''); INSERT INTO bkmoperror_code VALUES('F','041','0062','001','Nombre du contrôle de transaction différent du nombre de transaction (pacs 004)',''); INSERT INTO bkmoperror_code VALUES('F','041','0063','001','Incident lors de l''alimentation de la table des flux retour (bkseparf)',''); INSERT INTO bkmoperror_code VALUES('F','041','0064','001','Incident lors de la validation de l''alimentation de la table des flux retour (bkseparf)',''); INSERT INTO bkmoperror_code VALUES('F','041','0065','001','Incident FLUSH bksepaavmrejet',''); INSERT INTO bkmoperror_code VALUES('F','041','0066','001','Incident FLUSH bksepacpltr',''); INSERT INTO bkmoperror_code VALUES('F','041','0067','001','Valeur d''origine pour un camt056 non trouvée',''); INSERT INTO bkmoperror_code VALUES('F','041','0068','001',',',''); INSERT INTO bkmoperror_code VALUES('F','041','0069','001',',',''); INSERT INTO bkmoperror_code VALUES('F','041','0070','001','Repertoire de travail inexistant',''); INSERT INTO bkmoperror_code VALUES('F','041','0071','001','Repertoire d''archive inexistant',''); INSERT INTO bkmoperror_code VALUES('F','041','0072','001','Repertoire de réponse inexistant',''); INSERT INTO bkmoperror_code VALUES('F','041','0073','001','Incident SELECT bksepahrv - bksepahav',''); INSERT INTO bkmoperror_code VALUES('F','041','0074','001','Valeur SEPA déjà traitée',''); INSERT INTO bkmoperror_code VALUES('F','041','0075','001','La date de règlement est dépassée',''); INSERT INTO bkmoperror_code VALUES('F','041','0076','001','Le prélévement est inexistant',''); INSERT INTO bkmoperror_code VALUES('F','041','0077','001','Incident select lors de la recherche du prélévement',''); INSERT INTO bkmoperror_code VALUES('F','041','0078','001',',',''); INSERT INTO bkmoperror_code VALUES('F','041','0079','001',',',''); INSERT INTO bkmoperror_code VALUES('F','041','0080','001','Données déjà traitée',''); INSERT INTO bkmoperror_code VALUES('F','041','0081','001',',',''); INSERT INTO bkmoperror_code VALUES('F','041','0082','001','Le code peach n''a pas ete trouve',''); INSERT INTO bkmoperror_code VALUES('F','041','0083','001','Le nombre de modification ne correspond pas au nombre de transaction a modifier',''); INSERT INTO bkmoperror_code VALUES('F','041','0084','001','Impossible de calculer la référence du CAI',''); INSERT INTO bkmoperror_code VALUES('F','041','0085','001','Mandat verouillé',''); INSERT INTO bkmoperror_code VALUES('F','042','0001','001','Référence de dossier non trouvée',''); INSERT INTO bkmoperror_code VALUES('F','042','0002','001','Opération non trouvée',''); INSERT INTO bkmoperror_code VALUES('F','042','0003','001','Opération non trouvée',''); INSERT INTO bkmoperror_code VALUES('F','042','0004','001','Client du compte non trouvé',''); INSERT INTO bkmoperror_code VALUES('F','042','0005','001','Calcul des frais échoué',''); INSERT INTO bkmoperror_code VALUES('F','042','0006','001','Calcul des commission échoué',''); INSERT INTO bkmoperror_code VALUES('F','042','0007','001','Calcul des frais de gestion échoué',''); INSERT INTO bkmoperror_code VALUES('F','042','0008','001','Calcul des taxes échoué',''); INSERT INTO bkmoperror_code VALUES('F','042','0009','001','Condition DATVAL mal paramétrée',''); INSERT INTO bkmoperror_code VALUES('F','042','0010','001','Banque inconnue',''); INSERT INTO bkmoperror_code VALUES('F','042','0011','001','Compte inconnu',''); INSERT INTO bkmoperror_code VALUES('F','042','0012','001','Devise du compte inconnue',''); INSERT INTO bkmoperror_code VALUES('F','042','0013','001','Vérification des désaccords échouée',''); INSERT INTO bkmoperror_code VALUES('F','042','0014','001','Compte inconnu',''); INSERT INTO bkmoperror_code VALUES('F','042','0015','001','Suppression des compléments échouée',''); INSERT INTO bkmoperror_code VALUES('F','042','0016','001','Suppression de l''événement échouée',''); INSERT INTO bkmoperror_code VALUES('F','042','0017','001','DELETE bksemsta échoué',''); INSERT INTO bkmoperror_code VALUES('F','042','0018','001','INSERT bkebcavic échoué',''); INSERT INTO bkmoperror_code VALUES('F','042','0019','001','Erreur lors de l''insertion des compléments',''); INSERT INTO bkmoperror_code VALUES('F','042','0020','001','Erreur lors de l''alimentation spécifique Égypte de l''évènement',''); INSERT INTO bkmoperror_code VALUES('F','042','0021','001','.',''); INSERT INTO bkmoperror_code VALUES('F','043','0001','001','Programme déjà lancé',''); INSERT INTO bkmoperror_code VALUES('F','043','0002','001','Paramétre BANQUE inexistant',''); INSERT INTO bkmoperror_code VALUES('F','043','0003','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0004','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0005','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0006','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0007','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0008','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0009','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0010','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0011','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0012','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0013','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0014','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0015','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0016','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0017','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0018','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0019','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0020','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0021','001',',',''); INSERT INTO bkmoperror_code VALUES('F','043','0022','001','Incident DELETE table bksepacplta',''); INSERT INTO bkmoperror_code VALUES('F','044','0001','001','Programme déjà lancé',''); INSERT INTO bkmoperror_code VALUES('F','044','0002','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0003','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0004','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0005','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0006','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0007','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0008','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0009','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0010','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0011','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0012','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0013','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0014','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0015','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0016','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0017','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0018','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0019','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0020','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0021','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0022','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0023','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0024','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0025','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0026','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0027','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0028','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0029','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0030','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0031','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0032','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0033','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0034','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0035','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0036','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0037','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0038','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0039','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0040','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0041','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0042','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0043','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0044','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0045','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0046','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0047','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0048','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0049','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0050','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0051','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0052','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0053','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0054','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0055','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0056','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0057','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0058','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0059','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0060','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0061','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0062','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0063','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0064','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0065','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0066','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0067','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0068','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0069','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0070','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0071','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0072','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0073','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0074','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0075','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0076','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0077','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0078','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0079','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0080','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0081','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0082','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0083','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0084','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0085','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0086','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0087','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0088','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0089','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0090','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0091','001','Impossible de rechercher le COMSDD à partir d''un REFSDD dans bkeve',''); INSERT INTO bkmoperror_code VALUES('F','044','0092','001','Impossible de rechercher le COMSDD à partir d''un REFSDD dans bkheve',''); INSERT INTO bkmoperror_code VALUES('F','044','0093','001',',',''); INSERT INTO bkmoperror_code VALUES('F','044','0094','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0001','001','Programme déjà lancé',''); INSERT INTO bkmoperror_code VALUES('F','045','0002','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0003','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0004','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0005','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0006','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0007','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0008','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0009','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0010','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0011','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0012','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0013','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0014','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0015','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0016','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0017','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0018','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0019','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0020','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0021','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0022','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0023','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0024','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0025','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0026','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0027','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0028','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0029','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0030','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0031','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0032','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0033','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0034','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0035','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0036','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0037','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0038','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0039','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0040','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0041','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0042','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0043','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0044','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0045','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0046','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0047','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0048','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0049','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0050','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0051','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0052','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0053','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0054','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0055','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0056','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0057','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0058','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0059','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0060','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0061','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0062','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0063','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0064','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0065','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0066','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0067','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0068','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0069','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0070','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0071','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0072','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0073','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0074','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0075','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0076','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0077','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0078','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0079','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0080','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0081','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0082','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0083','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0084','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0085','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0086','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0087','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0088','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0089','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0090','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0091','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0092','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0093','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0094','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0095','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0096','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0097','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0098','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0099','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0100','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0101','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0102','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0103','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0104','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0105','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0106','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0107','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0108','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0109','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0110','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0111','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0112','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0113','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0114','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0115','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0116','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0117','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0118','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0119','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0120','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0121','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0122','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0123','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0124','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0125','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0126','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0127','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0128','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0129','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0130','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0131','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0132','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0133','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0134','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0135','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0136','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0137','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0138','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0139','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0140','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0141','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0142','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0143','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0144','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0145','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0146','001',',',''); INSERT INTO bkmoperror_code VALUES('F','045','0147','001','Impossible de trouver l''identifient du RECSDD dans les valeurs retour',''); INSERT INTO bkmoperror_code VALUES('T','046','0001','001','Probléme survenu lors de la sauvegarde de la transaction',''); INSERT INTO bkmoperror_code VALUES('T','046','0002','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0003','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0004','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0005','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0006','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0007','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0008','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0009','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0010','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0011','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0012','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0013','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0014','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0015','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0016','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0017','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0018','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0019','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0020','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0021','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0022','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0023','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0024','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0025','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0026','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0027','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0028','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0029','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0030','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0031','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0032','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0033','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0034','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0035','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0036','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0037','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0038','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0039','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0040','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0041','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0042','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0043','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0044','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0045','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0046','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0047','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0048','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0049','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0050','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0051','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0052','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0053','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0054','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0055','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0056','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0057','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0058','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0059','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0060','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0061','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0062','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0063','001',',',''); INSERT INTO bkmoperror_code VALUES('T','046','0064','001',',',''); INSERT INTO bkmoperror_code VALUES('T','047','0001','001','La classe de l''interface (itfinterf) est inconnue','Vérifier la configuration de l''interface d''émission des PSR via le programme cbgdispitf'); INSERT INTO bkmoperror_code VALUES('F','048','0001','001','Nature non trouvée en nomenclature 052',''); INSERT INTO bkmoperror_code VALUES('F','048','0002','001','Code opération inconnue pour une nature',''); INSERT INTO bkmoperror_code VALUES('F','048','0003','001','Impossible de creer la séquence',''); INSERT INTO bkmoperror_code VALUES('T','049','0001','001','Erreur lors de l''insertion dans bkcompens_af',''); INSERT INTO bkmoperror_code VALUES('T','049','0002','001','Erreur lors de la récupération de la date de compensation (paramètre inexistant)',''); INSERT INTO bkmoperror_code VALUES('T','049','0003','001','Erreur lors de la récupération du numéro d''ordre de bkcompens_af_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0004','001','Erreur lors de l''insertion dans bkcompens_af_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0005','001','Erreur lors de l''insertion dans bkcompens_rf',''); INSERT INTO bkmoperror_code VALUES('T','049','0006','001','Erreur lors de la récupération du numéro d''ordre de bkcompens_rf_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0007','001','Erreur lors de l''insertion dans bkcompens_rf_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0008','001','Erreur lors de l''insertion dans bkcompens_av',''); INSERT INTO bkmoperror_code VALUES('T','049','0009','001','Erreur lors de l''insertion dans bkcompens_av_chq',''); INSERT INTO bkmoperror_code VALUES('T','049','0010','001','Erreur lors de la récupération du numéro d''ordre de bkcompens_av_eve',''); INSERT INTO bkmoperror_code VALUES('T','049','0011','001','Erreur lors de l''insertion dans bkcompens_av_eve',''); INSERT INTO bkmoperror_code VALUES('T','049','0012','001','Erreur lors de l''insertion dans bkcompens_av_ieve',''); INSERT INTO bkmoperror_code VALUES('T','049','0013','001','Erreur lors de l''insertion dans bkcompens_av_evec',''); INSERT INTO bkmoperror_code VALUES('T','049','0014','001','Erreur lors de la récupération du numéro d''ordre de bkcompens_av_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0015','001','Erreur lors de l''insertion dans bkcompens_av_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0016','001','Erreur lors de l''insertion dans bkcompens_rv',''); INSERT INTO bkmoperror_code VALUES('T','049','0017','001','Erreur lors de l''insertion dans bkcompens_rv_chq',''); INSERT INTO bkmoperror_code VALUES('T','049','0018','001','Erreur lors de la récupération du numéro d''ordre de bkcompens_rv_eve',''); INSERT INTO bkmoperror_code VALUES('T','049','0019','001','Erreur lors de l''insertion dans bkcompens_rv_eve',''); INSERT INTO bkmoperror_code VALUES('T','049','0020','001','Erreur lors de l''insertion dans bkcompens_rv_evec',''); INSERT INTO bkmoperror_code VALUES('T','049','0021','001','Erreur lors de la récupération du numéro d''ordre de bkcompens_rv_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0022','001','Erreur lors de l''insertion dans bkcompens_rv_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0023','001','Valeur émise non trouvée',''); INSERT INTO bkmoperror_code VALUES('T','049','0024','001','Erreur lors de la sélection d''une valeur émise',''); INSERT INTO bkmoperror_code VALUES('T','049','0025','001','Erreur lors de l''insertion dans bkcompens_av_trf',''); INSERT INTO bkmoperror_code VALUES('T','049','0026','001','Erreur lors de l''insertion dans bkcompens_rv_trf',''); INSERT INTO bkmoperror_code VALUES('T','049','0027','001','Erreur lors de la mise à jour de la valeur aller',''); INSERT INTO bkmoperror_code VALUES('T','049','0028','001','Erreur lors de la mise à jour de la valeur retour',''); INSERT INTO bkmoperror_code VALUES('T','049','0029','001','gu_bl_cmp_dao_insert_fichier_emis',''); INSERT INTO bkmoperror_code VALUES('T','049','0030','001','gu_bl_cmp_dao_insert_fichier_recu',''); INSERT INTO bkmoperror_code VALUES('T','049','0031','001','gu_bl_cmp_dao_insert_valeur_emise',''); INSERT INTO bkmoperror_code VALUES('T','049','0032','001','gu_bl_cmp_dao_insert_valeur_emise_eve',''); INSERT INTO bkmoperror_code VALUES('T','049','0033','001','gu_bl_cmp_dao_insert_valeur_recue',''); INSERT INTO bkmoperror_code VALUES('T','049','0034','001','gu_bl_cmp_dao_insert_valeur_recue_eve',''); INSERT INTO bkmoperror_code VALUES('T','049','0035','001','Erreur lors de la mise à jour de l''identifiant du fichier de la valeur aller',''); INSERT INTO bkmoperror_code VALUES('T','049','0036','001','Erreur lors de l''insertion dans bkcompens_haf',''); INSERT INTO bkmoperror_code VALUES('T','049','0037','001','Erreur lors de l''insertion dans bkcompens_haf_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0038','001','Erreur lors de l''insertion dans bkcompens_hav',''); INSERT INTO bkmoperror_code VALUES('T','049','0039','001','Erreur lors de l''insertion dans bkcompens_hav_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0040','001','Erreur lors de l''insertion dans bkcompens_hav_trf',''); INSERT INTO bkmoperror_code VALUES('T','049','0041','001','Erreur lors de l''insertion dans bkcompens_hav_chq',''); INSERT INTO bkmoperror_code VALUES('T','049','0042','001','Erreur lors de l''insertion dans bkcompens_hav_eve',''); INSERT INTO bkmoperror_code VALUES('T','049','0043','001','Erreur lors de l''insertion dans bkcompens_hav_evec',''); INSERT INTO bkmoperror_code VALUES('T','049','0044','001','Erreur lors de l''insertion dans bkcompens_hav_ieve',''); INSERT INTO bkmoperror_code VALUES('T','049','0045','001','Erreur lors de l''insertion dans bkcompens_hrf',''); INSERT INTO bkmoperror_code VALUES('T','049','0046','001','Erreur lors de l''insertion dans bkcompens_hrf_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0047','001','Erreur lors de l''insertion dans bkcompens_hrv',''); INSERT INTO bkmoperror_code VALUES('T','049','0048','001','Erreur lors de l''insertion dans bkcompens_hrv_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0049','001','Erreur lors de l''insertion dans bkcompens_hrv_trf',''); INSERT INTO bkmoperror_code VALUES('T','049','0050','001','Erreur lors de l''insertion dans bkcompens_hrv_chq',''); INSERT INTO bkmoperror_code VALUES('T','049','0051','001','Erreur lors de l''insertion dans bkcompens_hrv_eve',''); INSERT INTO bkmoperror_code VALUES('T','049','0052','001','Erreur lors de l''insertion dans bkcompens_hrv_evec',''); INSERT INTO bkmoperror_code VALUES('T','049','0053','001','Erreur lors de la suppression de bkcompens_av',''); INSERT INTO bkmoperror_code VALUES('T','049','0054','001','Erreur lors de la suppression de bkcompens_av_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0055','001','Erreur lors de la suppression de bkcompens_av_trf',''); INSERT INTO bkmoperror_code VALUES('T','049','0056','001','Erreur lors de la suppression de bkcompens_av_chq',''); INSERT INTO bkmoperror_code VALUES('T','049','0057','001','Erreur lors de la suppression de bkcompens_av_eve',''); INSERT INTO bkmoperror_code VALUES('T','049','0058','001','Erreur lors de la suppression de bkcompens_av_evec',''); INSERT INTO bkmoperror_code VALUES('T','049','0059','001','Erreur lors de la suppression de bkcompens_av_ieve',''); INSERT INTO bkmoperror_code VALUES('T','049','0060','001','Erreur lors de la suppression de bkcompens_af',''); INSERT INTO bkmoperror_code VALUES('T','049','0061','001','Erreur lors de la suppression de bkcompens_af_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0062','001','Erreur lors de la suppression de bkcompens_rv',''); INSERT INTO bkmoperror_code VALUES('T','049','0063','001','Erreur lors de la suppression de bkcompens_rv_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0064','001','Erreur lors de la suppression de bkcompens_rv_trf',''); INSERT INTO bkmoperror_code VALUES('T','049','0065','001','Erreur lors de la suppression de bkcompens_rv_chq',''); INSERT INTO bkmoperror_code VALUES('T','049','0066','001','Erreur lors de la suppression de bkcompens_rv_eve',''); INSERT INTO bkmoperror_code VALUES('T','049','0067','001','Erreur lors de la suppression de bkcompens_rv_evec',''); INSERT INTO bkmoperror_code VALUES('T','049','0068','001','Erreur lors de la suppression de bkcompens_rf',''); INSERT INTO bkmoperror_code VALUES('T','049','0069','001','Erreur lors de la suppression de bkcompens_rf_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0070','001','Erreur lors de l''insertion dans bkcompens_rv_chq_img',''); INSERT INTO bkmoperror_code VALUES('T','049','0071','001','Erreur lors de la mise à jour de bkcompens_af',''); INSERT INTO bkmoperror_code VALUES('T','049','0072','001','Erreur lors de la mise à jour du fichier emis',''); INSERT INTO bkmoperror_code VALUES('T','049','0073','001','Erreur lors de la mise à jour de bkcompens_av',''); INSERT INTO bkmoperror_code VALUES('T','049','0074','001','Erreur lors de la mise à jour de la valeur emise',''); INSERT INTO bkmoperror_code VALUES('T','049','0075','001','Erreur lors de l''insertion de bkcompens_hrv_chq_img',''); INSERT INTO bkmoperror_code VALUES('T','049','0076','001','Erreur lors de la selection de la bkcompens_av',''); INSERT INTO bkmoperror_code VALUES('T','049','0077','001','Erreur lors de la selection de la bkcompens_av_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0078','001','Erreur lors de la selection de la bkcompens_av_eve',''); INSERT INTO bkmoperror_code VALUES('T','049','0079','001','Erreur lors de la selection de la bkcompens_av_evec',''); INSERT INTO bkmoperror_code VALUES('T','049','0080','001','Erreur lors de la selection de la bkcompens_av_ieve',''); INSERT INTO bkmoperror_code VALUES('T','049','0081','001','Erreur lors de la selection de la bkcompens_av_evec',''); INSERT INTO bkmoperror_code VALUES('T','049','0082','001','Erreur lors de la selection de la bkcompens_av_ieve',''); INSERT INTO bkmoperror_code VALUES('T','049','0083','001','Erreur lors de la selection de la bkcompens_av_chq',''); INSERT INTO bkmoperror_code VALUES('T','049','0084','001','Erreur lors de la selection de la bkcompens_av_trf',''); INSERT INTO bkmoperror_code VALUES('T','049','0085','001','Erreur lors de la selection de la bkcompens_av_trf',''); INSERT INTO bkmoperror_code VALUES('T','049','0086','001','Erreur lors de la selection de la bkcompens_afd_trf',''); INSERT INTO bkmoperror_code VALUES('T','049','0087','001','Erreur lors de la selection de la bkcompens_afd_trf',''); INSERT INTO bkmoperror_code VALUES('T','049','0088','001','Erreur lors de la selection de la bkcompens_af',''); INSERT INTO bkmoperror_code VALUES('T','049','0089','001','Erreur lors de la selection de la bkcompens_af',''); INSERT INTO bkmoperror_code VALUES('T','049','0090','001','Erreur lors de la selection de la bkcompens_af_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0091','001','Erreur lors de la selection de la bkcompens_av',''); INSERT INTO bkmoperror_code VALUES('T','049','0092','001','Erreur lors de la selection de la bkcompens_haf',''); INSERT INTO bkmoperror_code VALUES('T','049','0093','001','Erreur lors de la selection de la bkcompens_rv',''); INSERT INTO bkmoperror_code VALUES('T','049','0094','001','Erreur lors de la selection de la bkcompens_arv_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0095','001','Erreur lors de la selection de la bkcompens_rv_eve',''); INSERT INTO bkmoperror_code VALUES('T','049','0096','001','Erreur lors de la selection de la bkcompens_rv_evec',''); INSERT INTO bkmoperror_code VALUES('T','049','0097','001','Erreur lors de la selection de la bkcompens_rv_evec',''); INSERT INTO bkmoperror_code VALUES('T','049','0098','001','Erreur lors de la selection de la bkcompens_rv_chq',''); INSERT INTO bkmoperror_code VALUES('T','049','0099','001','Erreur lors de la selection de la bkcompens_rv_chq',''); INSERT INTO bkmoperror_code VALUES('T','049','0100','001','Erreur lors de la selection de la bkcompens_rv_chq_img',''); INSERT INTO bkmoperror_code VALUES('T','049','0101','001','Erreur lors de la selection de la bkcompens_rv_chq_img',''); INSERT INTO bkmoperror_code VALUES('T','049','0102','001','Erreur lors de la selection de la bkcompens_rv_trf',''); INSERT INTO bkmoperror_code VALUES('T','049','0103','001','Erreur lors de la selection de la bkcompens_rv_trf',''); INSERT INTO bkmoperror_code VALUES('T','049','0104','001','Erreur lors de la selection de la bkcompens_rfd',''); INSERT INTO bkmoperror_code VALUES('T','049','0105','001','Erreur lors de la selection de la bkcompens_rfd',''); INSERT INTO bkmoperror_code VALUES('T','049','0106','001','Erreur lors de la selection de la bkcompens_rf',''); INSERT INTO bkmoperror_code VALUES('T','049','0107','001','Erreur lors de la selection de la bkcompens_rf',''); INSERT INTO bkmoperror_code VALUES('T','049','0108','001','Erreur lors de la selection de la bkcompens_rf_eta',''); INSERT INTO bkmoperror_code VALUES('T','049','0109','001','Erreur lors de la selection de la bkcompens_rv',''); INSERT INTO bkmoperror_code VALUES('T','049','0110','001','Erreur lors de la selection de la bkcompens_hrf',''); INSERT INTO bkmoperror_code VALUES('T','049','0111','001','Erreur lors de l''OPEN de la bkcompens_af',''); INSERT INTO bkmoperror_code VALUES('T','049','0112','001','Erreur lors de la selection de la bkcompens_af',''); INSERT INTO bkmoperror_code VALUES('T','049','0113','001','Erreur lors du FETCH de la bkcompens_af',''); INSERT INTO bkmoperror_code VALUES('T','049','0114','001','Erreur lors de l''OPEN de la bkcompens_rf',''); INSERT INTO bkmoperror_code VALUES('T','049','0115','001','Erreur lors de la selection de la bkcompens_rf',''); INSERT INTO bkmoperror_code VALUES('T','049','0116','001','Erreur lors du FETCH de la bkcompens_rf',''); INSERT INTO bkmoperror_code VALUES('T','049','0117','001','Erreur lors de l''OPEN de la bkcompens_av',''); INSERT INTO bkmoperror_code VALUES('T','049','0118','001','Erreur lors de la selection de la bkcompens_av',''); INSERT INTO bkmoperror_code VALUES('T','049','0119','001','Erreur lors du FETCH de la bkcompens_av',''); INSERT INTO bkmoperror_code VALUES('T','049','0120','001','Erreur lors de l''OPEN de la bkcompens_rv',''); INSERT INTO bkmoperror_code VALUES('T','049','0121','001','Erreur lors de la selection de la bkcompens_rv',''); INSERT INTO bkmoperror_code VALUES('T','049','0122','001','Erreur lors du FETCH de la bkcompens_rv',''); INSERT INTO bkmoperror_code VALUES('T','049','0123','001','Erreur lors de la mise a jour de la valeur recue',''); INSERT INTO bkmoperror_code VALUES('T','049','0124','001','Erreur lors de l''insertion de l''etat de la valeur recue',''); INSERT INTO bkmoperror_code VALUES('T','049','0125','001','Incident lors de la recherche de la valeur d''origine',''); INSERT INTO bkmoperror_code VALUES('T','049','0126','001','Valeur d''origine inconnue',''); INSERT INTO bkmoperror_code VALUES('T','049','0127','001','Incident lors de la recherche de la valeur d''origine',''); INSERT INTO bkmoperror_code VALUES('T','049','0128','001','Erreur lors de la selection de la bkcompens_afdco',''); INSERT INTO bkmoperror_code VALUES('T','049','0129','001','Impossible de trouvé le fichier',''); INSERT INTO bkmoperror_code VALUES('T','049','0130','001','Erreur lors de la récuperation de la date de compensation',''); INSERT INTO bkmoperror_code VALUES('T','049','0131','001','Erreur lors de suppression dans bkcompens pa',''); INSERT INTO bkmoperror_code VALUES('T','049','0132','001','Erreur lors de mise a jour dans bkcompens pa',''); INSERT INTO bkmoperror_code VALUES('T','049','0133','001','Erreur lors d''insertion dans bkcompens pa',''); INSERT INTO bkmoperror_code VALUES('T','049','0134','001','Chèque d''origine en cours d''utilisation',''); INSERT INTO bkmoperror_code VALUES('T','049','0135','001','Erreur lors de la PREPARATION de la bkcompens_af_file',''); INSERT INTO bkmoperror_code VALUES('T','049','0136','001','Erreur lors de la SELECT de la bkcompens_af_file',''); INSERT INTO bkmoperror_code VALUES('T','049','0137','001','Erreur lors de la PREPARATION de la bkcompens_rf_file',''); INSERT INTO bkmoperror_code VALUES('T','049','0138','001','Erreur lors de la SELECT de la bkcompens_rf_file',''); INSERT INTO bkmoperror_code VALUES('T','049','0139','001','Erreur lors de l''insertion dans bkcompens_haf_file',''); INSERT INTO bkmoperror_code VALUES('T','049','0140','001','Erreur lors de l''insertion dans bkcompens_hrf_file',''); INSERT INTO bkmoperror_code VALUES('T','049','0141','001','Incident select',''); INSERT INTO bkmoperror_code VALUES('T','049','0142','001','Valeur d''origine non trouvée',''); INSERT INTO bkmoperror_code VALUES('T','049','0143','001','Incident select',''); INSERT INTO bkmoperror_code VALUES('T','049','0144','001','Impossible ed verouiller la valeur d''origine',''); INSERT INTO bkmoperror_code VALUES('F','050','0001','001','Paramètre DIRECTORY_INCOMING mal paramétré',''); INSERT INTO bkmoperror_code VALUES('F','050','0002','001','Paramètre DIRECTORY_INCOMING inexistant',''); INSERT INTO bkmoperror_code VALUES('F','050','0003','001','Erreur lors de la lecture du paramètre de l''interface',''); INSERT INTO bkmoperror_code VALUES('F','050','0004','001','Erreur lors de la lecture du paramétre des operations',''); INSERT INTO bkmoperror_code VALUES('F','051','0001','001','Erreur lors du dénombrement des évènements à traiter',''); INSERT INTO bkmoperror_code VALUES('F','051','0002','001','Enregistrement en cours de traitement',''); INSERT INTO bkmoperror_code VALUES('F','051','0003','001','Erreur OPEN cur_lock_eve',''); INSERT INTO bkmoperror_code VALUES('F','051','0004','001','Erreur FETCH cur_lock_eve',''); INSERT INTO bkmoperror_code VALUES('F','051','0005','001','Paramètre d''interface mal paramétré',''); INSERT INTO bkmoperror_code VALUES('F','051','0006','001','Paramètre d''interface inexistant',''); INSERT INTO bkmoperror_code VALUES('F','051','0007','001','Erreur lors de la lecture des paramètres de l''interface',''); INSERT INTO bkmoperror_code VALUES('F','051','0008','001','Le paramètre PREPARATION_MODE a été modifié durant le traitement des évènements',''); INSERT INTO bkmoperror_code VALUES('F','051','0009','001','Erreur lors de la lecture de la table bkcompens_rv_chq',''); INSERT INTO bkmoperror_code VALUES('F','051','0010','001','Erreur lors de la lecture de la table bkdetchqd',''); INSERT INTO bkmoperror_code VALUES('F','051','0011','001','Erreur lors de la récupération du code de rejet de chèque',''); INSERT INTO bkmoperror_code VALUES('F','051','0012','001','Erreur lors de la mise à jour de l''évènement',''); INSERT INTO bkmoperror_code VALUES('F','051','0013','001','gucmppre_traitement',''); INSERT INTO bkmoperror_code VALUES('F','051','0014','001','gucmppre_alim_bkcompens',''); INSERT INTO bkmoperror_code VALUES('F','051','0015','001','gucmppre_alim_bkcompens_av',''); INSERT INTO bkmoperror_code VALUES('F','051','0016','001','Erreur lors de la récupération de l''identifiant d''une valeur reçue',''); INSERT INTO bkmoperror_code VALUES('F','051','0017','001','Code rejet inexistant',''); INSERT INTO bkmoperror_code VALUES('F','051','0018','001','gucmppre_lec_param',''); INSERT INTO bkmoperror_code VALUES('F','051','0019','001','Programme déjà actif',''); INSERT INTO bkmoperror_code VALUES('F','051','0020','001','main_fonc',''); INSERT INTO bkmoperror_code VALUES('F','052','0001','001','Erreur lors de la récupération du numéro de séquence S_CMP_ID',''); INSERT INTO bkmoperror_code VALUES('F','052','0002','001','Erreur lors de la récupération du chrono',''); INSERT INTO bkmoperror_code VALUES('F','052','0003','001','gu_bl_cmp_get_id',''); INSERT INTO bkmoperror_code VALUES('F','052','0004','001','Paramètre itfparam mal paramétré',''); INSERT INTO bkmoperror_code VALUES('F','052','0005','001','Paramètre itfparam inexistant',''); INSERT INTO bkmoperror_code VALUES('F','052','0006','001','Erreur liée à la fonction tm_itfparam_get',''); INSERT INTO bkmoperror_code VALUES('F','052','0007','001','Erreur lors de la récuperation dans la table bkcompens_suivi_trf',''); INSERT INTO bkmoperror_code VALUES('F','052','0008','001','Erreur lors de la récuperation dans la table bkcompens_suivi_chq',''); INSERT INTO bkmoperror_code VALUES('F','052','0009','001','Erreur lors de la insertion dans la table bkcompens_suivi',''); INSERT INTO bkmoperror_code VALUES('F','052','0010','001','Incoherence des heures debut et fin cycle CHEQUES',''); INSERT INTO bkmoperror_code VALUES('F','052','0011','001','Incoherence des heures debut et fin cycle TRANSFERT',''); INSERT INTO bkmoperror_code VALUES('F','052','0012','001','Incoherence controle dernier cycle CHEQUES',''); INSERT INTO bkmoperror_code VALUES('F','052','0013','001','Incoherence controle dernier cycle TRANSFERT',''); INSERT INTO bkmoperror_code VALUES('F','052','0014','001','Incident lors de la recherche de la valeur d''origine',''); INSERT INTO bkmoperror_code VALUES('F','052','0015','001','Plusieurs valeurs d''origines trouvées',''); INSERT INTO bkmoperror_code VALUES('F','052','0016','001','Valeur d''origine non trouvée',''); INSERT INTO bkmoperror_code VALUES('F','052','0017','001','Incoherence des heures debut et fin cycle CHEQUES',''); INSERT INTO bkmoperror_code VALUES('F','052','0018','001','Incoherence des heures debut et fin cycle CHEQUES',''); INSERT INTO bkmoperror_code VALUES('F','052','0019','001','Incoherence des heures debut et fin cycle TRANSFERT',''); INSERT INTO bkmoperror_code VALUES('F','052','0020','001','Incoherence des heures debut et fin cycle TRANSFERT',''); INSERT INTO bkmoperror_code VALUES('F','052','0021','001','Incoherence des heures debut et fin cycle TRANSFERT',''); INSERT INTO bkmoperror_code VALUES('F','052','0022','001','.',''); INSERT INTO bkmoperror_code VALUES('F','052','0023','001','.',''); INSERT INTO bkmoperror_code VALUES('F','052','0024','001','.',''); INSERT INTO bkmoperror_code VALUES('F','052','0025','001','Systeme de compensation non déterminé',''); INSERT INTO bkmoperror_code VALUES('F','052','0026','001','Type de valeur non gerée par la banque',''); INSERT INTO bkmoperror_code VALUES('F','052','0027','001','Erreur lors de la recherche du systeme de compensation d''un fichier',''); INSERT INTO bkmoperror_code VALUES('F','052','0028','001','Erreur lors de la récuperation dans la table bkcompens_suivi',''); INSERT INTO bkmoperror_code VALUES('F','052','0029','001','.',''); INSERT INTO bkmoperror_code VALUES('F','052','0030','001','Incident lecture bkcompens_rf',''); INSERT INTO bkmoperror_code VALUES('F','052','0031','001','Incident update bknom lors du passage à la date de compensation suivante',''); INSERT INTO bkmoperror_code VALUES('F','052','0032','001','Incident lors de la recherche d''un cycle',''); INSERT INTO bkmoperror_code VALUES('F','052','0033','001','Nature d''opération de réglement mal paramétré',''); INSERT INTO bkmoperror_code VALUES('F','053','0001','001','Programme déjà en cours d''exécution',''); INSERT INTO bkmoperror_code VALUES('F','053','0002','001','Erreur lors de l''initialisation de l''interface des messages',''); INSERT INTO bkmoperror_code VALUES('F','053','0003','001','Erreur lors de la clôture de l''interface des messages',''); INSERT INTO bkmoperror_code VALUES('F','053','0004','001','gucmpenv_create_table_temp',''); INSERT INTO bkmoperror_code VALUES('F','053','0005','001','gucmpenv_drop_table_temp',''); INSERT INTO bkmoperror_code VALUES('F','053','0006','001','gucmpenv_traite_chq',''); INSERT INTO bkmoperror_code VALUES('F','053','0007','001','gucmpenv_traite_chq_rej',''); INSERT INTO bkmoperror_code VALUES('F','053','0008','001','gucmpenv_traite_chq_rep',''); INSERT INTO bkmoperror_code VALUES('F','053','0009','001','gucmpenv_traite_vir',''); INSERT INTO bkmoperror_code VALUES('F','053','0010','001','gucmpenv_charge_param',''); INSERT INTO bkmoperror_code VALUES('F','054','0001','001','Programme deja actif','Stoper le programme actif puis relancer'); INSERT INTO bkmoperror_code VALUES('F','054','0002','001','Erreur lors du traitement de la file d''attente','Contacter la hotline'); INSERT INTO bkmoperror_code VALUES('F','054','0003','001','Erreur lors de l''initialisation de la file d''attente','Verifier le parametrage de l''interface'); INSERT INTO bkmoperror_code VALUES('F','054','0004','001','Erreur a la fermeture de la file d''attente','Contacter la hotline'); INSERT INTO bkmoperror_code VALUES('F','054','0005','001','Erreur lors de la fermeture du fichier','Contacter la hotline'); INSERT INTO bkmoperror_code VALUES('F','054','0006','001','gucmprec_trt_fic',''); INSERT INTO bkmoperror_code VALUES('F','055','0001','001','Erreur lors du chargement du fichier','Contacter la hotline'); INSERT INTO bkmoperror_code VALUES('F','055','0002','001','Erreur lors de la creation de la table temporaire','Contacter la hotline'); INSERT INTO bkmoperror_code VALUES('F','055','0003','001','Format du nom de fichier incorrect','Renommer le fichier'); INSERT INTO bkmoperror_code VALUES('F','055','0004','001','Type d''operation inexistant','Renommer le fichier avec le bon type'); INSERT INTO bkmoperror_code VALUES('F','055','0005','001','Nombre de transac.entete <> nombre de transac.calculé','Modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0006','001','Montant entete <> montant calculé','Modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0007','001','Date incorrecte dans le nom du fichier','Renommer le fichier'); INSERT INTO bkmoperror_code VALUES('F','055','0008','001','Montant entete <> montant calculé (VIR)','Modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0009','001','Nombre de transac.entete <> nombre de transac.calculé (VIR)','Modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0010','001','Erreur lors de la recherche du fichier','Contacter la hotline'); INSERT INTO bkmoperror_code VALUES('F','055','0011','001','Fichier deja integré','Renommer le fichier'); INSERT INTO bkmoperror_code VALUES('F','055','0012','001','Numero de cycle incorrect','Modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0013','001','Numero de sous-cycle incorrect','Modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0014','001','Code bqe emetteur entete <> code bqe titre (CHQ)','Renommer le fichier ou modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0015','001','Code bqe destinataire entete <> code bqe titre (CHQ)','Renommer le fichier ou modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0016','001','Type de val entete <> type de val fichier (CHQ)','Renommer le fichier ou modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0017','001','Code établissement incorrect (CHQ)','Modifier la ligne de detail ou l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0018','001','Code etablissement destinataire incorrect (CHQ)','Modifier la ligne de detail ou l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0019','001','Nombre d''images <> nombre de cheques * 2','Ajouter des images cheques'); INSERT INTO bkmoperror_code VALUES('F','055','0020','001','Structure du fichier incorrect (VIR)','Modifier la ligne d''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0021','001','Code bqe destinataire <> code bqe titre (VIR)','Renommer le fichier ou modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0022','001','Code bqe emetteur <> code bqe titre (VIR)','Renommer le fichier ou modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0023','001','Date de generation <> titre (VIR)','Renommer le fichier ou modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0024','001','Numero de fichier <> titre (VIR)','Renommer le fichier ou modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0025','001','Devise doit etre devise nat (VIR)','Modifier la ligne d''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0026','001','Date de generation <> entete','Modifier la ligne de detail et modifier l''entete'); INSERT INTO bkmoperror_code VALUES('F','055','0027','001','gu_bl_cmprec_spec_maurice_alim_valeur',''); INSERT INTO bkmoperror_code VALUES('F','055','0028','001','Impossible de determiner le cycle de reception',''); INSERT INTO bkmoperror_code VALUES('F','055','0029','001','En dehors des heure de cycle de presentation chèque',''); INSERT INTO bkmoperror_code VALUES('F','056','0001','001','Erreur lors de la récupération du numéro de chèque de la valeur à émettre',''); INSERT INTO bkmoperror_code VALUES('F','056','0002','001','Erreur lors de la création de la table temporaire d''entête',''); INSERT INTO bkmoperror_code VALUES('F','056','0003','001','Erreur lors de la création de la table temporaire de détail',''); INSERT INTO bkmoperror_code VALUES('F','056','0004','001','Erreur lors de l''insertion dans la table temporaire d''entête',''); INSERT INTO bkmoperror_code VALUES('F','056','0005','001','Erreur lors de l''insertion dans la table temporaire de détail',''); INSERT INTO bkmoperror_code VALUES('F','056','0006','001','Erreur lors du vidage de la table temporaire d''entête',''); INSERT INTO bkmoperror_code VALUES('F','056','0007','001','Erreur lors du vidage de la table temporaire de détail',''); INSERT INTO bkmoperror_code VALUES('F','056','0008','001','gu_bl_cmpenv_spec_maurice_alim_zone_det_vir',''); INSERT INTO bkmoperror_code VALUES('F','056','0009','001','gu_bl_cmpenv_spec_maurice_get_dcom_cur',''); INSERT INTO bkmoperror_code VALUES('F','056','0010','001','gu_bl_cmpenv_spec_maurice_get_num_chq',''); INSERT INTO bkmoperror_code VALUES('F','056','0011','001','gu_bl_cmpenv_spec_maurice_get_motif_vir',''); INSERT INTO bkmoperror_code VALUES('F','056','0012','001','Erreur lors de la récupération du répertoire de sortie',''); INSERT INTO bkmoperror_code VALUES('F','056','0013','001','gu_bl_cmpenv_spec_maurice_alim_bkcompens',''); INSERT INTO bkmoperror_code VALUES('F','056','0014','001','gu_bl_cmpenv_spec_maurice_traite_chq',''); INSERT INTO bkmoperror_code VALUES('F','056','0015','001','gu_bl_cmpenv_spec_maurice_traite_chq_rej',''); INSERT INTO bkmoperror_code VALUES('F','056','0016','001','gu_bl_cmpenv_spec_maurice_traite_chq_rep',''); INSERT INTO bkmoperror_code VALUES('F','056','0017','001','gu_bl_cmpenv_spec_maurice_traite_vir',''); INSERT INTO bkmoperror_code VALUES('F','056','0018','001','Erreur lors de la récupération du sous-cycle',''); INSERT INTO bkmoperror_code VALUES('F','056','0019','001','gu_bl_cmpenv_spec_maurice_alim_zone_ent_chq',''); INSERT INTO bkmoperror_code VALUES('F','056','0020','001','gu_bl_cmpenv_spec_maurice_alim_zone_det_chq',''); INSERT INTO bkmoperror_code VALUES('F','056','0021','001','gu_bl_cmpenv_spec_maurice_alim_zone_det_vir',''); INSERT INTO bkmoperror_code VALUES('F','056','0022','001','Erreur lors de la récupération du motif de rejet d''une chèque',''); INSERT INTO bkmoperror_code VALUES('F','056','0023','001','gu_bl_cmpenv_spec_maurice_charge_param',''); INSERT INTO bkmoperror_code VALUES('F','056','0024','001','Erreur lors du déplacement du fichier vers le répertoire d''envoi',''); INSERT INTO bkmoperror_code VALUES('F','056','0025','001','gu_bl_cmpenv_spec_maurice_gen_fic',''); INSERT INTO bkmoperror_code VALUES('F','056','0026','001','Erreur lors de la récupération du nombre de valeurs de chèques à émettre',''); INSERT INTO bkmoperror_code VALUES('F','056','0027','001','Erreur lors de la récupération du nombre de valeurs de chèques à rejetés à émettre',''); INSERT INTO bkmoperror_code VALUES('F','056','0028','001','Erreur lors de la récupération du nombre de valeurs de chèques représentés à émettre',''); INSERT INTO bkmoperror_code VALUES('F','056','0029','001','Erreur lors de la récupération du nombre de valeurs de virements à émettre',''); INSERT INTO bkmoperror_code VALUES('F','056','0030','001','gu_bl_cmpenv_spec_maurice_get_num_chq',''); INSERT INTO bkmoperror_code VALUES('F','056','0031','001','gu_bl_cmpenv_spec_maurice_get_motif_vir',''); INSERT INTO bkmoperror_code VALUES('F','056','0032','001','Erreur lors de la recherche du cycle actuel',''); INSERT INTO bkmoperror_code VALUES('T','057','0001','001','Valeur émise non trouvée','Continuer'); INSERT INTO bkmoperror_code VALUES('T','057','0002','001','Erreur lors de la récuperation dans la table bkeve',''); INSERT INTO bkmoperror_code VALUES('T','057','0003','001','Erreur lors de mis a jour Dans la tableau bkeve',''); INSERT INTO bkmoperror_code VALUES('T','057','0004','001','Valeur émise deja existant',''); INSERT INTO bkmoperror_code VALUES('T','057','0005','001','Impossible de determiner le nom de la banque',''); INSERT INTO bkmoperror_code VALUES('F','058','0001','001','Valeur émise non trouveé','Continue'); INSERT INTO bkmoperror_code VALUES('F','058','0002','001','Erreur lors de la récuperation dans la table bknom',''); INSERT INTO bkmoperror_code VALUES('F','058','0003','001','Erreur lors de la récupreation dans la table bkcompens_rv',''); INSERT INTO bkmoperror_code VALUES('F','058','0004','001','Erreur lors de la récuperation dans la table bkcompens_rf_eta',''); INSERT INTO bkmoperror_code VALUES('F','058','0005','001','Erreur lors de la récuperation dans la table bkcompens_rf',''); INSERT INTO bkmoperror_code VALUES('F','058','0006','001','Erreur lors de l''insertion de un nouvelle enregistraient dans la table bkcompens_rf_eta',''); INSERT INTO bkmoperror_code VALUES('F','058','0007','001','Erreur lors de la récuperation des fichiers pré-intégré',''); INSERT INTO bkmoperror_code VALUES('F','058','0008','001','gu_bl_cmpmoni_prec_lance_integration',''); INSERT INTO bkmoperror_code VALUES('F','059','0001','001','Valeur émise non trouvée',''); INSERT INTO bkmoperror_code VALUES('F','059','0002','001','Erreur lors de la récuperation dans la table bkeve',''); INSERT INTO bkmoperror_code VALUES('F','059','0003','001','Erreur lors de la récuperation dans la table bkcompens_av',''); INSERT INTO bkmoperror_code VALUES('F','059','0004','001','Erreur lors de la récuperation dans la table bkcompens_rv',''); INSERT INTO bkmoperror_code VALUES('F','059','0005','001','Erreur lors de la récuperation dans la table bkeve_comche',''); INSERT INTO bkmoperror_code VALUES('F','059','0006','001','Impossible de fermer la compensation chèque, il reste des erreurs sur lesquelles il faut prendre une décision',''); INSERT INTO bkmoperror_code VALUES('F','059','0007','001','Erreur lors de la récuperation dans la table bkcompens_rf',''); INSERT INTO bkmoperror_code VALUES('F','059','0008','001','Erreur lors de la récuperation dans la table bkcompens_suivi',''); INSERT INTO bkmoperror_code VALUES('F','059','0009','001','Impossible de fermer la compensation, il reste des erreurs',''); INSERT INTO bkmoperror_code VALUES('F','059','0010','001','Erreur lors de la récuperation dans la table bkcompens_pa',''); INSERT INTO bkmoperror_code VALUES('F','059','0011','001','Le système ne gère aucun type de valeur (gucmpparam)',''); INSERT INTO bkmoperror_code VALUES('T','060','0001','001','Valeur émise non trouvée','Continuer'); INSERT INTO bkmoperror_code VALUES('T','060','0002','001','Erreur lors de la récuperation dans la table bkcompens_error',''); INSERT INTO bkmoperror_code VALUES('T','060','0003','001','Erreur lors de l''insertion dans la table bkcompens_error',''); INSERT INTO bkmoperror_code VALUES('F','061','0001','001','Valeur émise non trouvée',''); INSERT INTO bkmoperror_code VALUES('F','061','0002','001','Erreur lors de la récuperation dans la table bkcompens_av_hav',''); INSERT INTO bkmoperror_code VALUES('F','061','0003','001','Erreur lors de la récuperation dans la table bkcompens_rv_hrf',''); INSERT INTO bkmoperror_code VALUES('F','061','0004','001','Erreur lors de la récuperation dans la table bkeve',''); INSERT INTO bkmoperror_code VALUES('F','061','0005','001','Erreur lors de la récuperation dans la table bkchqxmlimg',''); INSERT INTO bkmoperror_code VALUES('F','061','0006','001','Erreur lors de la récuperation dans la table bkcompens_rv_chq',''); INSERT INTO bkmoperror_code VALUES('F','061','0007','001','Erreur lors de la récuperation dans la table bkcom',''); INSERT INTO bkmoperror_code VALUES('F','061','0008','001','Erreur lors de la récuperation dans la table bkbqeb',''); INSERT INTO bkmoperror_code VALUES('F','061','0009','001','Erreur lors de la récuperation dans la table bkcli',''); INSERT INTO bkmoperror_code VALUES('F','062','0001','001','fc_bl_ctrlvisu_set',''); INSERT INTO bkmoperror_code VALUES('F','063','0001','001','Parametre 098.SIGNATURES inexistant',''); INSERT INTO bkmoperror_code VALUES('F','063','0002','001','098.SIGNATURES - Numéro de version incorrect',''); INSERT INTO bkmoperror_code VALUES('F','063','0003','001','Erreur lors de la récupération de l''interface du programme cbdmsigdes',''); INSERT INTO bkmoperror_code VALUES('F','063','0004','001','L''interface du programme cbdmsigdes n''utilise pas de WebService',''); INSERT INTO bkmoperror_code VALUES('F','063','0005','001','fc_bl_signature_ges_acqsig',''); INSERT INTO bkmoperror_code VALUES('F','063','0006','001','Problème lors de la sélection de la date courante',''); INSERT INTO bkmoperror_code VALUES('F','063','0007','001','Erreur lors de l''insertion dans bksiga',''); INSERT INTO bkmoperror_code VALUES('F','063','0008','001','Erreur lors de la demande au serveur de signatures (début de session). Veuillez vérifier les logs',''); INSERT INTO bkmoperror_code VALUES('F','063','0009','001','Erreur lors de la lecture de evlanc',''); INSERT INTO bkmoperror_code VALUES('F','063','0010','001','Erreur lors de la suppresion de l''enregistrement de evlanc',''); INSERT INTO bkmoperror_code VALUES('F','063','0011','001','Erreur lors de l''instanciation de démarrage d''une session de demande de signatures',''); INSERT INTO bkmoperror_code VALUES('F','063','0012','001','Erreur lors de la récupération de l''interface du programme cbdmsigcpt',''); INSERT INTO bkmoperror_code VALUES('F','063','0013','001','fc_bl_signature_fin_session',''); INSERT INTO bkmoperror_code VALUES('F','063','0014','001','Erreur lors de l ''exécution du script SupprimeTousFichier',''); INSERT INTO bkmoperror_code VALUES('F','063','0015','001','fc_bl_signature_ins_bksiga',''); INSERT INTO bkmoperror_code VALUES('F','063','0016','001','Erreur lors de la récupération de l''interface du programme cbdmsigcli',''); INSERT INTO bkmoperror_code VALUES('F','063','0017','001','Erreur lors de la récupération de l''interface du programme cbdmsigfes',''); INSERT INTO bkmoperror_code VALUES('F','063','0018','001','fc_bl_signature_init_session',''); INSERT INTO bkmoperror_code VALUES('F','063','0019','001','fc_bl_signature_init_session',''); INSERT INTO bkmoperror_code VALUES('F','063','0020','001','fc_bl_signature_demande',''); INSERT INTO bkmoperror_code VALUES('F','063','0021','001','fc_bl_signature_demande',''); INSERT INTO bkmoperror_code VALUES('F','063','0022','001','fc_bl_signature_demande',''); INSERT INTO bkmoperror_code VALUES('F','063','0023','001','L''interface du programme cbdmsigcpt n''utilise pas de WebService',''); INSERT INTO bkmoperror_code VALUES('F','063','0024','001','L''interface du programme cbdmsigcli n''utilise pas de WebService',''); INSERT INTO bkmoperror_code VALUES('F','063','0025','001','L''interface du programme cbdmsigfes n''utilise pas de WebService',''); INSERT INTO bkmoperror_code VALUES('F','063','0026','001','Problème lors de la sélection de la date courante',''); INSERT INTO bkmoperror_code VALUES('F','064','0001','001','Erreur lors de l''initialisation de l''interface des messages',''); INSERT INTO bkmoperror_code VALUES('F','064','0002','001','Erreur lors de la déconnexion à l''interface des messages',''); INSERT INTO bkmoperror_code VALUES('F','065','0001','001','Impossible de determiner le nom de la banque (trf)',''); INSERT INTO bkmoperror_code VALUES('F','065','0002','001','Impossible de determiner le nom de la banque (chq)',''); INSERT INTO bkmoperror_code VALUES('F','065','0003','001','Erreur lors de la mise a jour de l''etat de bkcompens_av (chq)',''); INSERT INTO bkmoperror_code VALUES('F','065','0004','001','Erreur lors de la mise a jour de l''etat de bkcompens_av (trf)',''); INSERT INTO bkmoperror_code VALUES('F','065','0005','001','Erreur lors de la récuperation du cycle des chèques',''); INSERT INTO bkmoperror_code VALUES('F','065','0006','001','Erreur lors dela récuperation du cycle des virements',''); INSERT INTO bkmoperror_code VALUES('F','065','0007','001','gu_bl_cmpmoni_penv_lance_emission',''); INSERT INTO bkmoperror_code VALUES('F','065','0008','001','Erreur lors de la récuperation du cycle',''); INSERT INTO bkmoperror_code VALUES('F','065','0009','001','Erreur lors de la mise a jour de l''etat de bkcompens_av',''); INSERT INTO bkmoperror_code VALUES('F','065','0010','001','Paramètre ISSUING_ITF catégorie GENEREAL inexistant',''); INSERT INTO bkmoperror_code VALUES('F','066','0001','001','Paramétrage de la devise nationale incorrect ou inexistant',''); INSERT INTO bkmoperror_code VALUES('F','066','0002','001','Paramètre COMPTE inexistant en T999',''); INSERT INTO bkmoperror_code VALUES('F','066','0003','001','La saisie de l''agence est obligatoire',''); INSERT INTO bkmoperror_code VALUES('F','066','0004','001','L''agence saisie est incorrecte',''); INSERT INTO bkmoperror_code VALUES('F','066','0005','001','Le code banque saisi doit être différent de la banque locale',''); INSERT INTO bkmoperror_code VALUES('F','066','0006','001','Le numéro de compte doit être numérique',''); INSERT INTO bkmoperror_code VALUES('F','066','0007','001','La longueur du numéro de compte est incorrecte',''); INSERT INTO bkmoperror_code VALUES('F','066','0008','001','Erreur lors du contrôle du compte',''); INSERT INTO bkmoperror_code VALUES('F','066','0009','001','La clé de compte est erronée',''); INSERT INTO bkmoperror_code VALUES('F','066','0010','001','Le numéro de chèque doit être numérique',''); INSERT INTO bkmoperror_code VALUES('F','066','0011','001','Paramétrage de la devise saisie incorrect ou inexistant',''); INSERT INTO bkmoperror_code VALUES('F','066','0012','001','Le montant saisi doit être numérique',''); INSERT INTO bkmoperror_code VALUES('F','066','0013','001','Le second montant saisi doit être supérieur ou égal au premier montant saisi',''); INSERT INTO bkmoperror_code VALUES('F','066','0014','001','Erreur technique lors de la récupération du compte',''); INSERT INTO bkmoperror_code VALUES('F','066','0015','001','Erreur technique lors de la récupération de la banque',''); INSERT INTO bkmoperror_code VALUES('F','066','0016','001','La banque saisie est inexistante',''); INSERT INTO bkmoperror_code VALUES('F','066','0017','001','gucmpcvisu_controle_saisie',''); INSERT INTO bkmoperror_code VALUES('F','066','0018','001','Le suffixe saisi doit être numérique',''); INSERT INTO bkmoperror_code VALUES('F','066','0019','001','gucmpcvisu_lec_param',''); INSERT INTO bkmoperror_code VALUES('F','066','0020','001','Aucune donnée sélectionnée',''); INSERT INTO bkmoperror_code VALUES('F','066','0021','001','Erreur lors de la récupération des images chèques',''); INSERT INTO bkmoperror_code VALUES('F','066','0022','001','Erreur technique lors de la récupération du nom du client',''); INSERT INTO bkmoperror_code VALUES('F','066','0023','001','Le client n''existe pas',''); INSERT INTO bkmoperror_code VALUES('F','066','0024','001','Erreur lors du verrouillage d''un enregistrement de bkdetchqd',''); INSERT INTO bkmoperror_code VALUES('F','066','0025','001','gucmpcvisu_traitement',''); INSERT INTO bkmoperror_code VALUES('F','066','0026','001','gucmpcvisu_maj_val',''); INSERT INTO bkmoperror_code VALUES('F','066','0027','001','Erreur lors de la mise à jour de la table bkdetchqd',''); INSERT INTO bkmoperror_code VALUES('F','066','0028','001','Erreur lors de la mise à jour de la table bkcompens_rv_chq',''); INSERT INTO bkmoperror_code VALUES('F','066','0029','001','La saisie de la banque est obigatoire',''); INSERT INTO bkmoperror_code VALUES('F','066','0030','001','La saisie du compte est obligatoire',''); INSERT INTO bkmoperror_code VALUES('F','066','0031','001','La saisie de l''agence est obligatoire',''); INSERT INTO bkmoperror_code VALUES('F','066','0032','001','La saisie du suffixe est obligatoire',''); INSERT INTO bkmoperror_code VALUES('F','066','0033','001','La saisie du compte est obligatoire',''); INSERT INTO bkmoperror_code VALUES('F','066','0034','001','La saisie de la clé du compte est obligatoire',''); INSERT INTO bkmoperror_code VALUES('F','066','0035','001','La saisie de la devise est obligatoire',''); INSERT INTO bkmoperror_code VALUES('F','066','0036','001','Paramétrage de la devise nationale incorrect ou inexistant',''); INSERT INTO bkmoperror_code VALUES('F','066','0037','001','gucmpcvisu_lec_param',''); INSERT INTO bkmoperror_code VALUES('F','066','0038','001','gucmpcvisu_lec_param',''); INSERT INTO bkmoperror_code VALUES('F','066','0039','001','gucmpcvisu_lec_param',''); INSERT INTO bkmoperror_code VALUES('F','066','0040','001','Erreur technique lors de la récupération du compte',''); INSERT INTO bkmoperror_code VALUES('F','066','0041','001','Erreur technique lors de la récupération du compte',''); INSERT INTO bkmoperror_code VALUES('F','066','0042','001','gucmpcvisu_traitement',''); INSERT INTO bkmoperror_code VALUES('F','066','0043','001','gucmpcvisu_traitement',''); INSERT INTO bkmoperror_code VALUES('F','066','0044','001','L''agence saisie est incorrecte',''); INSERT INTO bkmoperror_code VALUES('F','066','0045','001','gucmpcvisu_controle_saisie',''); INSERT INTO bkmoperror_code VALUES('F','066','0046','001','gucmpcvisu_controle_saisie',''); INSERT INTO bkmoperror_code VALUES('F','066','0047','001','Erreur lors du contrôle du compte',''); INSERT INTO bkmoperror_code VALUES('F','066','0048','001','Le montant saisi doit être numérique',''); INSERT INTO bkmoperror_code VALUES('F','066','0049','001','La banque saisie est inexistante',''); INSERT INTO bkmoperror_code VALUES('F','066','0050','001','Erreur technique lors de la récupération de la banque',''); INSERT INTO bkmoperror_code VALUES('F','066','0051','001','Erreur technique lors de la récupération de la banque',''); INSERT INTO bkmoperror_code VALUES('F','066','0052','001','Erreur technique lors de la récupération de la banque',''); INSERT INTO bkmoperror_code VALUES('F','066','0053','001','Erreur lors du verrouillage d''un enregistrement de bkdetchqd',''); INSERT INTO bkmoperror_code VALUES('F','066','0054','001','gucmpcvisu_maj_val',''); INSERT INTO bkmoperror_code VALUES('F','066','0055','001','gucmpcvisu_maj_val',''); INSERT INTO bkmoperror_code VALUES('F','067','0001','001','Donnees en cours de traitement',''); INSERT INTO bkmoperror_code VALUES('F','067','0002','001','Incident @ TABLE @ SQLCODE @',''); INSERT INTO bkmoperror_code VALUES('F','067','0003','001','Donnees en cours de traitement',''); INSERT INTO bkmoperror_code VALUES('F','067','0004','001','Incident @ TABLE @ SQLCODE @',''); INSERT INTO bkmoperror_code VALUES('F','068','0001','001','Erreur lors de l''insertion dans bkeve',''); INSERT INTO bkmoperror_code VALUES('F','068','0002','001','Erreur lors de l''insertion dans bkevec',''); INSERT INTO bkmoperror_code VALUES('F','069','0001','001','Erreur lors de l''update du statut de bkcompens_rf',''); INSERT INTO bkmoperror_code VALUES('F','069','0002','001','Code banque emetteur incorrect',''); INSERT INTO bkmoperror_code VALUES('F','069','0003','001','Erreur lors de la recherche du code banque dans bkbqe',''); INSERT INTO bkmoperror_code VALUES('F','069','0004','001','Erreur lors de la recherche du compte dans bkcom',''); INSERT INTO bkmoperror_code VALUES('F','069','0005','001','Code banque destinataire incorrect',''); INSERT INTO bkmoperror_code VALUES('F','069','0006','001','Erreur lors de l''update du sort dans bkchr',''); INSERT INTO bkmoperror_code VALUES('F','069','0007','001','Type d''operation incorrect',''); INSERT INTO bkmoperror_code VALUES('F','069','0008','001','Erreur lors de l''insertion dans bkcompens_rv_eve et tables complementaires',''); INSERT INTO bkmoperror_code VALUES('F','069','0009','001','.',''); INSERT INTO bkmoperror_code VALUES('F','069','0010','001','Probléme lors de la recherche des information du chèque',''); INSERT INTO bkmoperror_code VALUES('F','069','0011','001','Aucun événement n''est associé à la valeur d''origine',''); INSERT INTO bkmoperror_code VALUES('F','069','0012','001','Probléme lors de la recherche du chèque en recouvrement',''); INSERT INTO bkmoperror_code VALUES('F','069','0013','001','Sort du chèque déjà positionné',''); INSERT INTO bkmoperror_code VALUES('F','069','0014','001','Montant du chèque différent',''); INSERT INTO bkmoperror_code VALUES('F','069','0015','001','.',''); INSERT INTO bkmoperror_code VALUES('F','069','0016','001','.',''); INSERT INTO bkmoperror_code VALUES('F','069','0017','001','Probléme lors de la recherche de la correspondance du code rejet',''); INSERT INTO bkmoperror_code VALUES('F','069','0018','001','Code rejet inconnu',''); INSERT INTO bkmoperror_code VALUES('F','069','0019','001','Incident lors de la mise à jour du chèque de recouvrement',''); INSERT INTO bkmoperror_code VALUES('F','069','0020','001','.',''); INSERT INTO bkmoperror_code VALUES('F','069','0021','001','Chèque déjà en cours de traitement',''); INSERT INTO bkmoperror_code VALUES('F','069','0022','001','Valeur d''origine du chèque déjà en cours de traitement',''); INSERT INTO bkmoperror_code VALUES('F','069','0023','001','Erreur lors de l''insertion de données complémentaires',''); INSERT INTO bkmoperror_code VALUES('F','069','0024','001','Erreur lors de la lecture dans bkcompens_pa',''); INSERT INTO bkmoperror_code VALUES('F','069','0025','001','Erreur lors de la lecture dans bkcli',''); INSERT INTO bkmoperror_code VALUES('F','069','0026','001','Incident lors de la création de la réservation de fond',''); INSERT INTO bkmoperror_code VALUES('F','069','0027','001','Incident lors de l''insertion dans bkcompens_rv_eve',''); INSERT INTO bkmoperror_code VALUES('F','069','0028','001','.',''); INSERT INTO bkmoperror_code VALUES('F','069','0029','001','Etat de la valeur d''origine incorrect',''); INSERT INTO bkmoperror_code VALUES('F','069','0030','001','Erreur lors de la recherche de la valeur d''origine',''); INSERT INTO bkmoperror_code VALUES('F','069','0031','001','Compte en instance de fermeture pour un chèque reçu',''); INSERT INTO bkmoperror_code VALUES('F','069','0032','001','Compte fermé pour un chèque reçu',''); INSERT INTO bkmoperror_code VALUES('F','069','0033','001','.',''); INSERT INTO bkmoperror_code VALUES('F','069','0034','001','.',''); INSERT INTO bkmoperror_code VALUES('F','070','0001','001','Pas de cheques correspondants aux selections',''); INSERT INTO bkmoperror_code VALUES('F','070','0002','001','Code compte est erroné',''); INSERT INTO bkmoperror_code VALUES('F','070','0003','001','Cle erroné',''); INSERT INTO bkmoperror_code VALUES('F','070','0004','001','Informations du cheque non trouvees',''); INSERT INTO bkmoperror_code VALUES('F','070','0005','001','Enregistrement @ inexistant dans la table @',''); INSERT INTO bkmoperror_code VALUES('F','070','0006','001','Incident @ Table @ Status @',''); INSERT INTO bkmoperror_code VALUES('F','071','0001','001','La table bkcompens_af ne peut pas etre verrouillee',''); INSERT INTO bkmoperror_code VALUES('F','071','0002','001','Il n''est pas possible de fair la MAJ du fichier émis',''); INSERT INTO bkmoperror_code VALUES('F','071','0003','001','l n''y a pas de valeur liée au fichier en cours',''); INSERT INTO bkmoperror_code VALUES('F','071','0004','001','La table bkcompens_av ne peut pas etre verrouillee',''); INSERT INTO bkmoperror_code VALUES('F','071','0005','001','Il n''est pas possible de fair la MAJ des valeurs liées au fichier émis',''); INSERT INTO bkmoperror_code VALUES('F','071','0006','001','La table bkcompens_av ne peut pas etre verrouillee',''); INSERT INTO bkmoperror_code VALUES('F','071','0007','001','Il n''y a pas d''événement lié à la valeur em cours',''); INSERT INTO bkmoperror_code VALUES('F','071','0008','001','Il n''est pas possible de fair la MAJ des valeurs liées au fichier émis',''); INSERT INTO bkmoperror_code VALUES('F','071','0009','001','La table bkeve ne peut pas etre verrouillee',''); INSERT INTO bkmoperror_code VALUES('F','071','0010','001','Il n''est pas possible de fair la MAJ de la table bkeve',''); INSERT INTO bkmoperror_code VALUES('F','072','0001','001','La table bkcompens_af ne peut pas etre verrouillee',''); INSERT INTO bkmoperror_code VALUES('F','072','0002','001','Il n''est pas possible de fair la MAJ du fichier émis',''); INSERT INTO bkmoperror_code VALUES('F','072','0003','001','Il n''y a pas de valeur liée au fichier en cours',''); INSERT INTO bkmoperror_code VALUES('F','072','0004','001','La table bkcompens_av ne peut pas etre verrouillee',''); INSERT INTO bkmoperror_code VALUES('F','072','0005','001','Il n''y a pas d''événement lié à la valeur em cours',''); INSERT INTO bkmoperror_code VALUES('F','072','0006','001','Il n''est pas possible de fair la MAJ des valeurs liées au fichier émis',''); INSERT INTO bkmoperror_code VALUES('F','073','0001','001','Paramètre COMPTE inexistant en table 999',''); INSERT INTO bkmoperror_code VALUES('F','073','0002','001','gu_bl_ctrl_visu_lec_param',''); INSERT INTO bkmoperror_code VALUES('F','073','0003','001','gu_bl_ctrl_visu_init',''); INSERT INTO bkmoperror_code VALUES('F','073','0004','001','gu_bl_ctrl_visu_aff',''); INSERT INTO bkmoperror_code VALUES('F','073','0005','001','gu_bl_ctrl_visu_nav_chq',''); INSERT INTO bkmoperror_code VALUES('F','073','0006','001','gu_bl_ctrl_visu_get_sig',''); INSERT INTO bkmoperror_code VALUES('F','073','0007','001','Erreur lors de la récupération du code client du compte',''); INSERT INTO bkmoperror_code VALUES('F','073','0008','001','Erreur lors de la récupération du code numérique de la devise',''); INSERT INTO bkmoperror_code VALUES('F','073','0009','001','gu_bl_ctrl_visu_chg_side',''); INSERT INTO bkmoperror_code VALUES('F','073','0010','001','gu_bl_ctrl_visu_aff_chq',''); INSERT INTO bkmoperror_code VALUES('F','073','0011','001','Aucune image chèque trouvée',''); INSERT INTO bkmoperror_code VALUES('F','073','0012','001','Erreur lors de la récupération de l''image chèque',''); INSERT INTO bkmoperror_code VALUES('F','073','0013','001','Erreur lors de la création de la table temporaire',''); INSERT INTO bkmoperror_code VALUES('F','073','0014','001','Erreur lors du chargement du fichier dans la table temporaire',''); INSERT INTO bkmoperror_code VALUES('F','073','0015','001','gu_bl_ctrl_visu_aff_com',''); INSERT INTO bkmoperror_code VALUES('F','073','0016','001','gu_bl_ctrl_visu_aff_chq_qry',''); INSERT INTO bkmoperror_code VALUES('F','073','0017','001','La saisie d''au moins un désaccord bénéficiaire est obligatoire',''); INSERT INTO bkmoperror_code VALUES('F','073','0018','001','La saisie d''au moins un désaccord émetteur est obligatoire',''); INSERT INTO bkmoperror_code VALUES('F','073','0019','001','gu_bl_ctrl_visu_validate',''); INSERT INTO bkmoperror_code VALUES('F','073','0020','001','gu_bl_ctrl_visu_abandon',''); INSERT INTO bkmoperror_code VALUES('F','073','0021','001','Erreur lors de la conversion de l''image recto du chèque',''); INSERT INTO bkmoperror_code VALUES('F','073','0022','001','Erreur lors de la conversion de l''image verso du chèque',''); INSERT INTO bkmoperror_code VALUES('F','073','0023','001','gu_bl_ctrl_visu_fin_prog',''); INSERT INTO bkmoperror_code VALUES('F','074','0001','001','Erreur lors de l''initialisation du contrôle visuel',''); INSERT INTO bkmoperror_code VALUES('F','074','0002','001','Erreur lors de la validation du contrôle visuel',''); INSERT INTO bkmoperror_code VALUES('F','074','0003','001','Problème lors du contrôle du combo',''); INSERT INTO bkmoperror_code VALUES('F','074','0004','001','Problème lors du contrôle du combo',''); INSERT INTO bkmoperror_code VALUES('F','074','0005','001','Problème lors du contrôle du combo',''); INSERT INTO bkmoperror_code VALUES('F','074','0006','001','Problème lors du contrôle du combo',''); INSERT INTO bkmoperror_code VALUES('F','074','0007','001','Problème lors du contrôle du combo',''); INSERT INTO bkmoperror_code VALUES('F','074','0008','001','Problème lors du contrôle du combo',''); INSERT INTO bkmoperror_code VALUES('F','074','0009','001','Erreur lors de la fin de session de signatures',''); INSERT INTO bkmoperror_code VALUES('F','074','0010','001','Sortie du traitement de l''écran de détail du contrôle visuel',''); INSERT INTO bkmoperror_code VALUES('F','075','0001','001','Chèque deja emis',''); INSERT INTO bkmoperror_code VALUES('F','075','0002','001','Erreur lors de la recherche d''un cheque dans bkeve',''); INSERT INTO bkmoperror_code VALUES('F','075','0003','001','Erreur lors de la recherche du cheque dans bkchq',''); INSERT INTO bkmoperror_code VALUES('F','075','0004','001','Cheque en doublon',''); INSERT INTO bkmoperror_code VALUES('F','075','0005','001','Cheque inconnu',''); INSERT INTO bkmoperror_code VALUES('F','075','0006','001','Montant different du cheque de banque',''); INSERT INTO bkmoperror_code VALUES('F','075','0007','001','Montant différent du cheque certifié',''); INSERT INTO bkmoperror_code VALUES('F','075','0008','001','Cheque non distribué',''); INSERT INTO bkmoperror_code VALUES('F','075','0009','001','Cheque soldé',''); INSERT INTO bkmoperror_code VALUES('F','075','0010','001','Erreur lors de la rechercher du chèques en recouvrement',''); INSERT INTO bkmoperror_code VALUES('F','075','0011','001','Chèque en recouvrement non trouvé',''); INSERT INTO bkmoperror_code VALUES('F','075','0012','001','Erreur lors de la rechercher du chèques en recouvrement',''); INSERT INTO bkmoperror_code VALUES('F','076','0001','001','Erreur lors du traitement du fichier',''); INSERT INTO bkmoperror_code VALUES('F','077','0001','001','Erreur lors de la validation',''); INSERT INTO bkmoperror_code VALUES('F','077','0002','001','Erreur lors de la recherche du compte',''); INSERT INTO bkmoperror_code VALUES('F','077','0003','001','Erreur lors de la recherche du code opération',''); INSERT INTO bkmoperror_code VALUES('F','077','0004','001','Erreur lors de la recherche du paramétre GES-INCO',''); INSERT INTO bkmoperror_code VALUES('F','077','0005','001','Paramétre GES-INCO non renseigné',''); INSERT INTO bkmoperror_code VALUES('T','078','0001','001','Enregistrement Age, Ope, Eve inexistant dans la table bkchr',''); INSERT INTO bkmoperror_code VALUES('T','078','0002','001','Erreur dans les tables bkchr, bkcompens_av_eve, bkcompens_av',''); INSERT INTO bkmoperror_code VALUES('T','078','0003','001','Erreur update table bkchr',''); INSERT INTO bkmoperror_code VALUES('T','078','0004','001','Incident table bkcompens_av_chq',''); INSERT INTO bkmoperror_code VALUES('T','078','0005','001','Incident UPDATE tables des valeurs émises',''); INSERT INTO bkmoperror_code VALUES('T','078','0006','001','Erreur lors de fonction api_gu_genvir_abrvir',''); INSERT INTO bkmoperror_code VALUES('T','078','0007','001','Erreur lors de fonction gu_bl_cmp_dao_lock_bkcompens_av',''); INSERT INTO bkmoperror_code VALUES('T','078','0008','001','Erreur lors de fonction api_gu_genvir_anuvir',''); INSERT INTO bkmoperror_code VALUES('T','078','0009','001','Erreur lors de fonction api_gu_genvir_resvir',''); INSERT INTO bkmoperror_code VALUES('F','079','0001','001','Erreur lors du lock d''une valeur sur bkcompens_rv',''); INSERT INTO bkmoperror_code VALUES('F','079','0002','001','Erreur lors de l''appel a api_gu_genchq_COMCHE',''); INSERT INTO bkmoperror_code VALUES('F','079','0003','001','Erreur lors du select cheques',''); INSERT INTO bkmoperror_code VALUES('F','079','0004','001','Erreur lors de l''appel a api_gu_genvir_COMVIR',''); INSERT INTO bkmoperror_code VALUES('F','079','0005','001','Erreur lors de l''appel a resolve erreur',''); INSERT INTO bkmoperror_code VALUES('F','079','0006','001','Erreur lors de l''appel a update valeur recue',''); INSERT INTO bkmoperror_code VALUES('F','079','0007','001','Erreur lors de l''appel a genvir_abcvir',''); INSERT INTO bkmoperror_code VALUES('F','079','0008','001','Erreur lors de l''appel a genvir_retvir',''); INSERT INTO bkmoperror_code VALUES('F','079','0009','001','Erreur lors de l''appel a VIRBQE',''); INSERT INTO bkmoperror_code VALUES('F','080','0001','001','Incident lors de l''insertion d''un message à poster','Revoir la structure de la table bkpostmsg ou contacter la Hotline.'); INSERT INTO bkmoperror_code VALUES('F','081','0001','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0002','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0003','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0004','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0005','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0006','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0007','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0008','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0009','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0010','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0011','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0012','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0013','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0014','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0015','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0016','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0017','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0018','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0019','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0020','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0021','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0022','001','.',''); INSERT INTO bkmoperror_code VALUES('F','081','0023','001','.',''); INSERT INTO bkmoperror_code VALUES('F','082','0001','001','Impossible de charger le fichier PSR',''); INSERT INTO bkmoperror_code VALUES('F','082','0002','001','Chemin du PSR non renseigne',''); INSERT INTO bkmoperror_code VALUES('F','082','0003','001','Alimentation erronee table PSR message',''); INSERT INTO bkmoperror_code VALUES('F','082','0004','001','Alimentation erronee table PSR Lot',''); INSERT INTO bkmoperror_code VALUES('F','082','0005','001','Alimentation erronee table PSR Transactions',''); INSERT INTO bkmoperror_code VALUES('F','082','0006','001','Rupture Fin Lot en erreur',''); INSERT INTO bkmoperror_code VALUES('F','082','0007','001','Creation PSR erronee',''); INSERT INTO bkmoperror_code VALUES('F','082','0008','001','Aucun Message à traiter pour l''identifiant',''); INSERT INTO bkmoperror_code VALUES('F','082','0009','001','Creation table temporaire tmppsr erronee',''); INSERT INTO bkmoperror_code VALUES('F','082','0010','001','.',''); INSERT INTO bkmoperror_code VALUES('F','082','0011','001','.',''); INSERT INTO bkmoperror_code VALUES('F','082','0012','001','Canal non renseigné',''); INSERT INTO bkmoperror_code VALUES('F','082','0013','001','Contenu du PAIN non renseigné',''); INSERT INTO bkmoperror_code VALUES('F','083','0001','001','Incident sur creation de sequence de base de donnees','Contacter la hotline'); INSERT INTO bkmoperror_code VALUES('F','083','0002','001','Incident sur selection de sequence de base de donnees','Contacter la hotline'); INSERT INTO bkmoperror_code VALUES('F','083','0003','001','Incident lors de la suppression d''une séquence',''); INSERT INTO bkmoperror_code VALUES('F','084','0001','001','Données déjà en cours d''utilisation',''); INSERT INTO bkmoperror_code VALUES('F','084','0002','001','Erreur SQL',''); INSERT INTO bkmoperror_code VALUES('F','084','0003','001','Données déjà en cours d''utilisation',''); INSERT INTO bkmoperror_code VALUES('F','084','0004','001','Erreur SQL',''); INSERT INTO bkmoperror_code VALUES('F','084','0005','001','.',''); INSERT INTO bkmoperror_code VALUES('F','084','0006','001','Code opération non trouvé',''); INSERT INTO bkmoperror_code VALUES('F','084','0007','001','Opération de nuit déjà en cours d''utilisation',''); INSERT INTO bkmoperror_code VALUES('F','084','0008','001','Erreur SQL',''); INSERT INTO bkmoperror_code VALUES('F','084','0009','001','Opération de nuit déjà en cours d''utilisation',''); INSERT INTO bkmoperror_code VALUES('F','084','0010','001','Erreur SQL',''); INSERT INTO bkmoperror_code VALUES('F','084','0011','001','.',''); INSERT INTO bkmoperror_code VALUES('F','084','0012','001','Code opération de nuit non trouvé',''); INSERT INTO bkmoperror_code VALUES('F','084','0013','001','.',''); INSERT INTO bkmoperror_code VALUES('F','084','0014','001','.',''); INSERT INTO bkmoperror_code VALUES('F','084','0015','001','Table d''operation inconnue',''); INSERT INTO bkmoperror_code VALUES('F','084','0016','001','Impossible de mettre à jour le num de l''opération',''); INSERT INTO bkmoperror_code VALUES('F','084','0017','001','.',''); INSERT INTO bkmoperror_code VALUES('F','084','0018','001','.',''); INSERT INTO bkmoperror_code VALUES('F','084','0019','001','.',''); INSERT INTO bkmoperror_code VALUES('F','084','0020','001','.',''); INSERT INTO bkmoperror_code VALUES('F','084','0021','001','Méthode de calcul de numéro d''événement inconnue',''); INSERT INTO bkmoperror_code VALUES('F','084','0022','001','.',''); INSERT INTO bkmoperror_code VALUES('F','084','0023','001','.',''); INSERT INTO bkmoperror_code VALUES('F','084','0024','001','.',''); INSERT INTO bkmoperror_code VALUES('F','084','0025','001','Impossible de determiner la situation des soldes',''); INSERT INTO bkmoperror_code VALUES('F','084','0026','001','Soldes indisponibles',''); INSERT INTO bkmoperror_code VALUES('F','084','0027','001','.',''); INSERT INTO bkmoperror_code VALUES('F','084','0028','001','.',''); INSERT INTO bkmoperror_code VALUES('F','084','0029','001','Opération de nuit déjà en cours d''utilisation',''); INSERT INTO bkmoperror_code VALUES('F','084','0030','001','Opération de jour déjà en cours d''utilisation',''); INSERT INTO bkmoperror_code VALUES('F','085','0001','001','.',''); INSERT INTO bkmoperror_code VALUES('F','085','0002','001','.',''); INSERT INTO bkmoperror_code VALUES('F','086','0001','001','.',''); INSERT INTO bkmoperror_code VALUES('F','086','0002','001','.',''); INSERT INTO bkmoperror_code VALUES('F','087','0001','001','Probléme d''initialisation de l''interface',''); INSERT INTO bkmoperror_code VALUES('F','087','0002','001','Probléme lors du traitement de l''interface',''); INSERT INTO bkmoperror_code VALUES('F','087','0003','001','.',''); INSERT INTO bkmoperror_code VALUES('F','087','0004','001','Probléme lors de la fermeture du message',''); INSERT INTO bkmoperror_code VALUES('F','087','0005','001','Probléme lors de l''envoi du flux converti',''); INSERT INTO bkmoperror_code VALUES('F','087','0006','001','Probléme lors de la sauvegarde du flux converti',''); INSERT INTO bkmoperror_code VALUES('F','087','0007','001','Probléme lors de la fermeture de l''interface',''); INSERT INTO bkmoperror_code VALUES('F','087','0008','001','Répertoire des rapports mal configuré',''); INSERT INTO bkmoperror_code VALUES('F','088','0001','001','Probléme d''initialisation du flux XML avec le contenu reçu',''); INSERT INTO bkmoperror_code VALUES('F','088','0002','001','Probléme d''initialisation du flux XML avec le chemin reçu',''); INSERT INTO bkmoperror_code VALUES('F','088','0003','001','Type de flux indétérminé',''); INSERT INTO bkmoperror_code VALUES('F','088','0004','001','Type de flux incorrect',''); INSERT INTO bkmoperror_code VALUES('F','088','0005','001','Erreur lors de la conversion',''); INSERT INTO bkmoperror_code VALUES('F','088','0006','001','répertoire XSLT mal configuré',''); INSERT INTO bkmoperror_code VALUES('F','088','0007','001','.',''); INSERT INTO bkmoperror_code VALUES('F','088','0008','001','.',''); INSERT INTO bkmoperror_code VALUES('F','089','0001','001','Code composé non trouvé',''); INSERT INTO bkmoperror_code VALUES('F','089','0002','001','Plusieurs codes composé trouvée',''); INSERT INTO bkmoperror_code VALUES('F','089','0003','001','Probléme lors de la recherche de code composé',''); INSERT INTO bkmoperror_code VALUES('F','090','0001','001','Compte CMPINCTRF0 inexistant en table 094',''); INSERT INTO bkmoperror_code VALUES('F','090','0002','001','Compte CMPSUSPENS inexistant en table 094',''); INSERT INTO bkmoperror_code VALUES('F','090','0003','001','Compte CMPRETURN0 inexistant en table 094',''); INSERT INTO bkmoperror_code VALUES('F','090','0004','001','Compte CMPCANCELC inexistant en table 094',''); INSERT INTO bkmoperror_code VALUES('F','090','0005','001','Compte CMPOUTTRF0 inexistant en table 094',''); INSERT INTO bkmoperror_code VALUES('F','090','0006','001','Compte CMPREJECT0 inexistant en table 094',''); INSERT INTO bkmoperror_code VALUES('F','090','0007','001','Compte CMPCANCELR inexistant en table 094',''); INSERT INTO bkmoperror_code VALUES('F','090','0008','001','Problème lors de la lecture de la nature d''opération ISAVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0009','001','Problème lors de la lecture de l''opération liée à ISAVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0010','001','Problème lors de la lecture de la nature d''opération RETVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0011','001','Problème lors de la lecture de l''opération liée à RETVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0012','001','Problème lors de la lecture de la nature d''opération ABCVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0013','001','Problème lors de la lecture de l''opération liée à ABCVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0014','001','Problème lors de la lecture de la nature d''opération REJVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0015','001','Problème lors de la lecture de l''opération liée à REJVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0016','001','Problème lors de la lecture de la nature d''opération RESVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0017','001','Problème lors de la lecture de l''opération liée à RESVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0018','001','Problème lors de la lecture de la nature d''opération ABRVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0019','001','Problème lors de la lecture de l''opération liée à ABRVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0020','001','Problème lors de la lecture de la nature d''opération ANUVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0021','001','Problème lors de la lecture de l''opération liée à ANUVIR',''); INSERT INTO bkmoperror_code VALUES('F','090','0022','001','Erreur lors de la lecture du compte client',''); INSERT INTO bkmoperror_code VALUES('F','090','0023','001','Erreur lors de la lecture des informations client',''); INSERT INTO bkmoperror_code VALUES('F','090','0024','001','Erreur lors du contrôle de désaccords sur le compte',''); INSERT INTO bkmoperror_code VALUES('F','090','0025','001','Erreur lors du second contrôle de désaccords sur le compte',''); INSERT INTO bkmoperror_code VALUES('F','090','0026','001','Erreur lors de la mise à jours des données',''); INSERT INTO bkmoperror_code VALUES('F','091','0001','001','Erreur lors de la lecture de l''évènement',''); INSERT INTO bkmoperror_code VALUES('F','091','0002','001','Evènement inexistant',''); INSERT INTO bkmoperror_code VALUES('F','091','0003','001','Erreur lors de la lecture du compte',''); INSERT INTO bkmoperror_code VALUES('F','091','0004','001','Compte inexistant',''); INSERT INTO bkmoperror_code VALUES('F','091','0005','001','Erreur lors de la mise à jour du compte lié à l''évènement COMVIR',''); INSERT INTO bkmoperror_code VALUES('F','091','0006','001','Erreur lors de la mise à jour du compte lié à l''évènement COMCHE',''); INSERT INTO bkmoperror_code VALUES('F','091','0007','001','Erreur lors de la mise à jour du compte',''); INSERT INTO bkmoperror_code VALUES('F','091','0008','001','Erreur lors de la mise à jour de l''évènement',''); INSERT INTO bkmoperror_code VALUES('T','093','0001','001','Date de compensation non trouvée',''); INSERT INTO bkmoperror_code VALUES('T','093','0002','001','Erreur lors de la mise à jour de bkcompens_av (zone et eta)',''); INSERT INTO bkmoperror_code VALUES('T','093','0003','001','Erreur lors de l''alimentation de bkcompens_af et bkcompens_af_eta',''); INSERT INTO bkmoperror_code VALUES('T','093','0004','001','Erreur lors de la génération du fichier',''); INSERT INTO bkmoperror_code VALUES('T','093','0005','001','Erreur lors de la recherche de VALA dans bkcompens_av_ieve',''); INSERT INTO bkmoperror_code VALUES('T','093','0006','001','Erreur lors de la recherche de VALA dans bkibqe',''); INSERT INTO bkmoperror_code VALUES('T','093','0007','001','Erreur lors de la recherche des motifs dans bkcompens_av_trf',''); INSERT INTO bkmoperror_code VALUES('T','093','0008','001','Erreir lors de l''update de bkcompens_av pendant la generation de fichier',''); INSERT INTO bkmoperror_code VALUES('F','094','0001','001','compte et ncp non renseigné','Modifier les parametres'); INSERT INTO bkmoperror_code VALUES('F','094','0002','001','client non trouvé','Relancer un programme'); INSERT INTO bkmoperror_code VALUES('T','095','0001','001','Erreur SEL_COUNT bkcompens_rf',''); INSERT INTO bkmoperror_code VALUES('T','095','0002','001','Le fichier a déjà été intégré',''); INSERT INTO bkmoperror_code VALUES('T','095','0003','001','Erreur lors de la lecture du paramètre 098.BANQUE',''); INSERT INTO bkmoperror_code VALUES('T','095','0004','001','Paramètre CLEARING_BRANCH inexistant dans la catégorie GENERAL',''); INSERT INTO bkmoperror_code VALUES('T','095','0005','001','Format de fichier reçu incorrect',''); INSERT INTO bkmoperror_code VALUES('T','095','0006','001','Format détail/pied incorrect',''); INSERT INTO bkmoperror_code VALUES('T','095','0007','001','Nombre de transactions différent du nombre de transactions calculé',''); INSERT INTO bkmoperror_code VALUES('T','095','0008','001','Format entête incorrect',''); INSERT INTO bkmoperror_code VALUES('T','095','0009','001','Structure entête incorrecte',''); INSERT INTO bkmoperror_code VALUES('T','095','0010','001','Date entête incohérente avec celle du nom de fichier',''); INSERT INTO bkmoperror_code VALUES('T','095','0011','001','Type de transaction incorrect',''); INSERT INTO bkmoperror_code VALUES('T','095','0012','001','Code destinataire du détail différent de celui de l''entête',''); INSERT INTO bkmoperror_code VALUES('T','095','0013','001','Paramètre CLEARING_CURRENCY inexistant dans la catégorie GENERAL',''); INSERT INTO bkmoperror_code VALUES('T','095','0014','001','Devise différente de la devise de compensation',''); INSERT INTO bkmoperror_code VALUES('T','095','0015','001','Le montant n''est pas numérique',''); INSERT INTO bkmoperror_code VALUES('T','095','0016','001','Le code émetteur CITAD est inexistant dans les données complémentaires de la fiche banque',''); INSERT INTO bkmoperror_code VALUES('T','095','0017','001','Code destinataire du pied différent de celui de l''entête',''); INSERT INTO bkmoperror_code VALUES('T','095','0018','001','Date de transaction du pied différent de celle de l''entête',''); INSERT INTO bkmoperror_code VALUES('T','095','0019','001','Incident SELECT_vala bkibqe',''); INSERT INTO bkmoperror_code VALUES('T','095','0020','001','Incident SELECT_etab_guib bkibqe',''); INSERT INTO bkmoperror_code VALUES('T','095','0021','001','Erreur lors de la création de la table temporaire',''); INSERT INTO bkmoperror_code VALUES('T','095','0022','001','Erreur lors du chargement de la table temporaire',''); INSERT INTO bkmoperror_code VALUES('T','095','0023','001','Lecture d''un fichier vide',''); INSERT INTO bkmoperror_code VALUES('T','095','0024','001','gu_bl_cmprec_spec_vietnam_controle_detail_vir',''); INSERT INTO bkmoperror_code VALUES('T','095','0025','001','gu_bl_cmprec_spec_vietnam_alim_valeur',''); INSERT INTO bkmoperror_code VALUES('T','095','0026','001','Incident EXECUTE bkcompens_rf',''); INSERT INTO bkmoperror_code VALUES('T','095','0027','001','gu_bl_cmprec_spec_vietnam_maj_tables',''); INSERT INTO bkmoperror_code VALUES('T','095','0028','001','gu_bl_cmprec_spec_vietnam_maj_tables',''); INSERT INTO bkmoperror_code VALUES('T','095','0029','001','gu_bl_cmprec_spec_vietnam_maj_tables',''); INSERT INTO bkmoperror_code VALUES('T','095','0030','001','gu_bl_cmprec_spec_vietnam_maj_tables',''); INSERT INTO bkmoperror_code VALUES('T','095','0031','001','gu_bl_cmprec_spec_vietnam_maj_tables',''); INSERT INTO bkmoperror_code VALUES('T','095','0032','001','gu_bl_cmprec_spec_vietnam_maj_tables',''); INSERT INTO bkmoperror_code VALUES('T','095','0033','001','gu_bl_cmprec_spec_vietnam_maj_tables',''); INSERT INTO bkmoperror_code VALUES('T','095','0034','001','gu_bl_cmprec_spec_vietnam_maj_tables',''); INSERT INTO bkmoperror_code VALUES('F','096','0001','001','Parametre manquant',''); INSERT INTO bkmoperror_code VALUES('F','096','0002','001','Parametre inexistant en table',''); INSERT INTO bkmoperror_code VALUES('F','096','0003','001','Agence de compensation non paramétrée',''); INSERT INTO bkmoperror_code VALUES('F','096','0004','001','Probleme de lecture des donnees en table',''); INSERT INTO bkmoperror_code VALUES('F','096','0005','001','Probléme de lecture du paramétre CHEQUE_TRIGGERING_FATE',''); INSERT INTO bkmoperror_code VALUES('F','096','0006','001','Impossible de récupéret le délai de réglement',''); INSERT INTO bkmoperror_code VALUES('F','096','0007','001','Impossible de récupéret le délai de réglement',''); INSERT INTO bkmoperror_code VALUES('F','096','0008','001','.',''); INSERT INTO bkmoperror_code VALUES('F','097','0001','001','Parametre manquant',''); INSERT INTO bkmoperror_code VALUES('F','098','0001','001','test',''); INSERT INTO bkmoperror_code VALUES('F','098','0002','001','Aucune valeur à traiter',''); INSERT INTO bkmoperror_code VALUES('F','099','0001','001','Erreur de paramétrage','Vérifier le paramétrage'); INSERT INTO bkmoperror_code VALUES('F','100','0001','001','Parametre CHEQUE_TRIGGERING_FATE mal parametre',''); INSERT INTO bkmoperror_code VALUES('F','100','0002','001','Parametre CHEQUE_REASON_REJECT mal parametre',''); INSERT INTO bkmoperror_code VALUES('F','100','0003','001','Erreur lors de la recuperation des informations de la table ''bkchr''',''); INSERT INTO bkmoperror_code VALUES('F','100','0004','001','Donnee(s) en cours de traitement',''); INSERT INTO bkmoperror_code VALUES('F','100','0005','001','Cheque deja paye',''); INSERT INTO bkmoperror_code VALUES('F','100','0006','001','Cheque deja impaye',''); INSERT INTO bkmoperror_code VALUES('F','100','0007','001','Sort du cheque deja positionne.',''); INSERT INTO bkmoperror_code VALUES('F','100','0008','001','Erreur lors de la mise à jour de ''bkchr''',''); INSERT INTO bkmoperror_code VALUES('F','100','0009','001','Erreur lors de la recherche du compte à débiter pour le sort impayé',''); INSERT INTO bkmoperror_code VALUES('F','100','0010','001','Erreur lors de la recherche du client à débiter pour le sort impayé',''); INSERT INTO bkmoperror_code VALUES('T','101','0001','001','Erreur lors de la suppression des exceptions aller',''); INSERT INTO bkmoperror_code VALUES('T','101','0002','001','Erreur lors de la suppression des exceptions retour',''); INSERT INTO bkmoperror_code VALUES('T','101','0003','001','Erreur lors de l''insertion de l''exception aller',''); INSERT INTO bkmoperror_code VALUES('T','101','0004','001','Erreur lors de l''insertion de l''exception retour',''); INSERT INTO bkmoperror_code VALUES('T','101','0005','001','Probleme de mise à jour des exception pour un systeme de compensation',''); INSERT INTO bkmoperror_code VALUES('T','102','0001','001','Paramétrage de la devise nationale incorrect ou inexistant',''); INSERT INTO bkmoperror_code VALUES('T','102','0002','001','Paramètre COMPTE inexistant en T999',''); INSERT INTO bkmoperror_code VALUES('T','102','0003','001','La saisie de l''''agence est obligatoire',''); INSERT INTO bkmoperror_code VALUES('T','102','0004','001','L''''agence saisie est incorrecte',''); INSERT INTO bkmoperror_code VALUES('T','102','0005','001','Le code banque saisi doit être différent de la banque locale',''); INSERT INTO bkmoperror_code VALUES('T','102','0006','001','Le numéro de compte doit être numérique',''); INSERT INTO bkmoperror_code VALUES('T','102','0007','001','La longueur du numéro de compte est incorrecte',''); INSERT INTO bkmoperror_code VALUES('T','102','0008','001','Erreur lors du contrôle du compte',''); INSERT INTO bkmoperror_code VALUES('T','102','0009','001','La clé de compte est erronée',''); INSERT INTO bkmoperror_code VALUES('T','102','0010','001','Le numéro de chèque doit être numérique',''); INSERT INTO bkmoperror_code VALUES('T','102','0011','001','Paramétrage de la devise saisie incorrect ou inexistant',''); INSERT INTO bkmoperror_code VALUES('T','102','0012','001','Le montant saisi doit être numérique',''); INSERT INTO bkmoperror_code VALUES('T','102','0013','001','Le second montant saisi doit être supérieur ou égal au premier montant saisi',''); INSERT INTO bkmoperror_code VALUES('T','102','0014','001','Erreur technique lors de la récupération du compte',''); INSERT INTO bkmoperror_code VALUES('T','102','0015','001','Erreur technique lors de la récupération de la banque',''); INSERT INTO bkmoperror_code VALUES('T','102','0016','001','La banque saisie est inexistante',''); INSERT INTO bkmoperror_code VALUES('T','102','0017','001','gurdccvisu_controle_saisie',''); INSERT INTO bkmoperror_code VALUES('T','102','0018','001','Le suffixe saisi doit être numérique',''); INSERT INTO bkmoperror_code VALUES('T','102','0019','001','gurdccvisu_lec_param',''); INSERT INTO bkmoperror_code VALUES('T','102','0020','001','Aucune donnée sélectionnée',''); INSERT INTO bkmoperror_code VALUES('T','102','0021','001','Erreur lors de la récupération des images chèques',''); INSERT INTO bkmoperror_code VALUES('T','102','0022','001','Erreur technique lors de la récupération du nom du client',''); INSERT INTO bkmoperror_code VALUES('T','102','0023','001','Le client n''''existe pas',''); INSERT INTO bkmoperror_code VALUES('T','102','0024','001','Erreur lors du verrouillage d''''un enregistrement de bkdetchqd',''); INSERT INTO bkmoperror_code VALUES('T','102','0025','001','gurdccvisu_traitement',''); INSERT INTO bkmoperror_code VALUES('T','102','0026','001','gurdccvisu_maj_val',''); INSERT INTO bkmoperror_code VALUES('T','102','0027','001','Erreur lors de la mise à jour de la table bkdetchqd',''); INSERT INTO bkmoperror_code VALUES('T','102','0028','001','Erreur lors de la mise à jour de la table bkrdcrv',''); INSERT INTO bkmoperror_code VALUES('T','102','0029','001','La saisie de la banque est obigatoire',''); INSERT INTO bkmoperror_code VALUES('T','102','0030','001','La saisie du compte est obligatoire',''); INSERT INTO bkmoperror_code VALUES('T','102','0031','001','La saisie de l''''agence est obligatoire',''); INSERT INTO bkmoperror_code VALUES('T','102','0032','001','La saisie du suffixe est obligatoire',''); INSERT INTO bkmoperror_code VALUES('T','102','0033','001','La saisie du compte est obligatoire',''); INSERT INTO bkmoperror_code VALUES('T','102','0034','001','La saisie de la clé du compte est obligatoire',''); INSERT INTO bkmoperror_code VALUES('T','102','0035','001','La saisie de la devise est obligatoire',''); INSERT INTO bkmoperror_code VALUES('T','102','0036','001','Paramétrage de la devise nationale incorrect ou inexistant',''); INSERT INTO bkmoperror_code VALUES('T','102','0037','001','gurdccvisu_lec_param',''); INSERT INTO bkmoperror_code VALUES('T','102','0038','001','gurdccvisu_lec_param',''); INSERT INTO bkmoperror_code VALUES('T','102','0039','001','gurdccvisu_lec_param',''); INSERT INTO bkmoperror_code VALUES('T','102','0040','001','Erreur technique lors de la récupération du compte',''); INSERT INTO bkmoperror_code VALUES('T','102','0041','001','Erreur technique lors de la récupération du compte',''); INSERT INTO bkmoperror_code VALUES('T','102','0042','001','gurdccvisu_traitement',''); INSERT INTO bkmoperror_code VALUES('T','102','0043','001','gurdccvisu_traitement',''); INSERT INTO bkmoperror_code VALUES('T','102','0044','001','L''''agence saisie est incorrecte',''); INSERT INTO bkmoperror_code VALUES('T','102','0045','001','gurdccvisu_controle_saisie',''); INSERT INTO bkmoperror_code VALUES('T','102','0046','001','gurdccvisu_controle_saisie',''); INSERT INTO bkmoperror_code VALUES('T','102','0047','001','Erreur lors du contrôle du compte',''); INSERT INTO bkmoperror_code VALUES('T','102','0048','001','Le montant saisi doit être numérique',''); INSERT INTO bkmoperror_code VALUES('T','102','0049','001','La banque saisie est inexistante',''); INSERT INTO bkmoperror_code VALUES('T','102','0050','001','Erreur technique lors de la récupération de la banque',''); INSERT INTO bkmoperror_code VALUES('T','102','0051','001','Erreur technique lors de la récupération de la banque',''); INSERT INTO bkmoperror_code VALUES('T','102','0052','001','Erreur technique lors de la récupération de la banque',''); INSERT INTO bkmoperror_code VALUES('T','102','0053','001','Erreur lors du verrouillage d''''un enregistrement de bkdetchqd',''); INSERT INTO bkmoperror_code VALUES('T','102','0054','001','gurdccvisu_maj_val',''); INSERT INTO bkmoperror_code VALUES('T','102','0055','001','gurdccvisu_maj_val',''); INSERT INTO bkmoperror_code VALUES('T','102','0056','001','gurdccvisu_maj_val',''); INSERT INTO bkmoperror_code VALUES('F','103','0001','001','Impossible de determiner le code opération de l''événement de creation de reservation de fonds',''); INSERT INTO bkmoperror_code VALUES('F','103','0002','001','Code opération mal paramétré pour RESERV',''); INSERT INTO bkmoperror_code VALUES('F','103','0003','001','Compte de la reservation inconnu',''); INSERT INTO bkmoperror_code VALUES('F','103','0004','001','Impossible de calculer le numéro d''événement d''une réservation de fonds',''); INSERT INTO bkmoperror_code VALUES('F','103','0005','001','Erreur lors de l''alimentation de la table bkidenreserv',''); INSERT INTO bkmoperror_code VALUES('F','103','0006','001','Code opération mal paramétré pour RESCRE',''); INSERT INTO bkmoperror_code VALUES('F','103','0007','001','Impossible de determiner le code opération de l''événement de creation de reservation de fonds',''); INSERT INTO bkmoperror_code VALUES('F','103','0008','001','Impossible de calculer le numéro d''événement d''une réservation de fonds',''); INSERT INTO bkmoperror_code VALUES('F','103','0009','001','Compte de la reservation inconnu',''); INSERT INTO bkmoperror_code VALUES('F','104','0001','001','Catégorie inexistante.',''); INSERT INTO bkmoperror_code VALUES('F','104','0002','001','La banque du bénéficiaire doit être au format BIC et l''agence renseignée.',''); INSERT INTO bkmoperror_code VALUES('F','104','0003','001','Le compte du bénéficiaire doit être au format BBAN.',''); INSERT INTO bkmoperror_code VALUES('F','104','0004','001','Le BIC de la banque bénéficiaire n''est pas membre à EBC.',''); INSERT INTO bkmoperror_code VALUES('F','104','0005','001','Incident SQL.',''); INSERT INTO bkmoperror_code VALUES('F','104','0006','001','Le BIC / agence de la banque bénéficiaire n''est pas membre à EBC.',''); INSERT INTO bkmoperror_code VALUES('F','104','0007','001','Instruction pour le créditeur inexistante.',''); INSERT INTO bkmoperror_code VALUES('F','104','0008','001','Le nombre de motif structuré et le nombre de motif non structuré sont différent de 0.',''); INSERT INTO bkmoperror_code VALUES('F','104','0009','001','Le nombre de motif non structuré est strictement supérieur à 1.',''); INSERT INTO bkmoperror_code VALUES('F','104','0010','001','Le nombre de motif structuré est strictement supérieur à 1.',''); INSERT INTO bkmoperror_code VALUES('F','104','0011','001','La longueur des informations sur la transaction est supérieur à 140 caractères.',''); INSERT INTO bkmoperror_code VALUES('F','104','0012','001','Les frais peuvent uniquement être partagés ou selon le servie level.',''); INSERT INTO bkmoperror_code VALUES('F','104','0013','001','Virement uniquement.',''); INSERT INTO bkmoperror_code VALUES('F','104','0014','001','Objet inexistant.',''); --Langue : 002 INSERT INTO bkmoperror_code VALUES('T','001','0001','002','Wrong database type. It must either be PROD, or PRE-PROD, or HOMOLOGATION.','Correct the settings of parameter "TYPE_BASE" in table of codes "098".'); INSERT INTO bkmoperror_code VALUES('T','001','0002','002','Parameter not set properly.','The parameter mentioned in the error message is not properly set. Correct the settings of the parameter using parameter management program "cbitfparam".'); INSERT INTO bkmoperror_code VALUES('T','001','0003','002','Missing parameter.','The mentioned parameter is not set, which implies that the coding system of parameters might not be up-to-date. Contact the Delta-Bank Support.'); INSERT INTO bkmoperror_code VALUES('T','001','0004','002','Problem while setting interfaces.',''); INSERT INTO bkmoperror_code VALUES('T','001','0005','002','Problem while processing interfaces.',''); INSERT INTO bkmoperror_code VALUES('T','001','0006','002','Problem while closing the interface.',''); INSERT INTO bkmoperror_code VALUES('T','001','0007','002','Error code missing from coding system!','The coding system of error codes (tables "bkmoperror_cat" and "bkmoperror_code") is not up-to-date. Contact the Delta-Bank Support.'); INSERT INTO bkmoperror_code VALUES('T','001','0008','002','Temporary work folder not found.',''); INSERT INTO bkmoperror_code VALUES('T','001','0009','002','Default accounting of transfers not set',''); INSERT INTO bkmoperror_code VALUES('T','001','0010','002','Default accounting of debits not set',''); INSERT INTO bkmoperror_code VALUES('T','001','0011','002','Incorrect BIC code in the central site bank definition','Modify the central site bank definition'); INSERT INTO bkmoperror_code VALUES('T','001','0012','002','Local IBAN size not set properly',''); INSERT INTO bkmoperror_code VALUES('T','002','0001','002','XSD validation failed.','Verify the stream, verify the XSD.'); INSERT INTO bkmoperror_code VALUES('T','003','0001','002','Simulation stream integrated into a production database.',''); INSERT INTO bkmoperror_code VALUES('T','003','0002','002','Production stream integrated into a test database (pre-prod or homologation).',''); INSERT INTO bkmoperror_code VALUES('T','003','0003','002','Pre-production stream integrated into a homologation database.',''); INSERT INTO bkmoperror_code VALUES('T','003','0004','002','Homologation stream integrated into a pre-production database.',''); INSERT INTO bkmoperror_code VALUES('T','003','0005','002','Pre-production stream integrated into a production database.',''); INSERT INTO bkmoperror_code VALUES('T','003','0006','002','Homologation stream integrated into a production database.',''); INSERT INTO bkmoperror_code VALUES('T','003','0007','002','Receipt of a stream generated by the Delta-Bank simulator of the payment order initiation service, on an environment that is not a test environment.','Verify the environment and routing of streams; if stream routing is correct and if the environment is a test environment, then set the environment variable TEST_CONNECTOR to 1.'); INSERT INTO bkmoperror_code VALUES('T','003','0008','002','Stream identifier not specified.',''); INSERT INTO bkmoperror_code VALUES('T','004','0001','002','Impossible to calculate the stream MD5 key.',''); INSERT INTO bkmoperror_code VALUES('T','004','0002','002','MD5 key duplicated: potential stream duplication.',''); INSERT INTO bkmoperror_code VALUES('T','004','0003','002','Transaction potentially duplicated.',''); INSERT INTO bkmoperror_code VALUES('T','004','0004','002','All transactions in the batch in error.',''); INSERT INTO bkmoperror_code VALUES('T','005','0001','002','ISO rule ''PaymentTypeInformationRule'' not respected.','The payment type must be indicated either in total, or unitarily per loan, or it must be absent.'); INSERT INTO bkmoperror_code VALUES('T','005','0002','002','ISO rule ''ChequeInstructionRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0003','002','ISO rule ''ChargesAccountRule'' not respected.','The expense account is missing or the charges institution must be absent.'); INSERT INTO bkmoperror_code VALUES('T','005','0004','002','ISO rule ''ChargesAccountAgentRule'' not respected.','The charges institution branch does not match a branch of the ordering customer.s institution.'); INSERT INTO bkmoperror_code VALUES('T','005','0005','002','ISO rule ''ChargeBearerRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0006','002','ISO rule ''UltimateDebtorRule'' not respected.','The ultimate debtor must be indicated either in total, or unitarily per loan, or it must be absent.'); INSERT INTO bkmoperror_code VALUES('T','005','0007','002','ISO rule ''ChequeAndCreditorAccountRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0008','002','ISO rule ''ChequeDeliveryAndCreditorAgentRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0009','002','ISO rule ''ChequeDeliveryAndNoCreditorAgentRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0010','002','ISO rule ''NonChequePaymentMethodRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0011','002','ISO rule ''ChequeNoDeliveryAndNoCreditorAgentRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0012','002','ISO rule ''IntermediaryAgent2Rule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0013','002','ISO rule ''IntermediaryAgent3Rule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0014','002','ISO rule ''InstructionForCreditorAgentRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0015','002','ISO rule ''IntermediaryAgent1AccountRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0016','002','ISO rule ''IntermediaryAgent2AccountRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0017','002','ISO rule ''IntermediaryAgent3AccountRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0018','002','ISO rule ''ChequeMaturityDateRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0019','002','ISO rule ''CreditorSchemeIdentificationRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0020','002','ISO rule ''UltimateCreditorRule'' not respected.','The ultimate creditor must be indicated either in total, or unitarily per loan, or it must be absent.'); INSERT INTO bkmoperror_code VALUES('T','005','0021','002','ISO rule ''AmendmentIndicatorTrueRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0022','002','ISO rule ''AmendmentIndicatorFalseRule'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0023','002','ISO rule ''PaymentInformationStatus'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0024','002','ISO rule ''AccountServicerReference'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0025','002','ISO rule ''UltimateDebtor'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0026','002','ISO rule ''Debtor'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0027','002','ISO rule ''DebtorAccount'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0028','002','ISO rule ''DebtorAgent'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0029','002','ISO rule ''DebtorAgentAccount'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0030','002','ISO rule ''CreditorAgent'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0031','002','ISO rule ''CreditorAgentAccount'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0032','002','ISO rule ''Creditor'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0033','002','ISO rule ''CreditorAccount'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','005','0034','002','ISO rule ''UltimateCreditor'' not respected.',''); INSERT INTO bkmoperror_code VALUES('T','006','0001','002','The channel is not active.',''); INSERT INTO bkmoperror_code VALUES('T','006','0002','002','The channel specified in the stream does not match the current channel.',''); INSERT INTO bkmoperror_code VALUES('T','006','0003','002','The channel does not receive any transfer.',''); INSERT INTO bkmoperror_code VALUES('T','006','0004','002','The channel does not receive any direct debit.',''); INSERT INTO bkmoperror_code VALUES('T','006','0005','002','Several channels for this interface.',''); INSERT INTO bkmoperror_code VALUES('T','007','0001','002','Impossible to read the stream.',''); INSERT INTO bkmoperror_code VALUES('T','007','0002','002','Invalid stream.',''); INSERT INTO bkmoperror_code VALUES('T','007','0003','002','There are some private data in duplicate in the stream.',''); INSERT INTO bkmoperror_code VALUES('T','008','0001','002','Ordering customer.s account not found.',''); INSERT INTO bkmoperror_code VALUES('T','008','0002','002','Ordering customer.s expense account not found.',''); INSERT INTO bkmoperror_code VALUES('T','008','0003','002','Transaction account not found.',''); INSERT INTO bkmoperror_code VALUES('T','008','0004','002','The expense account is not held by the ordering customer.',''); INSERT INTO bkmoperror_code VALUES('T','008','0005','002','The expense account is not held by the bank.',''); INSERT INTO bkmoperror_code VALUES('T','008','0006','002','At least one account (order or transaction level) must be in the transaction currency',''); INSERT INTO bkmoperror_code VALUES('T','008','0007','002','Ordering customer account . wrong format',''); INSERT INTO bkmoperror_code VALUES('T','008','0008','002','Charges account . wrong format',''); INSERT INTO bkmoperror_code VALUES('T','008','0009','002','Transaction account . wrong format',''); INSERT INTO bkmoperror_code VALUES('F','008','0010','002','The BIC code of the transaction is unknown',''); INSERT INTO bkmoperror_code VALUES('T','008','0011','002','Account not in favour of the TGR',''); INSERT INTO bkmoperror_code VALUES('T','009','0001','002','Transaction amount equals .0..',''); INSERT INTO bkmoperror_code VALUES('T','009','0002','002','Transaction amount is negative.',''); INSERT INTO bkmoperror_code VALUES('T','009','0003','002','Wrong SICA transfer code',''); INSERT INTO bkmoperror_code VALUES('T','009','0004','002','Economic code must be unique in the transaction',''); INSERT INTO bkmoperror_code VALUES('T','009','0005','002','At least one of the local references is wrong',''); INSERT INTO bkmoperror_code VALUES('T','009','0006','002','Wrong reference of notice of tax assessment',''); INSERT INTO bkmoperror_code VALUES('T','010','0001','002','Error in the event number.',''); INSERT INTO bkmoperror_code VALUES('T','010','0002','002','Error reading the beneficiary.s bank.',''); INSERT INTO bkmoperror_code VALUES('T','010','0003','002','Incident .insert bkeve.',''); INSERT INTO bkmoperror_code VALUES('T','010','0004','002','Unknown transaction currency.',''); INSERT INTO bkmoperror_code VALUES('T','010','0005','002','The local transfer type does not manage any multiple processing.',''); INSERT INTO bkmoperror_code VALUES('T','010','0006','002','The local transfer type does not manage any unit processing.',''); INSERT INTO bkmoperror_code VALUES('T','010','0007','002','Unknown local transfer type.',''); INSERT INTO bkmoperror_code VALUES('T','010','0008','002','Ordering customer.s account not found.',''); INSERT INTO bkmoperror_code VALUES('T','010','0009','002','Expense account not found.',''); INSERT INTO bkmoperror_code VALUES('T','010','0010','002','Beneficiary.s account not found.',''); INSERT INTO bkmoperror_code VALUES('T','010','0011','002','Economic code not found in the transaction.',''); INSERT INTO bkmoperror_code VALUES('T','010','0012','002','Economic code doesn''t match.',''); INSERT INTO bkmoperror_code VALUES('T','011','0001','002','Unknown transaction currency.',''); INSERT INTO bkmoperror_code VALUES('T','012','0001','002','Error while selecting the message.',''); INSERT INTO bkmoperror_code VALUES('T','012','0002','002','Error while selecting the batch.',''); INSERT INTO bkmoperror_code VALUES('T','012','0003','002','Error while selecting the transaction.',''); INSERT INTO bkmoperror_code VALUES('T','012','0004','002','Error while selecting the environment for the channel.',''); INSERT INTO bkmoperror_code VALUES('T','012','0005','002','Incident .insert bkmopbatch_rep.eta.',''); INSERT INTO bkmoperror_code VALUES('T','012','0006','002','Incident .insert bkmoptx_rep.eta.',''); INSERT INTO bkmoperror_code VALUES('T','012','0007','002','Incident .update bkmopmsg_rep.',''); INSERT INTO bkmoperror_code VALUES('T','012','0008','002','Incident .update bkmopbatch_rep.',''); INSERT INTO bkmoperror_code VALUES('T','012','0009','002','Incident .update bkmoptx_rep.',''); INSERT INTO bkmoperror_code VALUES('T','013','0001','002','Error integrating the message.',''); INSERT INTO bkmoperror_code VALUES('T','013','0002','002','Error integrating the batch.',''); INSERT INTO bkmoperror_code VALUES('T','013','0003','002','Error integrating the transaction.',''); INSERT INTO bkmoperror_code VALUES('T','013','0004','002','Error while loading bkmopmsg_md5',''); INSERT INTO bkmoperror_code VALUES('T','013','0005','002','Error while loading bkmoptx_md5',''); INSERT INTO bkmoperror_code VALUES('T','013','0006','002','Impossible to insert a response.',''); INSERT INTO bkmoperror_code VALUES('T','013','0007','002','Value not allowed in private data PtcInf_Sgt','The flow is rejected'); INSERT INTO bkmoperror_code VALUES('T','013','0008','002','EU is not a value allowed for item FlwInd','The flow is rejected'); INSERT INTO bkmoperror_code VALUES('T','013','0009','002','Error during the selection of the message status',''); INSERT INTO bkmoperror_code VALUES('T','013','0010','002','HU is not a value allowed for item FlwInd','The flow is rejected'); INSERT INTO bkmoperror_code VALUES('T','013','0011','002','Error during the selection of the economic code',''); INSERT INTO bkmoperror_code VALUES('T','013','0012','002','Error during the selection of the private data''s code of PSR',''); INSERT INTO bkmoperror_code VALUES('T','013','0013','002','Error while selecting the operation type',''); INSERT INTO bkmoperror_code VALUES('T','013','0014','002','Error while inserting bkmoplot_rev',''); INSERT INTO bkmoperror_code VALUES('T','013','0015','002','Error counting the structured or non-structured reasons',''); INSERT INTO bkmoperror_code VALUES('F','014','0001','002','Unknown local transfer currency.',''); INSERT INTO bkmoperror_code VALUES('F','014','0002','002','Local transfer type not allowed.',''); INSERT INTO bkmoperror_code VALUES('F','014','0003','002','Unknown local transfer type.',''); INSERT INTO bkmoperror_code VALUES('F','014','0004','002','Unknown processing branch.',''); INSERT INTO bkmoperror_code VALUES('F','014','0005','002','Error while loading account classes.',''); INSERT INTO bkmoperror_code VALUES('F','014','0006','002','Ordering customer.s account not found.',''); INSERT INTO bkmoperror_code VALUES('F','014','0007','002','Expense account not found.',''); INSERT INTO bkmoperror_code VALUES('F','014','0008','002','Beneficiary.s account not found.',''); INSERT INTO bkmoperror_code VALUES('F','014','0009','002','Account class of the ordering customer.s account not allowed for the operation.',''); INSERT INTO bkmoperror_code VALUES('F','014','0010','002','Account class of the beneficiary.s account not allowed for the operation.',''); INSERT INTO bkmoperror_code VALUES('F','014','0011','002','Event number not found.',''); INSERT INTO bkmoperror_code VALUES('F','014','0012','002','Unknown beneficiary bank.',''); INSERT INTO bkmoperror_code VALUES('F','014','0013','002','Incident during insertion.',''); INSERT INTO bkmoperror_code VALUES('F','014','0014','002','Local transfer type not set properly.',''); INSERT INTO bkmoperror_code VALUES('F','014','0015','002','Zero amount on the debit side forbidden',''); INSERT INTO bkmoperror_code VALUES('F','014','0016','002','Impossible to modify the ''VIRMUL''',''); INSERT INTO bkmoperror_code VALUES('F','014','0017','002','Impossible to modify events linked to the ''VIRMUL''',''); INSERT INTO bkmoperror_code VALUES('F','015','0001','002','Unknown local transfer currency.',''); INSERT INTO bkmoperror_code VALUES('F','015','0002','002','Ordering customer.s account not found.',''); INSERT INTO bkmoperror_code VALUES('F','015','0003','002','Expense account not found.',''); INSERT INTO bkmoperror_code VALUES('F','015','0004','002','Beneficiary.s account not found.',''); INSERT INTO bkmoperror_code VALUES('F','015','0005','002','Account class of the ordering customer.s account not allowed for the operation.',''); INSERT INTO bkmoperror_code VALUES('F','015','0006','002','Account class of the beneficiary.s account not allowed for the operation.',''); INSERT INTO bkmoperror_code VALUES('F','015','0007','002','Event number not found.',''); INSERT INTO bkmoperror_code VALUES('F','015','0008','002','Incident during insertion.',''); INSERT INTO bkmoperror_code VALUES('F','015','0009','002','Local transfer type not set properly.',''); INSERT INTO bkmoperror_code VALUES('T','015','0010','002','Parameter not set properly.',''); INSERT INTO bkmoperror_code VALUES('T','015','0011','002','Unknown organisation.',''); INSERT INTO bkmoperror_code VALUES('T','015','0012','002','The creditor.s account does not match the organisation account set.',''); INSERT INTO bkmoperror_code VALUES('T','015','0013','002','No operation code linked to PRLAUT (Between bracket are indicated the empty fields that can be the origine of the error)',''); INSERT INTO bkmoperror_code VALUES('T','015','0014','002','PRLAUT not allowed',''); INSERT INTO bkmoperror_code VALUES('F','015','0015','002','Zero amount on the debit side forbidden',''); INSERT INTO bkmoperror_code VALUES('F','015','0016','002','Zero amount on the credit side forbidden',''); INSERT INTO bkmoperror_code VALUES('F','016','0001','002','Unknown local transfer currency.',''); INSERT INTO bkmoperror_code VALUES('F','016','0002','002','Ordering customer.s account not found.',''); INSERT INTO bkmoperror_code VALUES('F','016','0003','002','Expense account not found.',''); INSERT INTO bkmoperror_code VALUES('F','016','0004','002','Account class of the ordering customer.s account not allowed for the operation.',''); INSERT INTO bkmoperror_code VALUES('F','016','0005','002','Event number not found.',''); INSERT INTO bkmoperror_code VALUES('F','016','0006','002','Incident during insertion.',''); INSERT INTO bkmoperror_code VALUES('F','016','0007','002','Incident during bank selection.',''); INSERT INTO bkmoperror_code VALUES('F','016','0008','002','Local transfer type not set properly.',''); INSERT INTO bkmoperror_code VALUES('T','016','0009','002','Parameter not set properly.',''); INSERT INTO bkmoperror_code VALUES('T','016','0010','002','Unknown organisation.',''); INSERT INTO bkmoperror_code VALUES('T','016','0011','002','The creditor.s account does not match the organisation account set.',''); INSERT INTO bkmoperror_code VALUES('T','016','0012','002','No operation code linked to PRLABQ (Between bracket are indicated the empty fields that can be the origine of the error)',''); INSERT INTO bkmoperror_code VALUES('T','016','0013','002','PRLABQ not allowed',''); INSERT INTO bkmoperror_code VALUES('F','016','0014','002','Zero amount on the credit side forbidden',''); INSERT INTO bkmoperror_code VALUES('F','017','0001','002','Wrong correspondent.',''); INSERT INTO bkmoperror_code VALUES('F','017','0002','002','Unknown international transfer currency.',''); INSERT INTO bkmoperror_code VALUES('F','017','0003','002','International transfer operation code not found.',''); INSERT INTO bkmoperror_code VALUES('F','017','0004','002','Ordering customer.s account currency not found.',''); INSERT INTO bkmoperror_code VALUES('F','017','0005','002','Expense account currency not found.',''); INSERT INTO bkmoperror_code VALUES('F','017','0006','002','Incident with the expense account.',''); INSERT INTO bkmoperror_code VALUES('F','017','0007','002','Wrong transit account configuration.',''); INSERT INTO bkmoperror_code VALUES('F','017','0008','002','Wrong transit account.',''); INSERT INTO bkmoperror_code VALUES('F','017','0009','002','Wrong transit account configuration . charges.',''); INSERT INTO bkmoperror_code VALUES('F','017','0010','002','Wrong transit account . charges.',''); INSERT INTO bkmoperror_code VALUES('F','017','0011','002','Unknown international transfer type.',''); INSERT INTO bkmoperror_code VALUES('F','017','0012','002','Wrong external customer.s bank account.',''); INSERT INTO bkmoperror_code VALUES('F','017','0013','002','Register not found.',''); INSERT INTO bkmoperror_code VALUES('F','017','0014','002','Wrong external customer.s bank account . multiple international transfer.',''); INSERT INTO bkmoperror_code VALUES('F','017','0015','002','Nature .ORDMIX. not set.',''); INSERT INTO bkmoperror_code VALUES('F','017','0016','002','Mixed order operation code not found.',''); INSERT INTO bkmoperror_code VALUES('F','017','0017','002','Correspondant not in account relationship',''); INSERT INTO bkmoperror_code VALUES('F','017','0018','002','Beneficiary''s BIC and IBAN are inconsistent',''); INSERT INTO bkmoperror_code VALUES('F','017','0019','002','Unknown correspondent',''); INSERT INTO bkmoperror_code VALUES('F','017','0020','002','Wrong ordering customer information',''); INSERT INTO bkmoperror_code VALUES('F','017','0021','002','Problem generating multiple transfers',''); INSERT INTO bkmoperror_code VALUES('F','017','0022','002','Problem generating the mixed event',''); INSERT INTO bkmoperror_code VALUES('T','018','0001','002','Program already launched.',''); INSERT INTO bkmoperror_code VALUES('T','018','0002','002','Processing program crash',''); INSERT INTO bkmoperror_code VALUES('T','018','0003','002','Errors found during the generation of the PSR.',''); INSERT INTO bkmoperror_code VALUES('F','019','0001','002','Batch valid, change of status to .NC..',''); INSERT INTO bkmoperror_code VALUES('F','019','0002','002','Transaction valid, change of status to .NC..',''); INSERT INTO bkmoperror_code VALUES('F','019','0003','002','The stream''s version is incorrect.',''); INSERT INTO bkmoperror_code VALUES('F','019','0004','002','The PSR''s version is incorrect.',''); INSERT INTO bkmoperror_code VALUES('F','019','0005','002','The message''s origin is incorrect',''); INSERT INTO bkmoperror_code VALUES('T','020','0001','002','The total sum of transactions does not match the batch amount.',''); INSERT INTO bkmoperror_code VALUES('T','020','0002','002','The number of transactions does not match that set at batch level.',''); INSERT INTO bkmoperror_code VALUES('T','020','0003','002','Transactions are not all in the same currency.',''); INSERT INTO bkmoperror_code VALUES('T','020','0004','002','The creditor.s account does not match the organisation account set.',''); INSERT INTO bkmoperror_code VALUES('T','021','0001','002','Coherence between the service determine and the received service',''); INSERT INTO bkmoperror_code VALUES('F','021','0002','002','Beneficiary bank not linked to SEPA',''); INSERT INTO bkmoperror_code VALUES('F','022','0001','002','Category not found',''); INSERT INTO bkmoperror_code VALUES('F','022','0002','002','The beneficiary.s bank must be in BIC format',''); INSERT INTO bkmoperror_code VALUES('F','022','0003','002','The beneficiary.s account must be in IBAN format',''); INSERT INTO bkmoperror_code VALUES('F','022','0004','002','Inconsistency between the BIC and IBAN of the beneficiary',''); INSERT INTO bkmoperror_code VALUES('F','022','0005','002','SQL incident',''); INSERT INTO bkmoperror_code VALUES('F','022','0006','002','The inconsistency check between BIC and IBAN is not set for parameter .SEPA.',''); INSERT INTO bkmoperror_code VALUES('F','022','0007','002','Parameter .SEPA. not found',''); INSERT INTO bkmoperror_code VALUES('F','022','0008','002','The number of structured reasons and the number of non-structured reasons are different from 0',''); INSERT INTO bkmoperror_code VALUES('F','022','0009','002','The number of non-structured reasons is strictly above 1',''); INSERT INTO bkmoperror_code VALUES('F','022','0010','002','The number of structured reasons is strictly above 1',''); INSERT INTO bkmoperror_code VALUES('F','022','0011','002','The size of transaction details exceeds 140 characters',''); INSERT INTO bkmoperror_code VALUES('F','022','0012','002','Charges can only be shared or according to the service level',''); INSERT INTO bkmoperror_code VALUES('F','022','0013','002','Local transfer only',''); INSERT INTO bkmoperror_code VALUES('F','023','0001','002','The input stream version is incorrect',''); INSERT INTO bkmoperror_code VALUES('F','023','0002','002','Unknown input stream: bkmopmsg.typmsg',''); INSERT INTO bkmoperror_code VALUES('F','024','0001','002','Error when reading the debug mode at the channel level','Contact the hotline'); INSERT INTO bkmoperror_code VALUES('F','024','0002','002','PSR generation in progress for the channel','Relaunch the process later'); INSERT INTO bkmoperror_code VALUES('F','024','0003','002','Error when reading the channel','Contact the hotline'); INSERT INTO bkmoperror_code VALUES('F','024','0004','002','Blocking error during PSR processing','Contact the hotline'); INSERT INTO bkmoperror_code VALUES('F','024','0005','002','Blocking error during PSR generation','Contact the hotline'); INSERT INTO bkmoperror_code VALUES('F','024','0006','002','Configuration error on the ABO interface : no authorized PSR/CAMT version','Correct the configuration'); INSERT INTO bkmoperror_code VALUES('F','024','0007','002','Blocking error on the database level','Contact the hotline'); INSERT INTO bkmoperror_code VALUES('F','027','0001','002','Error while recording a batch-level status in the display module .ABO.',''); INSERT INTO bkmoperror_code VALUES('F','027','0002','002','Error while recording a transaction-level status in the display module .ABO.',''); INSERT INTO bkmoperror_code VALUES('F','027','0003','002','The service is not activated',''); INSERT INTO bkmoperror_code VALUES('F','027','0004','002','Cannot identify the bank''s BIC code',''); INSERT INTO bkmoperror_code VALUES('F','027','0005','002','Missing type of transfer in channel definition (gumopcanal) for a service','Correct the channel definition'); INSERT INTO bkmoperror_code VALUES('F','028','0001','002','Error while reading the customer',''); INSERT INTO bkmoperror_code VALUES('F','029','0001','002','A disapproval is not set in table of codes .058.',''); INSERT INTO bkmoperror_code VALUES('F','029','0002','002','Parameter LTRF_RFND_OPE not set properly',''); INSERT INTO bkmoperror_code VALUES('F','029','0003','002','Impossible to calculate the event number for the reservation of funds',''); INSERT INTO bkmoperror_code VALUES('F','029','0004','002','Error while creating a reservation of funds',''); INSERT INTO bkmoperror_code VALUES('F','029','0005','002','Parameter TIME_WAIT not set properly',''); INSERT INTO bkmoperror_code VALUES('F','029','0006','002','Error while creating payment codes',''); INSERT INTO bkmoperror_code VALUES('F','029','0007','002','The transaction account is missing',''); INSERT INTO bkmoperror_code VALUES('F','029','0008','002','Impossible to work out the accounting',''); INSERT INTO bkmoperror_code VALUES('F','029','0009','002','Impossible to find the channel',''); INSERT INTO bkmoperror_code VALUES('F','029','0010','002','Impossible to find the message',''); INSERT INTO bkmoperror_code VALUES('F','029','0011','002','The transaction BIC is incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0012','002','All transactions from the batch are in error',''); INSERT INTO bkmoperror_code VALUES('F','029','0013','002','At least one of the transactions from the batch is in error',''); INSERT INTO bkmoperror_code VALUES('F','029','0014','002','Impossible to work out the operation for a PRLAUT',''); INSERT INTO bkmoperror_code VALUES('F','029','0015','002','Impossible to work out the operation for a PRLABQ',''); INSERT INTO bkmoperror_code VALUES('F','029','0016','002','Impossible to work out the event number for a PRLAUT',''); INSERT INTO bkmoperror_code VALUES('F','029','0017','002','Impossible to work out the event number for a PRLABQ',''); INSERT INTO bkmoperror_code VALUES('F','029','0018','002','Impossible to work out the collection method',''); INSERT INTO bkmoperror_code VALUES('F','029','0019','002','Impossible to work out the clearing branch for direct debits',''); INSERT INTO bkmoperror_code VALUES('F','029','0020','002','Wrong local reference(s):',''); INSERT INTO bkmoperror_code VALUES('F','029','0021','002','Error while searching for the original transaction',''); INSERT INTO bkmoperror_code VALUES('F','029','0022','002','Error while searching for the original transaction',''); INSERT INTO bkmoperror_code VALUES('F','029','0023','002','Error while searching for the original transaction',''); INSERT INTO bkmoperror_code VALUES('F','029','0024','002','Error while searching for the original transaction',''); INSERT INTO bkmoperror_code VALUES('F','029','0025','002','Configuration error',''); INSERT INTO bkmoperror_code VALUES('F','029','0026','002','Error in the payment date',''); INSERT INTO bkmoperror_code VALUES('F','029','0027','002','Error in the blocking of records',''); INSERT INTO bkmoperror_code VALUES('F','029','0028','002','Error in the blocking of records',''); INSERT INTO bkmoperror_code VALUES('F','029','0029','002','Error in the generation of the cancellation event',''); INSERT INTO bkmoperror_code VALUES('F','029','0030','002','Error in the generation of the cancellation event',''); INSERT INTO bkmoperror_code VALUES('F','029','0031','002','Error in the generation of the cancellation event',''); INSERT INTO bkmoperror_code VALUES('F','029','0032','002','Error in the generation of the direct debit receipt event',''); INSERT INTO bkmoperror_code VALUES('F','029','0033','002','Error in the generation of the direct debit receipt event',''); INSERT INTO bkmoperror_code VALUES('F','029','0034','002','Amount of the incorrect order',''); INSERT INTO bkmoperror_code VALUES('F','029','0035','002','Our branch account is incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0036','002','Other bank account (RIB_FR) is incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0037','002','Other bank account (RIB_SICA) is incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0038','002','NBS account is incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0039','002','Cannot find the coding system of the NBS account country',''); INSERT INTO bkmoperror_code VALUES('F','029','0040','002','Invalid IBAN account',''); INSERT INTO bkmoperror_code VALUES('F','029','0041','002','IBAN account is inconsistent with the BIC code',''); INSERT INTO bkmoperror_code VALUES('F','029','0042','002','Other bank account (RIB_MA) is incorrect',''); INSERT INTO bkmoperror_code VALUES('F','029','0043','002','Institution not specified',''); INSERT INTO bkmoperror_code VALUES('F','029','0044','002','Ordering customer?s institution is different from the bank?s',''); INSERT INTO bkmoperror_code VALUES('F','029','0045','002','Ordering customer?s BIC is different from the bank?s',''); INSERT INTO bkmoperror_code VALUES('F','029','0046','002','Error in the TGR transfer',''); INSERT INTO bkmoperror_code VALUES('F','029','0047','002','Error while inserting a VIRMUL',''); INSERT INTO bkmoperror_code VALUES('F','029','0048','002','Error while updating a VIMxxx',''); INSERT INTO bkmoperror_code VALUES('F','029','0049','002','Error while setting a disapproval on a transaction for a batch in cumulative accounting',''); INSERT INTO bkmoperror_code VALUES('F','029','0053','002','Beneficiary''s named not defined',''); INSERT INTO bkmoperror_code VALUES('F','029','0054','002','Reason not defined',''); INSERT INTO bkmoperror_code VALUES('F','029','0077','002','No organization in the stream',''); INSERT INTO bkmoperror_code VALUES('F','029','0082','002','Format of the Amplitude funds reservation is incorrect','Out of Amplitude scope, order rejected'); INSERT INTO bkmoperror_code VALUES('F','029','0083','002','Format of the Amplitude funds reservation is incorrect','Out of Amplitude scope, order rejected'); INSERT INTO bkmoperror_code VALUES('F','029','0084','002','Anomaly during cancellation of the funds reservation (from external reference)','Out of Amplitude scope, order rejected'); INSERT INTO bkmoperror_code VALUES('F','029','0085','002','Anomaly during cancellation of the funds reservation (from Amplitude reference)','Out of Amplitude scope, order rejected'); INSERT INTO bkmoperror_code VALUES('F','029','0086','002','Anomaly during the verification of the funds reservation (from Amplitude reference)','Out of Amplitude scope, order rejected'); INSERT INTO bkmoperror_code VALUES('F','029','0087','002','Anomaly during the verification of the funds reservation (from external reference)','Out of Amplitude scope, order rejected'); INSERT INTO bkmoperror_code VALUES('F','029','0088','002','Inconsistency between external and Amplitude reference of a funds reservation','Out of Amplitude scope, order rejected'); INSERT INTO bkmoperror_code VALUES('F','029','0089','002','Invalid funds reservation','Out of Amplitude scope, order rejected'); INSERT INTO bkmoperror_code VALUES('F','029','0090','002','Inconsystency of the debtor account between funds reservation and order received by SIOP','Out of Amplitude scope, order rejected'); INSERT INTO bkmoperror_code VALUES('F','029','0091','002','Inconsystency of the debtor account between funds reservation and order received by SIOP','Out of Amplitude scope, order rejected'); INSERT INTO bkmoperror_code VALUES('F','029','0092','002','Currency not defined','Out of Amplitude scope, order rejected'); INSERT INTO bkmoperror_code VALUES('F','029','0093','002','Anomaly during reading the customer profile','Contact the hotline'); INSERT INTO bkmoperror_code VALUES('F','029','0094','002','PLAT disapproval is not configured in table of code ''058''','Check the configuration'); INSERT INTO bkmoperror_code VALUES('F','029','0095','002','PMIN disapproval is not configured in table of code ''058''',''); INSERT INTO bkmoperror_code VALUES('F','032','0076','002','Incident while updating the table bkmoptx_rep',''); INSERT INTO bkmoperror_code VALUES('F','033','0001','002','Subsidiary''s BIC badly configured on the bank data sheet of the central site','Fix the configuration of the bank data sheet of the central site via cbgesban'); INSERT INTO bkmoperror_code VALUES('F','034','0001','002','Condition DVACAI does not exist',''); INSERT INTO bkmoperror_code VALUES('F','034','0002','002','Condition DVAAGE does not exist',''); INSERT INTO bkmoperror_code VALUES('F','034','0003','002','Condition DINCAI does not exist',''); INSERT INTO bkmoperror_code VALUES('F','034','0004','002','Condition DINAGE does not exist',''); INSERT INTO bkmoperror_code VALUES('F','034','0005','002','Condition DATVAL does not exist',''); INSERT INTO bkmoperror_code VALUES('F','034','0006','002','Condition EXOCOM does not exist',''); INSERT INTO bkmoperror_code VALUES('F','034','0007','002','Account is incorrect',''); INSERT INTO bkmoperror_code VALUES('F','034','0008','002','Insert into bkeve failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0009','002','Account selection 1 failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0010','002','Account selection 2 failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0011','002','Account selection 3 failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0012','002','Account selection 4 failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0013','002','Account selection 5 failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0014','002','Account selection 6 failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0015','002','Account selection 7 failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0016','002','Account selection 8 failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0017','002','Account selection 9 failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0018','002','Account selection 10 failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0019','002','Account selection 11 failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0020','002','Account selection 12 failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0021','002','bkicprl selection failed',''); INSERT INTO bkmoperror_code VALUES('F','034','0022','002','bkicprl update failed (UPD4)',''); INSERT INTO bkmoperror_code VALUES('F','034','0023','002','bkicprld update failed (UPD4)',''); INSERT INTO bkmoperror_code VALUES('F','034','0024','002','bkicprl update 1 failed (UPD2)',''); INSERT INTO bkmoperror_code VALUES('F','034','0025','002','bkicprld update 1 failed (UPD2)',''); INSERT INTO bkmoperror_code VALUES('F','034','0026','002','bkicprl update 2 failed (UPD2)',''); INSERT INTO bkmoperror_code VALUES('F','034','0027','002','bkicprld update 2 failed (UPD2)',''); INSERT INTO bkmoperror_code VALUES('F','034','0028','002','Insert into bkicprl failed (UPD1)',''); INSERT INTO bkmoperror_code VALUES('F','034','0029','002','Insert into bkicprld failed (UPD1)',''); INSERT INTO bkmoperror_code VALUES('F','034','0030','002','Currency does not exist',''); INSERT INTO bkmoperror_code VALUES('F','035','0001','002','Condition DATVAL does not exist',''); INSERT INTO bkmoperror_code VALUES('F','035','0002','002','Bank selection 1',''); INSERT INTO bkmoperror_code VALUES('F','035','0003','002','Bank selection 2',''); INSERT INTO bkmoperror_code VALUES('F','035','0004','002','Null value date',''); INSERT INTO bkmoperror_code VALUES('F','035','0005','002','Account not found',''); INSERT INTO bkmoperror_code VALUES('F','035','0006','002','Account selection',''); INSERT INTO bkmoperror_code VALUES('F','035','0007','002','Currency does not exist',''); INSERT INTO bkmoperror_code VALUES('F','039','0001','002','Error in TGR transfer','Please fix it through the business monitors'); INSERT INTO bkmoperror_code VALUES('F','039','0002','002','Error in a pledged transfer','Please fix it through the business monitors'); INSERT INTO bkmoperror_code VALUES('F','039','0003','002','Error while reading a non active channel','Call the hotline'); INSERT INTO bkmoperror_code VALUES('F','039','0008','002','DBMONEY wrong or not set','Set DBMONEY in the profile setting'); INSERT INTO bkmoperror_code VALUES('F','040','0001','002','The type of debit-balance account is wrong',''); INSERT INTO bkmoperror_code VALUES('F','040','0002','002','Wrong direct debit type',''); INSERT INTO bkmoperror_code VALUES('F','040','0003','002','Wrong transaction currency',''); INSERT INTO bkmoperror_code VALUES('F','040','0004','002','Creditor''s identifier not set',''); INSERT INTO bkmoperror_code VALUES('F','040','0005','002','Payment order identifier not set',''); INSERT INTO bkmoperror_code VALUES('F','040','0006','002','Accounting label ENCAISSDD0 not found',''); INSERT INTO bkmoperror_code VALUES('F','040','0007','002','Parameter SEPA-SDD not found',''); INSERT INTO bkmoperror_code VALUES('F','040','0008','002','Wrong payment date',''); INSERT INTO bkmoperror_code VALUES('F','040','0009','002','Clearing branch for SEPA not set properly',''); INSERT INTO bkmoperror_code VALUES('F','040','0010','002','Parameter SEPA not found',''); INSERT INTO bkmoperror_code VALUES('F','040','0011','002','Parameter SEPA2 not found',''); INSERT INTO bkmoperror_code VALUES('F','040','0012','002','Transaction nature PAISDD not found',''); INSERT INTO bkmoperror_code VALUES('F','040','0013','002','Incident while updating the table of SDD stop orders',''); INSERT INTO bkmoperror_code VALUES('F','040','0014','002','A stop order has already been set',''); INSERT INTO bkmoperror_code VALUES('F','040','0015','002','Disapproval set on the account to be credited',''); INSERT INTO bkmoperror_code VALUES('F','040','0016','002','Impossible to retrieve the digital currency of the transaction',''); INSERT INTO bkmoperror_code VALUES('F','040','0017','002','Impossible to identify the customer holding the account to be credited',''); INSERT INTO bkmoperror_code VALUES('F','040','0018','002','Collection account not found',''); INSERT INTO bkmoperror_code VALUES('F','040','0019','002','Error while generating event REASDD',''); INSERT INTO bkmoperror_code VALUES('F','040','0020','002','Error while generating event REISDD',''); INSERT INTO bkmoperror_code VALUES('F','040','0021','002','Error while generating event REPSDD',''); INSERT INTO bkmoperror_code VALUES('F','040','0022','002','Impossible to select the payment order',''); INSERT INTO bkmoperror_code VALUES('F','040','0023','002','Incident while updating the table of payment orders',''); INSERT INTO bkmoperror_code VALUES('F','040','0024','002','Incident while inserting into the table of payment orders',''); INSERT INTO bkmoperror_code VALUES('F','040','0025','002','Incident while selecting the payment order',''); INSERT INTO bkmoperror_code VALUES('F','040','0026','002','Incident while inserting into table bksepacreancier',''); INSERT INTO bkmoperror_code VALUES('F','040','0027','002','Incident while inserting into table bksepacreancier',''); INSERT INTO bkmoperror_code VALUES('F','040','0028','002','Problem while reading parameters',''); INSERT INTO bkmoperror_code VALUES('F','040','0029','002','Problem during checks',''); INSERT INTO bkmoperror_code VALUES('F','040','0030','002','Incident while selecting the creditor',''); INSERT INTO bkmoperror_code VALUES('F','040','0031','002','Incident while inserting into table bksepasdd',''); INSERT INTO bkmoperror_code VALUES('F','040','0032','002','Incident while inserting into table bksepacplsdd',''); INSERT INTO bkmoperror_code VALUES('F','040','0033','002','Incident while inserting the direct debit',''); INSERT INTO bkmoperror_code VALUES('F','042','0001','002','File reference not found',''); INSERT INTO bkmoperror_code VALUES('F','042','0002','002','Operation not found',''); INSERT INTO bkmoperror_code VALUES('F','042','0003','002','Operation not found',''); INSERT INTO bkmoperror_code VALUES('F','042','0004','002','Account holder not found',''); INSERT INTO bkmoperror_code VALUES('F','042','0005','002','Charges calculation failed',''); INSERT INTO bkmoperror_code VALUES('F','042','0006','002','Commission calculation failed',''); INSERT INTO bkmoperror_code VALUES('F','042','0007','002','Management charges calculation failed',''); INSERT INTO bkmoperror_code VALUES('F','042','0008','002','Tax calculation failed',''); INSERT INTO bkmoperror_code VALUES('F','042','0009','002','DATVAL condition not properly set',''); INSERT INTO bkmoperror_code VALUES('F','042','0010','002','Bank unknown',''); INSERT INTO bkmoperror_code VALUES('F','042','0011','002','Account unknown',''); INSERT INTO bkmoperror_code VALUES('F','042','0012','002','Account currency unknown',''); INSERT INTO bkmoperror_code VALUES('F','042','0013','002','Disapproval check failed',''); INSERT INTO bkmoperror_code VALUES('F','042','0014','002','Account unknown',''); INSERT INTO bkmoperror_code VALUES('F','042','0015','002','Complement deletion failed',''); INSERT INTO bkmoperror_code VALUES('F','042','0016','002','Event deletion failed',''); INSERT INTO bkmoperror_code VALUES('F','042','0017','002','''DELETE bksemsta'' failed',''); INSERT INTO bkmoperror_code VALUES('F','042','0018','002','''INSERT bkebcavic'' failed',''); INSERT INTO bkmoperror_code VALUES('F','042','0019','002','Error while inserting complements',''); INSERT INTO bkmoperror_code VALUES('T','047','0001','002','Class of the interface (itfinterf) is unknown','Check the configuration of the PSR issuing interface with the program cbgdispitf'); INSERT INTO bkmoperror_code VALUES('F','104','0001','002','Category not found.',''); INSERT INTO bkmoperror_code VALUES('F','104','0002','002','The beneficiary.s bank must be in BIC format and branch defined.',''); INSERT INTO bkmoperror_code VALUES('F','104','0003','002','The beneficiary.s account must be in BBAN format.',''); INSERT INTO bkmoperror_code VALUES('F','104','0004','002','The beneficiary.s bank BIC isn.t EBC member.',''); INSERT INTO bkmoperror_code VALUES('F','104','0005','002','SQL incident.',''); INSERT INTO bkmoperror_code VALUES('F','104','0006','002','The BIC and branch of beneficiary.s bank isn.t EBC member.',''); INSERT INTO bkmoperror_code VALUES('F','104','0007','002','Instruction for creditor agent',''); INSERT INTO bkmoperror_code VALUES('F','104','0008','002','The number of structured reasons and the number of non-structured reasons are different from 0.',''); INSERT INTO bkmoperror_code VALUES('F','104','0009','002','The number of non-structured reasons is strictly above 1.',''); INSERT INTO bkmoperror_code VALUES('F','104','0010','002','The number of structured reasons is strictly above 1.',''); INSERT INTO bkmoperror_code VALUES('F','104','0011','002','The size of transaction details exceeds 140 characters.',''); INSERT INTO bkmoperror_code VALUES('F','104','0012','002','Charges can only be shared or according to the service level.',''); INSERT INTO bkmoperror_code VALUES('F','104','0013','002','Local transfer only.',''); INSERT INTO bkmoperror_code VALUES('F','104','0014','002','Purpose not found.',''); -- ------------ -- EVOmdp_BGFIFR161011-02_01_STR_ora.sql -- ------------ --DROP TABLE bkseparf_001; --DROP TABLE bkseparfd; --DROP SEQUENCE BKSEPARFD_ID_S; --DROP SEQUENCE BKSEPARFD_MSGID_S; --DROP SEQUENCE BKSEPAROUTING_V2_ID_KEY_S; --DROP SEQUENCE seq_sepafent_idfic; --DROP SEQUENCE BKSEPARF_001_ID_S; ALTER TABLE bkseparf ADD CONSTRAINT i0_bkseparf PRIMARY KEY (idfic); CREATE TABLE bkseparfd ( id_bkseparfd NUMBER(15,0) CONSTRAINT NL_BKSEPARFD$ID_BKSEPARFD NOT NULL ,idfic CHAR(15) ,msgid CHAR(35) ,nbtx NUMBER ,mtot NUMBER(19,4) ,pacs CHAR(10) ,dreg DATE ,cre_date_time VARCHAR2(50) ); CREATE UNIQUE INDEX PK_BKSEPARFD ON bkseparfd (id_bkseparfd); ALTER TABLE bkseparfd ADD CONSTRAINT PK_BKSEPARFD PRIMARY KEY (id_bkseparfd); CREATE SEQUENCE seq_sepafent_idfic INCREMENT BY 1 START WITH 1 NOCACHE; CREATE SEQUENCE BKSEPARFD_ID_S INCREMENT BY 1 START WITH 1 MINVALUE 1 MAXVALUE 999999999999999 CYCLE; CREATE SEQUENCE BKSEPARFD_MSGID_S INCREMENT BY 1 START WITH 1 MINVALUE 1 MAXVALUE 99999999 CYCLE; CREATE SEQUENCE BKSEPAROUTING_V2_ID_KEY_S INCREMENT BY 1 START WITH 5000 MINVALUE 1 MAXVALUE 999999999999999 NOCACHE CYCLE; CREATE TABLE bkseparf_001 ( id_bkseparfd_001 NUMBER(15,0) CONSTRAINT NL_BKSEPARF_001$IDBKSEPARF001 NOT NULL ,idfic CHAR(15) CONSTRAINT NL_BKSEPARF_001$IDFIC NOT NULL ,peach CHAR(10) ,cra_status CHAR(2) CONSTRAINT CK_BKSEPARF_001$CRA_STATUS CHECK (cra_status IN ('NC', 'AT', 'TR')) ); CREATE UNIQUE INDEX PK_BKSEPARF_001 ON bkseparf_001 (id_bkseparfd_001); ALTER TABLE bkseparf_001 ADD CONSTRAINT PK_BKSEPARF_001 PRIMARY KEY (id_bkseparfd_001); CREATE INDEX FK_BKSEPARF_001$BKSEPARF ON bkseparf_001 (idfic); ALTER TABLE bkseparf_001 ADD CONSTRAINT FK_BKSEPARF_001$BKSEPARF FOREIGN KEY (idfic) REFERENCES bkseparf (idfic); CREATE SEQUENCE BKSEPARF_001_ID_S INCREMENT BY 1 START WITH 1 MINVALUE 1 MAXVALUE 999999999999999 NOCACHE CYCLE; -- ------------ -- DEF_8666_01_STR_ora.sql -- ------------ -- Renommage de la table bkmopdbtx pour recréation RENAME bkmopdbtx TO tmp_bkmopdbtx; -- Recréation de la table bkmopdbtx CREATE TABLE bkmopdbtx AS SELECT idtx, idlot, etab, guib, bic, cpte, typcpte, nom, dev, ncp, suf, typtx, mnt, devtx, charge, ref, lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8, lib9, lib10, purpose_tp, purpose_val, category_tp, category_val, srvlvl_tp, srvlvl_val, mndt_id, mndt_comp, market_info, locality_code FROM tmp_bkmopdbtx; -- Suppression des contraintes et index ALTER TABLE tmp_bkmopdbtx DROP CONSTRAINT fk_bkmopdbtx_1; ALTER TABLE tmp_bkmopdbtx DROP CONSTRAINT pk_bkmopdbtx CASCADE; DROP INDEX u1_bkmopdbtx; -- Recréation de l'index unique et des contraintes pour la table bkmopdbtx et les sous-tables CREATE UNIQUE INDEX u1_bkmopdbtx ON bkmopdbtx (idtx); ALTER TABLE bkmopdbtx ADD CONSTRAINT pk_bkmopdbtx PRIMARY KEY (idtx); ALTER TABLE bkmopdbtx ADD CONSTRAINT fk_bkmopdbtx_1 FOREIGN KEY (idlot) REFERENCES bkmopdblot(idlot); ALTER TABLE bkmopdbtx_etr ADD CONSTRAINT fk_bkmopdbtx_etr_1 FOREIGN KEY (idtx) REFERENCES bkmopdbtx(idtx); ALTER TABLE bkmopdbtxrptg ADD CONSTRAINT fk_bkmopdbtxrptg_1 FOREIGN KEY (idtx) REFERENCES bkmopdbtx(idtx); ALTER TABLE bkmopdbtxstrd ADD CONSTRAINT fk_bkmopdbtxstrd_1 FOREIGN KEY (idtx) REFERENCES bkmopdbtx(idtx); ALTER TABLE bkmopdbtx_lref ADD CONSTRAINT fk_bkmopdbtx_lref_1 FOREIGN KEY (idtx) REFERENCES bkmopdbtx(idtx); -- Suppresion de la table temporaire DROP TABLE tmp_bkmopdbtx; -- ------------ -- DIM_BCBF180109-01_01_STR_ora.sql -- ------------ --ANTIDOTE : --DROP TABLE bkerrbic; --DROP SEQUENCE bkerrbic_id_s; --Creation de la table des erreurs bkerrbic CREATE TABLE bkerrbic ( err_id NUMBER(15,0) /*Identifiant unique*/ CONSTRAINT NL_BKERRBIC$ERR_ID NOT NULL, age CHAR(5) /*agence*/ CONSTRAINT NL_BKERRBIC$AGE NOT NULL, objet VARCHAR2(50) /*Objet (Client/Dossier)*/ CONSTRAINT NL_BKERRBIC$OBJET NOT NULL, erreur VARCHAR2(100) /*Description de l'erreur*/ CONSTRAINT NL_BKERRBIC$ERREUR NOT NULL ); CREATE UNIQUE INDEX PK_BKERRBIC ON bkerrbic(err_id); ALTER TABLE bkerrbic ADD CONSTRAINT PK_BKERRBIC PRIMARY KEY (err_id); CREATE SEQUENCE BKERRBIC_ID_S START WITH 1 MAXVALUE 9999999999 CYCLE; -- ------------ -- DIM_BCBF180109-01_02_MAJ_ora.sql -- ------------ --Suppression de toutes les valeurs de bkconvbic TRUNCATE TABLE bkconvbic; --Insertion des nouvelles valeurs dans bkconvbic --D01 - Rôle du client INSERT INTO bkconvbic VALUES('D01','Rôle du client',1,'MainDebtor','Débiteur principal, Principal demandeur'); INSERT INTO bkconvbic VALUES('D01','Rôle du client',2,'CoDebtor','Co-débiteur, Co-demandeur'); INSERT INTO bkconvbic VALUES('D01','Rôle du client',3,'Guarantor','Garant'); --D02 - Classification de la personne INSERT INTO bkconvbic VALUES('D02','Classification de la personne',0,'NotSpecified','Non Spécifié'); INSERT INTO bkconvbic VALUES('D02','Classification de la personne',1,'Individual','Personne'); INSERT INTO bkconvbic VALUES('D02','Classification de la personne',2,'SoleTrader','Commerçant, entrepreneur'); --D03 - Sexe INSERT INTO bkconvbic VALUES('D03','Sexe',1,'Male','Homme'); INSERT INTO bkconvbic VALUES('D03','Sexe',2,'Female','Femme'); --D04 Code des pays INSERT INTO bkconvbic VALUES('D04','Code des pays',1,'AD','ANDORRE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',2,'AE','ÉMIRATS ARABES UNIS'); INSERT INTO bkconvbic VALUES('D04','Code des pays',3,'AF','AFGHANISTAN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',4,'AG','ANTIGUA-ET-BARBUDA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',5,'AI','ANGUILLA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',6,'AL','ALBANIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',7,'AM','ARMÉNIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',8,'AN','ANTILLES NEERLANDAISES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',9,'AO','ANGOLA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',10,'AQ','ANTARCTIQUE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',11,'AR','ARGENTINE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',12,'AS','SAMOA AMÉRICAINES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',13,'AT','AUTRICHE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',14,'AU','AUSTRALIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',15,'AW','ARUBA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',16,'AZ','AZERBAÏDJAN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',17,'BA','BOSNIE-HERZÉGOVINE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',18,'BB','BARBADE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',19,'BD','BANGLADESH'); INSERT INTO bkconvbic VALUES('D04','Code des pays',20,'BE','BELGIQUE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',21,'BF','BURKINA FASO'); INSERT INTO bkconvbic VALUES('D04','Code des pays',22,'BG','BULGARIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',23,'BH','BAHREÏN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',24,'BI','BURUNDI'); INSERT INTO bkconvbic VALUES('D04','Code des pays',25,'BJ','BÉNIN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',26,'BM','BERMUDES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',27,'BN','BRUNEI DARUSSALAM'); INSERT INTO bkconvbic VALUES('D04','Code des pays',28,'BO','BOLIVIE, l`ÉTAT PLURINATIONAL DE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',29,'BR','BRÉSIL'); INSERT INTO bkconvbic VALUES('D04','Code des pays',30,'BS','BAHAMAS'); INSERT INTO bkconvbic VALUES('D04','Code des pays',31,'BT','BHOUTAN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',32,'BV','BOUVET, ÎLE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',33,'BW','BOTSWANA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',34,'BY','BÉLARUS'); INSERT INTO bkconvbic VALUES('D04','Code des pays',35,'BZ','BELIZE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',36,'CA','CANADA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',37,'CC','COCOS (KEELING), ÎLES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',38,'CD','CONGO, LA RÉPUBLIQUE DÉMOCRATIQUE DU'); INSERT INTO bkconvbic VALUES('D04','Code des pays',39,'CF','CENTRAFRICAINE, RÉPUBLIQUE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',40,'CG','CONGO'); INSERT INTO bkconvbic VALUES('D04','Code des pays',41,'CI','CÔTE D`IVOIRE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',42,'CK','COOK, ÎLES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',43,'CL','CHILI'); INSERT INTO bkconvbic VALUES('D04','Code des pays',44,'CM','CAMEROUN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',45,'CN','CHINE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',46,'CO','COLOMBIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',47,'CR','COSTA RICA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',48,'CU','CUBA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',49,'CV','CAP-VERT'); INSERT INTO bkconvbic VALUES('D04','Code des pays',50,'CX','CHRISTMAS, ÎLE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',51,'CY','CHYPRE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',52,'CZ','TCHÈQUE, RÉPUBLIQUE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',53,'DE','ALLEMAGNE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',54,'DJ','DJIBOUTI'); INSERT INTO bkconvbic VALUES('D04','Code des pays',55,'DK','DANEMARK'); INSERT INTO bkconvbic VALUES('D04','Code des pays',56,'DM','DOMINIQUE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',57,'DO','DOMINICAINE, RÉPUBLIQUE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',58,'DZ','ALGÉRIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',59,'EC','ÉQUATEUR'); INSERT INTO bkconvbic VALUES('D04','Code des pays',60,'EE','ESTONIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',61,'EG','ÉGYPTE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',62,'EH','SAHARA OCCIDENTAL'); INSERT INTO bkconvbic VALUES('D04','Code des pays',63,'ER','ÉRYTHRÉE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',64,'ES','ESPAGNE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',65,'ET','ÉTHIOPIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',66,'FI','FINLANDE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',67,'FJ','FIDJI'); INSERT INTO bkconvbic VALUES('D04','Code des pays',68,'FK','FALKLAND, ÎLES (MALVINAS)'); INSERT INTO bkconvbic VALUES('D04','Code des pays',69,'FM','MICRONÉSIE, ÉTATS FÉDÉRÉS DE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',70,'FO','FÉROÉ, ÎLES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',71,'FR','FRANCE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',72,'GA','GABON'); INSERT INTO bkconvbic VALUES('D04','Code des pays',73,'GB','ROYAUME-UNI'); INSERT INTO bkconvbic VALUES('D04','Code des pays',74,'GD','GRENADE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',75,'GE','GÉORGIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',76,'GF','GUYANE FRANÇAISE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',77,'GH','GHANA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',78,'GI','GIBRALTAR'); INSERT INTO bkconvbic VALUES('D04','Code des pays',79,'GL','GROENLAND'); INSERT INTO bkconvbic VALUES('D04','Code des pays',80,'GM','GAMBIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',81,'GN','GUINÉE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',82,'GP','GUADELOUPE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',83,'GQ','GUINÉE ÉQUATORIALE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',84,'GR','GRÈCE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',85,'GS','GÉORGIE DU SUD-ET-LES ÎLES SANDWICH DU SUD'); INSERT INTO bkconvbic VALUES('D04','Code des pays',86,'GT','GUATEMALA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',87,'GU','GUAM'); INSERT INTO bkconvbic VALUES('D04','Code des pays',88,'GW','GUINÉE-BISSAU'); INSERT INTO bkconvbic VALUES('D04','Code des pays',89,'GY','GUYANA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',90,'HK','HONG KONG'); INSERT INTO bkconvbic VALUES('D04','Code des pays',91,'HM','HEARD-ET-ÎLES MACDONALD, ÎLE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',92,'HN','HONDURAS'); INSERT INTO bkconvbic VALUES('D04','Code des pays',93,'HR','CROATIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',94,'HT','HAÏTI'); INSERT INTO bkconvbic VALUES('D04','Code des pays',95,'HU','HONGRIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',96,'CH','SUISSE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',97,'ID','INDONÉSIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',98,'IE','IRLANDE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',99,'IL','ISRAËL'); INSERT INTO bkconvbic VALUES('D04','Code des pays',100,'IN','INDE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',101,'IO','OCÉAN INDIEN, TERRITOIRE BRITANNIQUE DE L`'); INSERT INTO bkconvbic VALUES('D04','Code des pays',102,'IQ','IRAQ'); INSERT INTO bkconvbic VALUES('D04','Code des pays',103,'IR','IRAN, RÉPUBLIQUE ISLAMIQUE D`'); INSERT INTO bkconvbic VALUES('D04','Code des pays',104,'IS','ISLANDE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',105,'IT','ITALIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',106,'JM','JAMAÏQUE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',107,'JO','JORDANIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',108,'JP','JAPON'); INSERT INTO bkconvbic VALUES('D04','Code des pays',109,'KE','KENYA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',110,'KG','KIRGHIZISTAN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',111,'KH','CAMBODGE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',112,'KI','KIRIBATI'); INSERT INTO bkconvbic VALUES('D04','Code des pays',113,'KM','COMORES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',114,'KN','SAINT-KITTS-ET-NEVIS'); INSERT INTO bkconvbic VALUES('D04','Code des pays',115,'KP','CORÉE, RÉPUBLIQUE POPULAIRE DÉMOCRATIQUE DE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',116,'KR','CORÉE, RÉPUBLIQUE DE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',117,'KW','KOWEÏT'); INSERT INTO bkconvbic VALUES('D04','Code des pays',118,'KY','CAÏMANS, ÎLES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',119,'KZ','KAZAKHSTAN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',120,'LA','LAO, RÉPUBLIQUE DÉMOCRATIQUE POPULAIRE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',121,'LB','LIBAN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',122,'LC','SAINTE-LUCIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',123,'LI','LIECHTENSTEIN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',124,'LK','SRI LANKA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',125,'LR','LIBÉRIA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',126,'LS','LESOTHO'); INSERT INTO bkconvbic VALUES('D04','Code des pays',127,'LT','LITUANIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',128,'LU','LUXEMBOURG'); INSERT INTO bkconvbic VALUES('D04','Code des pays',129,'LV','LETTONIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',130,'LY','LIBYE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',131,'MA','MAROC'); INSERT INTO bkconvbic VALUES('D04','Code des pays',132,'MC','MONACO'); INSERT INTO bkconvbic VALUES('D04','Code des pays',133,'MD','MOLDOVA, RÉPUBLIQUE DE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',134,'MG','MADAGASCAR'); INSERT INTO bkconvbic VALUES('D04','Code des pays',135,'MH','MARSHALL, ÎLES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',136,'MK','MACÉDOINE, L`EX-RÉPUBLIQUE YOUGOSLAVE DE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',137,'ML','MALI'); INSERT INTO bkconvbic VALUES('D04','Code des pays',138,'MM','MYANMAR'); INSERT INTO bkconvbic VALUES('D04','Code des pays',139,'MN','MONGOLIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',140,'MO','MACAO'); INSERT INTO bkconvbic VALUES('D04','Code des pays',141,'MP','MARIANNES DU NORD, ÎLES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',142,'MQ','MARTINIQUE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',143,'MR','MAURITANIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',144,'MS','MONTSERRAT'); INSERT INTO bkconvbic VALUES('D04','Code des pays',145,'MT','MALTE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',146,'MU','MAURICE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',147,'MV','MALDIVES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',148,'MW','MALAWI'); INSERT INTO bkconvbic VALUES('D04','Code des pays',149,'MX','MEXIQUE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',150,'MY','MALAISIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',151,'MZ','MOZAMBIQUE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',152,'NA','NAMIBIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',153,'NC','NOUVELLE-CALÉDONIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',154,'NE','NIGER'); INSERT INTO bkconvbic VALUES('D04','Code des pays',155,'NF','NORFOLK, ÎLE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',156,'NG','NIGÉRIA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',157,'NI','NICARAGUA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',158,'NL','PAYS-BAS'); INSERT INTO bkconvbic VALUES('D04','Code des pays',159,'NO','NORVÈGE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',160,'NP','NÉPAL'); INSERT INTO bkconvbic VALUES('D04','Code des pays',161,'NR','NAURU'); INSERT INTO bkconvbic VALUES('D04','Code des pays',162,'NU','NIUÉ'); INSERT INTO bkconvbic VALUES('D04','Code des pays',163,'NZ','NOUVELLE-ZÉLANDE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',164,'OM','OMAN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',165,'PA','PANAMA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',166,'PE','PÉROU'); INSERT INTO bkconvbic VALUES('D04','Code des pays',167,'PF','POLYNÉSIE FRANÇAISE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',168,'PG','PAPOUASIE-NOUVELLE-GUINÉE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',169,'PH','PHILIPPINES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',170,'PK','PAKISTAN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',171,'PL','POLOGNE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',172,'PM','SAINT-PIERRE-ET-MIQUELON'); INSERT INTO bkconvbic VALUES('D04','Code des pays',173,'PN','PITCAIRN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',174,'PR','PORTO RICO'); INSERT INTO bkconvbic VALUES('D04','Code des pays',175,'PS','PALESTINIEN OCCUPÉ, TERRITOIRE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',176,'PT','PORTUGAL'); INSERT INTO bkconvbic VALUES('D04','Code des pays',177,'PW','PALAOS'); INSERT INTO bkconvbic VALUES('D04','Code des pays',178,'PY','PARAGUAY'); INSERT INTO bkconvbic VALUES('D04','Code des pays',179,'QA','QATAR'); INSERT INTO bkconvbic VALUES('D04','Code des pays',180,'RE','RÉUNION'); INSERT INTO bkconvbic VALUES('D04','Code des pays',181,'RO','ROUMANIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',182,'RU','RUSSIE, FÉDÉRATION DE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',183,'RW','RWANDA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',184,'SA','ARABIE SAOUDITE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',185,'SB','SALOMON, ÎLES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',186,'SC','SEYCHELLES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',187,'SD','SOUDAN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',188,'SE','SUÈDE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',189,'SG','SINGAPOUR'); INSERT INTO bkconvbic VALUES('D04','Code des pays',190,'SH','SAINTE-HÉLÈNE, ASCENSION ET TRISTAN DA CUNHA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',191,'SI','SLOVÉNIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',192,'SJ','SVALBARD ET ÎLE JAN MAYEN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',193,'SK','SLOVAQUIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',194,'SL','SIERRA LEONE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',195,'SM','SAINT-MARIN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',196,'SN','SÉNÉGAL'); INSERT INTO bkconvbic VALUES('D04','Code des pays',197,'SO','SOMALIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',198,'SR','SURINAME'); INSERT INTO bkconvbic VALUES('D04','Code des pays',199,'ST','SAO TOMÉ-ET-PRINCIPE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',200,'SV','EL SALVADOR'); INSERT INTO bkconvbic VALUES('D04','Code des pays',201,'SY','SYRIENNE, RÉPUBLIQUE ARABE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',202,'SZ','SWAZILAND'); INSERT INTO bkconvbic VALUES('D04','Code des pays',203,'TC','TURKS-ET-CAÏCOS, ÎLES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',204,'TD','TCHAD'); INSERT INTO bkconvbic VALUES('D04','Code des pays',205,'TF','TERRES AUSTRALES FRANÇAISES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',206,'TG','TOGO'); INSERT INTO bkconvbic VALUES('D04','Code des pays',207,'TH','THAÏLANDE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',208,'TJ','TADJIKISTAN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',209,'TK','TOKELAU'); INSERT INTO bkconvbic VALUES('D04','Code des pays',210,'TM','TURKMÉNISTAN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',211,'TN','TUNISIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',212,'TO','TONGA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',213,'TP','TIMOR ORIENTAL'); INSERT INTO bkconvbic VALUES('D04','Code des pays',214,'TR','TURQUIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',215,'TT','TRINITÉ-ET-TOBAGO'); INSERT INTO bkconvbic VALUES('D04','Code des pays',216,'TV','TUVALU'); INSERT INTO bkconvbic VALUES('D04','Code des pays',217,'TW','TAÏWAN, PROVINCE DE CHINE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',218,'TZ','TANZANIE, RÉPUBLIQUE-UNIE DE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',219,'UA','UKRAINE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',220,'UG','OUGANDA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',221,'UM','ÎLES MINEURES ÉLOIGNÉES DES ÉTATS-UNIS'); INSERT INTO bkconvbic VALUES('D04','Code des pays',222,'US','ÉTATS-UNIS'); INSERT INTO bkconvbic VALUES('D04','Code des pays',223,'UY','URUGUAY'); INSERT INTO bkconvbic VALUES('D04','Code des pays',224,'UZ','OUZBÉKISTAN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',225,'VA','SAINT-SIÈGE (ÉTAT DE LA CITÉ DU VATICAN)'); INSERT INTO bkconvbic VALUES('D04','Code des pays',226,'VC','SAINT-VINCENT-ET-LES GRENADINES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',227,'VE','VENEZUELA, RÉPUBLIQUE BOLIVARIENNE DU'); INSERT INTO bkconvbic VALUES('D04','Code des pays',228,'VG','ÎLES VIERGES BRITANNIQUES'); INSERT INTO bkconvbic VALUES('D04','Code des pays',229,'VI','ÎLES VIERGES DES ÉTATS-UNIS'); INSERT INTO bkconvbic VALUES('D04','Code des pays',230,'VN','VIETNAM'); INSERT INTO bkconvbic VALUES('D04','Code des pays',231,'VU','VANUATU'); INSERT INTO bkconvbic VALUES('D04','Code des pays',232,'WF','WALLIS ET FUTUNA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',233,'WS','SAMOA'); INSERT INTO bkconvbic VALUES('D04','Code des pays',234,'YE','YÉMEN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',235,'YT','MAYOTTE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',236,'YU','YOUGOSLAVIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',237,'ZA','AFRIQUE DU SUD'); INSERT INTO bkconvbic VALUES('D04','Code des pays',238,'ZM','ZAMBIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',239,'ZW','ZIMBABWE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',240,'MF','SAINT MARTIN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',241,'IM','ISLE OF MAN'); INSERT INTO bkconvbic VALUES('D04','Code des pays',242,'AX','ILES ÅLAND'); INSERT INTO bkconvbic VALUES('D04','Code des pays',243,'GG','GUERNSEY'); INSERT INTO bkconvbic VALUES('D04','Code des pays',244,'JE','JERSEY'); INSERT INTO bkconvbic VALUES('D04','Code des pays',245,'ME','MONTÉNÉGRO'); INSERT INTO bkconvbic VALUES('D04','Code des pays',246,'BL','SAINT BARTHÉLEMY'); INSERT INTO bkconvbic VALUES('D04','Code des pays',247,'RS','SERBIE'); INSERT INTO bkconvbic VALUES('D04','Code des pays',248,'TL','TIMOR-ORIENTAL'); INSERT INTO bkconvbic VALUES('D04','Code des pays',249,'SS','SOUDAN DU SUD'); --D05 - Situation Familiale INSERT INTO bkconvbic VALUES('D05','Situation Familiale',1,'Single','Célibataire'); INSERT INTO bkconvbic VALUES('D05','Situation Familiale',2,'Married','Marié'); INSERT INTO bkconvbic VALUES('D05','Situation Familiale',3,'Divorced','Divorcé'); INSERT INTO bkconvbic VALUES('D05','Situation Familiale',5,'Widowed','Veuf'); INSERT INTO bkconvbic VALUES('D05','Situation Familiale',7,'Separated','Séparé'); INSERT INTO bkconvbic VALUES('D05','Situation Familiale',99,'Other','Autre'); --D07- Situation sociale INSERT INTO bkconvbic VALUES('D07','Situation sociale',0,'NotSpecified','Non précisé'); INSERT INTO bkconvbic VALUES('D07','Situation sociale',1,'Student','Etudiant'); INSERT INTO bkconvbic VALUES('D07','Situation sociale',2,'Employed','Employé ou travailleur indépendant (commerçant)'); INSERT INTO bkconvbic VALUES('D07','Situation sociale',3,'Unemployed','Sans emploi'); INSERT INTO bkconvbic VALUES('D07','Situation sociale',4,'Retired','Retraité'); INSERT INTO bkconvbic VALUES('D07','Situation sociale',5,'HomeMaker','Personne d`intérieur'); --D08 - Résidence INSERT INTO bkconvbic VALUES('D08','Résidence',1,'Yes','Résident du pays avec la citoyenneté du pays, ou citoyen d`un autre pays au sein du même marché (avec la même situation légale qu`un Résident)'); INSERT INTO bkconvbic VALUES('D08','Résidence',2,'No','Citoyen d`un autre pays'); --D09 - Emploi INSERT INTO bkconvbic VALUES('D09','Emploi',0,'NotSpecified','Non précisé'); INSERT INTO bkconvbic VALUES('D09','Emploi',1,'Farmer','Agriculteur'); INSERT INTO bkconvbic VALUES('D09','Emploi',4,'Accountant','Comptable'); INSERT INTO bkconvbic VALUES('D09','Emploi',7,'Lawyer','Avocat'); INSERT INTO bkconvbic VALUES('D09','Emploi',10,'Engineer','Ingénieur'); INSERT INTO bkconvbic VALUES('D09','Emploi',22,'AdministrativeOfficer','Responsable Administratif'); INSERT INTO bkconvbic VALUES('D09','Emploi',23,'Artisan','Artisan'); INSERT INTO bkconvbic VALUES('D09','Emploi',24,'AssistantManager','Assistant Cadre'); INSERT INTO bkconvbic VALUES('D09','Emploi',25,'Auditor','Contrôleur'); INSERT INTO bkconvbic VALUES('D09','Emploi',26,'BankAssistant','Assistant Banque'); INSERT INTO bkconvbic VALUES('D09','Emploi',27,'BankOfficer','Cadre Banque'); INSERT INTO bkconvbic VALUES('D09','Emploi',28,'Banker','Banquier'); INSERT INTO bkconvbic VALUES('D09','Emploi',29,'BranchManager','Cadre agence'); INSERT INTO bkconvbic VALUES('D09','Emploi',30,'BusinessAnalyst','Analyste des ventes'); INSERT INTO bkconvbic VALUES('D09','Emploi',31,'CEO_ChiefExecutiveOfficer','PDG - Président Directeur Général'); INSERT INTO bkconvbic VALUES('D09','Emploi',32,'ChiefMedicalExecutive','Chef Médical'); INSERT INTO bkconvbic VALUES('D09','Emploi',33,'CIO_ChiefInformationOfficer','DSI - Directeur Système d`Information'); INSERT INTO bkconvbic VALUES('D09','Emploi',34,'CivilEngineer','Ingénieur Civil'); INSERT INTO bkconvbic VALUES('D09','Emploi',35,'ClericalOfficer','Commis Principal'); INSERT INTO bkconvbic VALUES('D09','Emploi',36,'ComputerAnalystProgrammer','Analyste Programmeur'); INSERT INTO bkconvbic VALUES('D09','Emploi',37,'ComputerSystemsEngineer','Ingénieur Informatique'); INSERT INTO bkconvbic VALUES('D09','Emploi',38,'ControlRoomOperator','Opérateur de Salle de Contrôle'); INSERT INTO bkconvbic VALUES('D09','Emploi',39,'COO_ChiefOperatingOfficer','DO - Directeur des Opérations'); INSERT INTO bkconvbic VALUES('D09','Emploi',40,'DatabaseAdministrator','Administrateur de Base de Données'); INSERT INTO bkconvbic VALUES('D09','Emploi',41,'Director','Directeur'); INSERT INTO bkconvbic VALUES('D09','Emploi',42,'Driver','Chauffeur'); INSERT INTO bkconvbic VALUES('D09','Emploi',43,'Economist','Economiste'); INSERT INTO bkconvbic VALUES('D09','Emploi',44,'ElectricalEngineer','Ingénieur électricien'); INSERT INTO bkconvbic VALUES('D09','Emploi',45,'EstateOfficer','Fonctionnaire'); INSERT INTO bkconvbic VALUES('D09','Emploi',46,'FinancialAnalyst','Analyste financier'); INSERT INTO bkconvbic VALUES('D09','Emploi',47,'FinancialManager','Cadre financier'); INSERT INTO bkconvbic VALUES('D09','Emploi',48,'Foreman','Contremaître'); INSERT INTO bkconvbic VALUES('D09','Emploi',49,'HeadOfCorporateDivision','Chef de Division Groupe'); INSERT INTO bkconvbic VALUES('D09','Emploi',50,'HeadOfDailyOperations','Directeur des Opérations'); INSERT INTO bkconvbic VALUES('D09','Emploi',51,'HumanResourceOfficer','Directeur des Ressources Humaines'); INSERT INTO bkconvbic VALUES('D09','Emploi',52,'InsuranceOfficer','Directeur Assurance'); INSERT INTO bkconvbic VALUES('D09','Emploi',53,'InternalAuditor','Contrôleur Interne'); INSERT INTO bkconvbic VALUES('D09','Emploi',54,'InvestmentAdvisor','Conseiller en placements'); INSERT INTO bkconvbic VALUES('D09','Emploi',55,'ITSecurityAdministrator','Administrateur de sécurité informatique'); INSERT INTO bkconvbic VALUES('D09','Emploi',56,'ITTechnician','Technicien informatique'); INSERT INTO bkconvbic VALUES('D09','Emploi',57,'KitchenAttendant','Employé de cuisine'); INSERT INTO bkconvbic VALUES('D09','Emploi',58,'LaboratoryTechnician','Technicien de laboratoire'); INSERT INTO bkconvbic VALUES('D09','Emploi',59,'LegalOfficer','Directeur juridique'); INSERT INTO bkconvbic VALUES('D09','Emploi',60,'Librarian','Libraire'); INSERT INTO bkconvbic VALUES('D09','Emploi',61,'Liquidator','Liquidateur'); INSERT INTO bkconvbic VALUES('D09','Emploi',62,'Manager','Cadre'); INSERT INTO bkconvbic VALUES('D09','Emploi',63,'MarketingManager','Cadre marketing'); INSERT INTO bkconvbic VALUES('D09','Emploi',64,'MedicalDoctor','Docteur en médecine'); INSERT INTO bkconvbic VALUES('D09','Emploi',65,'MedicalOfficer','Médecin du travail'); INSERT INTO bkconvbic VALUES('D09','Emploi',66,'Messenger','Coursier'); INSERT INTO bkconvbic VALUES('D09','Emploi',68,'Nurse','Infirmière'); INSERT INTO bkconvbic VALUES('D09','Emploi',69,'OfficeManager','Cadre de bureau'); INSERT INTO bkconvbic VALUES('D09','Emploi',70,'OperationManager','Cadre des opérations'); INSERT INTO bkconvbic VALUES('D09','Emploi',71,'OrganizationalAnalyst','Analyste organisation'); INSERT INTO bkconvbic VALUES('D09','Emploi',72,'PersonalSecretary','Secrétaire'); INSERT INTO bkconvbic VALUES('D09','Emploi',73,'PersonnelManager','Cadre personnel'); INSERT INTO bkconvbic VALUES('D09','Emploi',74,'PharmaceuticalAssistant','Assistant pharmacie'); INSERT INTO bkconvbic VALUES('D09','Emploi',75,'PlanningOfficer','Responsable planning'); INSERT INTO bkconvbic VALUES('D09','Emploi',76,'ProductionManager','Cadre de production'); INSERT INTO bkconvbic VALUES('D09','Emploi',77,'Professor','Professeur'); INSERT INTO bkconvbic VALUES('D09','Emploi',78,'ProgrammeCoordinator','Coordinateur de programme'); INSERT INTO bkconvbic VALUES('D09','Emploi',79,'ProjectManager','Ched de projet'); INSERT INTO bkconvbic VALUES('D09','Emploi',80,'PublicRelationsAssistant','Assistant relations publiques'); INSERT INTO bkconvbic VALUES('D09','Emploi',81,'PublicRelationsManager','Cadre en relations publiques'); INSERT INTO bkconvbic VALUES('D09','Emploi',82,'PublicRelationsOfficer','Officier en relations publiques'); INSERT INTO bkconvbic VALUES('D09','Emploi',83,'PurchasingManager','Cadre achats'); INSERT INTO bkconvbic VALUES('D09','Emploi',84,'Receptionist','Réceptionniste'); INSERT INTO bkconvbic VALUES('D09','Emploi',85,'RecordsManagementOfficer','Responsable de gestion des dossiers'); INSERT INTO bkconvbic VALUES('D09','Emploi',86,'RegistryAssistant','Assistant registre'); INSERT INTO bkconvbic VALUES('D09','Emploi',87,'SalesManager','Directeur des ventes'); INSERT INTO bkconvbic VALUES('D09','Emploi',88,'SecurityGuard','Gardien de sécurité'); INSERT INTO bkconvbic VALUES('D09','Emploi',89,'SecurityOfficer','Officier de sécurité'); INSERT INTO bkconvbic VALUES('D09','Emploi',90,'ServiceManager','Gestionnaire de services'); INSERT INTO bkconvbic VALUES('D09','Emploi',91,'SocialAffairs','Affaires sociales'); INSERT INTO bkconvbic VALUES('D09','Emploi',92,'SpecialAssignments','Mission spéciale'); INSERT INTO bkconvbic VALUES('D09','Emploi',93,'Statistician','Statisticien'); INSERT INTO bkconvbic VALUES('D09','Emploi',94,'StoreManager','Directeur de magasin'); INSERT INTO bkconvbic VALUES('D09','Emploi',95,'Supervisor','Superviseur'); INSERT INTO bkconvbic VALUES('D09','Emploi',96,'SuppliesOfficer','Charge de l`Approvisionnement'); INSERT INTO bkconvbic VALUES('D09','Emploi',97,'TechnicalSupervisor','Superviseur Technique'); INSERT INTO bkconvbic VALUES('D09','Emploi',98,'TechnicianEngineer','Ingénieur tehnique'); INSERT INTO bkconvbic VALUES('D09','Emploi',99,'TelephoneOperator','Opérateur téléphonique'); INSERT INTO bkconvbic VALUES('D09','Emploi',100,'TransportOfficer','Officier de transport'); INSERT INTO bkconvbic VALUES('D09','Emploi',101,'TransportationManager','Cadre de transport'); INSERT INTO bkconvbic VALUES('D09','Emploi',102,'ViceCEO','PDG Adjoint / Directeur Général'); INSERT INTO bkconvbic VALUES('D09','Emploi',103,'WardAttendant','Préposé de salle'); INSERT INTO bkconvbic VALUES('D09','Emploi',9999,'Other','Autre'); --D10 - Niveau de formation INSERT INTO bkconvbic VALUES('D10','Niveau de formation',0,'NotSpecified','Non précisé'); INSERT INTO bkconvbic VALUES('D10','Niveau de formation',1,'NoEducation','Pas de formation'); INSERT INTO bkconvbic VALUES('D10','Niveau de formation',2,'Primary','Primaire, de base'); INSERT INTO bkconvbic VALUES('D10','Niveau de formation',3,'Secondary','Secondaire'); INSERT INTO bkconvbic VALUES('D10','Niveau de formation',4,'HigherEducation','Education supérieure'); INSERT INTO bkconvbic VALUES('D10','Niveau de formation',5,'AcademicDegree','Diplôme université'); INSERT INTO bkconvbic VALUES('D10','Niveau de formation',99,'Other','Autre'); --D12 - Forme Légale INSERT INTO bkconvbic VALUES('D12','Forme Légale',1,'JointLiabilityCompany','Société Anonyme'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',2,'SpecialPartnershipCompany','Société Partenariat Spéciale / Partenariat Limité'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',3,'LimitedLiabilityCompanyPublic','Société à Responsabilité Limitée Publique'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',4,'LimitedLiabilityCompanyPrivate','Société Anonyme à Responsabilité Limitée'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',5,'JointStockCompany','Société côtée'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',6,'Cooperative','Coopérative'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',7,'Foundations','Fondation'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',8,'Association','Association'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',9,'Audit','Audit'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',10,'Notary','Notaire'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',11,'CoPartnership','Co-partenariat'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',12,'NonRegisteredAssociation','Association non déclarée'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',13,'ReligiousOrganization','Organisation religieuse'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',14,'GovernmentalInstitution','Institution gouvernementale'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',15,'Political','Parti politique, syndicat'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',16,'PublicInstitution','Institution Publique'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',17,'Branch','Agence'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',18,'LegalPersonUnderPublicLaw','Personne morale de droit public'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',24,'SoleOwnershipLimitedLiabilityCo','Société Unipersonnelle à Responsabilité Limité (SURL)'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',25,'GeneralPartnership','Société en Nom Collectif (SNC)'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',26,'LimitedPartnership','Société en Commandite Simple (SCS)'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',27,'SimplifiedJointStockCompany','Société par Actions Simplifiées (SAS)'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',28,'EconomicInterestGrouping','Groupement d`Intérêt Economique (GIE)'); INSERT INTO bkconvbic VALUES('D12','Forme Légale',99,'Other','Autre'); --D13 - Etat de l'entreprise INSERT INTO bkconvbic VALUES('D13','Etat de l`entreprise',1,'Active','Active'); INSERT INTO bkconvbic VALUES('D13','Etat de l`entreprise',2,'Closed','Fermée'); INSERT INTO bkconvbic VALUES('D13','Etat de l`entreprise',3,'InBankrupcy','Pas fermé, mais sous procédure de faillite'); INSERT INTO bkconvbic VALUES('D13','Etat de l`entreprise',4,'SupervisoryCrisisAdministration','Sous tutelle de l`administration'); INSERT INTO bkconvbic VALUES('D13','Etat de l`entreprise',5,'OtherCourtActionByBank','Autre action en justice par la banque'); INSERT INTO bkconvbic VALUES('D13','Etat de l`entreprise',6,'BankruptcyPetitionByBank','Demande de mise en liquidation par la banque'); INSERT INTO bkconvbic VALUES('D13','Etat de l`entreprise',7,'Liquidation','Liquidation'); INSERT INTO bkconvbic VALUES('D13','Etat de l`entreprise',8,'AssetsFrozenOrSeized','Actifs gelés ou saisis'); --D14 - Secteur d'activité INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',2,'FinancialIntermediaries','Etablissements financiers'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',3,'Fishing','Pêche'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',8,'BuildingAndConstruction','Bâtiment et travaux publics'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',17,'RealEstate','Affaires immobilières et services fournis aux entreprises'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',29,'AgricultureAndHunting','Agriculture et chasse'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',30,'Forestry','Sylviculture et exploitation forestière'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',31,'CoalMining','Extraction du charbon'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',32,'CrudeOilAndNaturalGasProduction','Production de pétrole brut et de gaz naturel'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',33,'Mining','Extraction de minerais métalliques'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',34,'OtherMining','Extraction d`autres minéraux'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',35,'ManufactureOfFoodProductsBeveragesAndTobacco','Fabrication de produits alimentaires, boissons et tabac'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',36,'TextilesIndustriesClothingAndLeather','Industries des textiles, de l`habillement et du cuir'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',37,'WoodIndustryAndandManufacturing','Industrie du bois et fabrication d`ouvrages en bois y compris les meubles'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',38,'PaperManufacturingPrintingAndPublishing','Fabrication du papier, imprimerie et édition'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',39,'ChemicalIndustryAndChemicalManufacturing','Industrie chimique et fabrication de produits chimiques'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',40,'NonMetallicMineral','Produits minéraux non métalliques'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',41,'BasicMetalIndustries','Industrie métallurgique de base'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',42,'MetalManufacturingProductMachineryAndEquipment','Fabrication d`ouvrages en métaux, de machines, de matériel'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',43,'OtherManufacturingIndustries','Autres industries manufacturières'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',44,'ElectricityGasAndSteam','Electricité, gaz et vapeur'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',45,'WaterDistributionFacilitiesAndPublicWaterSupplyOtherThanForAgriculture','Installations de distribution d`eau et distribution publique de l`eau (autres que pour l`agriculture'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',46,'Wholesale','Commerce de gros'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',47,'Retail','Commerce de détail'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',48,'HotelsRestaurantsAndTourism','Restaurants, Hôtels et installations touristiques'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',49,'TransportWarehousingAndStorage','Transports et entrepôts'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',50,'Communication','Communication'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',51,'Insurances','Assurances'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',52,'PublicAdministrationAndNationalDefence','Administration publique et défense nationale'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',53,'HealthAndSimilarServices','Services sanitaires et services analogues'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',54,'SocialAndRelatedServicesProvidedToTheCommunity','services sociaux et services connexes fournis à la collectivité'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',55,'RecreationAndCultureServices','Services récréatifs et services culturels'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',56,'ServicesProvidedToHouseholdsAndIndividuals','Services fournis aux ménages et aux particuliers'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',57,'InternationalAndOtherExtraTerritorialOrganizations','Organisations internationales et autres organismes extra-territoriaux'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',58,'CommitmentToBeTheSubjectOfSubsequentCharging','Engagement devant faire l`objet d`imputation ultérieure'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',59,'Individuals','Particuliers'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',60,'Agriculture','Métiers de l`agriculture'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',61,'InformationTechnologies','Métiers de l`informatique'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',62,'Education','Métiers de l`enseignement'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',63,'MedicalServices','Services médicaux'); INSERT INTO bkconvbic VALUES('D14','Secteur d`activité',64,'Other','Autre'); --D15 - Situation négative de la personne INSERT INTO bkconvbic VALUES('D15.1','Situation négative de la personne',0,'NotSpecified','Non précisé'); INSERT INTO bkconvbic VALUES('D15.1','Situation négative de la personne',1,'NoNegativeStatus','Pas de situation négative'); INSERT INTO bkconvbic VALUES('D15.1','Situation négative de la personne',2,'SupervisoryOrCrisisAdministration','Sous tutelle ou contrôle de l`administration'); INSERT INTO bkconvbic VALUES('D15.1','Situation négative de la personne',3,'OtherCourtActionByBank','Autre action de justice par la banque'); INSERT INTO bkconvbic VALUES('D15.1','Situation négative de la personne',4,'BankruptcyPetitionByBank','Demande de liquidation par la banque'); INSERT INTO bkconvbic VALUES('D15.1','Situation négative de la personne',5,'BankruptcyPetition','Demande de liquidation'); INSERT INTO bkconvbic VALUES('D15.1','Situation négative de la personne',6,'CourtDeclaredBankruptcy','Faillite déclarée'); INSERT INTO bkconvbic VALUES('D15.1','Situation négative de la personne',7,'Receivership','Redressement judiciaire'); INSERT INTO bkconvbic VALUES('D15.1','Situation négative de la personne',8,'Liquidation','Liquidation'); INSERT INTO bkconvbic VALUES('D15.1','Situation négative de la personne',9,'AssetsFrozenOrSeized','Actifs gelés ou saisis'); INSERT INTO bkconvbic VALUES('D15.1','Situation négative de la personne',10,'CustomerUntraceableOrDeceased','Client introuvable ou mort'); --D15 - Type de relation (entre sujets) INSERT INTO bkconvbic VALUES('D15.2','Type de relation',1,'Spouse','Conjoint'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',2,'Soleowner','Actionnaire unique'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',3,'Shareholder','Actionnaire'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',4,'CEO','PDG'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',5,'COO','Directeur des opérations'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',6,'FinancialDirector','Directeur financier'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',7,'MainAccountant','Chef comptable'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',8,'TopManager','Cadre supérieur'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',9,'MiddleManager','Cadre moyen'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',10,'Representative','Autre représentant de l`entreprise'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',11,'Employee','Employé'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',12,'Employer','Employé'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',13,'CompanyFullyOwned','Entreprise en propriété exclusive'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',14,'CompanyPartlyOwned','Entreprise détenue en partie'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',15,'Branch','Succursale'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',16,'Affiliate','Filiale'); INSERT INTO bkconvbic VALUES('D15.2','Type de relation',99,'Other','Autre'); --D16 - Type du sujet INSERT INTO bkconvbic VALUES('D16','Type du sujet',1,'Individual','Aucun statut négatif'); INSERT INTO bkconvbic VALUES('D16','Type du sujet',2,'Company','Supervisory or crisis administration'); --D16.1 - Phase du contrat INSERT INTO bkconvbic VALUES('D16.1','Phase du contrat',1,'Open','Le contrat est ouvert. Voir D16.2'); INSERT INTO bkconvbic VALUES('D16.1','Phase du contrat',2,'Closed','Le contrat est fermé. Voir D16.3'); --D16.2 - Situation de contrat ouvert INSERT INTO bkconvbic VALUES('D16.2','Situation du contrat ouvert',1,'GrantedButNotActivated','Le contrat est octroyé, mais les fonds n`ont pas encore été versés (par exemple, en attente de certaines conditions)'); INSERT INTO bkconvbic VALUES('D16.2','Situation du contrat ouvert',2,'GrantedAndActivated','Le contrat est actif et ouvert. Les fonds ont été versés au principal débiteur'); INSERT INTO bkconvbic VALUES('D16.2','Situation du contrat ouvert',3,'Rescheduled','Le contrat est Actif et Ouvert, les conditions principales du contrat ont été modifées, changées et acceptées (portant par exemple sur le Montant Total, la Date Prévue de Fin de Contrat, etc.)'); --D16.3 - Situation de contrat fermé INSERT INTO bkconvbic VALUES('D16.3','Situation du contrat fermé',4,'SettledOnTime','Le contrat est entièrement Réglé et Fermé, entièrement remboursé, selon les conditions du contrat et l`échéancier.'); INSERT INTO bkconvbic VALUES('D16.3','Situation du contrat fermé',5,'SettledInAdvance','Le contrat est entièrement Réglé et Fermé, entièrement remboursé en avance - avant la date acceptée de fin de contrat.'); INSERT INTO bkconvbic VALUES('D16.3','Situation du contrat fermé',6,'WithArrearsNoRepossession','Le Contrat est Fermé avec des paiements en retard, et aucune procédure de reprise n`a eu lieu.'); INSERT INTO bkconvbic VALUES('D16.3','Situation du contrat fermé',7,'WithArrearsAndRepossession','Le Contrat est Fermé avec des paiements en retard, et une procédure de reprise a eu lieu.'); INSERT INTO bkconvbic VALUES('D16.3','Situation du contrat fermé',8,'Cancelled','Le Contrat est Fermé et Annulé à cause d`une usurpation d`identité (le principal créancier est une autre personne que le fraudeur) ou à cause d`une autre personne, dont la responsabilité n`incombe pas au principal débiteur d`origine.'); INSERT INTO bkconvbic VALUES('D16.3','Situation du contrat fermé',9,'SoldToThirdParty','Vendu à une partie Tierce pour recouvrement'); INSERT INTO bkconvbic VALUES('D16.3','Situation du contrat fermé',10,'WrittenOff','Créance Abandonnée'); --D17 - Situation de transfert INSERT INTO bkconvbic VALUES('D17','Situation du transfert',0,'NotSpecified','Non précisé'); INSERT INTO bkconvbic VALUES('D17','Situation du transfert',1,'NoTransfer','Le débiteur principal est l`original. Il n`y a pas eu de transfert.'); INSERT INTO bkconvbic VALUES('D17','Situation du transfert',2,'TransferredFromAnotherMainDebtor','Le contrat a été transféré au débiteur principal actuel par une autre personne. Dédié aux Contrats Ouverts et Fermés.'); INSERT INTO bkconvbic VALUES('D17','Situation du transfert',3,'TransferredToAnotherMainDebtor','Le contrat a été transféré du débiteur principal actuel à une autre personne, qui devient le créancier principal. Dédié uniquement aux Contrats Ouverts et Fermés.'); --D18 - Type de contrat INSERT INTO bkconvbic VALUES('D18','Type de contrat',1,'Installment','Contrat des versements'); INSERT INTO bkconvbic VALUES('D18','Type de contrat',2,'NonInstallment','Pas de contrat des versements'); INSERT INTO bkconvbic VALUES('D18','Type de contrat',3,'CreditCard','Carte de crédit'); INSERT INTO bkconvbic VALUES('D18','Type de contrat',4,'RevolvingCredit','Crédit Renouvelable'); INSERT INTO bkconvbic VALUES('D18','Type de contrat',5,'Invoice','Facture impayée ou non réglée'); --D19 - Objet du financement INSERT INTO bkconvbic VALUES('D19','Objet du financement',1,'PersonalLoan','Prêt personnel - non relié à un achat spécifique. Achats de biens de consommation à usage personnel'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',2,'PersonalLoanForExactPurpose','Crédit personnel - pour acheter un bien spécifique, avec accord de l`institution financière'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',3,'Mortgage','Prêt pour acheter un appartement ou un immeuble'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',4,'Leasing','Leasing'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',5,'Overdraft','Limite de crédit sur le compte courant'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',6,'Development','Développement'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',7,'WorkingCapital','Fonds de roulement'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',8,'Repair','Dépannage'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',9,'TelecomServices','Services de téléphoniqe mobile, etc.'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',10,'Construct','Construction'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',11,'PurchaseOfBuilding','Acquisition de bâtiment'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',12,'PurchaseOfPersonalConsumingProducts','Achat de biens de consommation'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',13,'SyndicatedLoan','Prêt syndiqué'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',14,'StudentLoan','Prêt étudiant'); INSERT INTO bkconvbic VALUES('D19','Objet du financement',99,'Other','Autre'); --D20 Liste des devises INSERT INTO bkconvbic VALUES('D20','Liste des devises',0,'NotSpecified','Non spécifié'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',1,'AED','Dirham des émirats arabes unis'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',2,'AFN','Afghani'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',3,'ALL','Lek'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',4,'AMD','Dram arménien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',5,'ANG','Florin des Antilles'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',6,'AOA','Kwanza'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',7,'ARS','Peso argentin'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',8,'AUD','Dollar australien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',9,'AWG','Florin d`Aruba'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',10,'AZN','Manat'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',11,'BAM','Mark convertible'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',12,'BBD','Dollar de Barbade'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',13,'BDT','Taka'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',14,'BGN','Lev de Bulgarie'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',15,'BHD','Dinar de Bahreïn'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',16,'BIF','Franc du Burundi'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',17,'BMD','Dollar des Bermudes'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',18,'BND','Dollar de Brunei'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',19,'BOB','Boliviano (Mvdol)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',20,'BOV','Bolivian Mvdol (funds code)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',21,'BRL','Real de Brésil'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',22,'BSD','Dollar des Bahamas'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',23,'BTN','Bhutan Ngultrum'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',24,'BWP','Pula'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',25,'BYR','Rouble bélorusse'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',26,'BZD','Dollar de Belize'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',27,'CAD','Dollar canadien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',28,'CDF','Franc Congolais'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',29,'CHE','WIR Bank (complementary currency) (Switzerland)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',30,'CHF','Franc Suisse'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',31,'CHW','WIR Bank (complementary currency) (Switzerland)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',32,'CLF','Unidad de Fomento (funds code) Chile'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',33,'CLP','Peso chilien (Unité d`investissement)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',34,'CNY','Yuan Ren-Min-Bi'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',35,'COP','Peso colombien (Unidad de Valor Real)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',36,'COU','Colombian Unidad de Valor Real'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',37,'CRC','Colon de Costa Rica'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',38,'CUC','Peso cubain convertible'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',39,'CUP','Peso cubain'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',40,'CVE','Escudo du Cap-Vert'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',41,'CZK','Couronne tchèque'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',42,'DJF','Franc de Djibouti'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',43,'DKK','Couronne danoise'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',44,'DOP','Peso dominicain'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',45,'DZD','Dinar algérien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',46,'EEK','Couronne estonienne'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',47,'EGP','Livre égyptienne'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',48,'ERN','Nakfa'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',49,'ETB','Birr éthiopien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',50,'EUR','Euro'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',51,'FJD','Dollar de Fidji'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',52,'FKP','Livre de Falkland'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',53,'GBP','Livre Sterling'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',54,'GEL','Lari'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',55,'GHS','Ghana Cedi'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',56,'GIP','Livre de Gibraltar'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',57,'GMD','Dalasi'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',58,'GNF','Franc guinéen'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',59,'GTQ','Quetzal'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',60,'GYD','Dollar de Guyane'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',61,'HKD','Dollar de Hong-Kong'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',62,'HNL','Lempira'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',63,'HRK','Kuna'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',64,'HTG','Gourde (Dollar des États-Unis)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',65,'HUF','Forint'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',66,'IDR','Rupiah'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',67,'ILS','Nouvel israëli sheqel'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',68,'INR','Roupie indienne'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',69,'IQD','Dinar iraquien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',70,'IRR','Rial iranien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',71,'ISK','Couronne islandaise'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',72,'JMD','Dollar jamaïcain'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',73,'JOD','Dinar jordanien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',74,'JPY','Yen'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',75,'KES','Shilling du Kenya'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',76,'KGS','Som'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',77,'KHR','Riel'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',78,'KMF','Franc des Comores'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',79,'KPW','Won de la Corée du Nord'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',80,'KRW','Won'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',81,'KWD','Dinar koweïtien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',82,'KYD','Dollar des Iles Caïmanes'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',83,'KZT','Tenge'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',84,'LAK','Kip'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',85,'LBP','Livre libanaise'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',86,'LKR','Roupie de Sri Lanka'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',87,'LRD','Dollar libérien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',88,'LSL','Lesotho loti'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',89,'LTL','Litas lituanien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',90,'LVL','Lats letton'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',91,'LYD','Dinar libyen'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',92,'MAD','Dirham marocain'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',93,'MDL','Leu de Moldovie'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',94,'MGA','Malagasy Ariary'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',95,'MKD','Denar'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',96,'MMK','Kyat'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',97,'MNT','Tugrik'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',98,'MOP','Pataca'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',99,'MRO','Ouguija'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',100,'MUR','Roupie de Maurice'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',101,'MVR','Rufiyaa'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',102,'MWK','Kwacha de Malawi'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',103,'MXN','Peso mexicain'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',104,'MXV','Peso mexicain (Mexican Unidad de Inversion - UDI)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',105,'MYR','Ringgit de Malaisie'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',106,'MZN','Metical'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',107,'NAD','Dollar Namibien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',108,'NGN','Naira'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',109,'NIO','Cordoba Oro'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',110,'NOK','Couronne norvégienne'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',111,'NPR','Roupie du Népal'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',112,'NZD','Dollar néo-zélandais'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',113,'OMR','Rial Omani'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',114,'PAB','Balboa (Dollar des États-Unis)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',115,'PEN','Nouveau Sol'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',116,'PGK','Kina'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',117,'PHP','Peso philippin'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',118,'PKR','Roupie du Pakistan'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',119,'PLN','Zloty'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',120,'PYG','Guarani'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',121,'QAR','Riyal du Qatar'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',122,'RON','Nouveau Leu'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',123,'RSD','Dinar de Serbie'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',124,'RUB','Rouble russe'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',125,'RWF','Franc du Rwanda'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',126,'SAR','Riyal saoudien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',127,'SBD','Dollar de Salomon'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',179,'SSP','Livre Sud Soudanaise'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',128,'SCR','Roupie des Seychelles'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',129,'SDG','Livre soudanaise'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',130,'SEK','Couronne suédoise'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',131,'SGD','Dollar de Singapour'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',132,'SHP','Livre de Sainte-Hélène'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',133,'SLL','Leone'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',134,'SOS','Shilling de Somalie'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',135,'SRD','Dollar de Suriname'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',136,'STD','Dobra'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',137,'SYP','Livre syrienne'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',138,'SZL','Lilangeni'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',139,'THB','Baht'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',140,'TJS','Somoni'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',141,'TMT','Manat Turkmenistan'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',142,'TND','Dinar tunisien'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',143,'TOP','Pa`anga'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',144,'TRY','Nouvelle Livre'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',145,'TTD','Dollar de la Trinité et de Tobago'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',146,'TWD','Nouveau dollar de Taïwan'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',147,'TZS','Shilling de Tanzanie'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',148,'UAH','Hryvnia'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',149,'UGX','Nouveau Shilling ougandais'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',150,'USD','Dollar des États-Unis'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',151,'USN','Dollar des États-Unis (prochain jour) (funds code)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',152,'USS','Dollar des États-Unis (même jour) (funds code)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',153,'UYU','Peso uruguayen'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',154,'UZS','Soum d`Ouzbékistan'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',155,'VEF','Bolivar Fuerte'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',156,'VND','Dong'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',157,'VUV','Vatu'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',158,'WST','Tala'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',159,'XAF','Franc CFA - BEAC  '); INSERT INTO bkconvbic VALUES('D20','Liste des devises',160,'XAG','Argent'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',161,'XAU','Or'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',162,'XBA','Unité européenne composée (EURCO)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',163,'XBB','Unité monétaire européenne (U.M.E.-6 monnaie)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',164,'XBC','Unité de compte 9 (U.E.C.-9 monnaie)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',165,'XBD','Unité de compte 17(U.E.C.-17 monnaie)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',166,'XCD','Dollar des Caraïbes orientales'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',167,'XDR','Droit de tirage spécial (D.T.S.)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',168,'XFU','Franc UIC (special settlement currency) (International Union of Railways)'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',169,'XOF','Franc CFA - BCEAO'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',170,'XPD','Palladium'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',171,'XPF','Franc CFP'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',172,'XPT','Platine'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',173,'XTS','Riyal du Yémen'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',174,'XXX','Pas de devise'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',175,'YER','Yemeni rial'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',176,'ZAR','Rand Sud Africain'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',177,'ZMK','Kwacha de Zambie'); INSERT INTO bkconvbic VALUES('D20','Liste des devises',178,'ZWL','Dollar du Zimbabwe'); --D21 - Périodicité des types de paiement INSERT INTO bkconvbic VALUES('D21','Périodicité des types de paiement',1,'FinalDay','Dernier jour de la période de contrat'); INSERT INTO bkconvbic VALUES('D21','Périodicité des types de paiement',2,'Days7','Périodicité de 7 jours'); INSERT INTO bkconvbic VALUES('D21','Périodicité des types de paiement',3,'Days15','Versements bimensuels'); INSERT INTO bkconvbic VALUES('D21','Périodicité des types de paiement',4,'Days30','Versements mensuels - tous les 30 jours'); INSERT INTO bkconvbic VALUES('D21','Périodicité des types de paiement',5,'Days60','Versements bimestriels - tous les 60 jours'); INSERT INTO bkconvbic VALUES('D21','Périodicité des types de paiement',6,'Days90','Versements trimestriels - tous les 90 jours'); INSERT INTO bkconvbic VALUES('D21','Périodicité des types de paiement',7,'Days120','Versements tous les quatre mois - tous les 120 jours'); INSERT INTO bkconvbic VALUES('D21','Périodicité des types de paiement',8,'Days150','Versements tous les cinq mois - tous les 150 jours'); INSERT INTO bkconvbic VALUES('D21','Périodicité des types de paiement',9,'Days180','Versements biannuels - tous les 180 jours'); INSERT INTO bkconvbic VALUES('D21','Périodicité des types de paiement',10,'Days360','Versements annuels - tous les 360 jours'); INSERT INTO bkconvbic VALUES('D21','Périodicité des types de paiement',11,'Irregular','Versement irréguliers'); --D22 - Type de garantie INSERT INTO bkconvbic VALUES('D22','Type de garantie',1,'Land','Terrain'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',2,'RealEstate','Immobilier'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',3,'MotorVehicle','Véhicule à moteur'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',4,'CashSecurity','Valeur de Sûreté'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',5,'Shares','Actions'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',6,'SavingsDeposits','Dépôts d`épargne'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',7,'Machinery','Machines'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',8,'InsurancePolicy','Assurance'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',9,'OtherIndividualProperty','Autre propriété individuelle'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',10,'PersonalGuarantees','Garantie personnelle - seulement dans le cas où le garant ne peut pas être déclaré au niveau de l`enregistrement personnel standard et lié au contrat dans le rôle de "garant"'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',11,'StateGuarantees','Garanties publiques'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',12,'Financial','Toute garantie financière non précisée'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',13,'NonFinancial','Toute garantie non financière non précisée'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',14,'Stocks','Actions'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',15,'Deposit','Dépôts'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',16,'SalaryDeposit','Salaire Dépôts'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',17,'TerminalBenefits','Bénéfice final'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',18,'Equipment','Equipement'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',19,'GovernmentSecurities','Titres d`état'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',20,'Gold','Or'); INSERT INTO bkconvbic VALUES('D22','Type de garantie',99,'Other','Autre'); --D23 - Situation négative de contrat INSERT INTO bkconvbic VALUES('D23','Situation négative de contrat',0,'NotSpecified','Non précisé'); INSERT INTO bkconvbic VALUES('D23','Situation négative de contrat',1,'NoNegativeStatus','Pas de situation négative'); INSERT INTO bkconvbic VALUES('D23','Situation négative de contrat',2,'UnauthorizedDebitBalanceOnCurrentAccount','Solde négatif non autorisé sur compte courant'); INSERT INTO bkconvbic VALUES('D23','Situation négative de contrat',3,'Blocked','Bloqué'); INSERT INTO bkconvbic VALUES('D23','Situation négative de contrat',4,'CancelledDueToDelayedPayments','Annulé pour cause de paiements en retard'); INSERT INTO bkconvbic VALUES('D23','Situation négative de contrat',5,'InsuranceFraud','Fraude assurance'); INSERT INTO bkconvbic VALUES('D23','Situation négative de contrat',6,'FraudTowardsBank','Fraude envers la banque'); INSERT INTO bkconvbic VALUES('D23','Situation négative de contrat',7,'CreditReassignedToNewDebtor','Crédit réalloué à nouveau débiteur'); INSERT INTO bkconvbic VALUES('D23','Situation négative de contrat',8,'AssignmentOfCreditToThirdParty','Allocation de crédit à une tierce partie (sans remise)'); INSERT INTO bkconvbic VALUES('D23','Situation négative de contrat',9,'LoanWrittenOff','Prêt radié au compte hors-bilan'); INSERT INTO bkconvbic VALUES('D23','Situation négative de contrat',10,'IncreasedRisk','Risque accru'); INSERT INTO bkconvbic VALUES('D23','Situation négative de contrat',11,'LoanTransferredToLosses','Prêt passé en pertes, 100% non liquide, sur les postes du bilan'); --D25 - Moyen de paiement INSERT INTO bkconvbic VALUES('D25','Moyen de paiement',1,'CurrentAccount','Compte courant'); INSERT INTO bkconvbic VALUES('D25','Moyen de paiement',2,'BillOfExchange','Lettre de change'); INSERT INTO bkconvbic VALUES('D25','Moyen de paiement',3,'BankingReceipt','Avis bancaire'); INSERT INTO bkconvbic VALUES('D25','Moyen de paiement',4,'DirectRemittance','Collecte directe'); INSERT INTO bkconvbic VALUES('D25','Moyen de paiement',5,'AuthorizationToDirectCurrentAccountDebit','Autorisation de débit sur compte courant'); -- ------------ -- DIMlab_UTB180122-01_01_STR_ora.sql -- ------------ --DROP INDEX FK_ABPPE$EVUTI; --DROP INDEX FK_ABLIENSPPE$BKCLI; --DROP INDEX FK_ABLIENSPPE$EVUTI; --DROP INDEX FK_ABHISPPE$EVUTI; --DROP INDEX FK_ABHISPPE$EVUTI2; --DROP INDEX FK_ABTRACFINPPE$EVUTI; --DROP INDEX FK_ABHISACT$EVUTI; --DROP INDEX FK_ABHISACT$BKCLI; --table abppe ALTER TABLE abppe DROP CONSTRAINT FK_ABPPE$EVUTI; DROP INDEX FK_ABPPE$EVUTI; CREATE INDEX FK_ABPPE$EVUTI ON abppe (cuti); ALTER TABLE abppe ADD CONSTRAINT FK_ABPPE$EVUTI FOREIGN KEY (cuti) REFERENCES evuti (cuti) ; --table abliensppe ALTER TABLE abliensppe DROP CONSTRAINT FK_ABPPE$BKCLI; DROP INDEX FK_ABLIENSPPE$BKCLI; CREATE INDEX FK_ABLIENSPPE$BKCLI ON abliensppe (cli); ALTER TABLE abliensppe ADD CONSTRAINT FK_ABLIENSPPE$BKCLI FOREIGN KEY (cli) REFERENCES bkcli (cli); --table abliensppe ALTER TABLE abliensppe DROP CONSTRAINT FK_ABLIENSPPE$EVUTI; DROP INDEX FK_ABLIENSPPE$EVUTI; CREATE INDEX FK_ABLIENSPPE$EVUTI ON abliensppe (cuti); ALTER TABLE abliensppe ADD CONSTRAINT FK_ABLIENSPPE$EVUTI FOREIGN KEY (cuti) REFERENCES evuti (cuti); --table abhisppe ALTER TABLE abhisppe DROP CONSTRAINT FK_ABHISPPE$EVUTI; DROP INDEX FK_ABHISPPE$EVUTI; CREATE INDEX FK_ABHISPPE$EVUTI ON abhisppe (cuti); ALTER TABLE abhisppe ADD CONSTRAINT FK_ABHISPPE$EVUTI FOREIGN KEY (cuti) REFERENCES evuti (cuti); --table abhisppe ALTER TABLE abhisppe DROP CONSTRAINT FK_ABHISPPE$EVUTI2; DROP INDEX FK_ABHISPPE$EVUTI2; CREATE INDEX FK_ABHISPPE$EVUTI2 ON abhisppe (cutim); ALTER TABLE abhisppe ADD CONSTRAINT FK_ABHISPPE$EVUTI2 FOREIGN KEY (cutim) REFERENCES evuti (cuti); --table abtracfinppe ALTER TABLE abtracfinppe DROP CONSTRAINT FK_ABTRACFINPPE$EVUTI; DROP INDEX FK_ABTRACFINPPE$EVUTI; CREATE INDEX FK_ABTRACFINPPE$EVUTI ON abtracfinppe (cuti); ALTER TABLE abtracfinppe ADD CONSTRAINT FK_ABTRACFINPPE$EVUTI FOREIGN KEY (cuti) REFERENCES evuti (cuti); --table abhisact ALTER TABLE abhisact DROP CONSTRAINT FK_ABHISACT$EVUTI; DROP INDEX FK_ABHISACT$EVUTI; CREATE INDEX FK_ABHISACT$EVUTI ON abhisact (cuti); ALTER TABLE abhisact ADD CONSTRAINT FK_ABHISACT$EVUTI FOREIGN KEY (cuti) REFERENCES evuti (cuti); --table abhisact ALTER TABLE abhisact DROP CONSTRAINT FK_ABTRACFINPPE$BKCLI; DROP INDEX FK_ABHISACT$BKCLI; CREATE INDEX FK_ABHISACT$BKCLI ON abhisact (cli); ALTER TABLE abhisact ADD CONSTRAINT FK_ABHISACT$BKCLI FOREIGN KEY (cli) REFERENCES bkcli (cli); -- --------------------------------- -- Mise a jour hebdomadaire de evmod -- --------------------------------- UPDATE evmod SET amod = '11.1.4', dmod = SYSDATE WHERE cmod = 'DELTA-BANK'; -- ---------------------------------------- -- Mise a jour hebdomadaire de evhistscript -- ---------------------------------------- INSERT INTO evhistscript VALUES ('mig_11.1.4_ora.sql',SYSDATE); ``` ServerController.java ```package com.sopraMdv.anotherProject.Controller; import java.io.IOException; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.jcraft.jsch.JSchException; import com.sopraMdv.anotherProject.dao.ServerDAO; import com.sopraMdv.anotherProject.entities.Server; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.scene.layout.VBox; @Controller public class ServerController { private Validator validator; private ObservableList<String> platforms = FXCollections.observableArrayList("Redhat", "AIX"); @FXML private Label errorLabel; @FXML private TextField nameServ; @FXML private TextField hostServ; @FXML private TextField portServ; @FXML private TextField userNameAmpServ; @FXML private TextField pathAmp; @FXML private TextField userNameGenerServ; @FXML private TextField pathGener; @FXML private ComboBox<String> platformOSServ; @FXML private ComboBox<String> typeServ; @FXML private ComboBox<String> protocolServ; @FXML private PasswordField passwordAmp; @FXML private PasswordField passwordGener; String nommsg,hostmsg,osmsg,cbaamsg,pw1msg,cbrdmsg,gaamsg,pw2msg,grdmsg,usermsg,pwmsg; @FXML private TextField username; @FXML private PasswordField password; private Session session; private DataBaseConnexion dbconnexion; public DataBaseConnexion getDbconnexion() { return dbconnexion; } @Autowired public void setDbconnexion(DataBaseConnexion dbconnexion) { this.dbconnexion = dbconnexion; } public Session getSession() { return session; } @Autowired public void setSession(Session session) { this.session = session; } private WelcomeController welcomecontroller; @Autowired public void setWelcomecontroller(WelcomeController welcomecontroller) { this.welcomecontroller = welcomecontroller; } private ServerDAO serverDao; private Server server = new Server(); public ServerDAO getServerDao() { return serverDao; } @Autowired public void setServerDao(ServerDAO serverDao) { this.serverDao = serverDao; } public Server getServer() { return server; } public void setServer(Server server) { this.server = server; } @FXML private void initialize() { platformOSServ.getItems().addAll(platforms); validator = Validation.buildDefaultValidatorFactory().getValidator(); Platform.runLater(()->((VBox)passwordGener.getParent()).requestFocus()); } public void createServ() throws JSchException { nommsg=hostmsg=osmsg=cbaamsg=pw1msg=cbrdmsg=gaamsg=pw2msg=grdmsg=""; server.setHote(hostServ.getText()); server.setNomServer(nameServ.getText()); server.setPlatformOS(platformOSServ.getValue()); server.setUserName(username.getText()); server.setPassword(password.getText()); server.setUserNameAmp(userNameAmpServ.getText()); server.setPasswordAmp(passwordAmp.getText()); server.setUserNameGener(userNameGenerServ.getText()); server.setPasswordGener(passwordGener.getText()); server.setPathAmp(pathAmp.getText()); server.setPathGener(pathGener.getText()); server.setId(null); Set<ConstraintViolation<Server>> serverViolations = validator.validate(server); if (serverViolations.isEmpty()) { //com.jcraft.jsch.Session SSHsession=dbconnexion.connectServer(server); //dbconnexion.getSession().disconnect(); //dbconnexion.setSession(null); //if (SSHsession!=null) { System.out.println("save server "); serverDao.save(server); //welcomecontroller.FireAnEvent(welcomecontroller.getServerlabel()); //SSHsession.disconnect(); //} else { // System.out.println("we can't save db "); //} // server.setId(null); } else { System.out.println("data is Invalid"); System.out.println("------------------------------------"); for (ConstraintViolation<Server> serverViolation : serverViolations) { if(serverViolation.getPropertyPath().toString().equals("nomServer")) { nommsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("hote")) { hostmsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("platformOS")) { osmsg = serverViolation.getMessage(); } /*else if (serverViolation.getPropertyPath().toString().equals("userNameAmp")) { cbaamsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("passwordAmp")) { pw1msg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("pathAmp")) { cbrdmsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("userNameGener")) { gaamsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("passwordGener")) { pw2msg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("pathGener")) { grdmsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("userName")) { usermsg = serverViolation.getMessage(); }else if (serverViolation.getPropertyPath().toString().equals("password")) { pwmsg = serverViolation.getMessage(); } */ } if (!nommsg.isEmpty()) { nameServ.getStyleClass().add("error"); }else { nameServ.getStyleClass().removeAll("error"); } if (!hostmsg.isEmpty()) { hostServ.getStyleClass().add("error"); }else { hostServ.getStyleClass().removeAll("error"); } if (!osmsg.isEmpty()) { platformOSServ.getStyleClass().add("error"); }else { platformOSServ.getStyleClass().removeAll("error"); } /*if (!cbaamsg.isEmpty()) { userNameAmpServ.getStyleClass().add("error"); }else { userNameAmpServ.getStyleClass().removeAll("error"); } if (!pw1msg.isEmpty()) { passwordAmp.getStyleClass().add("error"); }else { passwordAmp.getStyleClass().removeAll("error"); } if (!cbrdmsg.isEmpty()) { pathAmp.getStyleClass().add("error"); }else { pathAmp.getStyleClass().removeAll("error"); } if (!gaamsg.isEmpty()) { userNameGenerServ.getStyleClass().add("error"); }else { userNameGenerServ.getStyleClass().removeAll("error"); } if (!pw2msg.isEmpty()) { passwordGener.getStyleClass().add("error"); }else { passwordGener.getStyleClass().removeAll("error"); } if (!grdmsg.isEmpty()) { pathGener.getStyleClass().add("error"); }else { pathGener.getStyleClass().removeAll("error"); } */ errorLabel.setText("\t\tOuuups!!\nles champs en rouge sont invalides."); } } @FXML public void cancel(MouseEvent event) throws IOException { welcomecontroller.loadInMainPane(welcomecontroller.getMainpane(), "Env_list"); } } ``` 2018_07_10_11_13_54_mig_V11.1.1_ora.sql ```-- ------------ -- CIP-COBAC-2.1_ora.sql -- ------------ -- ------------------------------------------------------------ -- SEQUENCE de DROP -- ------------------------------------------------------------ -- DROP TABLE bkcip_idp_regul; --alter table bkcip_idp drop CONSTRAINT CK_BKCIP_IDP$CTR ; --alter table bkcip_ir drop CONSTRAINT CK_BKCIP_IR$CTR ; -- ------------------------------------------------------------ UPDATE bkcip_cli SET ir_dec = 0 ; alter table bkcip_idp drop CONSTRAINT CK_BKCIP_IDP$CTR ; alter table bkcip_idp add CONSTRAINT CK_BKCIP_IDP$CTR CHECK (ctr IN ( '0' /*A traiter */ ,'1' /*declare */ ,'2' /*en attente*/ ,'3' /*acquitté */ ,'4' /*anomalie*/ ,'5' /*Suspendu*/ ,'9' /*tmp */)); alter table bkcip_ir drop CONSTRAINT CK_BKCIP_IR$CTR ; alter table bkcip_ir add CONSTRAINT CK_BKCIP_IR$CTR CHECK (ctr IN ( '0' /*A traiter */ ,'1' /*declare */ ,'2' /*en attente*/ ,'3' /*acquitté */ ,'4' /*anomalie */ ,'5' /*Suspendu*/ ,'9' /*tmp */)); -- ------------------------------------------------------------ -- @STEP : 1.0 -- @TABLE : BKCIP_IDP_REGUL -- @DESC : CIP BEAC - audit evenment de regularisation -- ------------------------------------------------------------ create table bkcip_idp_regul ( id_cip_idp NUMBER(15,0) CONSTRAINT NL_BKCIP_IDP_REGUL$ID_CIP_IDP NOT NULL ,age CHAR(5) CONSTRAINT NL_BKCIP_IDP_REGUL$AGE NOT NULL ,ope CHAR(3) CONSTRAINT NL_BKCIP_IDP_REGUL$OPE NOT NULL ,eve CHAR(6) CONSTRAINT NL_BKCIP_IDP_REGUL$EVE NOT NULL ,age_cpt CHAR(5) CONSTRAINT NL_BKCIP_IDP_REGUL$AGE_CPT NOT NULL ,ncp CHAR(11) CONSTRAINT NL_BKCIP_IDP_REGUL$NCP NOT NULL ,suf CHAR(2) CONSTRAINT NL_BKCIP_IDP_REGUL$SUF NOT NULL ,dev CHAR(3) CONSTRAINT NL_BKCIP_IDP_REGUL$DEV NOT NULL ,numval CHAR(14) CONSTRAINT NL_BKCIP_IDP_REGUL$NUMVAL NOT NULL ,nat CHAR(6) CONSTRAINT NL_BKCIP_IDP_REGUL$NAT NOT NULL ,dou DATE CONSTRAINT NL_BKCIP_IDP_REGUL$DOU NOT NULL ,mht NUMBER(15,4) CONSTRAINT NL_BKCIP_IDP_REGUL$MHT NOT NULL ); CREATE INDEX FK_BKCIP_IDP_REGUL$BKCIP_IDP ON BKCIP_IDP_REGUL (id_cip_idp); ALTER TABLE BKCIP_IDP_REGUL ADD CONSTRAINT FK_BKCIP_IDP_REGUL$BKCIP_IDP FOREIGN KEY (id_cip_idp) REFERENCES bkcip_idp (id_cip_idp); -- ------------ -- mig_lien_crs_393_ora.sql -- ------------ --DONNEE 393 : EXISTENCE D'UN LIEN D'UN TYPE DONNE AVEC UN INDIVIDU CRS -- DELETE FROM abfseldce WHERE reffct = '027'; -- DELETE FROM abfseldcp WHERE reffct = '027'; -- DELETE FROM abfevadoe WHERE reffct = '602'; -- DELETE FROM abfevadop WHERE reffct = '602'; INSERT INTO abfseldce VALUES ('027','Selection lien entre client et individu CRS','882080','absel_type_lien_client_avec_individu_CRS'); INSERT INTO abfseldcp VALUES ('027','1','Type de lien','881467','S'); INSERT INTO abfevadoe VALUES ('602','Recherche existence lien avec individu CRS','882081','ab_rech_lien_avec_individu_CRS'); INSERT INTO abfevadop VALUES ('602','1','Type de lien','881467','E','O',' ',''); INSERT INTO abfevadop VALUES ('602','2','Existence du lien','881470','S','N','N',''); -- DELETE FROM ABDOMAD WHERE REFDO = '393'; -- DELETE FROM ABDOMADL WHERE REFDO = '393'; -- DELETE FROM ABDOMADC WHERE REFDO = '393'; -- DELETE FROM ABDOMADO WHERE REFDO = '393'; INSERT INTO ABDOMAD (REFDO, ORIGINE, TYPCLI, REFFCT, VALPAREFCT, NUMAFF, UTILSCEN, NOMLAB, DOU, DMO, UTI) VALUES ('393', '2', 'T', ' ', ' ', 393, 'N', ' ', TO_DATE(SYSDATE,'DD/MM/YYYY'), NULL, 'DELT'); INSERT INTO ABDOMADL (REFDO, REFLIB, LANG, LIB) VALUES ('393', 'C', '001', 'Existence d''un lien d''un type donné avec un client CRS'); INSERT INTO ABDOMADL (REFDO, REFLIB, LANG, LIB) VALUES ('393', 'D', '001', 'Existence d''un lien avec individu CRS'); INSERT INTO ABDOMADC (REFDO, REFFCT, VALPAREFCT) VALUES ('393', '027', ' '); INSERT INTO ABDOMADO (REFDO, NATURE, NIVEAU, TYPOBT, NOMTABLE, NOMCOL, CARDEB, CARFIN, REFFCT, NUMPARSFCT, VALPAREFCT1, VALPAREFCT2) VALUES ('393', ' ', 1, 'F', ' ', ' ', 0, 0, '602', 2, 'DONNEECPL1', ' '); -- ------------ -- mig_crs_domad_correction_ora.sql -- ------------ --Script de correction du script mig_crs_ora.sql qui aurait du être décloisonné ==>7961 DELETE FROM abfevadoe where reffct in ('096','600','601'); DELETE FROM abfevadop where reffct in ('096','600','601'); DELETE FROM abdomadl where refdo between '388' AND '392'; DELETE FROM abdomad where refdo between '388' AND '392'; DELETE FROM abdomado where refdo between '388' AND '392'; DELETE FROM abdomadc where refdo between '388' AND '392'; --Statut CRS d'un client INSERT INTO ABDOMAD(REFDO,ORIGINE,TYPCLI,REFFCT,VALPAREFCT,NUMAFF,UTILSCEN,NOMLAB,DOU,DMO,UTI) VALUES ('388', '2', 'T', '001', '072', 388, 'N', ' ', trunc(sysdate), NULL, 'USER'); INSERT INTO ABDOMADO(REFDO,NATURE,NIVEAU,TYPOBT,NOMTABLE,NOMCOL,CARDEB,CARFIN,REFFCT,NUMPARSFCT,VALPAREFCT1,VALPAREFCT2) VALUES ('388', ' ', 1, 'T', 'bkcli', 'crs_status', 0, 0, ' ', 0, ' ', ' '); INSERT INTO ABDOMADL(REFDO,REFLIB,LANG,LIB) VALUES ('388', 'C', '001', 'Statut CRS'); INSERT INTO ABDOMADL(REFDO,REFLIB,LANG,LIB) VALUES ('388', 'D', '001', 'Statut CRS '); --Donnée issur d'une nomenclature a partiru du statut CRS INSERT INTO ABDOMAD(REFDO,ORIGINE,TYPCLI,REFFCT,VALPAREFCT,NUMAFF,UTILSCEN,NOMLAB,DOU,DMO,UTI) VALUES ('389', '2', 'T', ' ', ' ', 389, 'N', ' ', trunc(sysdate), NULL, 'USER'); INSERT INTO ABDOMADO(REFDO,NATURE,NIVEAU,TYPOBT,NOMTABLE,NOMCOL,CARDEB,CARFIN,REFFCT,NUMPARSFCT,VALPAREFCT1,VALPAREFCT2) VALUES ('389', ' ', 1, 'T', 'bkcli', 'crs_status', 0, 0, ' ', 0, ' ', ' '); INSERT INTO ABDOMADO(REFDO,NATURE,NIVEAU,TYPOBT,NOMTABLE,NOMCOL,CARDEB,CARFIN,REFFCT,NUMPARSFCT,VALPAREFCT1,VALPAREFCT2) VALUES ('389', ' ', 2, 'F', ' ', ' ', 0, 0, '001', 3, 'DONNEECPL1', 'DONNEECPL2'); INSERT INTO ABDOMADL(REFDO,REFLIB,LANG,LIB) VALUES ('389', 'C', '001', 'Donnée issue d''une nomenclature à partir du statut CRS'); INSERT INTO ABDOMADL(REFDO,REFLIB,LANG,LIB) VALUES ('389', 'D', '001', 'Donnée issue nomenclature à partir du statut CRS '); INSERT INTO ABDOMADC(REFDO,REFFCT,VALPAREFCT) VALUES ('389', '003', ' '); --Date de statut CRS d'un client INSERT INTO ABDOMAD(REFDO,ORIGINE,TYPCLI,REFFCT,VALPAREFCT,NUMAFF,UTILSCEN,NOMLAB,DOU,DMO,UTI) VALUES ('390', '2', 'T', ' ', ' ', 390, 'N', ' ', trunc(sysdate), NULL, 'USER'); INSERT INTO ABDOMADO(REFDO,NATURE,NIVEAU,TYPOBT,NOMTABLE,NOMCOL,CARDEB,CARFIN,REFFCT,NUMPARSFCT,VALPAREFCT1,VALPAREFCT2) VALUES ('390', ' ', 1, 'T', 'bkcli', 'crs_date', 0, 0, ' ', 0, ' ', ' '); INSERT INTO ABDOMADL(REFDO,REFLIB,LANG,LIB) VALUES ('390', 'C', '001', 'Date de statut CRS'); INSERT INTO ABDOMADL(REFDO,REFLIB,LANG,LIB) VALUES ('390', 'D', '001', 'Date de statut CRS '); --Ancienneté de date de statut CRS selon une periodicité donnée INSERT INTO ABDOMAD(REFDO,ORIGINE,TYPCLI,REFFCT,VALPAREFCT,NUMAFF,UTILSCEN,NOMLAB,DOU,DMO,UTI) VALUES ('391', '2', 'T', ' ', ' ', 391, 'N', ' ', trunc(sysdate), NULL, 'USER'); INSERT INTO ABDOMADO(REFDO,NATURE,NIVEAU,TYPOBT,NOMTABLE,NOMCOL,CARDEB,CARFIN,REFFCT,NUMPARSFCT,VALPAREFCT1,VALPAREFCT2) VALUES ('391', ' ', 1, 'T', 'bkcli', 'crs_date', 0, 0, ' ', 0, ' ', ' '); INSERT INTO ABDOMADO(REFDO,NATURE,NIVEAU,TYPOBT,NOMTABLE,NOMCOL,CARDEB,CARFIN,REFFCT,NUMPARSFCT,VALPAREFCT1,VALPAREFCT2) VALUES ('391', ' ', 2, 'F', ' ', ' ', 0, 0, '027', 2, 'DONNEECPL1', ' '); INSERT INTO ABDOMADL(REFDO,REFLIB,LANG,LIB) VALUES ('391', 'C', '001', 'Ancienneté de date de statut CRS'); INSERT INTO ABDOMADL(REFDO,REFLIB,LANG,LIB) VALUES ('391', 'D', '001', 'Ancienneté de date de statut CRS '); INSERT INTO ABDOMADC(REFDO,REFFCT,VALPAREFCT) VALUES ('391', '008', ' '); --Existence residence fiscale FATCA ou CRS INSERT INTO abfevadoe(reffct,inti,nummess,nomfct) VALUES ('096','Recherche existence résidence fiscale FATCA ou CRS','882028','ab_rech_existe_resid_fisc_crs_fatca'); INSERT INTO abfevadop(reffct,numpar,inti,nummess,typepar,doncpl,formatp,longp) VALUES ('096','1','Existence résidence fiscale FATCA ou CRS','882029','S','N','N',NULL); INSERT INTO abdomadl(REFDO,REFLIB,LANG,LIB) VALUES ('392', 'C', '001', 'Existence d''une résidence fiscale CRS ou FATCA'); INSERT INTO abdomadl(REFDO,REFLIB,LANG,LIB) VALUES ('392', 'D', '001', 'Existence d''une résidence fiscale CRS ou FATCA '); INSERT INTO abdomad(REFDO,ORIGINE,TYPCLI,REFFCT,VALPAREFCT,NUMAFF,UTILSCEN,NOMLAB,DOU,DMO,UTI) VALUES ('392', '2', 'T', ' ', ' ', '392', 'N', ' ', trunc(sysdate), NULL, 'USER'); INSERT INTO abdomado(REFDO,NATURE,NIVEAU,TYPOBT,NOMTABLE,NOMCOL,CARDEB,CARFIN,REFFCT,NUMPARSFCT,VALPAREFCT1,VALPAREFCT2) VALUES ('392', ' ', '1', 'F', ' ', ' ', '0', '0', '096', '1', ' ', ' '); -- ------------ -- BSIC-CI170118-03_ora.sql -- ------------ --#=============================================================================== --# @author BOU - 01/2017 --# @desc Ce script permet de modifier la contrainte sur le champ type afin d'y ajouter le type B : adresse agence --# --#=============================================================================== ALTER TABLE bkfacav_bookad DROP CONSTRAINT CK_BKFACAV_BOOKAD$TYP; ALTER TABLE bkfacav_bookad ADD CONSTRAINT CK_BKFACAV_BOOKAD$TYP CHECK (typ IN ('C', 'D','B')); -- ------------ -- mig_ass_T2SA150402_ora.sql -- ------------ -- EVOLUTION T2SA150402 - Modification de la saisie de périodicité prélèvement -- Ajout d'une valeur par défaut pour le champ : nombre de mois INSERT INTO bklibel(MODU,IDEN,MESS,OBL,TYPC,CTRL,IDENM,ACCES) values ('ASS','6','655768','O','S','',NULL,'O'); INSERT INTO bkcorres(MODU,PROG,TRAIT,FENET,ZONE,IDEN) values ('ASS',' ',' ',' ','nb_mois_perprelv','6'); -- ------------ -- mig_TMAIBFS161114-03_ora.sql -- ------------ --Antidote --ALTER TABLE bkrecapfra DROP CONSTRAINT CK_BKRECAPFRA$orig; --ALTER TABLE bkrecapfra ADD CONSTRAINT CK_BKRECAPFRA$orig CHECK (orig IN ('Q' /* Traitement quotidien */, 'R' /* reprise de l'historique */)); ALTER TABLE bkrecapfra DROP CONSTRAINT CK_BKRECAPFRA$orig; ALTER TABLE bkrecapfra ADD CONSTRAINT CK_BKRECAPFRA$orig CHECK (orig IN ('Q' /* Traitement quotidien */, 'R' /* reprise de l'historique */, 'M' /* traitement manuel */)); -- ------------ -- mig_lab_BPCE160629-01_ora.sql -- ------------ --Delete from abfevadoe where reffct ='097'; --Delete from abfevadop where reffct ='097'; --Delete from abdomad where refdo ='394'; --Delete from abdomado where refdo ='394'; --Delete from abdomadl where refdo ='394'; --Delete from abdomadc where refdo ='394'; --DOMAD 394 : Libellé du pays à partir du code spécifique 5 INSERT INTO ABFEVADOE(REFFCT,INTI,NUMMESS,NOMFCT) VALUES ('097', 'Donnée d''une nomenclature à partir du code spécifique 5', '882082', 'ab_rech_pays_code_specifique_5') ; INSERT INTO ABFEVADOP(REFFCT,NUMPAR,INTI,NUMMESS,TYPEPAR,DONCPL,FORMATP,LONGP) VALUES ('097', 1, 'Code pays', '618626', 'S', 'N', 'A', 3); INSERT INTO ABDOMAD(REFDO,ORIGINE,TYPCLI,REFFCT,VALPAREFCT,NUMAFF,UTILSCEN,NOMLAB,DOU,DMO,UTI) VALUES ('394', '1', 'T', NULL, NULL, 394, 'N', NULL, TO_DATE(SYSDATE,'DD/MM/YYYY'), NULL, 'DELT'); INSERT INTO ABDOMADO(REFDO,NATURE,NIVEAU,TYPOBT,NOMTABLE,NOMCOL,CARDEB,CARFIN,REFFCT,NUMPARSFCT,VALPAREFCT1,VALPAREFCT2) VALUES ('394', ' ', 1, 'F', NULL, NULL, 0, 0, '097', 1, NULL, NULL); INSERT INTO ABDOMADO(REFDO,NATURE,NIVEAU,TYPOBT,NOMTABLE,NOMCOL,CARDEB,CARFIN,REFFCT,NUMPARSFCT,VALPAREFCT1,VALPAREFCT2) VALUES ('394', ' ', 2, 'F', NULL, NULL, 0, 0, '001', 3, 'DONNEECPL1', 'DONNEECPL2'); INSERT INTO ABDOMADC(REFDO,REFFCT,VALPAREFCT) VALUES ('394', '003', NULL); INSERT INTO ABDOMADL(REFDO,REFLIB,LANG,LIB) VALUES ('394', 'C', '001', 'Donnée issue d''une nomenclature à partir du code spécifique 5'); INSERT INTO ABDOMADL(REFDO,REFLIB,LANG,LIB) VALUES ('394', 'D', '001', 'Donnée issue d''une nom. à partir du code spé. 5 '); -- ------------ -- BFVSG170302-01_ora.sql -- ------------ -- BFVSG170302-01 : -- Script correctif du champ hmaj -- Forcage du champ hmaj en CHAR(6) ALTER TABLE bkhmajcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajicli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajmcl MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajenfcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajdircli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajactcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajprfcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajdficli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajtelcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajemacli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajcntcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajpidcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajprocli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajadcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajdoccli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajbudgcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajrevcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajchargcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajepatrcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajpatrcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajopetrcli MODIFY (hmaj CHAR(6)); ALTER TABLE bkhmajcoj MODIFY (hmaj CHAR(6)); -- ------------ -- mig_IFRS9_lot2_ora.sql -- ------------ ----DROP TABLE IF9_NOTE; ----DROP TABLE IF9_EAD; ----DROP TABLE IF9_PRV; ----DROP TABLE IF9_CYCLE; ----DROP TABLE IF9_NTVAL; ----DROP TABLE IF9_NTATTR; ----DROP TABLE IF9_NTPAR; ----DROP TABLE IF9_PGVAL; ----DROP TABLE IF9_PGATTR; ----DROP TABLE IF9_PGPAR; ----DROP TABLE IF9_EADGAR; ----DROP TABLE IF9_EADPAR; ----DROP TABLE IF9_EADNAT; ----ALTER TABLE IF9_VALCDT MODIFY (ID_IF9_VALID NUMBER(10,0) CONSTRAINT NL_VALCDT$ID_VALID NOT NULL); ----ALTER TABLE IF9_VALAUT MODIFY (ID_IF9_VALID NUMBER(10,0) CONSTRAINT NL_VALAUT$ID_VALID NOT NULL); ----ALTER TABLE IF9_VALCRC MODIFY (ID_IF9_VALID NUMBER(10,0) CONSTRAINT NL_VALCRC$ID_VALID NOT NULL); ----ALTER TABLE IF9_VALTIT MODIFY (ID_IF9_VALID NUMBER(10,0) CONSTRAINT NL_VALTIT$ID_VALID NOT NULL); ----ALTER TABLE IF9_VALCAU MODIFY (ID_IF9_VALID NUMBER(10,0) CONSTRAINT NL_VALCAU$ID_VALID NOT NULL); ----ALTER TABLE IF9_VALLSG MODIFY (ID_IF9_VALID NUMBER(10,0) CONSTRAINT NL_VALLSG$ID_VALID NOT NULL); ----ALTER TABLE IF9_VALISL MODIFY (ID_IF9_VALID NUMBER(10,0) CONSTRAINT NL_VALISL$ID_VALID NOT NULL); ------------------------------------------------------------------------------- ---- CREATION ET ALIMENTATION DES TABLES -- Table pour cycle de notation et provision IFRS 9 CREATE TABLE IF9_CYCLE ( ID_IF9_CYCLE NUMBER(10,0) CONSTRAINT NL_CYCLE$IDCYCLE NOT NULL, --- Identifiant unique (technique) ST_NOTE NUMBER(1,0) CONSTRAINT NL_CYCLE$ST_NOTE NOT NULL, --- Statut de la phase de notation CONSTRAINT CK_CYCLE$ST_NOTE CHECK(ST_NOTE IN ('0','1')) , --0 - Ouverte --1 - Cloturee DCALC_NOTE DATE CONSTRAINT NL_CYCLE$DCALC_NOTE NOT NULL, --- Date d'execution du calcul de la notation DFIN_NOTE DATE CONSTRAINT NL_CYCLE$DFIN_NOTE NOT NULL, --- Date de fin de la phase de notation UTI_NOTE CHAR(10) , --- Utilisateur ayant cloture la phase de notation ST_PROV NUMBER(1,0) CONSTRAINT NL_CYCLE$ST_PROV NOT NULL, --- Statut de la phase de provision CONSTRAINT CK_CYCLE$ST_PROV CHECK(ST_PROV IN ('0','1')), -- 0 - Ouverte -- 1 - Cloturee DCALC_PROV DATE , --- Date d'execution du calcul de provision UTI_CALPRV CHAR(10) , --- Utilisateur ayant lancé le calcul de provision DFIN_PROV DATE , --- Date de fin de la phase de provision UTI_PROV CHAR(10) , --- Utilisateur ayant cloture la phase de provision DEC_PROV NUMBER(1,0) CONSTRAINT CK_CYCLE$DEC_PROV CHECK(DEC_PROV IN ('0','1','2')), --- Decision sur la provision LAST_CYCLE NUMBER(1,0) CONSTRAINT CK_CYCLE$LAST_CYCLE CHECK(LAST_CYCLE IN ('0','1')) ); CREATE UNIQUE INDEX PK_IF9CYCLE ON IF9_CYCLE (ID_IF9_CYCLE); ALTER TABLE IF9_CYCLE ADD CONSTRAINT PK_IF9CYCLE PRIMARY KEY (ID_IF9_CYCLE) ; CREATE INDEX I1_IF9_CYCLE ON IF9_CYCLE (ST_NOTE); CREATE INDEX I2_IF9_CYCLE ON IF9_CYCLE (ST_PROV); CREATE INDEX I3_IF9_CYCLE ON IF9_CYCLE (LAST_CYCLE); --Table pour le paramétrage des règles de notation IFRS 9 CREATE TABLE IF9_NTPAR ( ID_IF9_NTPAR NUMBER(10,0) CONSTRAINT NL_NTPAR$IDNTPAR NOT NULL, --- Identifiant unique (technique) PLEVEL NUMBER(3,0) CONSTRAINT NL_NTPAR$PLEVEL NOT NULL, --- Niveau de paramétrage CONSTRAINT CK_NTPAR$PLEVEL CHECK(PLEVEL IN ('100','110', '120', '130', '200', '210', '220', '230', '300', '310', '320', '330')) , -- 100 - Global -- 110 - Global/Client Particulier -- 120 - Global/Client Socitété -- 130 - Global/Client Entreprise Individuelle -- 200 - Module -- 210 - Module/Client Particulier -- 220 - Module/Client Socitété -- 230 - Module/Client Entreprise Individuelle -- 300 - Produit -- 310 - Produit/Client Particulier -- 320 - Produit/Client Societé -- 330 - Produit/Client Entreprise Individuelle MODU CHAR(3) CONSTRAINT CK_NTPAR$MODU CHECK(MODU IN ('AUT','CDT', 'CRC', 'LSG', 'ISI', --- Code module - cas des paramètres niveau module/produit 'CAU', 'TIT')), TYPE_PROD VARCHAR2(10) , --- Code type (produit) - cas des paramètres niveau produit -- AUT - Autorisations simples -- CDT - Crédits amortissables -- CRC - Crédits revolving -- LSG - Leasing -- ISI - Finance islamique -- CAU - Cautions -- TIT - Titres TYPE_CLI CHAR(1) CONSTRAINT CK_NTPAR$TYPE_CLI CHECK(TYPE_CLI IN ('1', '2', '3')), --- Type de client -- 1 - Particulier -- 2 - Société -- 3 - Entreprise individuelle DESCRIPTION VARCHAR2(200) CONSTRAINT NL_NTPAR$DESCRIPTION NOT NULL, --- Description longue de l'attribut NOTE NUMBER(1,0) CONSTRAINT NL_NTPAR$NOTE NOT NULL, --- Note à affecter CONSTRAINT CK_NTPAR$NOTE CHECK(NOTE IN ('0','1','2','3')) , -- 0 - Non noté -- 1 - S1 - Bucket 1 -- 2 - S2 - Bucket 2 -- 3 - Exclu du calcul ACTIVE NUMBER(1,0) CONSTRAINT NL_NTPAR$ACTIVE NOT NULL, --- Règle active CONSTRAINT CK_NTPAR$ACTIVE CHECK(ACTIVE IN ('0','1')) , -- 0 Non -- 1 Oui DDEB DATE , --- Date de début d'application DFIN DATE , --- Date de fin d'application UTI CHAR(10) CONSTRAINT NL_NTPAR$UTI NOT NULL, --- Utilisateur ayant créé la règle HIS NUMBER(1,0) CONSTRAINT NL_NTPAR$HIS NOT NULL, --- Règle historisées CONSTRAINT CK_NTPAR$HIS CHECK(HIS IN ('0','1')) , -- 0 - Non -- 1 - Oui DHIS DATE --- Date d'historisation ); CREATE UNIQUE INDEX PK_IF9NTPAR ON IF9_NTPAR (ID_IF9_NTPAR); ALTER TABLE IF9_NTPAR ADD CONSTRAINT PK_IF9NTPAR PRIMARY KEY (ID_IF9_NTPAR) ; CREATE INDEX I1_IF9_NTPAR ON IF9_NTPAR (PLEVEL); CREATE INDEX I2_IF9_NTPAR ON IF9_NTPAR (MODU,TYPE_PROD,TYPE_CLI); CREATE INDEX I3_IF9_NTPAR ON IF9_NTPAR (NOTE); CREATE INDEX I4_IF9_NTPAR ON IF9_NTPAR (ACTIVE); --Table pour le paramétrage des règles de notation IFRS 9 - Attributs caractéristiques CREATE TABLE IF9_NTATTR ( ID_IF9_NTATTR NUMBER(10,0) CONSTRAINT NL_NTATTR$IDNTATTR NOT NULL, --- Identifiant unique (technique) ID_IF9_NTPAR NUMBER(10,0) CONSTRAINT NL_NTATTR$IDNTPAR NOT NULL, --- Identifiant de règle (technique) TYPE NUMBER(1,0) CONSTRAINT NL_NTATTR$TYPE NOT NULL, --- Type d'attribut CONSTRAINT CK_NTATTR$TYPE CHECK(TYPE IN ('1','2', '3')), -- 1 - Impayé -- 2 - Client -- 3 - IFRS9 KEY_CODE VARCHAR2(50) CONSTRAINT NL_NTATTR$KEY_CODE NOT NULL, --- Code identifiant (fonctionnel) de l'attribut OPERATOR NUMBER(2,0) CONSTRAINT CK_NTATTR$OPERATOR CHECK(OPERATOR IN ('1', '2', '3', '4', '5', '6', --- Opérateur '7', '8', '9', '10', '11', '12')), -- 1 - = -- 2 - != -- 3 - > -- 4 - < -- 5 - >= -- 6 - <= -- 7 - Liste de valeurs incluses -- 8 - Liste de valeurs exclues -- 9 - Compris entre -- 10 - Commence par -- 11 - Fini par -- 12 - Contient FORMAT CHAR(1) CONSTRAINT NL_NTATTR$FORMAT NOT NULL, --- Format de la valeur de l¿attribut CONSTRAINT CK_NTATTR$FORMAT CHECK(FORMAT IN ('A','N', 'E', 'D', 'B')) -- A Alphanumérique, N Numérique, E Entier, D Date, B Booléen ); CREATE UNIQUE INDEX PK_IF9NTATTR ON IF9_NTATTR (ID_IF9_NTATTR); ALTER TABLE IF9_NTATTR ADD CONSTRAINT PK_IF9NTATTR PRIMARY KEY (ID_IF9_NTATTR) ; CREATE INDEX FK_IF9NTATTR$NTPAR ON IF9_NTATTR (ID_IF9_NTPAR); ALTER TABLE IF9_NTATTR ADD CONSTRAINT FK_IF9NTATTR$IF9NTPAR FOREIGN KEY (ID_IF9_NTPAR) REFERENCES IF9_NTPAR (ID_IF9_NTPAR) ; CREATE INDEX I1_IF9_NTATTR ON IF9_NTATTR (TYPE); CREATE INDEX I2_IF9_NTATTR ON IF9_NTATTR (KEY_CODE); --Table pour le paramétrage des règles de notation IFRS 9 - Valeur des attributs CREATE TABLE IF9_NTVAL ( ID_IF9_NTVAL NUMBER(10,0) CONSTRAINT NL_NTVAL$IDNTVAL NOT NULL, --- Identifiant unique (technique) ID_IF9_NTATTR NUMBER(10,0) CONSTRAINT NL_NTVAL$IDNTATTR NOT NULL, --- Identifiant de l'attribut caractéristique DATAA VARCHAR2(150) , --- Valeur de l'attribut au format A DATAN NUMBER(22,7) , --- Valeur de l'attribut au format N ou E DATAD DATE , --- Valeur de l'attribut au format D DATAB NUMBER(1,0) CONSTRAINT CK_NTVAL$DATAB CHECK(DATAB IN ('0','1')) --- Valeur de l'attribut au format B: 0 FAUX, 1 VRAI ); CREATE UNIQUE INDEX PK_IF9NTVAL ON IF9_NTVAL (ID_IF9_NTVAL); ALTER TABLE IF9_NTVAL ADD CONSTRAINT PK_IF9NTVAL PRIMARY KEY (ID_IF9_NTVAL) ; CREATE INDEX FK_IF9NTVAK$IF9NTATTR ON IF9_NTVAL (ID_IF9_NTATTR); ALTER TABLE IF9_NTVAL ADD CONSTRAINT FK_IF9NTVAL$IF9NTATTR FOREIGN KEY (ID_IF9_NTATTR) REFERENCES IF9_NTATTR (ID_IF9_NTATTR); -- Table pour le paramétrage des règles de propagation IFRS 9 CREATE TABLE IF9_PGPAR ( ID_IF9_PGPAR NUMBER(10,0) CONSTRAINT NL_PGPAR$IDPGPAR NOT NULL, --- Identifiant unique (technique) PLEVEL NUMBER(1,0) CONSTRAINT NL_PGPAR$PLEVEL NOT NULL, --- Niveau de paramétrage CONSTRAINT CK_PGPAR$PLEVEL CHECK(PLEVEL IN ('0','1', '2', '3')) , --0 Global --1 Client Particulier --2 Client Société --3 Client Entreprise Individuelle DESCRIPTION VARCHAR2(200) CONSTRAINT NL_PGPAR$DESCRIPTION NOT NULL, ---Description longue de l¿attribut PROPAG NUMBER(1,0) CONSTRAINT NL_PGPAR$PROPAG NOT NULL , --- Mode de propagation CONSTRAINT CK_PGPAR$PROPAG CHECK(PROPAG IN ('0','1', '2','3')) , --0 - Pas de propagation --1 - Propagation aux dossiers du client --2 - Propagation aux dossiers du client et ses co-titulaires --3 - Propagation aux dossiers du groupe (Société et Entreprises individuelles) ACTIVE NUMBER(1,0) CONSTRAINT NL_PGPAR$ACTIVE NOT NULL, ---Règle active CONSTRAINT CK_PGPAR$ACTIVE CHECK(ACTIVE IN ('0', '1')) , --0 Non --1 Oui DDEB DATE , ---Date de début d'application DFIN DATE , ---Date de fin d'application UTI CHAR(10) CONSTRAINT NL_PGPAR$UTI NOT NULL , ---Dernier utilisateur ayant créé/modifié le paramètre HIS NUMBER(1,0) CONSTRAINT NL_PGPAR$HIS NOT NULL, ---Règle historisées CONSTRAINT CK_PGPAR$HIS CHECK(HIS IN ('0', '1')) , --0 Non --1 - Oui DHIS DATE ---Date d'historisation ); CREATE UNIQUE INDEX PK_IF9PGPAR ON IF9_PGPAR (ID_IF9_PGPAR); ALTER TABLE IF9_PGPAR ADD CONSTRAINT PK_IF9PGPAR PRIMARY KEY (ID_IF9_PGPAR) ; CREATE INDEX I1_IF9_PGPAR ON IF9_PGPAR (PLEVEL); CREATE INDEX I2_IF9_PGPAR ON IF9_PGPAR (PROPAG); CREATE INDEX I3_IF9_PGPAR ON IF9_PGPAR (ACTIVE); -- Table pour le paramétrage des règles de propagation IFRS 9 - Attributs caractéristiques CREATE TABLE IF9_PGATTR ( ID_IF9_PGATTR NUMBER(10,0) CONSTRAINT NL_PGATTR$ID_PGATTR NOT NULL, --- Identifiant unique (technique) ID_IF9_PGPAR NUMBER(10,0) CONSTRAINT NL_PGATTR$ID_PAGPAR NOT NULL, --- Référence à la regle(IF9_PGPAR) TYPE NUMBER(1,0) CONSTRAINT NL_PGATTR$TYPE NOT NULL, --- Type de l'attribut --1 - Impayé --2 - Client --3 - IFRS9 KEY_CODE VARCHAR2(50) CONSTRAINT NL_PGATTR$KEY_CODE NOT NULL, ---Code identifiant (fonctionnel) de l¿attribut OPERATOR NUMBER(2,0) CONSTRAINT CK_PGATTR$OPERATOR CHECK(OPERATOR IN --- Opérateur de comparaison lié au critère de sélection (>, <, =, ¿) ('1', '2', '3', '4', '5', '6', -- 1 - = '7', '8', '9', '10', '11', '12')), -- 2 - != -- 3 - > -- 4 - < -- 5 - >= -- 6 - <= -- 7 - Liste de valeurs incluses -- 8 - Liste de valeurs exclues -- 9 - Compris entre -- 10 - Commence par -- 11 - Fini par -- 12 - Contient FORMAT CHAR(1) CONSTRAINT CK_PGATTR$FORMAT CHECK(FORMAT IN ('A','N', 'E', 'D', 'B')) --- Format de la valeur de l'attribut ); CREATE UNIQUE INDEX PK_IF9PGATTR ON IF9_PGATTR (ID_IF9_PGATTR); ALTER TABLE IF9_PGATTR ADD CONSTRAINT PK_IF9PGATTR PRIMARY KEY (ID_IF9_PGATTR); CREATE INDEX FK_IF9PGATTR$PGPAR ON IF9_PGATTR (ID_IF9_PGPAR); ALTER TABLE IF9_PGATTR ADD CONSTRAINT FK_IF9PGATTR$IF9PGPAR FOREIGN KEY (ID_IF9_PGPAR) REFERENCES IF9_PGPAR (ID_IF9_PGPAR); CREATE INDEX I2_IF9_PGATTR ON IF9_PGATTR (TYPE); CREATE INDEX I3_IF9_PGPATTR ON IF9_PGATTR (KEY_CODE); -- Table pour le paramétrage des règles de notation IFRS 9 - Valeur des attributs CREATE TABLE IF9_PGVAL( ID_IF9_PGVAL NUMBER(10,0) CONSTRAINT NL_PGVAL$ID_PGVAL NOT NULL , --- Identifiant unique (technique) ID_IF9_PGATTR NUMBER(10,0) CONSTRAINT NL_PGVAL$ID_PGATTR NOT NULL , --- Identifiant de l'attribut caractéristique (IF9_PGATTR) DATAA VARCHAR2(150) , --- Valeur de l'attribut au format A DATAN NUMBER(22,7) , --- Valeur de l'attribut au format N/E DATAD DATE , --- Valeur de l'attribut au format D DATAB NUMBER(1,0) CONSTRAINT CK_PGVAL$DATAB CHECK(DATAB IN ('0', '1')) --- Valeur de l'attribut au format B: 0 - FAUX, 1 - VRAI ); CREATE UNIQUE INDEX PK_IF9PGVAL ON IF9_PGVAL (ID_IF9_PGVAL); ALTER TABLE IF9_PGVAL ADD CONSTRAINT PK_IF9PGVAL PRIMARY KEY (ID_IF9_PGVAL); CREATE INDEX FK_IF9PGVAL$IF9PGATTR ON IF9_PGVAL (ID_IF9_PGATTR); ALTER TABLE IF9_PGVAL ADD CONSTRAINT FK_IF9PGVAL$IF9PGATTR FOREIGN KEY (ID_IF9_PGATTR) REFERENCES IF9_PGATTR (ID_IF9_PGATTR); -- Table pour le paramétrages (IFRS 9) des taux par tranche d'exposition au défaut CREATE TABLE IF9_EADPAR( ID_IF9_EADPAR NUMBER(10,0) CONSTRAINT NL_EADPAR$ID_EADPAR NOT NULL , --- Identifiant unique (technique) PLEVEL NUMBER(3,0) CONSTRAINT NL_EADPAR$PLEVEL NOT NULL, --- Niveau de paramétrage CONSTRAINT CK_EADPAR$PLEVEL CHECK(PLEVEL IN ('100','110', '120', '130', '200', '210', '220', '230', '300', '310', '320', '330')) , -- 100 - Global -- 110 - Global/Client Particulier -- 120 - Global/Client Socitété -- 130 - Global/Client Entreprise Individuelle -- 200 - Module -- 210 - Module/Client Particulier -- 220 - Module/Client Socitété -- 230 - Module/Client Entreprise Individuelle -- 300 - Produit -- 310 - Produit/Client Particulier -- 320 - Produit/Client Societé -- 330 - Produit/Client Entreprise Individuelle MODU CHAR(3) CONSTRAINT CK_EADPAR$MODU CHECK(MODU IN ('AUT','CDT', 'CRC', 'LSG', 'ISI', --- Code module - cas des paramètres niveau module/produit 'CAU', 'TIT')), TYPE_PROD VARCHAR2(10) , --- Code type (produit) - cas des paramètres niveau produit -- AUT - Autorisations simples -- CDT - Crédits amortissables -- CRC - Crédits revolving -- LSG - Leasing -- ISI - Finance islamique -- CAU - Cautions -- TIT - Titres TYPE_CLI CHAR(1) CONSTRAINT CK_EADPAR$TYPE_CLI CHECK(TYPE_CLI IN ('1', '2', '3')), --- Type de client -- 1 - Particulier -- 2 - Société -- 3 - Entreprise individuelle B_S1 NUMBER(15,7) , --- Taux part bilan S1 B_S2 NUMBER(15,7) , --- Taux part bilan S2 HB_S1 NUMBER(15,7) , --- Taux part hors-bilan S1 HB_S2 NUMBER(15,7) , --- Taux part hors-bilan S2 UTI CHAR(10) CONSTRAINT NL_EADPAR$UTI NOT NULL, --- Utilisateur ayant créé la règle HIS NUMBER(1,0) CONSTRAINT NL_EADPAR$HIS NOT NULL, --- Règle historisées CONSTRAINT CK_EADPAR$HIS CHECK(HIS IN ('0','1')) , -- 0 - Non -- 1 - Oui DHIS DATE --- Date d'historisation ); CREATE UNIQUE INDEX PK_IF9EADPAR ON IF9_EADPAR (ID_IF9_EADPAR); ALTER TABLE IF9_EADPAR ADD CONSTRAINT PK_IF9EADPAR PRIMARY KEY (ID_IF9_EADPAR); CREATE INDEX I1_IF9_EADPAR ON IF9_EADPAR (PLEVEL); CREATE INDEX I2_IF9_EADPAR ON IF9_EADPAR (MODU,TYPE_PROD,TYPE_CLI); -- Table pour le paramétrage (IFRS 9) des taux par EAD - Définition par tranche de garantie CREATE TABLE IF9_EADGAR( ID_IF9_EADGAR NUMBER(10,0) CONSTRAINT NL_EADGAR$ID_EADGAR NOT NULL , --- Identifiant unique (technique) ID_IF9_EADPAR NUMBER(10,0) CONSTRAINT NL_EADGAR$ID_EADPAR NOT NULL , --- Identifiant de règle (technique) CNAT CHAR(3) CONSTRAINT NL_EADGAR$CNAT NOT NULL , --- Nature de garantie T_S1 NUMBER(15,7) CONSTRAINT NL_EADGAR$T_S1 NOT NULL , --- Taux S1 T_S2 NUMBER(15,7) CONSTRAINT NL_EADGAR$T_S2 NOT NULL --- Taux S2 ); CREATE UNIQUE INDEX PK_IF9EADGAR ON IF9_EADGAR (ID_IF9_EADGAR); ALTER TABLE IF9_EADGAR ADD CONSTRAINT PK_IF9EADGAR PRIMARY KEY (ID_IF9_EADGAR); CREATE INDEX FK_IF9EADGAR$IF9EADPAR ON IF9_EADGAR (ID_IF9_EADPAR); ALTER TABLE IF9_EADGAR ADD CONSTRAINT FK_IF9EADGAR$IF9EADPAR FOREIGN KEY (ID_IF9_EADPAR) REFERENCES IF9_EADPAR (ID_IF9_EADPAR); -- Table pour le paramétrage (IFRS 9) mode de gestion par nature de garantie CREATE TABLE IF9_EADNAT( ID_IF9_EADNAT NUMBER(10,0) CONSTRAINT NL_EADNAT$ID_EADNAT NOT NULL , --- Identifiant unique (technique) CNAT CHAR(3) CONSTRAINT NL_EADNAT$CNAT NOT NULL , --- Nature de garantie IF9_PRV NUMBER(1,0) CONSTRAINT CK_EADNAT$IF9_PRV CHECK(IF9_PRV IN ('0','1','2','3')) , --- Provision IFRS 9 -- 0 - Non renseigné (ou NULL) -- 1 - Pas de prise en compte de la garantie -- 2 - Déduction sur l'exposition -- 3 - Déclinaison par tranche HIS NUMBER(1,0) CONSTRAINT NL_EADNAT$HIS NOT NULL, --- Règle historisées CONSTRAINT CK_EADNAT$HIS CHECK(HIS IN ('0','1')) , -- 0 - Non -- 1 - Oui DHIS DATE , --- Date d'historisation UTI CHAR(10) CONSTRAINT NL_EADNAT$UTI NOT NULL --- Utilisateur ayant créé la règle ); CREATE UNIQUE INDEX PK_IF9EADNAT ON IF9_EADNAT (ID_IF9_EADNAT); ALTER TABLE IF9_EADNAT ADD CONSTRAINT PK_IF9EADNAT PRIMARY KEY (ID_IF9_EADNAT); --Table pour la notation IFRS 9 des dossiers CREATE TABLE IF9_NOTE ( ID_IF9_NOTE NUMBER(10,0) CONSTRAINT NL_NOTE$IDNOTE NOT NULL, --- Identifiant unique (technique) ID_IF9_VAL NUMBER(10,0) CONSTRAINT NL_NOTE$IDVAL NOT NULL, --- Identifiant du lien de valorisation -- AUT - Autorisations simples -- CDT - Crédits amortissables -- CRC - Crédits revolving -- LSG - Leasing -- ISI - Finance islamique -- CAU - Cautions -- TIT - Titres ID_IF9_CYCLE NUMBER(10,0) CONSTRAINT NL_NOTE$IDCYCLE NOT NULL, --- Identifiant du cycle (technique) -- 2 - Client -- 3 - IFRS9 MODU CHAR(3) CONSTRAINT NL_NOTE$MODU NOT NULL, CONSTRAINT CK_NOTE$MODU CHECK(MODU IN ('AUT', 'CDT', 'CRC', --- Code module - cas des paramètres niveau module/produit 'LSG', 'ISI', 'CAU','TIT')), NOTE_UNIT NUMBER(1,0) CONSTRAINT NL_NOTE$NOTE_UNIT NOT NULL, --- Notation issue de propagation CONSTRAINT CK_NOTE$NOTE_UNIT CHECK(NOTE_UNIT IN ('0', '1', '2','3')), -- 0 - Non noté -- 1 - S1 - Bucket 1 -- 2 - S2 - Bucket 2 -- 3 - S3 - Bucket 3 ID_IF9_NTPAR NUMBER(10,0) , --- Identifiant de règle (technique) DUNIT DATE CONSTRAINT NL_NOTE$DUNIT NOT NULL, --- Date de notation unitaire NOTE_PG NUMBER(1,0) CONSTRAINT CK_NOTE$NOTE_PG CHECK(NOTE_PG IN ('1', '2')), --- Notation issue de propagation -- 1 - S1 - Bucket 1 -- 2 - S2 - Bucket 2 -- 4 - < ID_IF9_PGPAR NUMBER(10,0) , --- Identifiant de règle (technique) DPROPAG DATE , --- Date de propagation NOTE_MAN NUMBER(1,0) CONSTRAINT CK_NOTE$NOTE_MAN CHECK(NOTE_MAN IN ('0','1', '2')), --- Notation manuelle -- 0 - Non noté -- 1 - S1 - Bucket 1 -- 2 - S2 - Bucket 2 COMMENTAIRE VARCHAR2(500) , --- Commentaire lié à la notation manuelle DMAN DATE , --- Date de notation manuelle UTI_MAN CHAR(10) , --- Utilisateur ayant noté manuellement NOTE NUMBER(1,0) CONSTRAINT CK_NOTE$NOTE CHECK(NOTE IN ('0','1', '2','3')), --- Notation en cours -- 0 - Non noté -- 1 - S1 - Bucket 1 -- 2 - S2 - Bucket 2 -- 3 - S3 - Bucket 3 ORIG NUMBER(1,0) CONSTRAINT CK_NOTE$ORIG CHECK(ORIG IN ('1', '2','3','4', '5')), --- Origine de la notation en cours -- 1 - Unitaire -- 2 - Propagation -- 3 - Manuelle -- 4 - CDL -- 5 - CTX CLI CHAR(15) CONSTRAINT NL_NOTE$CLI NOT NULL --- Client lié à la notation ); CREATE UNIQUE INDEX PK_IF9NOTE ON IF9_NOTE (ID_IF9_NOTE); ALTER TABLE IF9_NOTE ADD CONSTRAINT PK_IF9NOTE PRIMARY KEY (ID_IF9_NOTE) ; CREATE UNIQUE INDEX I1_IF9NOTE ON IF9_NOTE (ID_IF9_VAL,ID_IF9_CYCLE,MODU); CREATE INDEX FK_IF9NOTE$IF9CYCLE ON IF9_NOTE (ID_IF9_CYCLE); ALTER TABLE IF9_NOTE ADD CONSTRAINT FK_IF9NOTE$IF9CYCLE FOREIGN KEY (ID_IF9_CYCLE) REFERENCES IF9_CYCLE (ID_IF9_CYCLE); CREATE INDEX I2_IF9_NOTE ON IF9_NOTE (MODU); CREATE INDEX I3_IF9_NOTE ON IF9_NOTE (CLI); --Table pour les provisions IFRS 9 des dossiers CREATE TABLE IF9_PRV ( ID_IF9_PRV NUMBER(10,0) CONSTRAINT NL_PRV$IDPRV NOT NULL, --- Identifiant unique (technique) ID_IF9_VAL NUMBER(10,0) CONSTRAINT NL_PRV$IDVAL NOT NULL, --- Identifiant du lien de valorisation -- AUT - Autorisations simples -- CDT - Crédits amortissables -- CRC - Crédits revolving -- LSG - Leasing -- ISI - Finance islamique -- CAU - Cautions -- TIT - Titres ID_IF9_CYCLE NUMBER(10,0) , --- Type d'attribut -- 3 - IFRS9 MODU CHAR(3) CONSTRAINT NL_PRV$MOU NOT NULL, CONSTRAINT CK_PRV$MODU CHECK(MODU IN ('AUT', 'CDT', 'CRC', --- Code module - cas des paramètres niveau module/produit 'LSG', 'ISI', 'CAU','TIT')), TYPE_PROD VARCHAR2(10) , --- Code type (produit) - cas des paramètres niveau produit DEV_DOS CHAR(3) CONSTRAINT NL_PRV$DEV_DOS NOT NULL, --- Devise numérique du dossier TCHG NUMBER(15,7) CONSTRAINT NL_PRV$TCHG NOT NULL, --- Taux de change (devise du dossier vers devise nat.) PROV_S1 NUMBER(19,4) , --- Provision S1 - Bucket 1 (en devise nat.) PROV_S2 NUMBER(19,4) , --- Provision S2 - Bucket 2 (en devise nat.) PROV_S1_DEV NUMBER(19,4) , --- Provision S1 - Bucket 1 (en devise du dossier) PROV_S2_DEV NUMBER(19,4) , --- Provision S2 - Bucket 2 (en devise du dossier) PROV NUMBER(19,4) , --- Provision retenue (en devise nat.) PROV_DEV NUMBER(19,4) , --- Provision retenue (en devise du dossier) DOT NUMBER(19,4) , --- Montant de dotation (en devise nat.) REP NUMBER(19,4) , --- Montant de la reprise (en devise nat.) DOT_DEV NUMBER(19,4) , --- Montant de dotation (en devise du dossier) REP_DEV NUMBER(19,4) , --- Montant de la reprise (en devise du dossier) REP_TOT NUMBER(1,0) CONSTRAINT NL_PRV$REP_TOT NOT NULL, --- Reprise totale (fin de de provisionnement) -- 0 - Ligne de provision standard -- 1 - Ligne de provision de reprise totale CLI CHAR(15) CONSTRAINT NL_PRV$CLI NOT NULL, --- Client lié à la notation TCLI CHAR(1) CONSTRAINT NL_PRV$TCLI NOT NULL --- Client lié à la notation ); CREATE UNIQUE INDEX PK_IF9PRV ON IF9_PRV (ID_IF9_PRV); ALTER TABLE IF9_PRV ADD CONSTRAINT PK_IF9PRV PRIMARY KEY (ID_IF9_PRV) ; CREATE UNIQUE INDEX I1_IF9PRV ON IF9_PRV (ID_IF9_VAL,ID_IF9_CYCLE,MODU); CREATE INDEX FK_IF9_PRV$IF9CYCLE ON IF9_PRV (ID_IF9_CYCLE); ALTER TABLE IF9_PRV ADD CONSTRAINT FK_IF9PRV$IF9CYCLE FOREIGN KEY (ID_IF9_CYCLE) REFERENCES IF9_CYCLE (ID_IF9_CYCLE) ; CREATE INDEX I2_IF9_PRV ON IF9_PRV (MODU, DEV_DOS, TYPE_PROD, TCLI); CREATE INDEX I3_IF9_PRV ON IF9_PRV (CLI); --Table pour les provisions IFRS 9 des dossiers - Détail par tanches CREATE TABLE IF9_EAD ( ID_IF9_EAD NUMBER(10,0) CONSTRAINT NL_EAD$IDEAD NOT NULL, ID_IF9_PRV NUMBER(10,0) CONSTRAINT NL_EAD$IDPRV NOT NULL, --- Identifiant unique (technique) ID_IF9_EADPAR NUMBER(10,0) , --- Identifiant de la provision(technique) ID_IF9_EADGAR NUMBER(10,0) , --- Identifiant du paramétrage des taux (technique) ID_IF9_EADNAT NUMBER(10,0) , --- Identifiant du paramétrage des taux par tranche (technique) TYPE NUMBER(1,0) , --- Identifiant de règle (technique) --- Type de tranches -- 1 - Hors-bilan -- 2 - Bilan non couverte -- 3 - Garantie CNAT CHAR(3) , ---Nature de garantie IF9_PRV NUMBER(1,0) CONSTRAINT CK_EAD$IF9PRV CHECK(IF9_PRV IN ('0', '1', '2','3')), --- Provision IFRS 9 -- 0 - Non renseigné (ou NULL) -- 1 - Pas de prise en compte de la garantie -- 2 - Déduction sur l'exposition -- 3 - Déclinaison par tranche --- Code identifiant (fonctionnel) de l'attribut AGE_GAR CHAR(5) , --- Agence de la garantie EVE_GAR CHAR(6) , --- Numéro de la garantie AGE_ENG CHAR(5) , --- Agence du lien engagement garantie EVE_ENG CHAR(6) , --- Numero du lien engagement garantie MNT_BASE NUMBER(19,4) CONSTRAINT NL_EAD$MNT_MNT_BASE NOT NULL , --- Montant de base de la tranche (en devise nat.) MNT_EAD NUMBER(19,4) CONSTRAINT NL_EAD$MNT_EAD NOT NULL, --- Montant de l'EAD (en devise nat.) MNT_BASE_DEV NUMBER(19,4) CONSTRAINT NL_EAD$MNT_BASE_DEV NOT NULL , --- Montant de base de la tranche (en devise du dossier) MNT_EAD_DEV NUMBER(19,4) CONSTRAINT NL_EAD$MNT_EAD_DEV NOT NULL, --- Montant de l'EAD en devise du dossier (en devise du dossier) PROV_S1 NUMBER(19,4) , --- Provision S1 - Bucket 1 (en devise nat.) PROV_S2 NUMBER(19,4) , --- Provision S2 - Bucket 2 (en devise nat.) PROV_S1_DEV NUMBER(19,4) , --- Provision S1 - Bucket 1 (en devise du dossier) PROV_S2_DEV NUMBER(19,4) --- Provision S2 - Bucket 2 (en devise du dossier) ); CREATE UNIQUE INDEX PK_IF9EAD ON IF9_EAD (ID_IF9_EAD); ALTER TABLE IF9_EAD ADD CONSTRAINT PK_IF9EAD PRIMARY KEY (ID_IF9_EAD) ; CREATE INDEX FK_IF9EAD$IF9PRV ON IF9_EAD (ID_IF9_PRV); ALTER TABLE IF9_EAD ADD CONSTRAINT FK_IF9EAD$IF9PRV FOREIGN KEY (ID_IF9_PRV) REFERENCES IF9_PRV (ID_IF9_PRV) ; CREATE INDEX FK_IF9EAD$IF9EADPAR ON IF9_EAD (ID_IF9_EADPAR); ALTER TABLE IF9_EAD ADD CONSTRAINT FK_IF9EAD$IF9EADPAR FOREIGN KEY (ID_IF9_EADPAR) REFERENCES IF9_EADPAR (ID_IF9_EADPAR) ; CREATE INDEX FK_IF9EAD$IF9EADGAR ON IF9_EAD (ID_IF9_EADGAR); ALTER TABLE IF9_EAD ADD CONSTRAINT FK_IF9EAD$IF9EADGAR FOREIGN KEY (ID_IF9_EADGAR) REFERENCES IF9_EADGAR (ID_IF9_EADGAR) ; CREATE INDEX FK_IF9EAD$IF9EADNAT ON IF9_EAD (ID_IF9_EADNAT); ALTER TABLE IF9_EAD ADD CONSTRAINT FK_IF9EAD$IF9EADNAT FOREIGN KEY (ID_IF9_EADNAT) REFERENCES IF9_EADNAT (ID_IF9_EADNAT) ; --- Modification de la table IF9_VALAUT - Suprresion de la contrainte NOT NULL ALTER TABLE IF9_VALAUT DROP CONSTRAINT NL_VALAUT$ID_VALID; --- Modification de la table IF9_VALCDT - Suprresion de la contrainte NOT NULL ALTER TABLE IF9_VALCDT DROP CONSTRAINT NL_VALCDT$ID_VALID; --- Modification de la table IF9_VALCRC - Suprresion de la contrainte NOT NULL ALTER TABLE IF9_VALCRC DROP CONSTRAINT NL_VALCRC$ID_VALID; --- Modification de la table IF9_VALLSG - Suprresion de la contrainte NOT NULL ALTER TABLE IF9_VALLSG DROP CONSTRAINT NL_VALLSG$ID_VALID; --- Modification de la table IF9_VALTIT - Suprresion de la contrainte NOT NULL ALTER TABLE IF9_VALTIT DROP CONSTRAINT NL_VALTIT$ID_VALID; --- Modification de la table IF9_VALCAU - Suprresion de la contrainte NOT NULL ALTER TABLE IF9_VALCAU DROP CONSTRAINT NL_VALCAU$ID_VALID; --- Modification de la table IF9_VALISL - Suprresion de la contrainte NOT NULL ALTER TABLE IF9_VALISL DROP CONSTRAINT NL_VALISL$ID_VALID; -- ------------ -- BMAS161206-02_ora.sql -- ------------ -- BMAS161206-02 -- Rendre optionelle la saisie de l'adresse fiscale dans la gestion des résidences fiscales ALTER TABLE bkrfisccli DROP CONSTRAINT NL_BKRFISCCLI$TYP_ADR; DROP INDEX i0_BKRFISCCLI; CREATE INDEX i0_BKRFISCCLI ON bkrfisccli (code,typ,typ_adr); -- ------------ -- sgbdp170127-03_ora.sql -- ------------ CREATE INDEX i3_mohis ON mohis (age,dev,ncp,suf); -- ------------ -- mig_bsic_isi_17_E010_ora.sql -- ------------ --ANTIDOTE -- --ALTER TABLE pi_type DROP CONSTRAINT CK_PITYPE$GES_PREM_TRAN; --ALTER TABLE pi_type ADD CONSTRAINT CK_PI_TYPE$GES_PREM_TRAN CHECK(ges_prem_tran IN ('O','N')); --ALTER TABLE pi_dossiers DROP CONSTRAINT CK_PIDOSSIERS$GES_PREM_TRAN; --ALTER TABLE pi_dossiers ADD CONSTRAINT CK_PI_DOSSIERS$GES_PREM_TRAN CHECK(ges_prem_tran IN ('O','N')); -- Ajout de la gestion sans benefice de la premiere tanche ALTER TABLE pi_type DROP CONSTRAINT CK_PI_TYPE$GES_PREM_TRAN; ALTER TABLE pi_type ADD CONSTRAINT CK_PITYPE$GES_PREM_TRAN CHECK(ges_prem_tran IN ('O','N','S')); ALTER TABLE pi_dossiers DROP CONSTRAINT CK_PI_DOSSIERS$GES_PREM_TRAN; ALTER TABLE pi_dossiers ADD CONSTRAINT CK_PIDOSSIERS$GES_PREM_TRAN CHECK(ges_prem_tran IN ('O','N','S')); -- ------------ -- DIM_SGBCI170405-02_01_STR_ora.sql -- ------------ -- SGBCI170405-01 -- -- Le champ « cas » de bkadcli était passé de DECIMAL(6,0) à CHAR(9) dans l évolution V91-CTB-333/CBAO091215-02, mais la table bkadcltrf n avait pas suivi. ALTER TABLE bkadcltrf MODIFY (cas CHAR(9)); -- ------------ -- BES-FR170411-01_ora.sql -- ------------ --Ajout d'un index sur txidhav CREATE INDEX i1_bksepasdd ON bksepasdd(txidhav); -- ------------ -- EVO_PCBUEMOA_CDT_16_E171_01_STR_ORA.sql -- ------------ --ROADMAP - PCB UEMOA CDT - Décote restructuration - Version 11.1.1 26/04/2017 --ANTIDOTE --DROP TABLE bkaccprt_001; CREATE TABLE bkaccprt_001( age CHAR(5) NOT NULL, typ CHAR(3) NOT NULL, poste CHAR(3) NOT NULL, decot_surcot CHAR(1) DEFAULT 'N' CONSTRAINT NL_BKACCPRTER$DECOT_SURCOT NOT NULL); CREATE UNIQUE INDEX pk_bkaccprt_001 on bkaccprt_001(age,typ,poste); ALTER TABLE bkaccprt_001 ADD CONSTRAINT pk_bkaccprt_001 PRIMARY KEY (age,typ,poste); INSERT INTO bkaccprt_001(age,typ,poste) SELECT bkaccprt.age,bkaccprt.typ, bkaccprt.poste FROM bkaccprt; -- ----------- -- DIM_SGA170405-01_01_STR_ora.sql -- ----------- -- Mise a jout du poids par la nouvelle valeur par defaut UPDATE bkacodeb SET poids = poids + (niveau * 10000) WHERE 1=1; UPDATE bkacocre SET poids = poids + (niveau * 10000) WHERE 1=1; UPDATE bkacofra SET poids = poids + (niveau * 10000) WHERE 1=1; UPDATE bkacocde SET poids = poids + (niveau * 10000) WHERE 1=1; UPDATE bkacocmo SET poids = poids + (niveau * 10000) WHERE 1=1; UPDATE bkacoprl SET poids = poids + (niveau * 10000) WHERE 1=1; UPDATE bkacoteg SET poids = poids + (niveau * 10000) WHERE 1=1; -- Ajout index CREATE INDEX i2_bkacodeb ON bkacodeb (poids); CREATE INDEX i2_bkacocre ON bkacocre (poids); CREATE INDEX i2_bkacofra ON bkacofra (poids); CREATE INDEX i2_bkacocde ON bkacocde (poids); CREATE INDEX i2_bkacocmo ON bkacocmo (poids); CREATE INDEX i2_bkacoprl ON bkacoprl (poids); CREATE INDEX i2_bkacoteg ON bkacoteg (poids); -- ----------- -- EVO_CBT161010-01_STR_01_ora.sql -- ----------- ALTER TABLE bkiso8583out MODIFY (fi057 varchar2(255)); -- ----------- -- DEF_8862_STR_ora.sql -- ----------- CREATE TABLE tmp_bkec_factif AS SELECT * FROM bkec_factid; CREATE TABLE tmp_bkec_contratid AS SELECT * FROM bkec_contratid; DROP TABLE bkec_factid; DROP TABLE bkec_contratid; --Table des identifiant de la facture coté fournisseur CREATE TABLE bkec_factid ( id_facture NUMBER(9,0) CONSTRAINT NL_FACTID$ID_FACTURE NOT NULL, -- Identifiant unique d'une facture id_fournisseur NUMBER(6,0) CONSTRAINT NL_FACTID$ID_FOURNISSEUR NOT NULL, -- Identifiant unique d'un fournisseur de services type_donnee CHAR(1) CONSTRAINT NL_FACTID$TYPE_DONNEE NOT NULL , -- Type de la donnée à identifier CONSTRAINT CK_FACTID$TYPE_DONNEE CHECK(type_donnee IN ('1','2','3')) , num_iden NUMBER(1,0) CONSTRAINT NL_FACTID$NUM_IDEN NOT NULL, -- Numéro de l'identifiant de la facture val_iden CHAR(30) CONSTRAINT NL_FACTID$VAL_IDEN NOT NULL -- Valeur de l'identifiant ); CREATE UNIQUE INDEX i0_bkec_factid ON bkec_factid (id_facture, id_fournisseur, type_donnee, num_iden); CREATE INDEX i1_bkec_factid ON bkec_factid (id_fournisseur); CREATE INDEX i2_bkec_factid ON bkec_factid (num_iden,val_iden,type_donnee,id_fournisseur,id_facture); ALTER TABLE bkec_factid ADD CONSTRAINT PK_BKEC_FACTID PRIMARY KEY (id_facture, id_fournisseur, type_donnee, num_iden); ALTER TABLE bkec_factid ADD CONSTRAINT FK_BKEC_FACTID$BKEC_FOUR FOREIGN KEY (id_fournisseur) REFERENCES bkec_four (id_fournisseur); --Table des identifiant du contrat coté fournisseur CREATE TABLE bkec_contratid ( id_contrat NUMBER(9,0) CONSTRAINT NL_CONTRATID$ID_CONTRAT NOT NULL, -- Identifiant amplitude d'un contrat id_fournisseur NUMBER(6,0) CONSTRAINT NL_CONTRATID$ID_FOURNISSEUR NOT NULL, -- Identifiant unique d'un fournisseur de services type_donnee CHAR(1) CONSTRAINT NL_CONTRATID$TYPE_DONNEE NOT NULL , -- Type de la donnée à identifier CONSTRAINT CK_CONTRATID$TYPE_DONNEE CHECK(type_donnee IN ('1','2')) , num_iden NUMBER(1,0) CONSTRAINT NL_CONTRATID$NUM_IDEN NOT NULL, -- Numéro de l'identifiant de la facture cli CHAR(15) , -- Code client Amplitude val_iden CHAR(30) CONSTRAINT NL_CONTRATID$VAL_IDEN NOT NULL -- Valeur de l'identifiant ); CREATE UNIQUE INDEX i0_bkec_contratid ON bkec_contratid (id_contrat, id_fournisseur, type_donnee, num_iden); CREATE INDEX i1_bkec_contratid ON bkec_contratid (id_fournisseur); CREATE INDEX i2_bkec_contratid ON bkec_contratid (num_iden,val_iden,type_donnee,id_fournisseur,id_contrat); ALTER TABLE bkec_contratid ADD CONSTRAINT PK_BKEC_CONTRATID PRIMARY KEY (id_contrat, id_fournisseur, type_donnee, num_iden); ALTER TABLE bkec_contratid ADD CONSTRAINT FK_BKEC_CONTRATID$BKEC_FOUR FOREIGN KEY (id_fournisseur) REFERENCES bkec_four (id_fournisseur); INSERT INTO bkec_factid SELECT * FROM tmp_bkec_factif; INSERT INTO bkec_contratid SELECT * FROM tmp_bkec_contratid; DROP TABLE tmp_bkec_factif; DROP TABLE tmp_bkec_contratid; -- --------------------------------- -- Mise a jour hebdomadaire de evmod -- --------------------------------- Update evmod set amod = '11.1.1', dmod = SYSDATE where cmod = 'DELTA-BANK'; -- ---------------------------------------- -- Mise a jour hebdomadaire de evhistscript -- ---------------------------------------- insert into evhistscript values ('mig_V11.1.1_ora.sql',SYSDATE); ``` HistoriqueElementController.java ```package com.sopraMdv.anotherProject.Controller; import org.springframework.stereotype.Controller; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; @Controller public class HistoriqueElementController { @FXML private ImageView deletebtn; @FXML private Label chosebtn; @FXML private ImageView img; @FXML private Label idlabel; @FXML private void initialize() { deletebtn.setImage(new Image("/Resources/delete.png",false)); img.setImage(new Image("/Resources/file.png",false)); } } ``` KitDAO.java ```package com.sopraMdv.anotherProject.dao; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.sopraMdv.anotherProject.entities.DataBase; import com.sopraMdv.anotherProject.entities.Kit; @Repository public interface KitDAO extends CrudRepository<Kit, Long> { @Query("SELECT database FROM Kit k WHERE k.id = :id") public DataBase getDbByKit(@Param("id") Long kitId); } ``` ServerDAO.java ```package com.sopraMdv.anotherProject.dao; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import com.sopraMdv.anotherProject.entities.Server; public interface ServerDAO extends CrudRepository<Server, Long> { // @Query("SELECT S FROM Server S WHERE S.envi.id = :id") // public Server getServerByEnvid(@Param("id")Long long1); @Query("SELECT userName FROM Server S WHERE S.id = :id") public String getServeruserName(@Param("id")Long long1); @Query("SELECT S FROM Server S WHERE S.id = :id") public Server getServerbsid(@Param("id")Long long1); } ``` FilePathTreeItem.java ```package com.sopraMdv.anotherProject.util; import java.io.File; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import javafx.event.Event; import javafx.event.EventHandler; import javafx.scene.control.TreeItem; import javafx.scene.image.Image; import javafx.scene.image.ImageView; public class FilePathTreeItem extends TreeItem<String> { public static Image folderCollapseImage=new Image(FilePathTreeItem.class.getResource("/Resources/folder.png").toExternalForm()); public static Image folderExpandImage=new Image(FilePathTreeItem.class.getResource("/Resources/folder-open.png").toExternalForm()); public static Image fileImage=new Image(FilePathTreeItem.class.getResource("/Resources/text-x-generic.png").toExternalForm()); //this stores the full path to the file or directory private String fullPath; public void setFullPath(String fullPath) { this.fullPath = fullPath; } public String getFullPath(){return(this.fullPath);} private boolean isDirectory; public boolean isDirectory(){return(this.isDirectory);} @SuppressWarnings("unchecked") public FilePathTreeItem(Path file){ super(file.toString()); this.fullPath=file.toString(); //test if this is a directory and set the icon if(Files.isDirectory(file)){ this.isDirectory=true; this.setGraphic(new ImageView(folderCollapseImage)); }else{ this.isDirectory=false; this.setGraphic(new ImageView(fileImage)); //if you want different icons for different file types this is where you'd do it } //set the value if(!fullPath.endsWith(File.separator)){ //set the value (which is what is displayed in the tree) String value=file.toString(); int indexOf=value.lastIndexOf(File.separator); if(indexOf>0){ this.setValue(value.substring(indexOf+1)); }else{ this.setValue(value); } } this.addEventHandler(TreeItem.branchExpandedEvent(),new EventHandler(){ @Override public void handle(Event e){ FilePathTreeItem source=(FilePathTreeItem)e.getSource(); if(source.isDirectory()&&source.isExpanded()){ ImageView iv=(ImageView)source.getGraphic(); iv.setImage(folderExpandImage); } try{ if(source.getChildren().isEmpty()){ Path path=Paths.get(source.getFullPath()); BasicFileAttributes attribs=Files.readAttributes(path,BasicFileAttributes.class); if(attribs.isDirectory()){ DirectoryStream<Path> dir=Files.newDirectoryStream(path); for(Path file:dir){ FilePathTreeItem treeNode=new FilePathTreeItem(file); source.getChildren().add(treeNode); } } }else{ //if you want to implement rescanning a directory for changes this would be the place to do it } }catch(IOException x){ x.printStackTrace(); } } }); this.addEventHandler(TreeItem.branchCollapsedEvent(),new EventHandler(){ @Override public void handle(Event e){ FilePathTreeItem source=(FilePathTreeItem)e.getSource(); if(source.isDirectory()&&!source.isExpanded()){ ImageView iv=(ImageView)source.getGraphic(); iv.setImage(folderCollapseImage); } } }); }} ``` ProgrammeDeReprise.java ```package com.sopraMdv.anotherProject.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class ProgrammeDeReprise { @Id @GeneratedValue(strategy=GenerationType.SEQUENCE) private Long idProg; private String path; private String nomProg; @ManyToOne private Kit kit; public ProgrammeDeReprise() { super(); // TODO Auto-generated constructor stub } public ProgrammeDeReprise(Long idProg, String path, String nomProg, Kit kit) { super(); this.idProg = idProg; this.path = path; this.nomProg = nomProg; this.kit = kit; } public Long getIdProg() { return idProg; } public void setIdProg(Long idProg) { this.idProg = idProg; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getNomProg() { return nomProg; } public void setNomProg(String nomProg) { this.nomProg = nomProg; } public Kit getKit() { return kit; } public void setKit(Kit kit) { this.kit = kit; } } ```
ziola/MyFitnessApp
ziola/MyFitnessApp DownloadSchedule.java ```package com.ziola.myfitnessapp.async; import android.os.AsyncTask; import android.util.Log; import com.ziola.myfitnessapp.activity.CallerActivity; import com.ziola.myfitnessapp.model.Class; import com.ziola.myfitnessapp.model.DailySchedule; import com.ziola.myfitnessapp.model.ROOM; import com.ziola.myfitnessapp.model.SharedData; import com.ziola.myfitnessapp.util.DateHelper; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import static com.ziola.myfitnessapp.util.DateHelper.dateFormat; import static java.util.Calendar.DATE; /** * Created by mwypysiak on 2015-02-19. */ public class DownloadSchedule extends AsyncTask<Object, String, Map<String, DailySchedule>> { private static final String TAG = DownloadSchedule.class.toString(); private static final String SCHEDULE_URL = "http://timetable.x.creadhoc.com/pl/timetable?"; private static final String SCHEDULE_START = "start="; private static final String SCHEDULE_END = "&end="; private static final String GYM_DATA = "&clubId=1&studioId=0&languageSymbol=PL"; private final CallerActivity activity; public DownloadSchedule(CallerActivity activity) { this.activity = activity; } @Override protected Map<String, DailySchedule> doInBackground(Object[] params) { Map<String, DailySchedule> schedule = new HashMap<>(); Log.i(TAG, "Getting schedule data"); try { Calendar calendar = Calendar.getInstance(); String startDate = dateFormat.format(calendar.getTime()); calendar.add(DATE, 7); String endDate = dateFormat.format(calendar.getTime()); Document document = Jsoup.connect(SCHEDULE_URL + SCHEDULE_START + startDate + SCHEDULE_END + endDate + GYM_DATA).get(); Elements children = document.getElementById("mp-timetable-screen-container").children(); DailySchedule dailySchedule = null; for (Element elem : children) { String className = elem.className(); if (className.contains("mp-timetable-list-cal")) { dailySchedule = initDailySchedule(elem); continue; } if (className.contains("timetable-list-tab") && dailySchedule != null) { dailySchedule = parseDailySchedule(dailySchedule, elem); schedule.put(dateFormat.format(dailySchedule.getDate()), dailySchedule); continue; } } Log.i(TAG, "Schedule data downloaded"); } catch (Exception e) { Log.e(TAG, "Error getting schedule data", e); } return schedule; } private DailySchedule parseDailySchedule(DailySchedule dailySchedule, Element elem) { Elements rows = elem.getElementsByTag("tbody").get(0).getElementsByTag("tr"); for (Element row : rows) { ROOM type = ROOM.get(row.child(3).text().trim()); dailySchedule.addClass(new Class( row.attr("data-classname").trim(), row.attr("data-trainername").trim(), row.child(0).text().trim(), row.child(1).text().trim(), type), type); } return dailySchedule; } private DailySchedule initDailySchedule(Element elem) { int day = Integer.parseInt(elem.child(1).text()); Calendar calendar = Calendar.getInstance(); int currentDay = calendar.get(DATE); int toAdd = day - currentDay; if (toAdd < 0) { toAdd = calendar.getActualMaximum(DATE) - currentDay + day; } calendar.add(DATE, toAdd); DailySchedule dailySchedule = new DailySchedule(); dailySchedule.setDate(calendar.getTime()); return dailySchedule; } @Override protected void onPostExecute(Map<String, DailySchedule> schedule) { SharedData.schedule.clear(); SharedData.schedule.putAll(schedule); activity.postExecuteCallback(); } } ``` README.md ```# MyFitnessApp Prosta aplikacja pozwalająca na wygodniejsze przeglądanie harmonogramu zajęć na siłowni. ``` ScheduleFragment.java ```package com.ziola.myfitnessapp.fragment; /** * Created by mwypysiak on 2015-02-19. */ import android.app.ActionBar; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListView; import com.ziola.myfitnessapp.R; import com.ziola.myfitnessapp.adapter.ClassesAdapter; import com.ziola.myfitnessapp.model.DailySchedule; import com.ziola.myfitnessapp.model.SharedData; public class ScheduleFragment extends Fragment { public static final String DAY = "DAY"; private String mDay; private DailySchedule mDailySchedule; private ClassesAdapter mStudioAdapter; private ExpandableListView mLvClasses; public static ScheduleFragment newInstance(String date) { ScheduleFragment fragmentFirst = new ScheduleFragment(); Bundle args = new Bundle(); args.putString(DAY, date); fragmentFirst.setArguments(args); return fragmentFirst; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDay = getArguments().getString(DAY); mDailySchedule = SharedData.schedule.get(mDay); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_schedule, null); mLvClasses = (ExpandableListView) rootView.findViewById(R.id.lvClasses); mStudioAdapter = new ClassesAdapter(this.getActivity(), mDailySchedule); mLvClasses.setAdapter(mStudioAdapter); mLvClasses.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { return true; } }); for (int i = 0; i < mStudioAdapter.getGroupCount(); i++) { mLvClasses.expandGroup(i); } return rootView; } } ``` SplashScreenActivity.java ```package com.ziola.myfitnessapp.activity; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import com.ziola.myfitnessapp.R; import com.ziola.myfitnessapp.async.DownloadSchedule; public class SplashScreenActivity extends Activity implements CallerActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); if (isNetworkAvailable()) { DownloadSchedule ds = new DownloadSchedule(this); ds.execute(); } } private boolean isNetworkAvailable() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnected(); } @Override public void postExecuteCallback() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } } ``` DailySchedule.java ```package com.ziola.myfitnessapp.model; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by mwypysiak on 2015-02-19. */ public class DailySchedule { private Map<ROOM, List<Class>> classes = new HashMap<ROOM, List<Class>>(); private Date date; public List<Class> getClass(ROOM type) { return classes.get(type); } public void addClass(Class newClass, ROOM type) throws IllegalArgumentException { List<Class> list = classes.get(type); if(list == null) { list = new ArrayList<Class>(); } list.add(newClass); Collections.sort(list, Class.ClassComparator); classes.put(type, list); } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } ``` CallerActivity.java ```package com.ziola.myfitnessapp.activity; /** * Created by mwypysiak on 2015-02-23. */ public interface CallerActivity { void postExecuteCallback(); } ``` ClassesAdapter.java ```package com.ziola.myfitnessapp.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; import com.ziola.myfitnessapp.R; import com.ziola.myfitnessapp.model.Class; import com.ziola.myfitnessapp.model.DailySchedule; import com.ziola.myfitnessapp.model.ROOM; import java.util.List; import static com.ziola.myfitnessapp.model.ROOM.*; import static com.ziola.myfitnessapp.model.ROOM.CYCLING; import static com.ziola.myfitnessapp.model.ROOM.STUDIO; /** * Created by mwypysiak on 2015-02-23. */ public class ClassesAdapter extends BaseExpandableListAdapter { Context _context; DailySchedule schedule; public ClassesAdapter(Context _context, DailySchedule schedule) { this._context = _context; this.schedule = schedule; } @Override public int getGroupCount() { return 3; } @Override public int getChildrenCount(int groupPosition) { List list = (List) getGroup(groupPosition); return list != null ? list.size() : 0; } @Override public Object getGroup(int groupPosition) { switch (groupPosition) { case 0: return schedule.getClass(STUDIO); case 1: return schedule.getClass(FLOOR); case 2: return schedule.getClass(CYCLING); } return null; } @Override public Object getChild(int groupPosition, int childPosition) { switch (groupPosition) { case 0: return schedule.getClass(STUDIO).get(childPosition); case 1: return schedule.getClass(FLOOR).get(childPosition); case 2: return schedule.getClass(CYCLING).get(childPosition); } return null; } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public boolean hasStableIds() { return false; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(_context).inflate(R.layout.item_class_header, parent, false); } switch (groupPosition) { case 0: ((TextView) convertView.findViewById(R.id.tvClassType)).setText(STUDIO.getName()); break; case 1: ((TextView) convertView.findViewById(R.id.tvClassType)).setText(FLOOR.getName()); break; case 2: ((TextView) convertView.findViewById(R.id.tvClassType)).setText(CYCLING.getName()); break; } return convertView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { // Get the data item for this position Class currentClass = (Class) getChild(groupPosition, childPosition); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(_context).inflate(R.layout.item_class, parent, false); } // Lookup view for data population TextView tvClassName = (TextView) convertView.findViewById(R.id.tvClassName); TextView tvTrainerName = (TextView) convertView.findViewById(R.id.tvTrainerName); TextView tvTime = (TextView) convertView.findViewById(R.id.tvTime); // Populate the data into the template view using the data object tvClassName.setText(currentClass.getName()); tvTrainerName.setText(currentClass.getTrainer()); tvTime.setText(currentClass.getStartTime() + " - " + currentClass.getEndTime()); // Return the completed view to render on screen return convertView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return false; } } ``` MainActivity.java ```package com.ziola.myfitnessapp.activity; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import com.ziola.myfitnessapp.R; public class MainActivity extends FragmentActivity { SchedulePagerAdapter mSchedulePagerAdapter; ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSchedulePagerAdapter = new SchedulePagerAdapter(getFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSchedulePagerAdapter); } } ``` Class.java ```package com.ziola.myfitnessapp.model; import java.util.Comparator; /** * Created by mwypysiak on 2015-02-19. */ public class Class { public static final Comparator<Class> ClassComparator = new Comparator<Class>() { @Override public int compare(Class lhs, Class rhs) { return lhs.getStartTime().compareTo(rhs.getStartTime()); } }; private String name; private String trainer; private String startTime; private String endTime; private ROOM room; public Class(String name, String trainer, String startTime, String endTime, ROOM room) { this.trainer = trainer; this.startTime = startTime; this.name = name; this.room = room; this.endTime = endTime; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTrainer() { return trainer; } public void setTrainer(String trainer) { this.trainer = trainer; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public ROOM getRoom() { return room; } public void setRoom(ROOM room) { this.room = room; } } ``` ROOM.java ```package com.ziola.myfitnessapp.model; /** * Created by mwypysiak on 2015-02-19. */ public enum ROOM { STUDIO("Studio"), FLOOR("Gym Floor"), CYCLING("Cycling"); private final String name; ROOM(String name) { this.name = name; } public static ROOM get(String value) { for (ROOM room : values()) { if (room.getName().equals(value)) { return room; } } throw new IllegalArgumentException(value + " is not associated with any value of " + ROOM.class.getCanonicalName()); } public String getName() { return this.name; } } ``` SchedulePagerAdapter.java ```package com.ziola.myfitnessapp.activity; import android.app.Fragment; import android.app.FragmentManager; import android.support.v13.app.FragmentStatePagerAdapter; import com.ziola.myfitnessapp.fragment.ScheduleFragment; import com.ziola.myfitnessapp.util.DateHelper; import java.util.Calendar; import static com.ziola.myfitnessapp.util.DateHelper.dateFormat; import static java.util.Calendar.DATE; /** * Created by mwypysiak on 2015-02-20. */ public class SchedulePagerAdapter extends FragmentStatePagerAdapter { public SchedulePagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { Calendar cal = Calendar.getInstance(); cal.add(DATE, i); return ScheduleFragment.newInstance(dateFormat.format(cal.getTime())); } @Override public int getCount() { return 7; } @Override public CharSequence getPageTitle(int position) { Calendar cal = Calendar.getInstance(); cal.add(DATE, position); return dateFormat.format(cal.getTime()); } }``` DateHelper.java ```package com.ziola.myfitnessapp.util; import java.text.SimpleDateFormat; /** * Created by mwypysiak on 2015-02-23. */ public class DateHelper { public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); } ``` SharedData.java ```package com.ziola.myfitnessapp.model; import java.util.HashMap; import java.util.Map; /** * Created by mwypysiak on 2015-02-23. */ public class SharedData { public static Map<String, DailySchedule> schedule = new HashMap<>(); } ``` DownloadHandlerActivity.java ```package com.ziola.myfitnessapp.async; /** * Created by mwypysiak on 2015-02-19. */ public interface DownloadHandlerActivity { public void handleResult(Object data); } ```
ziombo/KrsDataFront
ziombo/KrsDataFront environment.prod.ts ```export const environment = { production: true, baseUrl: 'https://localhost:44345/api/krsdata' }; ```
ziongh/PushBulletToRoamResearch
ziongh/PushBulletToRoamResearch Program.cs ```using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; namespace ConversorPushBullet { class Program { static void Main(string[] args) { var myJsonString = File.ReadAllText("E:\\Downloads\\pushbullet.json"); var allPushBullets = JsonConvert.DeserializeObject<PushBulletMessages>(myJsonString); var messagesByDay = allPushBullets.pushes.GroupBy(s => s.created.Date); var roamPages = new List<RoamPage>(); foreach (var messagesOnDay in messagesByDay) { var pageName = messagesOnDay.Key.ToStringMine(); var pageMessages = new List<RoamMessage>(); foreach (var message in messagesOnDay) { if(string.IsNullOrEmpty(message.title?.Trim()) && string.IsNullOrEmpty(message.url?.Trim())) continue; pageMessages.Add(new RoamMessage{ messageString = "#[[Quick Capture]]", children = new List<RoamMessage> { new RoamMessage { messageString = $"[{message.title?.Trim()}]({message.url?.Trim()}) [[Waiting]]" } } }); } if (!pageMessages.Any()) { continue; } roamPages.Add(new RoamPage() { title = pageName, children = pageMessages }); } var output = JsonConvert.SerializeObject(roamPages, new JsonSerializerSettings{ Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore, Culture = CultureInfo.InvariantCulture }); File.WriteAllText("E:\\Downloads\\roam.json",output); Console.WriteLine("OK!"); } } public class PushBulletMessages { public List<PushBulletMessage> pushes {get;set;} } public class PushBulletMessage { public string title {get;set;} public string url {get;set;} [JsonConverter(typeof(CustomDateTimeConverter))] public DateTime created {get;set;} } public class RoamPage { public string title {get;set;} public List<RoamMessage> children {get;set;} } public class RoamMessage { [JsonProperty(PropertyName = "string")] public string messageString {get;set;} public List<RoamMessage> children {get;set;} } /// <summary> /// Custom DateTime JSON serializer/deserializer /// </summary> public class CustomDateTimeConverter : DateTimeConverterBase { /// <summary> /// DateTime format /// </summary> private const string Format = "dd. MM. yyyy HH:mm"; /// <summary> /// Writes value to JSON /// </summary> /// <param name="writer">JSON writer</param> /// <param name="value">Value to be written</param> /// <param name="serializer">JSON serializer</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(((DateTime)value).ToString(Format)); } /// <summary> /// Reads value from JSON /// </summary> /// <param name="reader">JSON reader</param> /// <param name="objectType">Target type</param> /// <param name="existingValue">Existing value</param> /// <param name="serializer">JSON serialized</param> /// <returns>Deserialized DateTime</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.Value == null) { return null; } var s = reader.Value.ToString(); var datePArt = s.Split(",")[0]; long.TryParse(datePArt, out var ticks); return ticks.FromUnixTime(); } } ///<summary> ///</summary> public static class UnixDateTimeHelper { private const string InvalidUnixEpochErrorMessage = "Unix epoc starts January 1st, 1970"; /// <summary> /// Convert a long into a DateTime /// </summary> public static DateTime FromUnixTime(this Int64 self) { var ret = new DateTime(1970, 1, 1); return ret.AddSeconds(self); } /// <summary> /// Convert a DateTime into a long /// </summary> public static Int64 ToUnixTime(this DateTime self) { if (self == DateTime.MinValue) { return 0; } var epoc = new DateTime(1970, 1, 1); var delta = self - epoc; if (delta.TotalSeconds < 0) throw new ArgumentOutOfRangeException(InvalidUnixEpochErrorMessage); return (long) delta.TotalSeconds; } public static string ToStringMine(this DateTime dt) { string suffix = "th"; if (dt.Day < 10 || dt.Day > 20) { switch (dt.Day % 10) { case 1: suffix = "st"; break; case 2: suffix = "nd"; break; case 3: suffix = "rd"; break; default: suffix = "th"; break; } } string format = $"MMM dd\"{suffix}\", yyyy"; string s = dt.ToString(format, DateTimeFormatInfo.InvariantInfo); return s; } } } ```
zionlang/reference-docs
zionlang/reference-docs README.md ```# reference-docs A set of reference documents related to Language Design, Parsers, Type Theory and Category Theory. ```
zionnite/wow_php
zionnite/wow_php wow.sql ```-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Dec 11, 2020 at 09:43 AM -- Server version: 10.4.14-MariaDB -- PHP Version: 7.2.33 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `wow` -- -- -------------------------------------------------------- -- -- Table structure for table `forum` -- CREATE TABLE `forum` ( `id` int(11) NOT NULL, `title` varchar(155) NOT NULL, `body` longtext NOT NULL, `image` varchar(155) NOT NULL, `author` varchar(155) NOT NULL, `author_image` varchar(155) NOT NULL, `time` varchar(55) NOT NULL, `type` varchar(55) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `forum` -- INSERT INTO `forum` (`id`, `title`, `body`, `image`, `author`, `author_image`, `time`, `type`) VALUES (1, 'passerby', 'love', 'dan.png', 'kiss', 'love.jpg', '21113', 'gotv'); -- -------------------------------------------------------- -- -- Table structure for table `forum_comment` -- CREATE TABLE `forum_comment` ( `id` int(11) NOT NULL, `forum_id` int(11) NOT NULL, `author` varchar(155) NOT NULL, `body` longtext NOT NULL, `time` varchar(55) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `forum_comment` -- INSERT INTO `forum_comment` (`id`, `forum_id`, `author`, `body`, `time`) VALUES (1, 1, 'daniel', 'loveth', '23322'), (2, 1, 'osato', 'perfect love', '322322'); -- -------------------------------------------------------- -- -- Table structure for table `quote` -- CREATE TABLE `quote` ( `id` int(11) NOT NULL, `title` varchar(255) NOT NULL, `body` longtext NOT NULL, `image` varchar(155) NOT NULL, `author` varchar(255) NOT NULL, `author_image` varchar(155) NOT NULL, `time` varchar(55) NOT NULL, `type` varchar(55) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `quote` -- INSERT INTO `quote` (`id`, `title`, `body`, `image`, `author`, `author_image`, `time`, `type`) VALUES (1, 'I love Christ', 'money is good now', 'image.png', 'james Osator', 'author.png', '123232323', 'Grief'), (2, 'I love Christ', 'money is good now', 'image.png', 'james Osator', 'author.png', '123232323', 'Pains'); -- -- Indexes for dumped tables -- -- -- Indexes for table `forum` -- ALTER TABLE `forum` ADD PRIMARY KEY (`id`); -- -- Indexes for table `forum_comment` -- ALTER TABLE `forum_comment` ADD PRIMARY KEY (`id`); -- -- Indexes for table `quote` -- ALTER TABLE `quote` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `forum` -- ALTER TABLE `forum` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `forum_comment` -- ALTER TABLE `forum_comment` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `quote` -- ALTER TABLE `quote` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; ``` Api.php ```<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Api extends My_Controller { public function __construct(){ parent::__construct(); } public function index(){ $data['content'] =''; $data['content'] ='1'; $this->load->view('welcome_message'); } public function get_quote(){ $msg =array(); $action =$this->Action->get_quote(); if(is_array($action)){ foreach($action as $row){ $id =$row['id']; $title =$row['title']; $desc =$row['body']; $image = base_url().'quote_img/images/'.$row['image']; $author =$row['author']; $author_img = base_url().'agent/images/'.$row['author_image']; $time =$this->Action->time_stamp($row['time']); $type =$row['type']; $is_background =$row['is_background']; $background_link =$row['background_link']; $cat_id =$row['cat_id']; $msg[] =array('id'=>$id,'title'=>$title,'desc'=>$desc,'image'=>$image,'author'=>$author,'author_image'=>$author_img,'time'=>$time,'type'=>$type,'status'=>'success','status_msg'=>'Data fetched successfully', 'is_background'=>$is_background,'background_link'=>$background_link, 'cat_id'=>$cat_id); } }else{ $msg[] =array('status'=>'fail','status_msg'=>'Couldn\'t fetch data from server'); } echo json_encode($msg); } // public function get_quote($current_page){ // $msg =array(); // $action =$this->Action->get_quote($current_page); // if(is_array($action)){ // foreach($action as $row){ // $id =$row['id']; // $title =$row['title']; // $desc =$row['body']; // $image =$row['image']; // $author =$row['author']; // $author_img =$row['author_image']; // $time =$this->Action->time_stamp($row['time']); // $type =$row['type']; // $is_background =$row['is_background']; // $background_link =$row['background_link']; // $cat_id =$row['cat_id']; // // $msg[] =array('id'=>$id,'title'=>$title,'desc'=>$desc,'image'=>$image,'author'=>$author,'author_image'=>$author_img,'time'=>$time,'type'=>$type,'status'=>'success','status_msg'=>'Data fetched successfully', // 'is_background'=>$is_background,'background_link'=>$background_link, // 'cat_id'=>$cat_id); // } // }else{ // $msg[] =array('status'=>'fail','status_msg'=>'Couldn\'t fetch data from server'); // } // echo json_encode($msg); // } // public function get_quote_2($page =NULL){ $msg =array(); $start = 0; $limit = 20; $total =$this->Action->count_quote(); // if($page > $total) { // $page = $total; $msg[] = array('status'=>'end 1'); echo json_encode($msg); }else{ $msg =array(); $start = ($page - 1) * $limit; $this->db->limit($limit,$start); $this->db->order_by('id','desc'); $query =$this->db->get('quote'); foreach ($query->result_array() as $row) { $id =$row['id']; $title =$row['title']; $desc =$row['body']; $image = base_url().'quote_img/images/'.$row['image']; $author =$row['author']; $author_img = base_url().'agent/images/'.$row['author_image']; $time =$this->Action->time_stamp($row['time']); $type =$row['type']; $is_background =$row['is_background']; $background_link =$row['background_link']; $cat_id =$row['cat_id']; $msg[] =array('id'=>$id,'title'=>$title,'desc'=>$desc,'image'=>$image,'author'=>$author,'author_image'=>$author_img,'time'=>$time,'type'=>$type,'status'=>'success','status_msg'=>'Data fetched successfully', 'is_background'=>$is_background,'background_link'=>$background_link, 'cat_id'=>$cat_id); } if(count($msg) != 0){ echo json_encode($msg); }else{ $msg[] = array('status'=>'end 2'); echo json_encode($msg); } } } public function get_quote_by_id($id){ $msg =array(); $action =$this->Action->get_quote_by_id($id); if(is_array($action)){ foreach($action as $row){ $id =$row['id']; $title =$row['title']; $desc =$row['body']; $image = base_url().'quote_img/images/'.$row['image']; $author =$row['author']; $author_img = base_url().'agent/images/'.$row['author_image']; $time =$this->Action->time_stamp($row['time']); $type =$row['type']; $is_background =$row['is_background']; $background_link =$row['background_link']; $cat_id =$row['cat_id']; $msg[] =array('id'=>$id,'title'=>$title,'desc'=>$desc,'image'=>$image,'author'=>$author,'author_image'=>$author_img,'time'=>$time,'type'=>$type,'status'=>'success','status_msg'=>'Data fetched successfully', 'is_background'=>$is_background,'background_link'=>$background_link, 'cat_id'=>$cat_id); } }else{ $msg[] =array('status'=>'fail','status_msg'=>'Couldn\'t fetch data from server, reason be that Quote ID not found or Server is Busy!'); } echo json_encode($msg); } public function get_category(){ $msg =array(); $action =$this->Action->get_category(); if(is_array($action)){ foreach($action as $row){ $cat_id =$row['cat_id']; $cat_name =$row['cat_name']; $msg[] =array('cat_id'=>$cat_id,'cat_name'=>$cat_name); } }else{ $msg[] =array('status'=>'fail','status_msg'=>'Couldn\'t fetch data from server'); } echo json_encode($msg); } public function get_quote_by_cat_id($id){ $msg =array(); $action =$this->Action->get_quote_by_cat_id($id); if(is_array($action)){ foreach($action as $row){ $id =$row['id']; $title =$row['title']; $desc =$row['body']; $image = base_url().'quote_img/images/'.$row['image']; $author =$row['author']; $author_img = base_url().'agent/images/'.$row['author_image']; $time =$this->Action->time_stamp($row['time']); $type =$row['type']; $is_background =$row['is_background']; $background_link =$row['background_link']; $cat_id =$row['cat_id']; $msg[] =array('id'=>$id,'title'=>$title,'desc'=>$desc,'image'=>$image,'author'=>$author,'author_image'=>$author_img,'time'=>$time,'type'=>$type,'status'=>'success','status_msg'=>'Data fetched successfully', 'is_background'=>$is_background,'background_link'=>$background_link, 'cat_id'=>$cat_id); } }else{ $msg[] =array('status'=>'fail','status_msg'=>'Couldn\'t fetch data from server, reason be that Quote ID not found or Server is Busy!'); } echo json_encode($msg); } public function get_quote_by_cat_id_2($id=NULL,$page=NULL){ $msg =array(); $start = 0; $limit = 20; $total =$this->Action->count_quote_by_cat_id($id); // if($page > $total) { // $page = $total; $msg[] = array('status'=>'end'); echo json_encode($msg); }else{ $msg =array(); $start = ($page - 1) * $limit; $this->db->limit($limit,$start); $this->db->order_by('id','desc'); $this->db->where('cat_id',$id); $query =$this->db->get('quote'); foreach ($query->result_array() as $row) { $id =$row['id']; $title =$row['title']; $desc =$row['body']; $image = base_url().'quote_img/images/'.$row['image']; $author =$row['author']; $author_img = base_url().'agent/images/'.$row['author_image']; $time =$this->Action->time_stamp($row['time']); $type =$row['type']; $is_background =$row['is_background']; $background_link =$row['background_link']; $cat_id =$row['cat_id']; $msg[] =array('id'=>$id,'title'=>$title,'desc'=>$desc,'image'=>$image,'author'=>$author,'author_image'=>$author_img,'time'=>$time,'type'=>$type,'status'=>'success','status_msg'=>'Data fetched successfully', 'is_background'=>$is_background,'background_link'=>$background_link, 'cat_id'=>$cat_id); } if(count($msg) != 0){ echo json_encode($msg); }else{ $msg[] = array('status'=>'end'); echo json_encode($msg); } } } public function get_forum(){ $msg =array(); $action =$this->Action->get_forum(); if(is_array($action)){ foreach($action as $row){ $id =$row['id']; $title =$row['title']; $desc =$row['body']; $date_entered =$row['date_created']; $image = base_url().'forum_post_img/'.$date_entered.'/'.$row['image']; $author =$row['author']; $author_img = base_url().'/forum_post_img/'.$date_entered.'/'.$row['author_image']; $time =$this->Action->time_stamp($row['time']); $type =$row['type']; $comment_counter =$this->Action->forum_comment_counter($id); $msg[] =array('id'=>$id,'title'=>$title,'desc'=>$desc,'image'=>$image,'author'=>$author,'author_image'=>$author_img,'time'=>$time,'type'=>$type,'status'=>'success', 'status_msg'=>'Data fetched successfully','comment_counter'=>$comment_counter); } }else{ $msg[] =array('status'=>'fail','status_msg'=>'Couldn\'t fetch data from server'); } echo json_encode($msg); } public function get_forum_2($page=NULL){ $msg =array(); $start = 0; $limit = 20; $total =$this->Action->count_forum(); // if($page > $total) { // $page = $total; $msg[] = array('status'=>'end'); echo json_encode($msg); }else{ $msg =array(); $start = ($page - 1) * $limit; $this->db->limit($limit,$start); $this->db->order_by('id','desc'); $query =$this->db->get('forum'); foreach ($query->result_array() as $row) { $id =$row['id']; $title =$row['title']; $desc =$row['body']; $date_entered =$row['date_created']; $image = base_url().'forum_post_img/'.$date_entered.'/'.$row['image']; $author =$row['author']; $author_img = base_url().'/forum_post_img/'.$date_entered.'/'.$row['author_image']; $time =$this->Action->time_stamp($row['time']); $type =$row['type']; $comment_counter =$this->Action->forum_comment_counter($id); $msg[] =array('id'=>$id,'title'=>$title,'desc'=>$desc,'image'=>$image,'author'=>$author,'author_image'=>$author_img,'time'=>$time,'type'=>$type,'status'=>'success', 'status_msg'=>'Data fetched successfully','comment_counter'=>$comment_counter); } if(count($msg) != 0){ echo json_encode($msg); }else{ $msg[] = array('status'=>'end'); echo json_encode($msg); } } } public function get_forum_by_id($id){ $msg =array(); $action =$this->Action->get_forum_by_id($id); if(is_array($action)){ foreach($action as $row){ $id =$row['id']; $title =$row['title']; $desc =$row['body']; $date_entered =$row['date_created']; $image = base_url().'forum_post_img/'.$date_entered.'/'.$row['image']; $author =$row['author']; $author_img = base_url().'/forum_post_img/'.$date_entered.'/'.$row['author_image']; $time =$this->Action->time_stamp($row['time']); $type =$row['type']; $comment_counter =$this->Action->forum_comment_counter($id); $msg[] =array('id'=>$id,'title'=>$title,'desc'=>$desc,'image'=>$image,'author'=>$author,'author_image'=>$author_img,'time'=>$time,'type'=>$type, 'status'=>'success','status_msg'=>'Data fetched successfully','comment_counter'=>$comment_counter); } }else{ $msg[] =array('status'=>'fail','status_msg'=>'Couldn\'t fetch data from server'); } echo json_encode($msg); } public function get_forum_comment_by_id($id){ $msg =array(); $action =$this->Action->get_forum_by_id($id); if(is_array($action)){ foreach($action as $row){ $id =$row['id']; $title =$row['title']; $desc =$row['body']; $date_entered =$row['date_created']; $image = base_url().'forum_post_img/'.$date_entered.'/'.$row['image']; $author =$row['author']; $author_img = base_url().'/forum_post_img/'.$date_entered.'/'.$row['author_image']; $time =$this->Action->time_stamp($row['time']); $type =$row['type']; $comment_counter =$this->Action->forum_comment_counter($id); $comment =$this->Action->get_forum_comment($id); if(is_array($comment)){ foreach($comment as $row){ $com_id =$row['id']; $commenter =$row['author']; $comment_body =$row['body']; $comment_time =$this->Action->time_stamp($row['time']); $msg[] =array('com_id'=>$com_id,'com_author'=>$commenter,'com_body'=>$comment_body,'com_time'=>$comment_time); } }else{ $msg[] =array('status'=>'fail','status_msg'=>'Couldn\'t fetch Comment from server'); } } }else{ $msg[] =array('status'=>'fail','status_msg'=>'Couldn\'t fetch data from server'); } echo json_encode($msg); } public function get_forum_comment_by_id_2($forum_id=NULL,$page=NULL){ $msg =array(); $start = 0; $limit = 20; $total =$this->Action->count_forum_comment($forum_id); // if($page > $total) { // $page = $total; $msg[] = array('status'=>'end 1'); echo json_encode($msg); }else{ $msg =array(); $start = ($page - 1) * $limit; $this->db->where('id',$forum_id); $query =$this->db->get('forum'); foreach ($query->result_array() as $row) { $id =$row['id']; $title =$row['title']; $desc =$row['body']; $date_entered =$row['date_created']; $image = base_url().'forum_post_img/'.$date_entered.'/'.$row['image']; $author =$row['author']; $author_img = base_url().'/forum_post_img/'.$date_entered.'/'.$row['author_image']; $time =$this->Action->time_stamp($row['time']); $type =$row['type']; $comment_counter =$this->Action->forum_comment_counter($id); $comment =$this->Action->get_forum_comment($forum_id,$limit,$start); if(is_array($comment)){ foreach($comment as $row){ $com_id =$row['id']; $commenter =$row['author']; $comment_body =$row['body']; $comment_time =$this->Action->time_stamp($row['time']); $msg[] =array('com_id'=>$com_id,'com_author'=>$commenter,'com_body'=>$comment_body,'com_time'=>$comment_time); } }else{ $msg[] =array('status'=>'fail','status_msg'=>'Couldn\'t fetch Comment from server'); } } if(count($msg) != 0){ echo json_encode($msg); }else{ $msg[] = array('status'=>'end 2'); echo json_encode($msg); } } } public function make_comment(){ $msg =array(); $fname =$this->input->post('name'); $email =$this->input->post('email'); $comment =$this->input->post('comment'); $forum_id =$this->input->post('forum_id'); $data =array('forum_id'=>$forum_id,'author'=>$fname,'email'=>$email,'body'=>$comment,'time'=>time()); $this->db->set($data); $this->db->insert('forum_comment'); if($this->db->affected_rows() > 0){ $msg['status'] = true; }else{ $msg['status'] = false; } echo json_encode($msg); } public function make_post(){ $msg =array(); $title = $this->input->post('title'); $body = $this->input->post('body'); $author = $this->input->post('author'); $email = $this->input->post('email'); $date = date('Y-m-d'); @mkdir('forum_post_img'); @mkdir('forum_post_img/'.$date); $postImg = $_FILES['post_image']['name']; $postImgPath = 'forum_post_img/'.$date.'/'.$postImg; $postTmp = $_FILES['post_image']['tmp_name']; move_uploaded_file($postTmp,$postImgPath); $profileImg = $_FILES['profile_image']['name']; $profileImgPath = 'forum_post_img/'.$date.'/'.$profileImg; $profileTmp = $_FILES['profile_image']['tmp_name']; move_uploaded_file($profileTmp,$profileImgPath); $data =array('title'=>$title, 'body'=>$body, 'author'=>$author, 'email'=>$email, 'time'=>time(), 'image'=>$postImg, 'author_image'=>$profileImg, 'date_created'=>$date, ); $this->db->set($data); $this->db->insert('forum'); if($this->db->affected_rows() > 0){ $msg['status'] = true; }else{ $msg['status'] = false; } echo json_encode($msg); } public function search_forum(){ $msg = array(); $search_term = $this->input->post('search_term'); $this->db->like('title',$this->db->escape_like_str($search_term,'both')); $this->db->or_like('body',$this->db->escape_like_str($search_term,'both')); $query = $this->db->get('forum'); if($query->num_rows() > 0){ foreach($query->result_array() as $row){ $id =$row['id']; $title =$row['title']; $desc =$row['body']; $date_entered =$row['date_created']; $image = base_url().'forum_post_img/'.$date_entered.'/'.$row['image']; $author =$row['author']; $author_img = base_url().'/forum_post_img/'.$date_entered.'/'.$row['author_image']; $time =$this->Action->time_stamp($row['time']); $type =$row['type']; $comment_counter =$this->Action->forum_comment_counter($id); $msg[] =array('id'=>$id,'title'=>$title,'desc'=>$desc,'image'=>$image,'author'=>$author,'author_image'=>$author_img,'time'=>$time,'type'=>$type,'status'=>'success', 'status_msg'=>'Data fetched successfully','comment_counter'=>$comment_counter); } }else{ $msg[] =array('status'=>'fail','status_msg'=>'Couldn\'t fetch data from server'); } echo json_encode($msg); } public function search_forum_by_page($page=NULL){ $search_term = $this->input->post('search_term'); $msg =array(); $start = 0; $limit = 1; $total =$this->Action->count_forum_search($search_term); // if($page > $total) { // $page = $total; $msg[] = array('status'=>'end'); echo json_encode($msg); }else{ $msg =array(); $start = ($page - 1) * $limit; $this->db->limit($limit,$start); $this->db->order_by('id','desc'); $this->db->like('title',$this->db->escape_like_str($search_term,'both')); $this->db->or_like('body',$this->db->escape_like_str($search_term,'both')); $query = $this->db->get('forum'); foreach ($query->result_array() as $row) { $id =$row['id']; $title =$row['title']; $desc =$row['body']; $date_entered =$row['date_created']; $image = base_url().'forum_post_img/'.$date_entered.'/'.$row['image']; $author =$row['author']; $author_img = base_url().'/forum_post_img/'.$date_entered.'/'.$row['author_image']; $time =$this->Action->time_stamp($row['time']); $type =$row['type']; $comment_counter =$this->Action->forum_comment_counter($id); $msg[] =array('id'=>$id,'title'=>$title,'desc'=>$desc,'image'=>$image,'author'=>$author,'author_image'=>$author_img,'time'=>$time,'type'=>$type,'status'=>'success', 'status_msg'=>'Data fetched successfully','comment_counter'=>$comment_counter); } if(count($msg) != 0){ echo json_encode($msg); }else{ $msg[] = array('status'=>'end'); echo json_encode($msg); } } } public function send_private_message(){ $msg =array(); $name = $this->input->post('name'); $email = $this->input->post('email'); $message = $this->input->post('message'); $data = array('name'=>$name,'email'=>$email, 'message'=>$message,'date'=>date('Y-m-d'), 'time'=>time(),'status'=>'0'); $this->db->set($data); $this->db->insert('message'); if($this->db->affected_rows() > 0){ $msg['status'] = true; }else{ $msg['status'] = false; } echo json_encode($msg); } } ``` Action.php ```<?php class Action extends My_Model{ public function __construct(){ parent::__construct(); } public function get_quote(){ $query =$this->db->get('quote'); if($query->num_rows() > 0){ return $query->result_array(); } return false; } // public function get_quote($current_page){ // $this->db->limit($current_page); // $query =$this->db->get('quote'); // if($query->num_rows() > 0){ // return $query->result_array(); // } // return false; // } public function count_quote(){ return $this->db->from('quote')->count_all_results(); } public function get_quote_by_id($id){ $this->db->where('id',$id); $query =$this->db->get('quote'); if($query->num_rows() > 0){ return $query->result_array(); } return false; } public function get_category(){ $query =$this->db->get('category'); if($query->num_rows() > 0){ return $query->result_array(); } return false; } public function count_quote_by_cat_id($id){ return $this->db->from('quote')->where('cat_id',$id)->count_all_results(); } public function get_quote_by_cat_id($id){ $this->db->where('cat_id',$id); $query =$this->db->get('quote'); if($query->num_rows() > 0){ return $query->result_array(); } return false; } public function count_forum(){ return $this->db->from('forum')->count_all_results(); } public function get_forum(){ $query =$this->db->get('forum'); if($query->num_rows() > 0){ return $query->result_array(); } return false; } public function get_forum_by_id($id){ $this->db->where('id',$id); $query =$this->db->get('forum'); if($query->num_rows() > 0){ return $query->result_array(); } return false; } public function get_forum_comment($forum_id,$limit,$start){ $this->db->limit($limit,$start); $this->db->where('forum_id',$forum_id); $query =$this->db->get('forum_comment'); if($query->num_rows() > 0){ return $query->result_array(); } return false; } public function forum_comment_counter($forum_id){ $this->db->where('forum_id',$forum_id); $counter = $this->db->from('forum_comment')->count_all_results(); return "$counter"; } public function count_forum_comment($forum_id){ $this->db->where('forum_id',$forum_id); return $this->db->from('forum_comment')->count_all_results(); } public function count_forum_search($search_term){ $this->db->like('title',$this->db->escape_like_str($search_term,'both')); $this->db->or_like('body',$this->db->escape_like_str($search_term,'both')); return $this->db->from('forum')->count_all_results(); } public function time_stamp($session_time) { $time_difference = time() - $session_time ; $seconds = $time_difference ; $minutes = round($time_difference / 60 ); $hours = round($time_difference / 3600 ); $days = round($time_difference / 86400 ); $weeks = round($time_difference / 604800 ); $months = round($time_difference / 2419200 ); $years = round($time_difference / 29030400 ); if($seconds <= 60){ return "$seconds seconds ago"; }elseif($minutes <=60){ if($minutes==1){ return "one minute ago"; }else{ return "$minutes minutes ago"; } }else if($hours <=24){ if($hours==1){ return "one hour ago"; }else{ return "$hours hours ago"; } }else if($days <=7){ if($days==1){ return "one day ago"; }else{ return "$days days ago"; } }else if($weeks <=4){ if($weeks==1){ return "one week ago"; }else{ return "$weeks weeks ago"; } }else if($months <=12){ if($months==1){ return "one month ago"; }else{ return "$months months ago"; } }else{ if($years==1){ return "one year ago"; }else{ return "$years years ago"; } } } } ```
zirajauni/hyeladzira
zirajauni/hyeladzira readme.md ```# hyeladzira ```
zirwam/mwvoicesinsta
zirwam/mwvoicesinsta sketch.js ```var x; var imageFilea; var imageFile; var imageFile2; var quotes; var accom; var bio; var currentQuote; var boxShowing = null; var showfeed = false var maph=620, mapw=400; function preload (){ //imageFilea = loadImage('assets/scrool.jpg') imageFile = loadImage('assets/background.jpg') imageFile2 = loadImage('assets/arrow.png') } function setup() { createCanvas(windowWidth,windowHeight); quotes = [ '"I maintain that nothing useful and lasting can emerge from violence." - Shirin Ebadi.', '"As long as you are responsible for building a healthy community, then that’s what gives you motivation and hope, and prevents you from losing hope."- Daisy Khan', '"If people can see Earth from up here, they see it without those borders, see it without any differences in race or religion, they would have a completely different perspective. Because when you see it from that angle, you cannot think of your home or your country. All you can see is one Earth ..." - Anousheh Ansari', '"Women are intersectional human beings who live multi-issued lives... when we are respected, when we are able to thrive and given the same opportunities as our male counterparts, when we are given space to lead and rise — our nation will rise."- Linda Sarsour', '"Its not my responsibility to be beautiful,I\'m not alive for that purpose.My existence is not about how desirable you find me." -Warshan Shire', '"As a Muslim woman, I’ve been liberated from a silent kind of bondage. I don’t answer to the slaves of God on earth. I answer to their King."-Yasmin Mogahed', '"If one man can destroy everything, why can\'t one girl change it?" — Malala Yousafzai', '"I have a calling and purpose in this world. We must stand and speak up against injustices, my family gets that, it’s not easy but this is who I am. If loving my land means I will die, so be it.”— Fadumo Dayib', '“Whatever title or office we may be privileged to hold, it is what we do that defines who we are … Each of us must decide what kind of person we want to be—what kind of legacy that we want to pass on.”—Queen Rania Al Abdullah of Jordan', '"I believe in rebellion as a form of honesty, to be our most authentic self is to rebellious"- Noor Tagouri', '“By working to increase self esteem and self confidence in addition to basic self defense knowledge, we are strengthening women in body, mind and spirit.” - Zainab Abdulla', '"Yes, there are oppressed women in the Muslim world. Women are oppressed the world over. These are our mutual struggles" - Amirah Sackett', '"Not seeing women that look like you in media in general and especially in beauty competitions sends the message that you’re not beautiful or you have to change the way you look to be considered beautiful, and that’s not true." -Halima Aden', '"If there’s someone that can speak to a lived experience that you cannot, do not take up that space, do not speak on their behalf, let them speak for themselves." -Amani Al-Khatahtbeh', '“It’s important we women show we are not afraid.” - Linda Sarsour', '"Set lofty goals for yourself and believe that with really hard work you can achieve them" -Ibtihaj Muhammad' ]; bio = [ '"Muslim Women Voices" is an interactive website that showcases the opinions and accomplishments of Muslim women. A large portion of the media, in today\'s day and time, portrays Muslim women as weak and oppressed. This project was created to tell an opposing narrative, showing the opinions and strengths of them, instead.' ]; accom = [ 'Nusayba bint Ka\'b Al-Ansariyah was one of the first advocates of women rights. She once asked Prophet Muhammed (PBUH) why only men where mentioned in the quran. Soon after, a revelation from the was recieved which stated that women can attain every quality to which men have access.', 'Fatima al-Fihri was the the founder of the oldest degree granting university in the world. The Guinness Book of World Record and UNESCO recognizes the university to be the "oldest continously operating institution of higher education".', 'Sultan Raziya was the Suktan of Dehli from 1236 to 1240. she estaiblishes schools, academies, centers of research and public libraries.', 'Laleh Baktiar was the first american woman to translate the Quran into English.', 'Shirin Ebadi was the first Muslim woman to recieve the first Nobel Peace Prize.', 'Shirin Ebadi was the first woman to achieve Cheif Justice status.', 'Amina Wadud was the first female imam to lead a mixed- congregation prayer.', 'Daisy Khan founded the Women\'s Islamic Intiative in Spiritualityand Equalit, the only global movement that works to reclaim women\'s rights in slam using human rights and social justice.', 'Anousheh Ansari was the first muslim women taht traveled to space.', 'Dalia Mogahed was the US\' first muslim woman in the White House. She was one of Barack Obama\'s closest advisors\' advocating the views and opinions of Muslims across the country.', 'Ibtihaj Muhammad was the first Muslim American fencer in the world.', 'Malala Yousafzai, a Pakistani activist for female education, is the youngest holder of the Nobel Peace Prize.', 'Sayeeda Warsi was the first Muslim minister to sit in the British cabinet.', 'Ibtihaj Muhammad was the first Muslim American female to win a Olympic medal.' ]; getNewWords(); } //function keyPressed() { //saveFrames("out", "png", 1, 25); //} function getNewWords() { currentQuote= quotes[floor(random(quotes.length))]; currentAccom= accom[floor(random(accom.length))]; } function draw() { background(220); image(imageFile, 0, 0, windowWidth, windowHeight); fill(255,202,193, 240) noStroke() rect((200/400)*windowWidth, (150/620)*windowHeight, 300, 150) fill(255) textAlign(CENTER,CENTER) textSize(40); text("muslim women", (200/400)*windowWidth, (140/620)*windowHeight); textSize(69); text("VOICES", (200/400)*windowWidth, (185/620)*windowHeight); textFont("TimesNewRoman"); fill(255,202,193, 240) noStroke() rectMode(CENTER) rect((200/400)*windowWidth, (352/620)*windowHeight, 200, 50) rect((200/400)*windowWidth, (435/620)*windowHeight, 200, 50) rect((200/400)*windowWidth, (515/620)*windowHeight, 200, 50) fill(255) textAlign(CENTER) textSize(34); text("quotes", (200/400)*windowWidth, (330/620)*windowHeight); text("about us", (200/400)*windowWidth, (490/620)*windowHeight); textSize(34); text("women", (200/400)*windowWidth, (410/620)*windowHeight); if(boxShowing === "quotes"){ rect((200/400)*windowWidth, (310/620)*windowHeight, windowWidth*(3/4), 480); fill(255,202,193) ellipse( windowWidth*(3.75/4), windowHeight /2, 30 ,30); image(imageFile2, windowWidth*(3.65/4), windowHeight /2.074, 20, 20) //rectMode(CENTER); textSize(20) textAlign(CENTER,CENTER) text(currentQuote,(200/400)*windowWidth, (310/620)*windowHeight, windowWidth/2, windowHeight/1.5); } if(boxShowing === "accom"){ //textAlign(CENTER) // rectMode(CORNER); rect((200/400)*windowWidth, (310/620)*windowHeight, windowWidth*(3/4), 480); // text("hi", 0,h/2, width, height); fill(255,202,193) ellipse( windowWidth*(3.75/4), windowHeight /2, 30, 30); image(imageFile2, windowWidth*(3.65/4), windowHeight /2.074, 20, 20) textSize(20) textAlign(CENTER,CENTER) text(currentAccom,(200/400)*windowWidth, (310/620)*windowHeight, windowWidth/2, windowHeight/1.5); } if(boxShowing === "about"){ rect((200/400)*windowWidth, (310/620)*windowHeight, windowWidth*(3/4), 480); fill(255,202,193) //ellipse( width*(3.75/4), height /2, 25, 25); textAlign(CENTER) textSize(18) fill(255,202,193) text("contact us at:", (200/400)*windowWidth, (420/620)*windowHeight, windowWidth, windowHeight); text("instagram : @mwvoices", (200/400)*windowWidth, (460/620)*windowHeight, windowWidth, windowHeight); text("muslimwomenvoices@gmail.com", (200/400)*windowWidth, (495/620)*windowHeight, windowWidth, windowHeight); textAlign(CENTER,CENTER) text(bio, (200/400)*windowWidth, (270/620)*windowHeight, windowWidth/2, windowHeight); } } function mousePressed() { if(mouseX>(100/400)*windowWidth&& mouseX<(300/400)*windowWidth&& mouseY>(410/620)*windowHeight&& mouseY<(460/620)*windowHeight){ boxShowing= "accom" } else if(mouseX>(100/400)*windowWidth&& mouseX<300/400*windowWidth&& mouseY>330/620*windowHeight&& mouseY<380/620*windowHeight){ boxShowing= "quotes" } else if(mouseX>(100/400)*windowWidth&& mouseX<300/400*windowWidth&& mouseY>490/620*windowHeight&& mouseY<540/620*windowHeight){ boxShowing= "about" } else if(mouseX>(windowWidth*(3.75/4))-12.5&& mouseX<(windowWidth*(3.75/4))+12.5&& mouseY>windowHeight /2 -12.5&& mouseY<windowHeight /2+12.5){ getNewWords(); } else { boxShowing = null } }```
ziu-templates/react
ziu-templates/react README.md ```# react a react template with webpack ```
zivpug/firepoll
zivpug/firepoll README.md ```firepoll ======== AngularJs + Firebase real time poll app sample Sample app for real time angularJs polls, based on Firebase and Google charts (via Google Chart Api Directive Module for AngularJS - https://github.com/bouil/angular-google-chart) App allows creating new polls and voting on polls from the list. You can also add options to an existing poll. Working sample @ http://ziv-p.com/firepoll/ full description @ http://ziv-p.com/blog/2014/03/17/firepoll-real-time-poll-app/ ``` controller.js ```angular.module('firepollapp').controller('mainCtrl',function($scope, $firebase){ // firebase // Set YOURAPP - to your firebase address var ref = new Firebase("https://YOURAPP.firebaseio.com/polls/"); // Automatically syncs everywhere in realtime $scope.polls = $firebase(ref); // create basic objects $scope.selectedPoll = ''; $scope.selectedPollOptions = []; $scope.load = true; /* Select a poll from the poll's list moveing the poll data to a separate object from the firebase object It gives more flexibility with it's construct and data types (for example - firebase will return values as string type, while google charts has to have them as numbers - note the parseInt on the values) It does adds a need to create a watcher for any incoming changes. Also, used a separate object for poll voting options ($scope.selectedPollOptions) for some more flexibility */ // Loading poll from the list (in the firebase object) $scope.selectPoll = function(id){ if (id){ // don't run on initial watch // hold selected polls id $scope.selectedPoll = id; // clean poll options object $scope.selectedPollOptions = []; // clean chart data chart1.data = []; // populate chart's title from the firebase object chart1.options.title = $scope.polls[id].name; // google charts require column names in the first dataset row. // will give some little pain later chart1.data.push(['option','value']); // populate chart.data with the values from firebase // don't forget to parseInt the values or it will not draw the chart for (i=0; i<$scope.polls[id].options.length; i++) { if ($scope.polls[id].options[i][0] && $scope.polls[id].options[i][1]) { // if you don't have a numeric value - reset the value var val = parseInt($scope.polls[id].options[i][1]); var option = [$scope.polls[id].options[i][0], val]; // push data from the firebase object to the chart data object chart1.data.push(option); // push the options from the firebase object to the poll options object $scope.selectedPollOptions.push($scope.polls[id].options[i]); } } $scope.chart = chart1; } }; // deep watch for the firebase object, to have the chart update in real time, when the object updates // needed to handle the object separation $scope.$watch('polls', function(){ $scope.selectPoll($scope.selectedPoll); },true); // data loaded from firebase - angularfire event // use to switch the loader off $scope.polls.$on("loaded", function() { $scope.load = false; }); // vote on poll $scope.vote = function(index){ // calc new total // add +1 to index to compensate for first row in chart data not being poll options index ++; if (angular.isNumber(chart1.data[index][1] )) { newTotal = parseInt(chart1.data[index][1]) + 1; } else { newTotal = 1 } // move index one back index--; // update value in the firebase object $scope.polls[$scope.selectedPoll].options[index][1] = newTotal; // save changes to the object and the remote firebase $scope.polls.$save(); }; // Add "other" option to selected poll $scope.addOther = function(){ if ($scope.vote.optionOther){ // add new option to the firebase object with 1 vote $scope.polls[$scope.selectedPoll].options.push([$scope.vote.optionOther, 1]); // save the firebase object - update firebase remote $scope.polls.$save(); // clear the "other" form field $scope.vote.optionOther = ''; } }; ////// google chart basic object var chart1 = {}; chart1.type = "PieChart"; // chart options. use google chart reference for more info // pie chart: https://developers.google.com/chart/interactive/docs/gallery/piechart chart1.options = { title: '', chartArea:{left:30,top:30,width:"300",height:"300"}, sliceVisibilityThreshold:0, displayExactValues: true, pieSliceText: 'percentage', width: 400, height: 300, is3D: true, slices: {} }; /// create poll - form methods // reset the form $scope.resetForm = function(){ $scope.pollForm = {}; $scope.pollForm.options = []; }; // call one reset on load for object declaration $scope.resetForm(); // Add a poll option to the creation form $scope.addPollOption = function(){ $scope.pollForm.options.push(['', '0']); }; // remove pull option from the form $scope.removeOption = function(index){ $scope.pollForm.options.splice(index,1); }; // Create a new poll $scope.pollCreate = function(){ // add to poll to the Firebase object - this will update it at the server // check for empty options for (i=0; i<$scope.pollForm.options.length; i++){ // make sure no empty options if (angular.isUndefined($scope.pollForm.options[i][0]) || $scope.pollForm.options[i][0]=='') {$scope.pollForm.options.splice(i,1)} } if ($scope.pollForm.name && ($scope.pollForm.options.length>0)) { // add the new form to the firebase object. it will be updated automagically in firebase $scope.polls.$add($scope.pollForm); // reset the poll creation form $scope.resetForm(); } }; }); ``` setup.js ```angular.module('firepollapp', ['googlechart', 'firebase']); angular.module('firepollapp').run(function($rootScope) { }); ```
zivzone/Awesome-AI-Step-By-Step
zivzone/Awesome-AI-Step-By-Step README.md ```# Awesome-AI-Step-By-Step - It's a repo which to record every awesome AI-related projecty/work/repo/etc ## Coding ### Python - [Python-100-Days](https://github.com/jackfrued/Python-100-Days) ## Tutorial - [莫煩](https://morvanzhou.github.io/) ```