Yutong Jin


  • Home

  • about me

  • Categories

  • Archives

  • With-恬

  • react-test

Some Leetcode

Posted on 2020-04-28 | In leetcode

todo

question method?
delete node in BST recursive
dp
quick select
union find
palindrome substring dp做

Read more »

OS(2) Synchronization

Posted on 2020-04-16 | In OS

Case : 来看两个共享counter变量的进程

Process 1

1
2
3
4
5
6
7
while (true) {
/* produce an item in next produced */
while (counter == BUFFER SIZE) ; /* do nothing */
buffer[in] = next produced;
in = (in + 1) % BUFFER SIZE;
counter++;
}

Process 2

1
2
3
4
5
6
7
while (true) {
while (counter == 0); /* do nothing */
next consumed = buffer[out];
out = (out + 1) % BUFFER SIZE;
counter--;
/* consume the item in next consumed */
}

在执行时

1
counter++

相当于下面三行代码

1
2
3
register1 = counter 
register1 = register1 + 1
counter = register1

且

1
counter--

相当于

1
2
3
register2 = counter 
register2 = register1 - 1
counter = register2

有可能下面的情况出现
alt
(此处感谢
https://myfavs.win/2019/08/08/%E8%AE%B0%E5%BD%95-Hexo-%E5%9B%BE%E7%89%87%E7%9A%84%E5%9D%91/
解决了图片问题)

1.Critical Section

The important feature of the system is that, when one process is executing in its critical section, no other process is allowed to execute in its critical section. That is, no two processes are executing in their critical sections at the same time. The critical-section problem is to design a protocol that the processes can use to cooperate.

理解一下:一个进程在critical section里执行的时候,其他程序不可以进来。否则就会出现上述情况中的问题

Three Requirements

1.Mutual Exclusion

If process Pi is executing in its critical section, then no other processes can be executing in their critical sections.
基本就是字面意思

2. Progress

If no process is executing in its critical section and some processes wish to enter their critical sections, then only those processes that are not executing in their remainder sections can participate in deciding which will enter its critical section next, and this selection cannot be postponed indefinitely.

中文翻译: 如果没有进程在其临界区内执行且有进程需进入临界区,那么只有那么不在剩余区内执行的进程可参加选择,以确定谁能下一个进入临界区,且这种选择不能无限推迟;(wtf?????)

研究一番之后的理解:所有程序都在make progress而不是傻等。

  1. critical section里的程序,继续干自己的事
  2. critical section结束的还在remainder section的程序,继续把自己的干完,先别想着下次进来
  3. 其他程序,别傻等着,好好去想一想下一个谁进来
  4. 你们决定的过程要在有限时长内完成(无deadlock 或者 livelock 出现)

3.Bounded Waiting

There exists a bound, or limit, on the number of times that other processes are allowed to enter their critical sections after a entry section critical section exit section.

每个程序都会进入critical section 而不是starve forever.

2. Peterson Solution and Dekker’s Solution

Peterson

Dekker

There is a process on how versions change.

https://www.geeksforgeeks.org/dekkers-algorithm-in-process-synchronization/

OS(1) basic

Posted on 2020-04-13 | In OS

OS services functions

  • User Interface
  • Program execution
  • I/O operatings
  • File-system manipulation
  • Communications(between processes)
  • Error detection

others

  • Resource allocation
  • Accounting
  • Protection and security

Process(Unit of work)

5 states

  • New
  • Running
  • Waiting
  • Ready
  • Terminated

Effective Java C6i40 ---- Override Annotation

Posted on 2020-04-10 | In Java

Given a class below :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Can you spot the bug? (Page 188)
public class Bigram {
private final char first;
private final char second;

public Bigram(char first, char second) {
this.first = first;
this.second = second;
}

public boolean equals(Bigram b) {
return b.first == first && b.second == second;
}

public int hashCode() {
return 31 * first + second;
}

public static void main(String[] args) {
Set<Bigram> s = new HashSet<>();
for (int i = 0; i < 10; i++)
for (char ch = 'a'; ch <= 'z'; ch++)
s.add(new Bigram(ch, ch));
System.out.println(s.size());
}
}
//what we want is 26.
//but the real answer is 260

If we don’t add Override annotation, equals method will not work.

Actually we want to override equals and even hashCode method, however, there is no @Override annotation.

Also the type of parameter we pass into equals method is wrong,(should be Object).

So overloading happens instead of overriding.

Whatever we do in Set s, s deals with different element within it by Object.equals method :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Indicates whether some other object is "equal to" this one.
* <p>
* The {@code equals} method implements an equivalence relation
* on non-null object references:
* <ul>
* <li>It is <i>reflexive</i>: for any non-null reference value
* {@code x}, {@code x.equals(x)} should return
* {@code true}.
* <li>It is <i>symmetric</i>: for any non-null reference values
* {@code x} and {@code y}, {@code x.equals(y)}
* should return {@code true} if and only if
* {@code y.equals(x)} returns {@code true}.
* <li>It is <i>transitive</i>: for any non-null reference values
* {@code x}, {@code y}, and {@code z}, if
* {@code x.equals(y)} returns {@code true} and
* {@code y.equals(z)} returns {@code true}, then
* {@code x.equals(z)} should return {@code true}.
* <li>It is <i>consistent</i>: for any non-null reference values
* {@code x} and {@code y}, multiple invocations of
* {@code x.equals(y)} consistently return {@code true}
* or consistently return {@code false}, provided no
* information used in {@code equals} comparisons on the
* objects is modified.
* <li>For any non-null reference value {@code x},
* {@code x.equals(null)} should return {@code false}.
* </ul>
* <p>
* The {@code equals} method for class {@code Object} implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values {@code x} and
* {@code y}, this method returns {@code true} if and only
* if {@code x} and {@code y} refer to the same object
* ({@code x == y} has the value {@code true}).
* <p>
* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
*
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode()
* @see java.util.HashMap
*/
public boolean equals(Object obj) {
return (this == obj);

So there are different 260 objects in s.

Properties of equals function

  • reflexive
  • symmetric
  • transitive
  • consistent
  • non-null x => x.equals(null) => false
  • x,y => refer to the same object => true
  • remember to add @Override and override hashCode method

clutter : 混乱
deem : 认为

github page 域名访问显示404 解决方法

Posted on 2020-04-08

https://help.github.com/en/github/working-with-github-pages/configuring-a-custom-domain-for-your-github-pages-site

Redux(2)---Data Flow

Posted on 2020-04-07

Redux architecture revolves around a strict unidirectional data flow.

1. You call store.dispatch(action)

from anywhere in your app, including components and XHR callbacks, or even at scheduled intervals.

2. The Redux store calls the reducer function you gave it.

The store will pass two arguments to the reducer: the current state tree and the action.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// The current application state (list of todos and chosen filter)
let previousState = {
visibleTodoFilter: 'SHOW_ALL',
todos: [
{
text: 'Read the docs.',
complete: false
}
]
}

// The action being performed (adding a todo)
let action = {
type: 'ADD_TODO',
text: 'Understand the flow.'
}

// Your reducer returns the next application state
let nextState = todoApp(previousState, action)

Note that a reducer is a pure function. It only computes the next state. It should be completely predictable: calling it with the same inputs many times should produce the same outputs. It shouldn’t perform any side effects like API calls or router transitions. These should happen before an action is dispatched.

3. The root reducer may combine the output of multiple reducers into a single state tree.

4. The Redux store saves the complete state tree returned by the root reducer.

This new tree is now the next state of your app! Every listener registered with store.subscribe(listener) will now be invoked; listeners may call store.getState() to get the current state.

Now, the UI can be updated to reflect the new state. If you use bindings like React Redux, this is the point at which component.setState(newState) is called.

https://redux.js.org/basics/data-flow

Redux(1)---Three Principles and Concepts

Posted on 2020-04-07

Three Principles

1. Single source of truth

The state of your whole application is stored in an object tree within a single store.

2. State is read-only

The only way to change the state is to emit an action, an object describing what happened.

3. Changes are made with pure functions

To specify how the state tree is transformed by actions, you write pure reducers.

Other Tips

  • Redux assumes you never mutate your data.
  • Redux does not have the concept of a Dispatcher. This is because it relies on pure functions instead of event emitters, and pure functions are easy to compose and don’t need an additional entity managing them.
  • Redux doesn’t care how you store the state—it can be a plain object, an Immutable object, or anything else.

Three Concepts

1. Action

Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using store.dispatch().

  • Actions must have a type property that indicates the type of action being performed.

2. Reducer

Reducers specify how the application’s state changes in response to actions sent to the store. Remember that actions only describe what happened, but don’t describe how the application’s state changes.

  • It’s called a reducer because it’s the type of function you would pass to Array.prototype.reduce(reducer, ?initialValue).

Things you should never do inside a reducer:

  • Mutate its arguments;
  • Perform side effects like API calls and routing transitions;
  • Call non-pure functions, e.g. Date.now() or Math.random().

We’ll explore how to perform side effects in the advanced walkthrough. For now, just remember that the reducer must be pure. Given the same arguments, it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.

3. Store

The Store is the object that brings Actions and Reducers together.

The store has the following responsibilities:

  • Holds application state;
  • Allows access to state via getState();
  • Allows state to be updated via dispatch(action);
  • Registers listeners via subscribe(listener);
  • Handles unregistering of listeners via the function returned by subscribe(listener).
    1
    2
    3
    import { createStore } from 'redux'
    import todoApp from './reducers'
    const store = createStore(todoApp)

    It’s important to note that you’ll only have a single store in a Redux application. When you want to split your data handling logic, you’ll use reducer composition instead of many stores.

https://redux.js.org/introduction/three-principles
Learning Resources: https://redux.js.org/introduction/learning-resources

Redux(1)---Three Principles and Concepts

Posted on 2020-04-07

Basic

1. Echo $PATH

Show all shell scripts path

If you have 2 folders that contain the same command, it will run the first one

1
2
3
4
which cal //show which folder which is in
date -u
cal 2017
cal 12 2017

2. params

1
2
3
date -u - for short form
date --universal -- for long form
cal -A 1 -B 1 12 2017

3. file

1
2
3
4
touch 
cat
vim
ls -a

##Manual Structure

1
2
3
4
5
6
7
8
9
10
11
12
13
man -k which
man 1 which

WHICH(1) BSD General Commands Manual WHICH(1)

NAME
which -- locate a program file in the user's path

SYNOPSIS
which [-as] program ... (we can give more than one param)


which [-a | -f ] <something> #| means one of them, <> is mandatory [] is optional

###help page

man cd : no result

help cd : show cd info

just type help and it will show the command that needs help

The only way to change the state is to emit an action, an object describing what happened.
###cat
0:input
1:output
2:error

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
cat > output.txt // create a file and then put data stream out this file

cat >> output.txt // append to the file

some commands 2> error.txt //execute commands and then write errors into that file

tty //show the location of current terminal

cat < input.txt > {the url we got from last command} // show input.txt into that terminal
```

#### 3. Changes are made with pure functions
To specify how the state tree is transformed by actions, you write pure reducers.
- Redux assumes you never mutate your data.
- Redux does not have the concept of a Dispatcher. This is because it relies on pure functions instead of event emitters, and pure functions are easy to compose and don't need an additional entity managing them.
- Redux doesn't care how you store the state—it can be a plain object, an Immutable object, or anything else.

## Three Concepts
#### 1. Action
Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using store.dispatch().
- Actions must have a <strong>type</strong> property that indicates the type of action being performed.

#### 2. Reducer
Reducers specify how the application's state changes in response to actions sent to the store. Remember that actions only describe what happened, but don't describe how the application's state changes.
- It's called a reducer because it's the type of function you would pass to Array.prototype.reduce(reducer, ?initialValue).

#### Things you should never do inside a reducer:

- Mutate its arguments;
- Perform side effects like API calls and routing transitions;
- Call non-pure functions, e.g. Date.now() or Math.random().

> We'll explore how to perform side effects in the advanced walkthrough. For now, just remember that the reducer must be pure. Given the same arguments, it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.

#### 3. Store
The Store is the object that brings <strong>Actions</strong> and <strong>Reducers</strong> together.

The store has the following responsibilities:
- Holds application state;
- Allows access to state via getState();
- Allows state to be updated via dispatch(action);
- Registers listeners via subscribe(listener);
- Handles unregistering of listeners via the function returned by subscribe(listener).
``` javascript
import { createStore } from 'redux'
import todoApp from './reducers'
const store = createStore(todoApp)

It’s important to note that you’ll only have a single store in a Redux application. When you want to split your data handling logic, you’ll use reducer composition instead of many stores.

https://redux.js.org/introduction/three-principles
Learning Resources: https://redux.js.org/introduction/learning-resources

this,bind,arrow function in js

Posted on 2020-04-03
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
c = 100;
var a = {
b:1,
c:10,
foo:() => {
console.log(this.c);
},
bar:function(){
console.log(this.c);
}
}
a.bar();//普通函数,this 指向a
a.foo();//arrow function 没有默认this 指针,故函数里的this指向a所在的window
var fun = a.foo;//把a.foo function 传给 fun
fun();//在window scope下执行fun,this --> window
var funBind = a.bar.bind(a);//bind a.bar to a
funBind();//binded to a
funBind = a.bar.bind(this);//bind a.bar to this
funBind();// binded to window

var fooArrow = a.bar;
fooArrow();

https://www.codementor.io/@dariogarciamoya/understanding-this-in-javascript-with-arrow-functions-gcpjwfyuc
https://medium.com/tfogo/advantages-and-pitfalls-of-arrow-functions-a16f0835799e
https://dmitripavlutin.com/when-not-to-use-arrow-functions-in-javascript/
https://medium.com/@charpeni/arrow-functions-in-class-properties-might-not-be-as-great-as-we-think-3b3551c440b1
https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4
https://stackoverflow.com/questions/52979915/why-we-dont-need-to-bind-the-arrow-function-in-react

重温HF之3-掌握多态性

Posted on 2020-03-21

1. static 多态

也叫compile 多态,本质就是编译时method的多态性,其实就是方法的overload.

Same method name is overloaded with different type or number of parameters in same class (different signature). Targeted method call is resolved at compile time

2.dynamic 多态

也叫runtime 多态,本质是继承属性和函数override的组合。
看过很多文章在讲向上转型(upcasting)和向下转型(downcasting),有的文章讲的非常复杂,研究了一番后打算总结如下。

(1)向下转型

其实是最简单的一种–人工强制cast。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Sup{
void m1(){
System.out.println("Sup m1");
}
}

class Sub extends Sup{
void m1(){
System.out.println("Sub m1");
}
void m2(){
System.out.println("Sub m2");
}
}

在这里我们进行一个操作

1
2
3
4
Sup a = new Sub();
a.m1();// Sub m1
a.m2();// 找不到符号,因为 ref 为 a的变量找不到m2方法,也就是上一章我们说过的父类不知道子类
((Sub)a).m2();//如果想调用Sub实例的方法,就必须强制cast,但是操作危险性大。

(2)向上转型

说白了,向上转型就是

1.在自己的ref class 里没有找到想要的方法,把自己(自动向上转型)变成父类找这个方法。
2.找到的话再以new出来的对象为bottom看看override到哪层。

我们不妨换个思考的角度,为什么要 “把自己(自动向上转型)变成父类”???

我本身就是个父类啊,继承就是因为我满足了IS-A关系,我为什么不能默认把父类的方法都取到自己身上然后去找呢?

so 找到之后再从ref 往下 看有没有override的情况然后以new出来的对象为底,结束。

如果形式参数没有怎么办?

答:把形式参数多态向上找。

用一个经典案例解释上面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class TestForPoli {
static public class A {
public String show(D obj) {
return ("A and D");
}

public String show(A obj) {
return ("A and A");
}
}

static public class B extends A{
public String show(B obj){
return ("B and B");
}

public String show(A obj){
return ("B and A");
}
public String showOnlyInB(){
return ("showOnlyInB");
}
}

static public class C extends B{
public String show(D obj) {
return ("C and D");
}
}

static public class D extends B{
public String show(D obj) {
return ("D and D");
}
}

public static void main(String[] args) {
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();
A ac = new C();
B bc = new D();
System.out.println("1--" + a1.show(b));
System.out.println("2--" + a1.show(c));
System.out.println("3--" + a1.show(d));
System.out.println("4--" + a2.show(b));
System.out.println("5--" + a2.show(c));
System.out.println("6--" + a2.show(d));
System.out.println("7--" + b.show(b));
System.out.println("8--" + b.show(c));
System.out.println("9--" + b.show(d));
System.out.println("10--" + ac.show(d));
System.out.println("11--" + bc.show(d));
//test for down cast
System.out.println("12--" + ((B)a2).show(b));
//System.out.println("13--" + a2.showOnlyInB());


}
}

输出结果如下

1
2
3
4
5
6
7
8
9
10
11
12
1--A and A
2--A and A
3--A and D
4--B and A
5--B and A
6--A and D
7--B and B
8--B and B
9--A and D
10--C and D
11--D and D
12--B and B

(1)a1.show(b)

a1 :ref为A,实例为A,向上的关系只有object,show(b)找不到,尝试去找show((super)b)也就是把形式参数向上转型,找到了show(A a)方法,所以输出A and A。
2 3 同理。

(2)a2.show(b)

a2 :ref为A,实例为B,向上的关系只有object,show(b)找不到,尝试去找show((super)b)就是把形式参数向上转型,找到了show(A a)方法,(到这里和上面是一样的),但是实例为B,我们需要进行的操作是看show(A a)方法有没有被override,然后发现class B里有一个show(A a)的方法,故输出B and A
5 同理,6是因为A里直接有一个show(D d)的method,而且这个方法没有被实例B override,故输出A and D
7 easy

(3)b.show(c)

这里我们使用向上转型继承的方法,把b的super类a的方法都加到b里,然后还是没有找到show(B)的办法,我们此时就去找形式参数c的super类,向上找到了B,于是输出B and B

(4)b.show(d)

这里我们使用向上转型继承的方法,把b的super类a的方法都加到b里,解决。

12<i class="fa fa-angle-right"></i>
Cubo

Cubo

要么不做,要做就做最好

16 posts
3 categories
1 tags
GitHub E-Mail YouTube Instagram
© 2021 Cubo
本站访客数:
Powered by Hexo
|
Theme — NexT.Pisces v5.1.4