# Introduction

Just some basic notes and stuff written by Liu and Gentleman.Hu

## Only Notes

* Nothing just notes
* Nothing just ...

  All Notes By [Liu](https://github.com/Forgotten-Forever) and [Gentleman.Hu](https://github.com/GentlemanHu)


# Files

[generateSummary.js](https://github.com/We2one/Notes/tree/c9b58ba98e99c4cb88d0f0a66922f73d3c24e2a9/files/generateSummary.js)

[generateSummary.py](https://github.com/We2one/Notes/tree/c9b58ba98e99c4cb88d0f0a66922f73d3c24e2a9/files/generateSummary.py)


# Http


# Http基础

```yaml
   Author: Gentleman.Hu
   Create Time: 2021-06-18 17:26:25
   Modified by: Gentleman.Hu
   Modified time: 2021-06-18 18:19:23
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: HTTP基础
```

## HTTP的定义

Hypertext Transfer Protocol, 超文本传输协议, 与HTML一起诞生, 用于请求和传输HTML内容.

## HTTP工作机制

### 浏览器

用户输入地址后回车或点击链接->浏览器拼装HTTP报文并发送给服务器->服务器处理请求后发送响应报文给浏览器->浏览器解析响应报文并使用渲染引擎显示到界面

### 手机APP

用户点击界面或者自动触发联网请求-> Android代码调用拼装HTTP报文并发送请求到服务器->服务器处理请求后发送响应报文给手机->Android代码处理响应报文并作出相应处理(存储数据,加工数据,显示数据到界面等)

## URL和HTTP报文

### URL格式

1. 协议类型
2. 服务器地址(端口号)
3. 路径(path)

协议://服务器地址\[:port]/路径 <https://www.crushing.xyz>

### 报文格式

* 请求报文

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20210618173705.png)

* 响应报文

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20210618173840.png)

### 请求方法 - Request Method

* GET
  * 获取资源
  * 不对服务器数据进行修改
  * 不发送body

```javascript
GET /users/1 HTTP/1.1
Host: api.github.com
```

对应的Retrofit代码:

```java
@GET("/users/{id}")
Call<User> getUser(@Path("id") String id, @Query("gender") String gender);
```

* POST
  * 增加或者修改资源
  * 发送给服务器的内容在body里

```javascript
POST /users HTTP/1.1 
Host: api.github.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13

name=godlin&gender=male
```

对应Retrofit代码:

```java
@FormUrlEncoded
@POST("/users")
Call<User> addUser(@Field("name") String name, @Field("gender") String gender);
```

* PUT

```javascript
PUT /users HTTP/1.1
Host: api.github.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13

gender=female
```

对应Retrofit代码:

```java
@FormUrlEncoded
@PUT("/users/{id}")
Call<User> updateUser(@Path("id") String id, @Field("gender") String gender);
```

* DELETE

```javascript
DELETE /users HTTP/1.1
Host: api.github.com
```

Retrofit代码

```java
@DELETE("/users/{id}")
Call<User> deleteUser(@Path("id") String id,@Query("gender") String gender);
```

* HEAD
  * 跟GET用法一致
  * 唯一区别,返回响应无Body

### 状态码 - Status Code

* 1xx: 临时消息,100继续发送,101正在切换协议
* 2xx: 成功.200 ok,201 创建成功
* 3xx: 重定向. 301永久移动,302临时移动,304内容未改变
* 4xx: 客户端错误. 400客户端请求错误,401认证失败,403禁止,404找不到
* 5xx: 服务器错误. 500服务器内部错误.

### 头部 - Header

> 作用: HTTP消息的metadata

* Host: 目标主机. ! 不是用于网络寻址的,而是在目标服务器上用于定位子服务器的.
* Content-Type: 指定Body类型,主要4类
  * text/html
  * x-www-form-urlencoded
  * multipart/form-data
  * application/json, image/jpeg, application/zip ...&#x20;
* Content-Length
* Transfer: chunked
* Location
* User-Agent: 用户代理.谁实际发送请求,接受响应.
* Range/Accept-Range
  * Accept-Range: bytes 服务器按照字节取范围数据
  * Range: bytes=- 请求报文出现,表示取那段数据
  * Content-Range: -/total 响应报文中出现,表示发送的是那段数据
  * 作用: 断点续传,多线程下载
* Accept: 客户端可以接受的数据类型.如 text/html
* Accept-Charset: 客户端接受的字符集.如 utf-8
* Accept-Encoding: 客户端接受的压缩编码类型.如gzip
* Content-Encoding: 压缩类型. 如gzip

## Cache

> 作用: 在客户端或者中间网络节点缓存数据,降低从服务器取数据的频率,提高网络性能.

## REST

* 使用资源的格式定义URL
* 规范使用method定义网络请求操作
* 规范使用status code表示响应状态
* 其他服务HTTP规范的设计准则

> copy from hencoder notes pdf


# Okhttp理解

```yaml
   Author: Gentleman.Hu
   Create Time: 2021-06-18 21:28:25
   Modified by: Gentleman.Hu
   Modified time: 2021-06-22 14:39:25
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description:
```

## 理解okhttp中的`getResponseWithInterceptorChain()`

\`\`\`kotlin @Throws(IOException::class)


# Jetpack


# Notes

```yaml
   Author: Gentleman.Hu
   Create Time: 2021-09-24 13:44:41
   Modified by: Gentleman.Hu
   Modified time: 2021-09-24 13:44:58
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: 学习Jetpack 架构组件记录的笔记
```


# 101


# Basis


# Index

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-10-26 22:20:11
   Modified by: Gentleman.Hu
   Modified time: 2020-11-15 17:39:47
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description:
```

## Basis of CS

* 一个教程站

  [journaldev](https://www.journaldev.com/)

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201115173840.png)


# Front


# Angular


# Angular start 01

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-11-04 10:32:18
   Modified by: Gentleman.Hu
   Modified time: 2020-11-05 15:51:43
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description:
```

## Angular Start

### 目录结构

> [详细(ts)doc](https://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators)
>
> [官方文档](https://angular.io/guide/dependency-injection-providers)

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201104104120.png)

> `app.component.spec.ts`，\[单元测试]\([typescript - What are the "spec.ts" files generated by Angular CLI for? - Stack Overflow](https://stackoverflow.com/a/37502922))

* ① Root component，根组件
  * ![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201104110131.png)
  * ① 对应html中的 DOM中的selector位置，被解释翻译点
  * ② 对应此组件的HTML模板
  * ③ 对应此组件的css样式
  * ④ 此组件类的成员和方法函数等
* ② Main module，主模块
  * `app.module.ts`，应用具体定义配置模块，定义了所有相关组件和依赖等
  * ![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201104104843.png)
  * `@NgModule`，这个ts注解标识是Angular的module类
  * `declarations` ，标识哪些组件可以再本应用使用
  * `imports`，引入其他的module，提供函数使用
  * `providers`，injector，提供运行时的注入 \[doc]\([Angular](https://angular.io/guide/dependency-injection-providers))
  * `bootstrap`，本应用的入口组件
* ③ Root HTML，根HTML页
* ④ Entry point，入口
  * ![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201104111236.png)
  * 启动应用
* ⑤ Angular CLI config，cli配置

> `declarations`
>
> The declarations block defines all the components that are allowed to be used in the scope of the HTML within this module. Any component that you create must be declared before it can be used.
>
> `imports`
>
> You will not create each and every functionality used in the application, and the imports array allows you to import other Angular application and library modules and thus leverage the components, services, and other capabilities that have already been created in those modules.
>
> `bootstrap`
>
> The bootstrap array defines the component that acts as the entry point to your application. If the main component is not added here, your application will not kick-start, as Angular will not know what elements to look for in your index.html.

## 创建一个组件

> [Understanding*Compontents*](https://docs.angularjs.org/guide/component)
>
> ['$'符号作用](https://stackoverflow.com/a/37928549)

* `ng generate component path/name`
* 以上命令利用cli工具创建component
* ![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201104112224.png)
* cli将自动在`app.module.ts`中添加声明和依赖
* ![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201104134758.png)
* 可以看到自动生成的component，`selector`正是对应html中的selector，对应解析翻译。
* `ngOnInit()`此方法是实现OnInit接口的方法，设置了Hook，当此Component初始化时候触发
* 里边填写相应的初始化变量，类似Java构造方法


# Angular start 02


# Typescript


# Index

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-11-08 22:31:10
   Modified by: Gentleman.Hu
   Modified time: 2020-11-10 23:49:56
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: Index of TypeScript Start
```

## What

* [youtube](https://www.youtube.com/watch?v=BwuLxPH8IDs)
* [official\_site](https://www.typescriptlang.org/docs)
* [difference\_js\_ts\_node](https://stackshare.io/stackups/nodejs-vs-typescript-vs-javascript)


# Ts 01

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-11-08 22:29:31
   Modified by: Gentleman.Hu
   Modified time: 2020-11-10 23:57:02
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: TypeScript Start
```

## TypeScript Start 01

> <https://www.youtube.com/watch?v=BwuLxPH8IDs>

## Basic

### Init

* `npm init`
* `npm install --save-dev lite-server`
* `npm start`

  ![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201108231235.gif)

### Core Types

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201108231706.png)

* ts中静态类型,可在编译期检查到类型不匹配错误
* js动态类型,随意转换

```typescript
function add(n1: number, n2: number){
  if(typeof n1 !== 'number' || typeof n2 !== 'number'){
    throw new Error('Incorrect input!');
  }
  return n1 + n2;
}

const number1 = '5'
const number2 = 2.5;

const result = add(number1,number2);
console.log(result);
```

如上代码,在ts中,写代码期间(编译前期间)就可被编译器检查到类型不匹配.

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201110235608.png)

## 一些疑问与探索

* html标签中`<script src=" " defer>`的`defer`啥意思？

  > [defer\_in\_html](https://www.w3schools.com/tags/att_script_defer.asp#:~:text=The%20defer%20attribute%20is%20a,the%20page%20has%20finished%20parsing.\&text=If%20neither%20async%20or%20defer,browser%20continues%20parsing%20the%20page)

```markup
Definition and Usage
The defer attribute is a boolean attribute.

When present, it specifies that the script is executed when the page has finished parsing.

Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).

Note: There are several ways an external script can be executed:

If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)
If async is not present and defer is present: The script is executed when the page has finished parsing
If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page
```

* `--save-dev`和`--save`区别

  > [difference\_\_](https://stackoverflow.com/a/28510398)

```
There are (at least) two types of package dependencies you can indicate in your package.json files:

Those packages that are required in order to use your module are listed under the "dependencies" property. Using npm you can add those dependencies to your package.json file this way:

npm install --save packageName
Those packages required in order to help develop your module are listed under the "devDependencies" property. These packages are not necessary for others to use the module, but if they want to help develop the module, these packages will be needed. Using npm you can add those devDependencies to your package.json file this way:

npm install --save-dev packageName
```


# Java


# Concurrency


# Frameworks


# Jdbc与连接池

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-10-03 15:28:51
   Modified by: Gentleman.Hu
   Modified time: 2020-10-07 16:11:55
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description:
```

## JDBC与连接池

> [QuickGuide](https://www.tutorialspoint.com/jdbc/jdbc-quick-guide.htm) Java DataBase COnnectivity

### JDBC与基本CRUD

#### 基本

* 基本步骤
  * 注册驱动
  * 建立连接
  * 获取数据库连接对象(Connection)
  * 定义sql语句
  * 获取sql执行对象(Statement)
  * 执行sql,获取结果
  * 处理结果
  * 关闭连接,释放资源
* OnAction 1. 引入包`import java.sql.*;` 2. 注册驱动`Class.forName("com.mysql.jdbc.Driver)` 3. 建立连接

  ```java
   static final String USER = "username";
   static final String PASS = "password";
   System.out.println("Connecting to database...);
   conn = DriverManager.getConnection(DB_URL,USER,PASS);
  ```

  1. 执行sql

     ```java
     System.out.println("Creating statement ...);
     stmt = conn.createStatement();
     String sql;
     sql = "select * from one_table";
     ResultSet rs = stmt.executeQuery(sql);
     ```
  2. 处理结果

     ```java
     while(rs.next()){
         int id  = rs.getInt("id");
     int age = rs.getInt("age");
     String first = rs.getString("first");
     String last = rs.getString("last");

     //Display values
     System.out.print("ID: " + id);
     System.out.print(", Age: " + age);
     System.out.print(", First: " + first);
     System.out.println(", Last: " + last);
     }
     ```
  3. 关闭连接,释放资源

     ```java
     rs.close();
     stmt.close();
     conn.close();
     ```
* Full

```java
  //STEP 1. Import required packages
import java.sql.*;

public class FirstExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/EMP";

   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);

      //STEP 5: Extract data from result set
      while(rs.next()){
         //Retrieve by column name
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");

         //Display values
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }
      //STEP 6: Clean-up environment
      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      }// nothing we can do
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end FirstExample
```

* 相关Exception表一览

| Method                         | Description                                                                                                                                                                                                     |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| getErrorCode( )                | Gets the error number associated with the exception.                                                                                                                                                            |
| getMessage( )                  | Gets the JDBC driver's error message for an error handled by the driver or gets the Oracle error number and message for a database error.                                                                       |
| getSQLState( )                 | Gets the XOPEN SQLstate string. For a JDBC driver error, no useful information is returned from this method. For a database error, the five-digit XOPEN SQLstate code is returned. This method can return null. |
| getNextException( )            | Gets the next Exception object in the exception chain.                                                                                                                                                          |
| printStackTrace( )             | Prints the current exception, or throwable, and its backtrace to a standard error stream.                                                                                                                       |
| printStackTrace(PrintStream s) | Prints this throwable and its backtrace to the print stream you specify.                                                                                                                                        |
| printStackTrace(PrintWriter w) | Prints this throwable and its backtrace to the print writer you specify.                                                                                                                                        |

* 用try catch finally包裹

```java
try {
   // Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
   // Your exception handling code goes between these 
   // curly braces, similar to the exception clause 
   // in a PL/SQL block.
}
finally {
   // Your must-always-be-executed code goes between these 
   // curly braces. Like closing database connection.
}
```

* JDBC 中Data 类型对应表

| SQL         | JDBC/Java            | setXXX        | updateXXX        |
| ----------- | -------------------- | ------------- | ---------------- |
| VARCHAR     | java.lang.String     | setString     | updateString     |
| CHAR        | java.lang.String     | setString     | updateString     |
| LONGVARCHAR | java.lang.String     | setString     | updateString     |
| BIT         | boolean              | setBoolean    | updateBoolean    |
| NUMERIC     | java.math.BigDecimal | setBigDecimal | updateBigDecimal |
| TINYINT     | byte                 | setByte       | updateByte       |
| SMALLINT    | short                | setShort      | updateShort      |
| INTEGER     | int                  | setInt        | updateInt        |
| BIGINT      | long                 | setLong       | updateLong       |
| REAL        | float                | setFloat      | updateFloat      |
| FLOAT       | float                | setFloat      | updateFloat      |
| DOUBLE      | double               | setDouble     | updateDouble     |
| VARBINARY   | byte\[ ]             | setBytes      | updateBytes      |
| BINARY      | byte\[ ]             | setBytes      | updateBytes      |
| DATE        | java.sql.Date        | setDate       | updateDate       |
| TIME        | java.sql.Time        | setTime       | updateTime       |
| TIMESTAMP   | java.sql.Timestamp   | setTimestamp  | updateTimestamp  |
| CLOB        | java.sql.Clob        | setClob       | updateClob       |
| BLOB        | java.sql.Blob        | setBlob       | updateBlob       |
| ARRAY       | java.sql.Array       | setARRAY      | updateARRAY      |
| REF         | java.sql.Ref         | SetRef        | updateRef        |
| STRUCT      | java.sql.Struct      | SetStruct     | updateStruct     |

* 批处理 JDBC - Batch Processing

Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database.

When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.

* JDBC drivers are not required to support this feature. You should use the *DatabaseMetaData.supportsBatchUpdates()* method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
* The **addBatch()** method of *Statement, PreparedStatement,* and *CallableStatement* is used to add individual statements to the batch. The **executeBatch()** is used to start the execution of all the statements grouped together.
* The **executeBatch()** returns an array of integers, and each element of the array represents the update count for the respective update statement.
* Just as you can add statements to a batch for processing, you can remove them with the **clearBatch()** method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.
* Streaming Data(流):

A PreparedStatement object has the ability to use input and output streams to supply parameter data. This enables you to place entire files into database columns that can hold large values, such as CLOB and BLOB data types.

There are following methods which can be used to stream data:

* **setAsciiStream():** This method is used to supply large ASCII values.
* **setCharacterStream():** This method is used to supply large UNICODE values.
* **setBinaryStream():** This method is used to supply large binary values.

The setXXXStream() method requires an extra parameter, the file size, besides the parameter placeholder. This parameter informs the driver how much data should be sent to the database using the stream.

#### 事务

> 事务：一个包含多个步骤的业务操作。如果这个业务操作被事务管理，则这多个步骤要么同时成功，要么同时失败。

使用Connection对象来管理事务

* 开启事务：setAutoCommit(boolean autoCommit) ：调用该方法设置参数为false，即开启事务
* 在执行sql之前开启事务
* 提交事务：commit()&#x20;
* 当所有sql都执行完提交事务
* 回滚事务：rollback()&#x20;
* 在catch中回滚事务
* 简单demo

  ```java
    public class JDBCDemo10 {

        public static void main(String[] args) {
            Connection conn = null;
            PreparedStatement pstmt1 = null;
            PreparedStatement pstmt2 = null;

            try {
                //1.获取连接
                conn = JDBCUtils.getConnection();
                //开启事务
                conn.setAutoCommit(false);

                //2.定义sql
                //2.1 张三 - 500
                String sql1 = "update account set balance = balance - ? where id = ?";
                //2.2 李四 + 500
                String sql2 = "update account set balance = balance + ? where id = ?";
                //3.获取执行sql对象
                pstmt1 = conn.prepareStatement(sql1);
                pstmt2 = conn.prepareStatement(sql2);
                //4. 设置参数
                pstmt1.setDouble(1,500);
                pstmt1.setInt(2,1);

                pstmt2.setDouble(1,500);
                pstmt2.setInt(2,2);
                //5.执行sql
                pstmt1.executeUpdate();
                // 手动制造异常
                int i = 3/0;

                pstmt2.executeUpdate();
                //提交事务
                conn.commit();
            } catch (Exception e) {
                //事务回滚
                try {
                    if(conn != null) {
                        conn.rollback();
                    }
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }finally {
                JDBCUtils.close(pstmt1,conn);
                JDBCUtils.close(pstmt2,null);
            }
  ```

### 数据库连接池与JDBC Template

> [jdbc-jdbc-connection-pooling](https://www.progress.com/tutorials/jdbc/jdbc-jdbc-connection-pooling)

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201007145250.png)

#### 基础连接池

> 一个容器(集合)，存放数据库连接的容器。 当系统初始化好后，容器被创建，容器中会申请一些连接对象，当用户来访问数据库时，从容器中获取连接对象，用户访问完之后，会将连接对象归还给容器。

1. 好处： 1. 节约资源 2. 用户访问高效
2. 实现： 标准接口：DataSource javax.sql包下的
3. 方法：
   * 获取连接：getConnection()
   * 归还连接：Connection.close()。如果连接对象Connection是从连接池中获取的，那么调用Connection.close()方法，则不会再关闭连接了。而是释放连接
4. 几个常见厂商实现的数据库连接池 1. C3P0：数据库连接池技术 2. Druid：数据库连接池实现技术，由阿里巴巴提供的
5. c3p0配置文件
   * `c3p0.properties`或者`c3p0-config.xml`
   * 直接放置在`src`目录即可
6. c3p0创建过程

   * ComboPooledDataSource
   * getConnection

   ```java
   DataSource ds = new ComboPooleddataSource();
   Connection conn = ds.getConnection();
   ```
7. Druid:

   * 配置文件
     * 可以properties
     * 可以任意名称,任意位置
   * 过程
     * 加载配置文件.Properties
     * 通过工厂获取连接池对象.`DruidDataSourceFactory`
     * 获取连接:`getConnection`

   ```java
   Properties pro = new Properties();
   InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
   pro.load(is);

   DataSource ds = DruidDataSourceFactory.createDataSource(pro);

   Connection conn = ds.getConnection();
   ```

   * Full in util class

   ```java
   public class JDBCUtils {

             //1.定义成员变量 DataSource
             private static DataSource ds ;

             static{
                 try {
                     //1.加载配置文件
                     Properties pro = new Properties();
                     pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
                     //2.获取DataSource
                     ds = DruidDataSourceFactory.createDataSource(pro);
                 } catch (IOException e) {
                     e.printStackTrace();
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
             }

             /**
              * 获取连接
              */
             public static Connection getConnection() throws SQLException {
                 return ds.getConnection();
             }

             /**
              * 释放资源
              */
             public static void close(Statement stmt,Connection conn){
                /* if(stmt != null){
                     try {
                         stmt.close();
                     } catch (SQLException e) {
                         e.printStackTrace();
                     }
                 }

                 if(conn != null){
                     try {
                         conn.close();//归还连接
                     } catch (SQLException e) {
                         e.printStackTrace();
                     }
                 }*/

                close(null,stmt,conn);
             }
             public static void close(ResultSet rs , Statement stmt, Connection conn){
                 if(rs != null){
                   try {
                       rs.close();
                   } catch (SQLException e) {
                       e.printStackTrace();
                   }
               }

                      if(stmt != null){
                     try {
                         stmt.close();
                     } catch (SQLException e) {
                         e.printStackTrace();
                     }
                 }

                 if(conn != null){
                     try {
                         conn.close();//归还连接
                     } catch (SQLException e) {
                         e.printStackTrace();
                     }
                 }
             }

             /**
              * 获取连接池方法
              */

             public static DataSource getDataSource(){
                 return  ds;
             }

         }
   ```

#### Spring JDBC

> [Spring\_Guide](https://spring.io/guides/gs/relational-data-access/) [JavaPointTutorial](https://www.javatpoint.com/spring-JdbcTemplate-tutorial)

* Spring JDBCTemplate class method table

| No. | Method                                                         | Description                                                                                 |
| --- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| 1)  | public int update(String query)                                | is used to insert, update and delete records.                                               |
| 2)  | public int update(String query,Object... args)                 | is used to insert, update and delete records using PreparedStatement using given arguments. |
| 3)  | public void execute(String query)                              | is used to execute DDL query.                                                               |
| 4)  | public T execute(String sql, PreparedStatementCallback action) | executes the query by using PreparedStatement callback.                                     |
| 5)  | public T query(String sql, ResultSetExtractor rse)             | is used to fetch records using ResultSetExtractor.                                          |
| 6)  | public List query(String sql, RowMapper rse)                   | is used to fetch records using RowMapper.                                                   |

* Employee.java

```java
public class Employee {  
private int id;  
private String name;  
private float salary;  
//no-arg and parameterized constructors  
//getters and setters  
}
```

* EmployeeDao.java

```java
import org.springframework.jdbc.core.JdbcTemplate;  

public class EmployeeDao {  
private JdbcTemplate jdbcTemplate;  

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
    this.jdbcTemplate = jdbcTemplate;  
}  

public int saveEmployee(Employee e){  
    String query="insert into employee values(  
    '"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')";  
    return jdbcTemplate.update(query);  
}  
public int updateEmployee(Employee e){  
    String query="update employee set   
    name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";  
    return jdbcTemplate.update(query);  
}  
public int deleteEmployee(Employee e){  
    String query="delete from employee where id='"+e.getId()+"' ";  
    return jdbcTemplate.update(query);  
}  

}
```

* applicationContext.xml

```markup
<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  

<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />  
<property name="username" value="system" />  
<property name="password" value="oracle" />  
</bean>  

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
<property name="dataSource" ref="ds"></property>  
</bean>  

<bean id="edao" class="com.javatpoint.EmployeeDao">  
<property name="jdbcTemplate" ref="jdbcTemplate"></property>  
</bean>  

</beans>
```

* Test.java

```java
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
public class Test {  

public static void main(String[] args) {  
    ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");  

    EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");  
    int status=dao.saveEmployee(new Employee(102,"Amit",35000));  
    System.out.println(status);  

    /*int status=dao.updateEmployee(new Employee(102,"Sonoo",15000)); 
    System.out.println(status); 
    */  

    /*Employee e=new Employee(); 
    e.setId(102); 
    int status=dao.deleteEmployee(e); 
    System.out.println(status);*/  

}  

}
```

#### Another(Not written by Gentleman.Hu)

* Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发
* 步骤：
* 导入jar包
* 创建JdbcTemplate对象。依赖于数据源DataSource
  * JdbcTemplate template = new JdbcTemplate(ds);
* 调用JdbcTemplate的方法来完成CRUD的操作
  * update():执行DML语句。增、删、改语句
  * queryForMap():查询结果将结果集封装为map集合，将列名作为key，将值作为value 将这条记录封装为一个map集合
    * 注意：这个方法查询的结果集长度只能是1
  * queryForList():查询结果将结果集封装为list集合
    * 注意：将每一条记录封装为一个Map集合，再将Map集合装载到List集合中
  * query():查询结果，将结果封装为JavaBean对象
    * query的参数：RowMapper
      * 一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
      * new BeanPropertyRowMapper<类型>(类型.class)
  * queryForObject：查询结果，将结果封装为对象
    * 一般用于聚合函数的查询
* 练习：
  * 需求： 1. 修改1号数据的 salary 为 10000 2. 添加一条记录 3. 删除刚才添加的记录 4. 查询id为1的记录，将其封装为Map集合 5. 查询所有记录，将其封装为List 6. 查询所有记录，将其封装为Emp对象的List集合 7. 查询总记录数
  * 代码：

    \`\`\`java import cn.itcast.domain.Emp; import cn.itcast.utils.JDBCUtils; import org.junit.Test; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper;

import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map;

public class JdbcTemplateDemo2 {

```
//Junit单元测试，可以让方法独立执行
```

​\
//1. 获取JDBCTemplate对象 private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); /\*\*

*

```
1.  修改1号数据的 salary 为 10000
```

```
    \*/

    @Test

    public void test1(){

//2. 定义sql String sql = "update emp set salary = 10000 where id = 1001"; //3. 执行sql int count = template.update(sql); System.out.println(count); }

/\*\*
```

\*

```
1.  添加一条记录

    \*/

    @Test

    public void test2(){

    String sql = "insert into emp(id,ename,dept\_id) values(?,?,?)";

    int count = template.update(sql, 1015, "郭靖", 10);

    System.out.println(count);

}

/\*\*
```

* 3.删除刚才添加的记录 \*/ @Test public void test3(){ String sql = "delete from emp where id = ?"; int count = template.update(sql, 1015); System.out.println(count); }

  /\*\*
* 4.查询id为1001的记录，将其封装为Map集合
* 注意：这个方法查询的结果集长度只能是1 */ @Test public void test4(){ String sql = "select* from emp where id = ? or id = ?"; Map map = template.queryForMap(sql, 1001,1002); System.out.println(map); //{id=1001, ename=孙悟空, job\_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept\_id=20}

  }

  /\*\*
*

```
1.  查询所有记录，将其封装为List
```

```
    \*/

    @Test

    public void test5(){

    String sql = "select \* from emp";

    List> list = template.queryForList(sql);

for (Map stringObjectMap : list) { System.out.println(stringObjectMap); } }

/\*\*
```

\*

````
1.  查询所有记录，将其封装为Emp对象的List集合

    \*/

@Test public void test6(){ String sql = "select \* from emp"; List list = template.query(sql, new RowMapper() {

```
@Override
public Emp mapRow(ResultSet rs, int i) throws SQLException {
    Emp emp = new Emp();
    int id = rs.getInt("id");
    String ename = rs.getString("ename");
    int job_id = rs.getInt("job_id");
    int mgr = rs.getInt("mgr");
    Date joindate = rs.getDate("joindate");
    double salary = rs.getDouble("salary");
    double bonus = rs.getDouble("bonus");
    int dept_id = rs.getInt("dept_id");

    emp.setId(id);
    emp.setEname(ename);
    emp.setJob_id(job_id);
    emp.setMgr(mgr);
    emp.setJoindate(joindate);
    emp.setSalary(salary);
    emp.setBonus(bonus);
    emp.setDept_id(dept_id);

    return emp;
}
```

});
````

​\
for (Emp emp : list) { System.out.println(emp); } }

```
/**
  * 6. 查询所有记录，将其封装为Emp对象的List集合
  */

@Test
public void test6_2(){
    String sql = "select * from emp";
    List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
    for (Emp emp : list) {
        System.out.println(emp);
    }
}

/**
  * 7. 查询总记录数
  */

@Test
public void test7(){
    String sql = "select count(id) from emp";
    Long total = template.queryForObject(sql, Long.class);
    System.out.println(total);
}
```

} \`\`\`


# Rxjava基础

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-10-07 12:47:15
   Modified by: Gentleman.Hu
   Modified time: 2020-10-07 14:03:01
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: 一些RxJava的基础
```

## RxJava概览

> \[官方文档]\(<http://reactivex.io/documentation/observable.html>') [QuickStart](https://www.tutorialspoint.com/rxjava/rxjava_quick_guide.htm) [ObserverDesign](https://www.vogella.com/tutorials/DesignPatternObserver/article.html#:~:text=The%20observer%20pattern%20defines%20a,are%20called%20observers%20or%20listeners.)

RxJava是专门为Java编写的一个拓展.它就是用Java实现了[`ReactiveX`](/java-ways/101/basis/java/frameworks/rxjava-ji-chu#reactive)项目. 特点(characteristics)

* 应用观察者模式(Observer Pattern)
* 数据/事件序列
* 可用运算符以声明方式组合序列
* 内置针对线程,同步,线程安全,并发等的数据结构

ReactiveX - ReactiveX - ReactiveX is a project which aims to provide reactive programming concept to various programming languages. Reactive Programming refers to the scenario where program reacts as and when data appears. It is a event based programming concept and events can propagate to registers observers. - As per the Reactive, they have combined the best of Observer pattern, Iterator pattern and functional pattern. - The Observer pattern done right. ReactiveX is a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming. - Functional Programming Functional programming revolves around building the software using pure functions. A pure function do not depends upon previous state and always returns the same result for the same parameters passed. Pure functions helps avoiding problems associated with shared objects, mutable data and side effects often prevalent in multi-threading environments. - Reactive Programming Reactive programming refers to event driven programming where data streams comes in asynchronous fashion and get processed when they are arrived. - Functional Reactive Programming RxJava implements both the concepts together, where data of streams changes over time and consumer function reacts accordingly. - The Reactive Manifesto - Reactive Manifesto is an on-line document stating the high standard of application software systems. As per the manifesto, following are the key attributes of a reactive software − - Responsive − Should always respond in a timely fashion. - Message Driven − Should use asynchronous message-passing between components so that they maintain loose coupling. - Elastic − Should stay responsive even under high load. - Resilient − Should stay responsive even if any component(s) fail. - Key components of RxJava RxJava have two key components: Observables and Observer. - Observable − It represents an object similar to Stream which can emit zero or more data, can send error message, whose speed can be controlled while emitting a set of data, can send finite as well as infinite data. - Observer − It subscribes to Observable's data of sequence and reacts per item of the observables. Observers are notified whenever Observable emits a data. An Observer handles data one by one. An observer is never notified if items are not present or a callback is not returned for a previous item.

## HelloWorld

```java
import io.reactivex.Flowable;
public class HelloWorld{
    public static void main(String[] args) {
        Flowbale.just("Hello World")
            .subscribe(System.out::println);
 }
}
```

## RxJava的观察者模式原理

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201007133613.gif)

### 基本组件

#### Observables

* Observable提供数据给Observer(Subscriber)监听
* Observable可以有任意多个子项目
* Observable也可以只给信号而不提供任何项目
* Observable可以成功终止
* Observable或许永远不会终止,比如按钮可以一直点击.
* Observable会抛出异常

#### Subscriber

* Observable可以有任意多个Observer(Subscriber)
* 当Observable发出项目,每个Subscriber的`onNext()`方法都会触发(invoked).
* 当Observable发出的项目完成时,每个Subscriber的`onComplete`方法都会触发.
* 如果Observable错误(error),每个Subscriber的`onError()`方法都会触发.

### 组件创建

* 下边是创建Observables的基本类
  * `Flowable` − 0..N flows, Emits 0 or n items. Supports Reactive-Streams and back-pressure.
  * `Observable` − 0..N flows ,but no back-pressure.
  * `Single` − 1 item or error. Can be treated as a reactive version of method call.
  * `Completable` − No item emitted. Used as a signal for completion or error. Can be treated as a reactive version of Runnable.
  * `MayBe` − Either No item or 1 item emitted. Can be treated as a reactive version of Optional.
* 下边是一些从方法创建Observables对象的方便方法
  * `just(T item)` − Returns an Observable that signals the given (constant reference) item and then completes.
  * `fromIterable(Iterable source)` − Converts an Iterable sequence into an ObservableSource that emits the items in the sequence.
  * `fromArray(T... items)` − Converts an Array into an ObservableSource that emits the items in the Array.
  * `fromCallable(Callable supplier)` − Returns an Observable that, when an observer subscribes to it, invokes a function you specify and then emits the value returned from that function.
  * `fromFuture(Future future)` − Converts a Future into an ObservableSource.
  * `interval(long initialDelay, long period, TimeUnit unit)` − Returns an Observable that emits a 0L after the initialDelay and ever increasing numbers after each period of time thereafter.

break on 2020-10-07 14:02:56

continue

> [Single Observable](https://www.tutorialspoint.com/rxjava/rxjava_quick_guide.htm)


# Spring框架基础

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-10-03 21:25:02
   Modified by: Gentleman.Hu
   Modified time: 2020-10-07 16:39:55
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description:
```

## Spring框架基础

### AOP 概念

* Target
* Proxy
* JoinPoint
* PointCut
* Advice
* Aspect
* Weaving

### XML配置AOP

写法

> `execution([修饰符] 返回值类型 包名.类名.方法名 (参数))`

* 修饰符可以省略
* 返回类型,包名,类名,方法名可以用`*`代替任意
* 包名和类名之间有一个点`.`代表当前包的类,两个点`..`代表当前包及其子包下的类.
* 参数列表可以使用两个点`..`表示任意个数,任意类型的参数列表

```java
execution(public void god.hu.aop.target.method())
execution(void god.hu.aop.target.*(..))
execution(* god.hu.aop.*.*(..))
execution(* god.hu.aop..*.*(..))
execution(* *..*.*(..))
```

使用xml和注解都可配置

注解开发aop步骤

1. 使用`@aspect`表明注解类
2. 使用`@before ,@after,etc`等通知注解标注通知方法
3. 在配置文件中配置aop自动代理
4. 注解表

| 名称   | 表达                | 含义          |
| ---- | ----------------- | ----------- |
| 前置   | `@Before`         | 切入点之前执行     |
| 后置   | `@AfterReturning` | 切入点之后执行     |
| 环绕   | `@Around`         | 之前和之后都执行    |
| 异常抛出 | `@AfterThrowing`  | 在抛出异常后执行    |
| 最终通知 | `@After`          | 都会执行，无论是否异常 |

break on 2020-10-07 16:39:27

continue at [OwnJavaWay](https://github.com/GentlemanHu/Java-Way/issues/15)


# Sugar\&skill


# Tool


# Docker


# Docker basis

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-11-01 10:47:02
   Modified by: Gentleman.Hu
   Modified time: 2020-11-02 11:23:19
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: Docker new one
```

## Docker

### Installation

> [get-started](https://www.docker.com/get-started)

对应系统下载.

安装好,在托盘图标可以看到状态,启动成功

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201101171631.gif)

* 查看版本

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201101171751.png)

### Images,Containers,and Ports

> docker image COMMAND

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201101172030.png)

* show containers

> docker image ps

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201101172213.png)

* 基本命令平时就查看,其他build等简单使用

> docker container COMMAND

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201101172426.png)

* show containers

> docker container ls \[-a] 显示全部(包含未运行的)

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201101172710.png)

> > image就是镜像,静态的,通过image可以生成container
>
> docker pull COMMAND

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201101173513.png)

拉取image

> docker run COMMAND

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201101175006.png)

> docker run --name name -d imagename

通过image创建container并运行 -d,dettach

* 开放端口

> docker run -p outer:inner imagename

outer: 外部端口 inner: 内部端口

比如 8080:80 ,外部宿主计算机端口映射到docker内部80端口

* 开放多个端口

-p 8080:80 -p 2222:222 -p etc...

* 删除container

> docker rm -f containername

* 删除image

> docker rmi imagename

### Volumes - Host adn Container

* share file from host

> docker run --name name -v /some/folder:/usr/local/nginx/html:ro -p 8080:80 nginx:latest

* going inside container

> docker exec -it containername bash(/bin/sh)

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201101184623.png)

### Building Images

* Dockerfile

```
FROM ubuntu:18.04
COPY . /app
RUN make /app
CMD python /app/app.py
```

> [Reference](https://docs.docker.com/engine/reference/builder/)

* docker build

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201102111111.png)

* docker push&#x20;

推送到duckerhub或者其他docker仓库

* .dockerignore

> [Reference](https://docs.docker.com/engine/reference/builder/#dockerignore-file)

```
# comment
*/temp*
*/*/temp*
temp?
```

| Rule        | Behavior                                                                                                                                                                                                      |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `# comment` | Ignored.                                                                                                                                                                                                      |
| `*/temp*`   | Exclude files and directories whose names start with `temp` in any immediate subdirectory of the root. For example, the plain file `/somedir/temporary.txt` is excluded, as is the directory `/somedir/temp`. |
| `*/*/temp*` | Exclude files and directories starting with `temp` from any subdirectory that is two levels below the root. For example, `/somedir/subdir/temporary.txt` is excluded.                                         |
| `temp?`     | Exclude files and directories in the root directory whose names are a one-character extension of `temp`. For example, `/tempa` and `/tempb` are excluded.                                                     |

此文件忽略通过规则定义的文件 然而,往往忽略的,需要在`dockerfile`中重新`RUN`来在部署时候生成`module`等

* Alpine

很精简的,体积很小.适合集成docker中

> [official](https://alpinelinux.org/) [docker\_alpine](https://hub.docker.com/_/alpine)

```
FROM alpine:3.7
RUN apk add --no-cache mysql-client
ENTRYPOINT ["mysql"]
```

一个使用例子 36.8MB

### Resources

* <https://hub.docker.com/_/alpine>
* [dockerignore](https://stackoverflow.com/a/25748464)


# Kubernetes play

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-11-02 10:22:59
   Modified by: Gentleman.Hu
   Modified time: 2020-11-02 11:23:45
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: kubernetes play
```

## Kubernetes aka k8s

> [play\_ground](https://www.katacoda.com/courses/kubernetes/playground)


# Git


# Git basic

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-09-19 20:20:08
   Modified by: Gentleman.Hu
   Modified time: 2020-09-25 19:15:41
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description:
```

## Git some notes

### 1. git存储方式

* 按照元数据内部存储类似k/v存储

  ```
  git hash-object -w "filename" #查看hash
  ```

  ![image-20200720190551457](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/image-20200720190551457.png)
* 基本使用

  ```
  git add -A ;#添加所有
  git commit -am "meg";#提交到本地仓库
  git rm --cached target -r(recursion);#删除暂存区的文件（add后的文件）
  git push;#提交到远程仓库
  git branch -d {dev};#删除分支
  git checkoout <branch name>;#切换分支
  git merge <merge target>;#合并分支。若有冲突，则需要手动修改再commit 
  git log ;
  ```

  ![image-20200720193811323](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/image-20200720193811323.png)
* 几种创建分支
  * 基于当前分支新建分支

    > git branch&#x20;
  * 基于提交新建分支

    > git branch &#x20;
  * 基于tag新建分支

    > git branch &#x20;
  * 其他待实际操作发现

## 一些问题

* `git commit -a`和`git add .`区别
  * `git commit -a` means almost\[\*] the same thing as `git add -u && git commit`.
  * It's not the same as `git add .` as this would add untracked files that aren't being ignored, `git add -u` only stages changes (including deletions) to already tracked files.
  * \[*] There's a subtle difference if you're not at the root directory of your repository. `git add -u` stages updates to files in the current directory and below, it's equivalent to `git add -u .` whereas `git commit -a` stages and commits changes to* all\* tracked files.

    > source:[区别](https://stackoverflow.com/questions/3541647/git-add-vs-git-commit-a)
* `git add -A` and `git add .` and `git add -u` 区别
  * **According to git version 1.x**

    “**git add -A**” is equivalent to “**git add .**” and “**git add -u**“

    * **git add -A** stages All

    * **git add .** stages new and modified, without deleted

    * **git add -u** stages modified and deleted, without new

      The important point about **git add .** is that it looks at the working tree and adds all those paths to the staged changes if they are either changed or are new and not ignored, it does not stage any ‘rm’ actions.

      **git add -u** looks at all the already tracked files and stages the changes to those files if they are different or if they have been removed. It does not add any new files, it only stages changes to already tracked files.

      **git add -A** is a handy shortcut for doing both.

    * **git add -A is equivalent to git add –all**

    * **git add -u is equivalent to git add –update**

    * **According to git version 2.x**

      * **git add -A** stages All
      * **git add .** stages All in same path
      * **git add -u** stages modified and deleted, without new

      There is no more difference in **2.0**. **git add .** equals to **git add -A** for the same path, the only difference is if there are new files in other paths of the tree.

      With **Git 2.0**, **git add -A** is **default**: **git add .** equals **git add -A .**

    > Source:\[differences]\([https://www.dineshonjava.com/difference-between-git-add-a-and-git-add-dot-and-git-u/#:\~:text=git%20add%20%2Du%20looks%20at,handy%20shortcut%20for%20doing%20both.](https://www.dineshonjava.com/difference-between-git-add-a-and-git-add-dot-and-git-u/#:~:text=git%20add%20-u%20looks%20at,handy%20shortcut%20for%20doing%20both.))
    >
    > [`git add .`and `git add -u`](https://stackoverflow.com/a/2190440)
* git 如何处理Symlink file，如何处理链接的文件？

  * 只是记录追踪了合格链接文件，并未追踪这个链接引用的文件

    So, that's what Git does to a symbolic link: when you git checkout the symbolic link, you either get a text file with a reference to a full filesystem path, or a symlink, depending on configuration. **The data referenced by the symlink is not stored in the repository.**

  > [how works](https://stackoverflow.com/a/46510347)

  * 建议写成相对路径添加e.g.`ln -s ../xxx.md xxx.md`

    ```bash
    # Not good for Git repositories
    ln -s /Users/gio/repo/foo.md ./bar/foo.md

    # Good for Git repositories
    cd ./bar && ln -s ../foo.md foo.md
    ```

    The reason for this is that given that a symlink contains the path to the referenced file, if the path is relative to a specific machine the link won't work on others. If it's relative to the repository itself on the other hand, the OS will always be able to find the source.

    > [Source](https://www.mokacoding.com/blog/symliks-in-git/)

:Way to my success!


# Vim


# Vim advance

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-11-06 16:17:19
   Modified by: Gentleman.Hu
   Modified time: 2020-11-06 20:58:43
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: 一些vim进阶用法
```

## 基础

| 符号 | 对应单词                | 含义                                |
| -- | ------------------- | --------------------------------- |
| y  | yank                | 拷贝, 大写yank到行尾                     |
| t  | till                | 直到                                |
| c  | change              | 改                                 |
| g  | not sure(namespace) | "go"                              |
| a  | append              | 小写后插,大写前插                         |
| o  | not sure            | 小写下行插,大写上行插                       |
| d  | delete              | 小写跟数字,删除指定数量,大写从cursor删到行尾        |
| \~ | 改变大小写               | 改变大小写                             |
| p  | put                 | 寄存器存的内容放在cursor后,大写放之前.前边跟数字,放置n遍 |
| e  | end                 | 末尾                                |
| $  | end                 | 末尾                                |
| 0  | start               | 首                                 |
| %  | not sure            | 匹配到对应括号                           |
| z  | not sure            | z. cursor居中屏幕;zt,top;zb,bottom    |
| \* | mark/star           | 快速标记                              |

* 上表并不完整, 列举仅仅常用

## 用例实践

* 多行添加注释

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201106165738.gif)

* gt+"字符",删除直到某个"字符"

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201106170133.gif)

* 其他慢慢探索

## Macro用例实践

> 在spacevim中录制macro

| Key                | Mode   | Action                           |
| ------------------ | ------ | -------------------------------- |
| `<leader>` + `qr`  | Normal | Same as native `q`               |
| `<leader>` + `qr/` | Normal | Same as native `q/`, open cmdwin |
| `<leader>` + `qr?` | Normal | Same as native `q?`, open cmdwin |
| `<leader>` + `qr:` | Normal | Same as native `q:`, open cmdwin |

> 普通vim直接`q`即可进入录制,spacevim改变了映射,`qr`刻可进入录制

* 简单加引号

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201106171938.gif)

* 其他用例可参照资源, 各种玩法, 等待探索

## Resources

* [油管\_大神](https://www.youtube.com/watch?v=IiwGbcd8S7I)
* [vim\_micros](https://spin.atomicobject.com/2014/11/23/record-vim-macros/)
* [stack\_exchange\_what\_is\_meaning\_of\_blabla\_invim](https://vi.stackexchange.com/a/18745)
* [vim\_CheatSheet](https://www.fprintf.net/vimCheatSheet.html)
* [dot\_command\_in\_vim](https://stackoverflow.com/a/7325105)


# Cs


# Imp


# Lru

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-10-19 17:35:22
   Modified by: Gentleman.Hu
   Modified time: 2020-10-20 15:01:46
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: LRU算法实现
```

## LRU 算法实现

Least Recently Used

> [source\_from\_csdn](https://blog.csdn.net/elricboa/article/details/78847305)

设计原则:如果一个`数据`在对近一段时间`没有被访问到`,那么在将来他被访问的可能性也很小.就是说,当限定的空间已存满数据时,应当把`最久没有被访问到`的`数据`淘汰.

* 实现方法 1. 用一个数组存储数据,给每个数据项标记一个访问时间戳,每次插入新数据项的时候,先把数组中存在的数据项的时间戳自增,并将新数据项的时间戳置为0并插入到数组中.每次访问数组中的数据项的时候,将被访问的数据项的时间戳置为0.当数据空间已满时,将时间戳最大的数据项淘汰. 2. 利用一个链表实现,每次新插入数据的时候将新数据插到链表的头部;每次缓存命中(数据被访问),则将数据移到链表头部;那么当链表满的时候,就将表尾部的数据丢弃. 3. 利用链表和hashmap.当需要插入新得数据项的时候,如果新数据项在链表中存在(命中),则把该节点移动到链表头部,如果不存在,则新建节点,放在链表头部,若缓存满了,则把链表最后一个节点删除即可.在访问数据的时候,如果数据项在链表中存在,则把该节点移动到链表头部,否则返回-1.这样链表尾部节点就是最近最久未访问数据项.
* 评价 1. 需要不停维护数据项访问时间戳,insert,delete和访问数据时间复杂度都是O(n). 2. 链表在定位数据时候时间复杂度为O(n).

实际多采用第三种实现

* LRU算法对比

| 对比点 | 对比                       |
| --- | ------------------------ |
| 命中率 | LRU-2 > MQ(2) > 2Q > LRU |
| 复杂度 | LRU-2 > MQ(2) > 2Q > LRU |
| 代价  | LRU-2 > MQ(2) > 2Q > LRU |

### 具体实现

1. LinkedHashMap实现

```java
public class LRU<K,V>{
  private static final float hashLoadFactory = 0.75f;
  private LinkedHashMap<K,V> map;
  private int cacheSize;

  public LRU(int cacheSize){
    this.cacheSize = cacheSize;
    // Math.ceil(double x) - 返回参数值的
    int capacity = (int)Math.ceil(cacheSize/hashLoadFactory)+1;
    map = new LinkedHashMap<K,V>(capacity,hashLoadFactory,true){
      private static final long serialVersionUID = 1L;

      @Override
      protected boolean removeEldestEntry(Map.Entry eldest){
        return size()>LRU.this.cacheSize;
      }
    };
  }

  public synchronized V get(K key){
    return map.get(key);
  }

  public synchronized void put(K key,V value){
    map.put(key,value);
  }

  public synchronized void clear(){
    map.clear();
  }
}
```

## References

* Math.ceil()和Math.floor()和Math.round()区别

这三个方法分别遵循下列舍入规则：

* Math.ceil()执行向上舍入，即它总是将数值向上舍入为最接近的整数；
* Math.floor()执行向下舍入，即它总是将数值向下舍入为最接近的整数；
* Math.round()执行标准舍入，即它总是将数值四舍五入为最接近的整数(这也是我们在数学课上学到的舍入规则)。


# Index

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-10-19 17:34:47
   Modified by: Gentleman.Hu
   Modified time: 2020-10-20 15:21:21
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: 此目录包含一些常用算法和数据结构实现
```

## Index

### 操作系统

> [几种调度算法](https://blog.csdn.net/zh13487/article/details/83928284) [几种页面置换算法](https://www.cnblogs.com/fkissx/p/4712959.html)

* 页面置换算法
  * FCFS
  * SJF
  * HRRF
  * RR
  * SRTF
  * MFQ
  * ...
* 进程调度算法
  * OPT
  * FIFO
  * LRU
  * CLOCK
  * ...

## 数据结构

> [cnblogs](https://www.cnblogs.com/skywang12345/p/3624343.html) [csdn](https://blog.csdn.net/weixin_44181671/article/details/108589880)

* 树
  * 二叉树
  * 满二叉树
  * 完全二叉树
  * 顺序二叉树
  * 赫夫曼树
  * 二叉查找树/二叉排序树/二叉搜索树
  * 平衡二叉树(AVL)
    * 红黑树
  * 多路查找树
    * B树
    * B+树


# Snippets


# Jpa和spring系列注解表

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-10-20 15:41:01
   Modified by: Gentleman.Hu
   Modified time: 2020-10-20 16:13:14
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: Spring系列注解表
```

## JPA注解cheat sheet

> [all\_jpa\_annotation\_list](https://dzone.com/articles/all-jpa-annotations-mapping-annotations) [>pdf<\_minibook\_for\_JPA](http://enos.itcollege.ee/~jpoial/java/naited/JPA_Mini_Book.pdf) [cheat\_sheet\_of\_jpa](https://hajba.hu/2014/11/25/java-persistence-api-annotation-cheat-sheet/)

| JPA Annotations                  |
| -------------------------------- |
|                                  |
| 1. @Access                       |
|                                  |
| 2. @AssociationOverride          |
|                                  |
| 3. @AssociationOverrides         |
|                                  |
| 4. @AttributeOverride            |
|                                  |
| 5. @AttributeOverrides           |
|                                  |
| 6. @Basic                        |
|                                  |
| 7. @Cacheable                    |
|                                  |
| 8. @CollectionTable              |
|                                  |
| 9. @Column                       |
|                                  |
| 10. @ColumnResult                |
|                                  |
| 11. @ConstructorResult           |
|                                  |
| 12. @Convert                     |
|                                  |
| 13. @Converter                   |
|                                  |
| 14. @Converts                    |
|                                  |
| 15. @DiscriminatorColumn         |
|                                  |
| 16. @DiscriminatorValue          |
|                                  |
| 17. @ElementCollection           |
|                                  |
| 18. @Embeddable                  |
|                                  |
| 19. @Embedded                    |
|                                  |
| 20. @EmbeddedId                  |
|                                  |
| 21. @Entity                      |
|                                  |
| 22. @EntityListeners             |
|                                  |
| 23. @EntityResult                |
|                                  |
| 24. @Enumerated                  |
|                                  |
| 25. @ExcludeDefaultListeners     |
|                                  |
| 26. @ExcludeSuperclassListeners  |
|                                  |
| 27. @FieldResult                 |
|                                  |
| 28. @ForeignKey                  |
|                                  |
| 29. @GeneratedValue              |
|                                  |
| 30. @Id                          |
|                                  |
| 31. @IdClass                     |
|                                  |
| 32. @Index                       |
|                                  |
| 33. @Inheritance                 |
|                                  |
| 34. @JoinColumn                  |
|                                  |
| 35. @JoinColumns                 |
|                                  |
| 36. @JoinTable                   |
|                                  |
| 37. @Lob                         |
|                                  |
| 38. @ManyToMany                  |
|                                  |
| 39. @ManyToOne                   |
|                                  |
| 40. @MapKey                      |
|                                  |
| 41. @MapKeyClass                 |
|                                  |
| 42. @MapKeyColumn                |
|                                  |
| 43. @MapKeyEnumerated            |
|                                  |
| 44. @MapKeyJoinColumn            |
|                                  |
| 45. @MapKeyJoinColumns           |
|                                  |
| 46. @MapKeyTemporal              |
|                                  |
| 47. @MappedSuperclass            |
|                                  |
| 48. @MapsId                      |
|                                  |
| 49. @NamedAttributeNode          |
|                                  |
| 50. @NamedEntityGraph            |
|                                  |
| 51. @NamedEntityGraphs           |
|                                  |
| 52. @NamedNativeQueries          |
|                                  |
| 53. @NamedNativeQuery            |
|                                  |
| 54. @NamedQueries                |
|                                  |
| 55. @NamedQuery                  |
|                                  |
| 56. @NamedStoredProcedureQueries |
|                                  |
| 57. @NamedStoredProcedureQuery   |
|                                  |
| 58. @NamedSubgraph               |
|                                  |
| 59. @OneToMany                   |
|                                  |
| 60. @OneToOne                    |
|                                  |
| 61. @OrderBy                     |
|                                  |
| 62. @OrderColumn                 |
|                                  |
| 63. @PersistenceContext          |
|                                  |
| 64. @PersistenceContexts         |
|                                  |
| 65. @PersistenceProperty         |
|                                  |
| 66. @PersistenceUnit             |
|                                  |
| 67. @PersistenceUnits            |
|                                  |
| 68. @PostLoad                    |
|                                  |
| 69. @PostPersist                 |
|                                  |
| 70. @PostRemove                  |
|                                  |
| 71. @PostUpdate                  |
|                                  |
| 72. @PrePersist                  |
|                                  |
| 73. @PreRemove                   |
|                                  |
| 74. @PreUpdate                   |
|                                  |
| 75. @PrimaryKeyJoinColumn        |
|                                  |
| 76. @PrimaryKeyJoinColumns       |
|                                  |
| 77. @QueryHint                   |
|                                  |
| 78. @SecondaryTable              |
|                                  |
| 79. @SecondaryTables             |
|                                  |
| 80. @SequenceGenerator           |
|                                  |
| 81. @SqlResultSetMapping         |
|                                  |
| 82. @SqlResultSetMappings        |
|                                  |
| 83. @StoredProcedureParameter    |
|                                  |
| 84. @Table                       |
|                                  |
| 85. @TableGenerator              |
|                                  |
| 86. @Temporal                    |
|                                  |
| 87. @Transient                   |
|                                  |
| 88. @UniqueConstraint            |
|                                  |
| 89. @Version                     |

## Spring系列注解对照表

> [Spring CheatSheet](https://github.com/We2one/Notes/tree/07fadddfb519e81cee2c6d83e75feadfb89aa509/java-ways/snippets/adevguide.com/all-spring-annotations-cheat-sheet/README.md) [Annotation\_CheatSheet](https://github.com/We2one/Notes/tree/07fadddfb519e81cee2c6d83e75feadfb89aa509/java-ways/snippets/jrebel.com/blog/spring-annotations-cheat-sheet/README.md) [Gist\_CheatSheet\_With\_Color](https://www.javagists.com/spring-boot-cheatsheet)

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/spring_annotation_cheat_sheet.png)


# Java与oracle数据库各种操作

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-09-25 10:42:34
   Modified by: Gentleman.Hu
   Modified time: 2020-09-25 19:14:58
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description:
```

## Java与Oracle数据库各种操作

### 链接数据库

```java
//step1 load the driver class  
Class.forName("oracle.jdbc.driver.OracleDriver");  

//step2 create  the connection object  
Connection con=DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  

//step3 create the statement object  
Statement stmt=con.createStatement();  

//step4 execute query  
ResultSet rs=stmt.executeQuery("select * from emp");  
while(rs.next())  
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  

//step5 close the connection object  
con.close();
```

1. 加载drive类
2. 建立连接
3. 通过Connection创建Statement对象
4. 建立ResultSet对象以接受Statement执行的query结果
5. 关闭连接

## 相关链接

* [Java Database Connectivity](https://www.javatpoint.com/example-to-connect-to-the-oracle-database)
* [Official Guide](https://docs.oracle.com/cd/E11882_01/appdev.112/e12137/getconn.htm#TDPJD127)


# Maven初始化template

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-09-25 10:38:02
   Modified by: Gentleman.Hu
   Modified time: 2020-09-25 19:15:04
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description:
```

## Maven初始化配置pom文件

```markup
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>god.hu</groupId>
    <artifactId>OwnFilms</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>15</maven.compiler.source>
        <maven.compiler.target>15</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.12.7</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
                <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
                <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
                <plugin>
                    <artifactId>maven-site-plugin</artifactId>
                    <version>3.7.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-project-info-reports-plugin</artifactId>
                    <version>3.0.0</version>
                </plugin>
                <plugin>
                    <!-- Build an executable JAR -->
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.1.0</version>
                    <configuration>
                        <archive>
                            <manifest>
                                <addClasspath>true</addClasspath>
                                <classpathPrefix>lib/</classpathPrefix>
                                <mainClass>god.hu.Main</mainClass>
                            </manifest>
                        </archive>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>
```

## 相关链接

* [One template from gist](https://gist.github.com/sparsick/aec73d514b1ef248d92d)
* [Official site guide](https://maven.apache.org/guides/introduction/introduction-to-the-pom.html)


# Nginx配置

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-11-09 22:53:52
   Modified by: Gentleman.Hu
   Modified time: 2020-11-09 23:27:06
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: 一些nginx配置
```

## Index of 目录

* nginx 开启对某目录的index

```
location /somedirectory/ {
    autoindex on;
    autoindex_exact_size off;
    autoindex_format html;
    autoindex_localtime on;
}
```

## 反代不显示图片等信息

```
location /
{
    proxy_pass http://127.0.0.1:8083;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header REMOTE-HOST $remote_addr;

    add_header X-Cache $upstream_cache_status;

    #Set Nginx Cache

        add_header Cache-Control no-cache;
    expires 12h;
}
location ~ .*.(js|css|png|img|gif|jpg)$ {
proxy_pass http://127.0.0.1:8083;
}
```

### Apache 的多目录分流代理

```
<VirtualHost *:80>
    ServerAdmin webmasterexample.com
    DocumentRoot "/www/wwwroot/tt.521521.ml/blackhole/blackhole/"
    ServerName SSL.tt.521521.ml
    ServerAlias tt.521521.ml 
    #errorDocument 404 /404.html
    ErrorLog "/www/wwwlogs/tt.521521.ml-error_log"
    CustomLog "/www/wwwlogs/tt.521521.ml-access_log" combined
    #引用重定向规则，注释后配置的重定向代理将无效
    IncludeOptional /www/server/panel/vhost/apache/redirect/tt.521521.ml/*.conf
    #HTTP_TO_HTTPS_START
    <IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteCond %{SERVER_PORT} !^443$
        RewriteRule (.*) https://%{SERVER_NAME}$1 [L,R=301]
    </IfModule>
    #HTTP_TO_HTTPS_END
    #SSL
    SSLEngine On
    SSLCertificateFile /www/server/panel/vhost/cert/tt.521521.ml/fullchain.pem
    SSLCertificateKeyFile /www/server/panel/vhost/cert/tt.521521.ml/privkey.pem
    SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
    SSLProtocol All -SSLv2 -SSLv3 -TLSv1
    SSLHonorCipherOrder On

    #PHP
    <FilesMatch \.php$>
            SetHandler "proxy:unix:/tmp/php-cgi-72.sock|fcgi://localhost"
    </FilesMatch>

    #Proxypass /ray http://127.0.0.1:51816
    #ProxyPassReverse /ray http://127.0.0.1:51816

     <Location "/feel">
    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule    /(.*)  ws://localhost:51816/feel [P,L]
    RewriteCond %{HTTP:Upgrade} !=websocket [NC]
    RewriteRule   /(.*)   http://localhost:51816/feel [P,L]
    Proxypass  http://127.0.0.1:51816/feel
    ProxyPassReverse  http://127.0.0.1:51816/feel

  </Location>
    #DENY FILES
     <Files ~ (\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)$>
       Order allow,deny
       Deny from all
    </Files>

    #PATH
    <Directory "/www/wwwroot/tt.521521.ml/">
        SetOutputFilter DEFLATE
        Options FollowSymLinks
        AllowOverride All
        Require all granted
        DirectoryIndex index.php index.html index.htm default.php default.html default.htm
    </Directory>
</VirtualHost>
<VirtualHost *:443>
    ServerAdmin webmasterexample.com
    DocumentRoot "/www/wwwroot/tt.521521.ml/blackhole/blackhole/"
    ServerName SSL.tt.521521.ml
    ServerAlias tt.521521.ml 
    #errorDocument 404 /404.html
    ErrorLog "/www/wwwlogs/tt.521521.ml-error_log"
    CustomLog "/www/wwwlogs/tt.521521.ml-access_log" combined
    #引用重定向规则，注释后配置的重定向代理将无效
    IncludeOptional /www/server/panel/vhost/apache/redirect/tt.521521.ml/*.conf
    #HTTP_TO_HTTPS_START
    <IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteCond %{SERVER_PORT} !^443$
        RewriteRule (.*) https://%{SERVER_NAME}$1 [L,R=301]
    </IfModule>
    #HTTP_TO_HTTPS_END
    #SSL
    SSLEngine On
    SSLCertificateFile /www/server/panel/vhost/cert/tt.521521.ml/fullchain.pem
    SSLCertificateKeyFile /www/server/panel/vhost/cert/tt.521521.ml/privkey.pem
    SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
    SSLProtocol All -SSLv2 -SSLv3 -TLSv1
    SSLHonorCipherOrder On

    #PHP
    <FilesMatch \.php$>
            SetHandler "proxy:unix:/tmp/php-cgi-72.sock|fcgi://localhost"
    </FilesMatch>

    #Proxypass /ray http://127.0.0.1:51816
    #ProxyPassReverse /ray http://127.0.0.1:51816

     <Location "/feel">
    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule    /(.*)  ws://localhost:51816/feel [P,L]
    RewriteCond %{HTTP:Upgrade} !=websocket [NC]
    RewriteRule   /(.*)   http://localhost:51816/feel [P,L]
    Proxypass  http://127.0.0.1:51816/feel
    ProxyPassReverse  http://127.0.0.1:51816/feel

  </Location>
    #DENY FILES
     <Files ~ (\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)$>
       Order allow,deny
       Deny from all
    </Files>

    #PATH
    <Directory "/www/wwwroot/tt.521521.ml/">
        SetOutputFilter DEFLATE
        Options FollowSymLinks
        AllowOverride All
        Require all granted
        DirectoryIndex index.php index.html index.htm default.php default.html default.htm
    </Directory>
</VirtualHost>
```


# Nginx反代后配置自动ssl续签

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-11-13 13:56:23
   Modified by: Gentleman.Hu
   Modified time: 2020-11-13 13:59:37
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description:
```

## Nginx配置反代后,如何自动续签ssl

> [引用](https://blog.csdn.net/fjh1997/article/details/105765531)

* 反代

```
  RewriteEngine On
  RewriteCond %{HTTP:Upgrade} =websocket [NC]
  RewriteRule /(.*)           ws://localhost:8080/$1 [P,L]
  RewriteCond %{HTTP:Upgrade} !=websocket [NC]
  RewriteRule /(.*)           http://localhost:8080/$1 [P,L]

  ProxyRequests off
  ProxyPass        / http://localhost:8080/ nocanon
  ProxyPassReverse / http://localhost:8080/
```

* 自动续签

```
server {
  listen  443 ssl;
  listen       [::]:443 ssl;
  ssl_certificate       /data/example.com.pem;
  ssl_certificate_key   /data/example.com.pem;
  ssl_protocols         TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers           HIGH:!aNULL:!MD5;
  server_name           example.com;
  client_max_body_size    1000m;
  location ^~ /.well-known/acme-challenge/ {
        default_type "text/plain";
        allow all;
        root /var/www/example.com/;
   }

  location / { 
        proxy_redirect off;
        proxy_pass http://xxxxxxx:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;


        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

  }
```

* 负载均衡

> <https://blog.csdn.net/specter11235/article/details/79922149?depth_1->


# 终端033颜色

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-09-25 10:33:54
   Modified by: Gentleman.Hu
   Modified time: 2020-09-25 19:14:20
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description:
```

## 终端中各种颜色,Java静态类

```java
/**
 * (     (   ((      (   (    ((     .  (   ((    ((
 * )\    )\ (\()     )\  )\  (\()     . )\  ))\  (\()
 * ((_)  ((())(_)    (_()((_)))(_)      ((_)((_))))(_)
 * \ \    / / __|    /   \ _ \ __|     / _ \| \| | __|
 * \ \/\/ /| _|     | - |   / _|     | (_) | .  | _|
 * \_/\_/ |___|    |_|_|_|_\___|     \___/|_|\_|___|
 * Author: Gentleman.Hu
 * Date: 2020/9/16 7:22 上午
 * Email: justfeelingme@gamil.com
 * Home: https://crushing.xyz
 * Description: Some colors for printing colorful text in console
 */
public class ConsoleColors {

    // Reset
    public static final String RESET = "\033[0m";  // Text Reset

    // Regular Colors
    public static final String BLACK = "\033[0;30m";   // BLACK
    public static final String RED = "\033[0;31m";     // RED
    public static final String GREEN = "\033[0;32m";   // GREEN
    public static final String YELLOW = "\033[0;33m";  // YELLOW
    public static final String BLUE = "\033[0;34m";    // BLUE
    public static final String PURPLE = "\033[0;35m";  // PURPLE
    public static final String CYAN = "\033[0;36m";    // CYAN
    public static final String WHITE = "\033[0;37m";   // WHITE

    // Bold
    public static final String BLACK_BOLD = "\033[1;30m";  // BLACK
    public static final String RED_BOLD = "\033[1;31m";    // RED
    public static final String GREEN_BOLD = "\033[1;32m";  // GREEN
    public static final String YELLOW_BOLD = "\033[1;33m"; // YELLOW
    public static final String BLUE_BOLD = "\033[1;34m";   // BLUE
    public static final String PURPLE_BOLD = "\033[1;35m"; // PURPLE
    public static final String CYAN_BOLD = "\033[1;36m";   // CYAN
    public static final String WHITE_BOLD = "\033[1;37m";  // WHITE

    // Underline
    public static final String BLACK_UNDERLINED = "\033[4;30m";  // BLACK
    public static final String RED_UNDERLINED = "\033[4;31m";    // RED
    public static final String GREEN_UNDERLINED = "\033[4;32m";  // GREEN
    public static final String YELLOW_UNDERLINED = "\033[4;33m"; // YELLOW
    public static final String BLUE_UNDERLINED = "\033[4;34m";   // BLUE
    public static final String PURPLE_UNDERLINED = "\033[4;35m"; // PURPLE
    public static final String CYAN_UNDERLINED = "\033[4;36m";   // CYAN
    public static final String WHITE_UNDERLINED = "\033[4;37m";  // WHITE

    // Background
    public static final String BLACK_BACKGROUND = "\033[40m";  // BLACK
    public static final String RED_BACKGROUND = "\033[41m";    // RED
    public static final String GREEN_BACKGROUND = "\033[42m";  // GREEN
    public static final String YELLOW_BACKGROUND = "\033[43m"; // YELLOW
    public static final String BLUE_BACKGROUND = "\033[44m";   // BLUE
    public static final String PURPLE_BACKGROUND = "\033[45m"; // PURPLE
    public static final String CYAN_BACKGROUND = "\033[46m";   // CYAN
    public static final String WHITE_BACKGROUND = "\033[47m";  // WHITE

    // High Intensity
    public static final String BLACK_BRIGHT = "\033[0;90m";  // BLACK
    public static final String RED_BRIGHT = "\033[0;91m";    // RED
    public static final String GREEN_BRIGHT = "\033[0;92m";  // GREEN
    public static final String YELLOW_BRIGHT = "\033[0;93m"; // YELLOW
    public static final String BLUE_BRIGHT = "\033[0;94m";   // BLUE
    public static final String PURPLE_BRIGHT = "\033[0;95m"; // PURPLE
    public static final String CYAN_BRIGHT = "\033[0;96m";   // CYAN
    public static final String WHITE_BRIGHT = "\033[0;97m";  // WHITE

    // Bold High Intensity
    public static final String BLACK_BOLD_BRIGHT = "\033[1;90m"; // BLACK
    public static final String RED_BOLD_BRIGHT = "\033[1;91m";   // RED
    public static final String GREEN_BOLD_BRIGHT = "\033[1;92m"; // GREEN
    public static final String YELLOW_BOLD_BRIGHT = "\033[1;93m";// YELLOW
    public static final String BLUE_BOLD_BRIGHT = "\033[1;94m";  // BLUE
    public static final String PURPLE_BOLD_BRIGHT = "\033[1;95m";// PURPLE
    public static final String CYAN_BOLD_BRIGHT = "\033[1;96m";  // CYAN
    public static final String WHITE_BOLD_BRIGHT = "\033[1;97m"; // WHITE

    // High Intensity backgrounds
    public static final String BLACK_BACKGROUND_BRIGHT = "\033[0;100m";// BLACK
    public static final String RED_BACKGROUND_BRIGHT = "\033[0;101m";// RED
    public static final String GREEN_BACKGROUND_BRIGHT = "\033[0;102m";// GREEN
    public static final String YELLOW_BACKGROUND_BRIGHT = "\033[0;103m";// YELLOW
    public static final String BLUE_BACKGROUND_BRIGHT = "\033[0;104m";// BLUE
    public static final String PURPLE_BACKGROUND_BRIGHT = "\033[0;105m"; // PURPLE
    public static final String CYAN_BACKGROUND_BRIGHT = "\033[0;106m";  // CYAN
    public static final String WHITE_BACKGROUND_BRIGHT = "\033[0;107m";   // WHITE
}
```

## 相关链接

* [Colours in Bash Prompt](https://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329)
* [Color code generator](https://xdevs.com/guide/color_serial/)
* [ANSI Escape Sequences](http://ascii-table.com/ansi-escape-sequences.php)
* [Cursor Movement](https://tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html)
* [ANSI from gist](https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797)


# Ways


# Java ways 01

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-09-19 20:20:08
   Modified by: Gentleman.Hu
   Modified time: 2020-09-25 19:15:22
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: Way to be Java God.
```

## Java Ways 01

### `线程`并行，同一时刻

* To start the threads at `exactly` the same time (at least as good as possible), you can use a [CyclicBarrier](http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CyclicBarrier.html) :
* Codes are as follows:

```java
// We want to start just 2 threads at the same time, but let's control that 
// timing from the main thread. That's why we have 3 "parties" instead of 2.
final CyclicBarrier gate = new CyclicBarrier(3);

Thread t1 = new Thread(){
    public void run(){
        gate.await();
        //do stuff    
    }};
Thread t2 = new Thread(){
    public void run(){
        gate.await();
        //do stuff    
    }};

t1.start();
t2.start();

// At this point, t1 and t2 are blocking on the gate. 
// Since we gave "3" as the argument, gate is not opened yet.
// Now if we block on the gate from the main thread, it will open
// and all threads will start to do stuff!

gate.await();
System.out.println("all threads started");
```

> This doesn't have to be a `CyclicBarrier`, you could also use a `CountDownLatch` or even a lock.

* This still can't make sure that they are started exactly at the same time on standard JVMs, but you can get pretty close. Getting pretty close is still useful when you do for example performance tests. E.g., if you are trying to measure throughput of a data structure with different number of threads hitting it, you want to use this kind of construct to get the most accurate result possible.

  On other platforms, starting threads exactly can be a very valid requirement btw.

`From` [StackOverFlow](https://stackoverflow.com/questions/3376586/how-to-start-two-threads-at-exactly-the-same-time)


# Interview


# Question

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-10-20 18:03:17
   Modified by: Gentleman.Hu
   Modified time: 2020-10-20 22:26:55
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description:
```

## 面试题

* SOAP,WSDL,UDDI了解?
  * [csdn](https://blog.csdn.net/fupengyao/article/details/51612069)

    ```
    1、SOAP 即 Simple Object AccessProtocol 也就是简单对象访问协议。 SOAP 是用于在应用程序之间进行通信的一种通信协议。SOAP 基于XML 和 HTTP ，其通过XML 来实现消息描述，然后再通过 HTTP 实现消息传输。 SOAP 协议的一个重要特点是它独立于底层传输机制，Web 服务应用程序可以根据需要选择自己的数据传输协议， 可以在发送消息时来确定相应传输机制。 2、WSDL 即Web Services Description Language也就是 Web 服务描述语言。 服务提供者通过服务描述将所有用于访问 Web服务的规范传送给服务请求者，通过服务描述便可以不必了解对方的底层平台，编程语言等。（服务所提供的操作、如何访问服务、服务位于何处） 3、UDDI 即 Universal Description，Discovery and Integration，也就是通用的描述，发现以及整合。 WSDL 呢，用来描述了访问特定的 Web 服务的一些相关的信息，可以在互联网上，或者是在企业的不同部门之间。 UDDI的话，是一个跨产业，跨平台的开放性架构，可以帮助 Web 服务提供商在互联网上发布 Web 服务的信息。 UDDI 呢是一种目录服务，企业可以通过 UDDI 来注册和搜索 Web 服务。 简单来时候话，UDDI 就是一个目录，只不过在这个目录中存放的是一些关于 Web 服务的信息而已。
    ```
* JDO(JAVA Data Object)
* 谈谈Java规范中和WebService相关的规范有哪些？
  * [csdn](https://blog.csdn.net/troubleshooter/article/details/78455036)

    \`\`\`md

    JAVA *\**&#x540C;拥有三种WebService 规范，各自是JAXM\&SAAJ、JAX-WS（JAX-RPC）、JAX-RS。
* JAX-WS(JSR 224)：这个规范是早期的基于SOAP的Web Service规范JAX-RPC的替代版本，它并不提供向下兼容性，因为RPC样式的WSDL以及相关的API已经在Java EE5中被移除了。WS-MetaData是JAX-WS的依赖规范，提供了基于注解配置Web Service和SOAP消息的相关API。
* JAXM(JSR 67)：定义了发送和接收消息所需的API,相当于Web Service的服务器端。
* JAX-RS(JSR 311 & JSR 339 & JSR 370)：是Java针对REST（Representation State Transfer）架构风格制定的一套Web Service规范。REST是一种软件架构模式，是一种风格，它不像SOAP那样本身承载着一种消息协议， (两种风格的Web Service均采用了HTTP做传输协议，因为HTTP协议能穿越防火墙，Java的远程方法调用（RMI）等是重量级协议，通常不能穿越防火墙），因此可以将REST视为基于HTTP协议的软件架构。REST中最重要的两个概念是资源定位和资源操作，而HTTP协议恰好完整的提供了这两个点。HTTP协议中的URI可以完成资源定位，而GET、POST、OPTION、DELETE方法可以完成资源操作。因此REST完全依赖HTTP协议就可以完成Web Service，而不像SOAP协议那样只利用了HTTP的传输特性，定位和操作都是由SOAP协议自身完成的，也正是由于SOAP消息的存在使得基于SOAP的Web Service显得笨重而逐渐被淘汰。

  \`\`\`
* 操作系统里的内存碎片你怎么理解，有什么解决办法？
* 怎么杀死进程？


# Requirements

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-10-13 19:40:21
   Modified by: Gentleman.Hu
   Modified time: 2020-11-12 19:08:48
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: My interview requirements all in one
```

## 基础

* 常见数据结构算法
* 网络编程,TCP/IP ,Http, Socket等
* SQL语言,MySql,NoSql,Memcached等
* 操作系统知识

## 强化基础

* Spring全家桶使用及其原理理解
* 多线程,IO,AIO,BIO等,JUC,JMM,JVM等知识
* 设计模式和原则
* 数据库三大范式
* 大数据相关
  * HDSF
  * Hadoop
  * Yarn
  * Kafka
  * 等
* 中间件
  * Dubbo
  * mq
  * kafka
  * es
  * ..
* 分布式系统原理,存储,计算,消息队列,集群管理等理解
* Rest,RPC等
* MongoDB,Hbase等
* Java, Web UI/Angular.JS, big data/Spark, Data/ETL, AI/ML .

## 其他

* 负载均衡,高可用,容灾备份

## Android

* Java语言,Kotlin语言熟练
* 跨平台框架React Native,Flutter
* Android SDK熟练,常用组件
* Android Framework层理解

### 一个安卓岗

```yaml
1. 全日制本科以上在校生，计算机、软件、通信等相关专业

2. 有扎实的Java 或C，Ｃ++基础知识，拥有良好的编程规范，熟悉常用的数据结构和设计模式

3. 熟悉 Android 应用开发，对 UI 开发、应用框架、网络通信、多线程IO模型和数据库存储等有较深了解

4. 善于学习和运用新知识，有进取心。

5. 具有主动的沟通意识，良好的团队合作精神，和一定的承压能力。

6. 热爱移动产品研发，有较强的学习能力，有强烈的求知欲、好奇心和进取心 ，能及时关注和学习业界最新的移动开发技术

7. 熟悉kotlin基础知识或有Android项目开发经验者优先
```

another

```yaml
3.对OOP有深刻的理解，有扎实的JAVA基础，熟练Spring、Hibernate、redis等技术应用
4.熟悉数据库设计规范，熟练Mysql数据库开发技术
5.熟悉日常的Linux操作命令
6.熟悉I/O、多线程、集合等基础框架，熟悉分布式、缓存、消息机制等。具备高效解决问题的能力
```

Lazada,Java一般开发岗

```yaml
2. 2年及以上使用JAVA开发的经验，JAVA基础扎实，理解io、多线程、集合等基础框架，对JVM原理有一定的了解，对Spring,ibatis,struts等开源框架熟悉；
3. 熟悉分布式系统的设计和应用，熟悉分布式、缓存、消息等机制；能对分布式常用技术进行合理应用，解决问题；
4. 掌握多线程及高性能的设计与编码及性能调优；有高并发应用开发经验；
5. 掌握Linux 操作系统和大型数据库（Oracle、MySql）；对sql优化有丰富的经验；
6. 学习能力强，适应能力好，有强烈的责任心，具备耐心/细心的品质；
7. 有良好英语沟通者优先考虑。
```

```yaml
2.熟悉linux的编程环境，了解Linux日常运维的基本命令，数据shell脚本更佳
3.熟悉Mysql及sql语言，了解no-sql、key-value 存储原理。能进行基本的数据分析和sql语句的编程
4.熟悉Java及Web应用的开发，了解spring，ibatis，cache，rpc，jvm等机制与代码，有了解源码者优先考虑
5.java基础扎实，熟练掌握网络和多线程编程，对tcp/ip,http协议有很深刻的了解，并了解xml和html语言
6.熟悉基本的设计模式，了解分布式
7.有一定的自学能力，积极向上
8.英文听说读写能力优秀者优先
```

牛客一个大神字节面试(JAVA)真题合集

```yaml
作者：字节跳动｜内推
链接：https://www.nowcoder.com/discuss/562887?channel=1009&source_id=home_feed
来源：牛客网

Java基础
1.JAVA 中的几种数据类型是什么，各自占用多少字节。

2.String 类能被继承吗，为什么。

3. 两个对象的 hashCode() 相同，则 equals() 也一定为 true，对吗？

4. String 属于基础的数据类型吗？

5.Java 中操作字符串都有哪些类？它们之间有什么区别？

6.Java 中 IO 流分为几种？

7.BIO、NIO、AIO 有什么区别？

8.用过哪些 Map 类，都有什么区别，HashMap 时线程安全的吗，并发下使用的 Map 是什么，他们的内部原理分别是什么，比如存储方法，hashcode，扩容，默认容量等。

9. 如何将字符串反转？

10.抽象类必须要有抽象方法吗？

11.普通类和抽象类有哪些区别？

12.抽象类能使用 final 修饰吗？

13.ArrayList 和 LinkedList 有什么区别？

14.ConcurrentHashMap的数据结构（必考）

15.volatile作用（必考）

16.Atomic类如何保证原子性（CAS操作）（必考）

17.为什么要使用线程池（必考）

Redis
Redis的应用场景
Redis支持的数据类型（必考）
zset跳表的数据结构（必考）
Redis的数据过期策略（必考）
Redis的LRU过期策略的具体实现
如何解决Redis缓存雪崩，缓存穿透问题
Redis的持久化机制（必考）
Redis为什么是单线程的？
什么是缓存穿透？怎么解决？
Redis持久化有几种方式？
Redis为什么这么快？（必考）
Redis怎么实现分布式锁？
Redis如何做内存优化？
Redis淘汰策略有哪些？
Redis常见的性能问题有哪些？该如何解决？
Redis的使用要注意什么？
ZooKeeper
CAP定理
ZAB协议
leader选举算法和流程
zookeeper 是什么？
zookeeper 有几种部署模式？
zookeeper 怎么保证主从节点的状态同步？
Mysql
事务的基本要素
事务隔离级别（必考）
如何解决事务的并发问题(脏读，幻读)（必考）
MVCC多版本并发控制（必考）
binlog,redolog,undolog都是什么，起什么作用
InnoDB的行锁/表锁
myisam和innodb的区别，什么时候选择myisam
为什么选择B+树作为索引结构（必考）
索引B+树的叶子节点都可以存哪些东西（必考）
查询在什么时候不走（预期中的）索引（必考）
sql如何优化
explain是如何解析sql的
order by原理
JVM
运行时数据区域（内存模型）（必考）
垃圾回收机制（必考）
垃圾回收算法（必考）
Minor GC和Full GC触发条件
GC中Stop the world（STW）
各垃圾回收器的特点及区别
双亲委派模型
JDBC和双亲委派模型关系
JVM 中一次完整的 GC 流程是什么样子的，对象如何晋升到老年代，说说你知道的几种主要的 JVM 参数
Spring
Spring的IOC/AOP的实现（必考）
动态代理的实现方式（必考）
Spring如何解决循环依赖（三级缓存）（必考）
Spring的后置处理器
Spring的@Transactional如何实现的（必考）
Spring的事务传播级别
BeanFactory和ApplicationContext的联系和区别
其他
高并发系统的限流如何实现
高并发秒杀系统的设计
负载均衡如何设计
操作系统篇
进程和线程的区别
进程同步的几种方式
线程间同步的方式
什么是缓冲区溢出。有什么危害，其原因是什么
进程中有哪几种状态
分页和分段有什么区别
多线程篇
多线程的几种实现方式，什么是线程安全
volatile 的原理，作用，能代替锁吗?
sleep 和 wait 的区别
sleep(0)的意义
Lock 和 Synchronized 的区别
synchronized 的原理是什么，一般用在什么地方（比如加载静态方法和非静态方法的区别）
补充
另外还会考一些计算机网络之类的。像消息队列，RPC框架这种考的比较少。计算机网络就是分层啊，tcp/udp啊，三次握手之类的。操作系统就是进程与线程啊，进程的数据结构以及如何通信之类的。

数据结构的排序算法也比较常考，考的话一定会让你手写个快排。剩下的算法题就靠LeetCode的积累了。其实非算法岗考的算法题都蛮简单的，很多题完全就是考察你智力是否正常，稍微难点的涉及到一些算法思想的按照LeetCode题目类型的分类，每种题做一两道基本就能完全应付面试了。
```


# Leetcode101


# Acwing


# Index

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-11-08 13:05:48
   Modified by: Gentleman.Hu
   Modified time: 2020-11-08 13:06:03
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: index of acwing
```

> [acwing题库](https://www.acwing.com/problem/)


# 背包问题

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-11-08 12:39:42
   Modified by: Gentleman.Hu
   Modified time: 2020-11-08 13:10:13
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: 对背包问题的探索与学习
```

## 背包问题

> <https://www.acwing.com/problem/content/2/>

### 问题描述

有N件物品和一个容量是V的背包.每件物品只能使用一次.

有i件物品的体积是Vi,价值是Wi.

求解将哪些物品装入背包,可使这些物品的总体积不超过背包容量,且总价值最大. 输出最大价值.

**输入格式** 第一行两个整数,N,V,用空格隔开,分别表示物品数量和背包容积.

接下来有N行,每行两个整数Vi,Wi,用空格隔开,分别表示第i件物品的体积和价值.

**输出格式** 输出一个整数,表示最大价值.

**数据范围** 0\<N,V<=1000 0\<Vi,Wi<=1000

输入样例

```
4 5
1 2
2 4
3 4
4 5
```

输出样例:

```
8
```

### Soltion

> [一维动态规划状态转移方程解释](https://www.acwing.com/solution/content/3982/)


# Explores


# Solutions


# Algorithms


# Index

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-10-17 18:08:50
   Modified by: Gentleman.Hu
   Modified time: 2020-10-17 18:09:34
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: index of leetcode algorithms problems
```

## Index

> [source](https://leetcode.com/problemset/algorithms/)

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201017180708.png)


# Concurrency


# Index

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-10-17 11:02:49
   Modified by: Gentleman.Hu
   Modified time: 2020-10-17 11:05:13
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: index of concurrency in leetcode
```

## Concurrency set in leetcode

> [Concurrency](https://leetcode.com/problemset/concurrency/)

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201017110503.png)


# Shell


# Index

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-10-17 18:09:46
   Modified by: Gentleman.Hu
   Modified time: 2020-10-17 18:10:53
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: index of leetcode shell problems
```

## Index

> [source](https://leetcode.com/problemset/shell/)

![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201017181045.png)


# Sql


# Index

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-10-17 17:26:10
   Modified by: Gentleman.Hu
   Modified time: 2020-10-17 17:59:35
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description: index of leetcode SQL SET problem.
```

## Index

> [source](https://leetcode.com/problemset/database/)

* ![](https://cdn.jsdelivr.net/gh/gentlemanhu/public-store/images/20201017175859.png)


# 牛客


# 剑指offer


# Youtube离线下载

```yaml
   Author: Gentleman.Hu
   Create Time: 2020-09-19 20:20:08
   Modified by: Gentleman.Hu
   Modified time: 2020-09-25 19:15:30
   Email: justfeelingme@gmail.com
   Home: https://crushing.xyz
   Description:
```

## Youtube离线下载

### 1.安装MediaDownloader

[MediaDownloader](https://github.com/Kallys/MediaDownloader)

### 2.配置rclone

### 3.配置inotify

* 监测mp3文件生成

  ```
    #!/bin/bash
    TARGET='/www/wwwroot/be.feelingyou.ml/MediaDownloader/public/downloads'
    downloadpath='/www/wwwroot/be.feelingyou.ml/MediaDownloader/public/downloads'

    inotifywait -m --exclude "[^m][^p][^3]$" $TARGET -e create -e moved_to | \
        while read path action file; do
                echo "The file '$file' appeared in directory '$TARGET' via '$action'"
            if [[ "$file" =~ .*temp.*$ ]]; then
                echo "这是临时文件不上传"
            elif [[ "$file" =~ .*mp3$ ]]; then
                /usr/bin/php /www/wwwroot/pan.i-love-you.ml/one.php upload:file "$TARGET/$file" /Youtube-dl/musics/
            fi
        done
  ```
* 监测mp4

  ```
  #!/bin/bash
  TARGET='/www/wwwroot/be.feelingyou.ml/MediaDownloader/public/downloads'
  downloadpath='/www/wwwroot/be.feelingyou.ml/MediaDownloader/public/downloads'

  inotifywait -m --exclude "[^m][^p][^4]$" $TARGET -e create -e moved_to | \
      while read path action file; do
             echo "The file '$file' appeared in directory '$TARGET' via '$action'"
          if [[ "$file" =~ .*temp.*$ ]]; then
             echo "这是临时文件不上传"
          elif [[ "$file" =~ .*mp4$ ]]; then
              /usr/bin/php /www/wwwroot/pan.i-love-you.ml/one.php upload:file "$TARGET/$file" /Youtube-dl/videos/
          fi
      done
  ```
* 监测webm

  ```
  #!/bin/bash
  TARGET='/www/wwwroot/be.feelingyou.ml/MediaDownloader/public/downloads'
  downloadpath='/www/wwwroot/be.feelingyou.ml/MediaDownloader/public/downloads'

  inotifywait -m --exclude "[^w][^e][^b][^m]$" $TARGET -e create -e moved_to | \
      while read path action file; do
              echo "The file '$file' appeared in directory '$TARGET' via '$action'"
          if [[ "$file" =~ .*temp.*$ ]]; then
              echo "这是临时文件不上传"
  #        if [[ "$file" =~ .f*.webm$ ]]; then
  #            echo "这是初始文件不上传"
          elif [[ "$file" =~ .*webm$ ]]; then
              /usr/bin/php /www/wwwroot/pan.i-love-you.ml/one.php upload:file "$TARGET/$file" /Youtube-dl/videos/
              rm -rf "$TARGET/$file"
          fi
      done
  ```
* 监测mkv

  ```
  #!/bin/bash
  TARGET='/www/wwwroot/be.feelingyou.ml/MediaDownloader/public/downloads'
  downloadpath='/www/wwwroot/be.feelingyou.ml/MediaDownloader/public/downloads'

  inotifywait -m --exclude "[^m][^k][^v]$" $TARGET -e create -e moved_to | \
      while read path action file; do
             echo "The file '$file' appeared in directory '$TARGET' via '$action'"
          if [[ "$file" =~ .*temp.*mkv$ ]]; then
             echo "这是临时文件不上传"
          elif [[ "$file" =~ .f*.*mp4$ ]]; then
              echo "这是初始文件不上传"
          elif [[ "$file" =~ .*mkv$ ]]; then
              /usr/bin/php /www/wwwroot/pan.i-love-you.ml/one.php upload:file "$TARGET/$file" /Youtube-dl/videos/
              rm -rf "$TARGET/$file"
          fi
      done
  #inotifywait -m -e create -e moved_to --format "%f" $TARGET
  #    while read FILENAME; do
  #        #if [[ "$FILENAME" =~ .*mkv$ || "$FILENAME" =~ .*webm$ ]]; then
  #                #echo "mkv file"
  #            #filepath=$FILENAME
  #                #/usr/bin/php /www/wwwroot/pan.i-love-you.ml/one.php upload:file "$filepath" /Youtube-dl/videos/
  #                #rm -rf "$filepath"
  #                #exit 0
  #        #fi
  #   done

  # if [ $2 -eq 0 ]; then
  #     exit 0
  # fi
  # while true; do
  #     filepath=$path
  #     path=${path%/*}
  #     if [ "$path" = "$downloadpath" ] && [ $2 -eq 1 ]; then
  #         /usr/bin/php /www/wwwroot/pan.i-love-you.ml/one.php upload:file "$filepath" /upload/
  #         rm -rf "$filepath"
  #         exit 0
  #     elif [ "$path" = "$downloadpath" ]; then
  #         /usr/bin/php /www/wwwroot/pan.i-love-you.ml/one.php upload:folder "$filepath"/ /upload/"${filepath##*/}"/
  #         rm -rf "$filepath"/
  #         exit 0
  #     fi
  # done
  ```

  > 可能某些还未监测
* 较完美监测

  ```
  #!/bin/bash
  TARGET='/root/tmp'
  downloadpath='/www/wwwroot/be.feelingyou.ml/MediaDownloader/public/downloads'

  inotifywait -m $TARGET -e create -e moved_to |
      while read path action file; do
          echo "The file '$file' appeared in directory '$TARGET' via '$action'"
          filename="${file##*/}"
          extension="${filename##*.}"
          case $extension in
          mp3)
              echo "$file"
              echo "$extension"
              ;;
          *)
              echo "$file"
              echo "$extension"
              ;;
          esac
      done
  ```

### 4.安装任意一款OneDrive的index

* cuteone
* oneindex
* Olxdex?
* pyone
* ...

### 其他待完善


# Python days


