Wednesday, March 31, 2021

 Sams Teach yourself Apache 2 in 24 hours note

1. By default Mac BigSur has the apache

run the command to verify: httpd -v 

The installation path: /private/etc/apache2

The log location: /var/log/apache2

Document root: /Library/WebServer/Documents

2. httpd.conf

The ServerRoot directive takes a single argument: a directory path pointing to the directory where the server lives.

None disables per-directory files in that directory and any of its subdirectories. This improves performance and is the default Apache configuration.

1: <Directory />
2: AllowOverride none
3: </Directory>

3. control:

apachectl start/stop/restart/graceful

from the browser, http://localhost:80 will show "It works"

ErrorDocument 404 "Oops, we couldn't find your document!"

or

ErrorDocument 404 http://search.example.com
Alias /icons/ /usr/local/apache2/icons/

will cause a request for http://www.example.com/icons/image.gif to make Apache look for the /usr/local/apache2/icons/image.gif file.

4. reverse proxy

A reverse proxy is a Web server that sits in front of other Web servers, known as backend servers. The reverse proxy Web server can be configured to pass certain requests to the backend servers and return the result to the clients as if it were the reverse proxy that generated the content

You can use the ProxyPass and ProxyPassReverse directives to map URLs in the reverse proxy to URLs in the backend servers.

In certain situations, the backend server might issue redirects. These redirects will include a Location: header that contains a reference to the backend server (backend.example.com). The ProxyPassReverse directive will intercept these headers and rewrite them so that they include a reference to the reverse proxy (rproxy.example.com) instead.

The previous examples could be rewritten as follows:

ProxyPass /dynamic/ http://backend.example.com/
ProxyPassReverse /dynamic/ http://backend.example.com/
Note that the ProxyPassReverse directive operates only at the HTTP header level. It will not inspect or rewrite links inside HTML documents.

It is possible to prevent certain URLs from not being proxied by specifying an exclamation sign (!) as the remote site URL in ProxyPass directives. It is important that those directives are placed before other ProxyPass directives. For example, the following configuration will pass all requests to a backend site, except requests for images, which will be served locally:

ProxyPass /images/ !
ProxyPass / http://backend.example.com

5. SSL

If both sender and receiver share the same key, the process is referred to as symmetric cryptography. If sender and receiver have different, complementary keys, the process is called asymmetric or public key cryptography.

Public key cryptography takes a different approach. Instead of both parties sharing the same key, there is a pair of keys: one public and the other private. The public key can be widely distributed, whereas the owner keeps the private key secret. These two keys are complementary; a message encrypted with one of the keys can be decrypted only by the other key.

Anyone wanting to transmit a secure message to you can encrypt the message using your public key, assured that only the owner of the private key—you—can decrypt it. Even if the attacker has access to the public key, he cannot decrypt the communication. In fact, you want the public key to be as widely available as possible. Public key cryptography can also be used to provide message integrity and authentication. RSA is the most popular public key algorithm.

The SSL protocol uses public key cryptography in an initial handshake phase to securely exchange symmetric keys that can then be used to encrypt the communication.

SSL uses certificates to authenticate parties in a communication. Public key cryptography can be used to digitally sign messages. In fact, just by encrypting a message with your secret key, the receiver can guarantee it came from you. Other digital signature algorithms involve first calculating a digest of the message and then signing the digest.

Trust can be achieved by using digital certificates. Digital certificates are electronic documents that contain a public key and information about its owner (name, address, and so on). To be useful, the certificate must be signed by a trusted third party (certification authority, or CA) who certifies that the information is correct. 

Certificates have a period of validity and can expire or be revoked. Certificates can be chained so that the certification process can be delegated. For example, a trusted entity can certify companies, which in turn can take care of certifying its own employees.

If this whole process is to be effective and trusted, the certificate authority must require appropriate proof of identity from individuals and organizations before it issues a certificate.

The main standard defining certificates is X.509, adapted for Internet usage. An X.509 certificate contains the following information:

  • Issuer: The name of the signer of the certificate

  • Subject: The person holding the key being certified

  • Subject public key: The public key of the subject

  • Control information: Data such as the dates in which the certificate is valid

  • Signature: The signature that covers the previous data

6.

To get a certificate issued by a CA, you must submit what is called a certificate signing request. To create a request, issue the following command:

# ./usr/local/ssl/install/bin/openssl req -new -key www.example.com.key
 -out www.example.com.csr

You can also create a self-signed certificate. That is, you can be both the issuer and the subject of the certificate. Although this is not very useful for a commercial Web site, it will enable you to test your installation of mod_ssl or to have a secure Web server while you wait for the official certificate from the CA.

You need to indicate where to find the server's certificate and the file containing the associated key. You do so by using SSLCertificateFile and SSLCertificateKeyfile directives.

You can control which ciphers and protocols are used via the SSLCipherSuite and SSLProtocol commands

 The SSLMutex directive enables you to control the internal locking mechanism of the SSL engine. 


asdf

a

sdfa


asdf

nexus 5 root

 Nexus 5 root:

https://www.androidinfotech.com/root-google-nexus-5/

Just follow the tutorial, it's pretty good guide.

Sunday, March 28, 2021

小米3W手机刷ROM

小米系统刷ROM或者root,不需要借助任何第三方电脑或手机软件。

root的话,需要下载开发版的ROM。

现在打开以前5年前的小米3W手机,发现系统还挺流畅的,尽管Android版本比较低,是4.4.4.

发现小米手机自己刷ROM很方便,因为我的音量键坏了,无法卡刷,只能线刷。

下载ROM: https://mirom.ezbox.idv.tw/phone/cancro/

我使用的是国际稳定版:https://bigota.d.miui.com/V9.5.7.0.MXDMIFA/miui_MI3WMI4WGlobal_V9.5.7.0.MXDMIFA_df826857ee_6.0.zip 

拷贝到手机的downloaded_rom目录,从手机里的更新里面选手动更新,就可以了:https://jingyan.baidu.com/article/fec4bce297fd35f2608d8b7e.html

后期版本(MIUI9之后)该选项隐藏的比较深,可参考这个手工选择安装包:https://jingyan.baidu.com/article/295430f11bca3f4c7f00505c.html

但是小米官网做的太差,不能从官方下载ROM包,我的chrome浏览器进入,看到的是下面这个:

应该到这个地方:https://xiaomirom.com/rom/mi-4-mi-4-lte-ct-cancro-global-fastboot-recovery-rom/

如果出现无法启动,可以使用线刷:https://miuiver.com/how-to-flash-xiaomi-phone/



Wednesday, March 17, 2021

RxJS note

 1.

let​ myObs$ = clicksOnButton(myButton);

 $is a convention in the Rx world that indicates that the variable in question is an observable.

Much like a promise, we need to unwrap our observable to access the values it contains. The observable unwrapping method is called subscribe.

The function passed into subscribe is called every time the observable emits a value. 

  myObs$.subscribe(clickEvent => console.log(​'The button was clicked!'​));

2.

tsc stopwatch.ts

Got the below error:

node_modules/rxjs/internal/Observable.d.ts:89:59 - error TS2585: 'Promise' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.

Need run the below to fix (editing the tsconfig.json doesn't work)

npm i @types/node

3.

delay: delay all events coming through the observable chain

​import​ { interval, of } ​from​ ​'rxjs'​;

import { delay, map, take } from 'rxjs/operators';

of​(​'hello'​, ​'world'​, ​'!'​).pipe(

    delay(5000),

    map(word=>word.split('')

    )

).subscribe(console.log);


​​let​ tenthSecond$ = interval(1000);

​tenthSecond$.pipe(

    map(num=>num/10),

    take(3)

).subscribe(console.log);


4. switchMap

The switchMap operator will create a derived observable (called inner observable) from a source observable and emit those values.

When the source emits a new value, it will create a new inner observable and switch to those values instead. What gets unsubscribed from are the inner observables that get created on the fly, and not the source observable.

5.

// RxJS v6+
import { Subject, BehaviorSubject } from 'rxjs';

const subject = new Subject();
const behaviorSubject = new BehaviorSubject('a');

const subjects = [subject, behaviorSubject];
const log = (subjectType: string) => (e: any) => console.log(`${subjectType}${e}`);

//log equals the below log2
const log2 = (subjectType: string)=>{
  return (e: any)=>{
    console.log(`${subjectType}${e}`);
  }
}

console.clear()
console.log('SUBSCRIBE 1');
subject.subscribe(log2('s1 subject'));
behaviorSubject.subscribe(log2('s1 behaviorSubject'));

Monday, March 15, 2021

Angular development with TypeScript note

 Angular development with TypeScript

1. source code

https://github.com/Farata/angulartypescript

forum:

https://forums.manning.com/forums/angular-development-with-typescript-2E

Although most of his books are printed, his Java Programming for Kids, Parents, and Grandparents is available for free download in several languages at http://myflex.org/books/java4kids/java4kids.htm.

2.

Angular is a component-based framework, and any Angular app is a tree of components.

A parent component can pass data to its child by binding the values to the child’s component property. A child component has no knowledge of where the data came from. A child component can pass data to its parent (without knowing who the parent is) by emitting events. This architecture makes components self-contained and reusable.

Most of the business logic of your app is implemented in services, which are classes without a UI. Angular will create instances of your service classes and will inject them into your components.

3.

You don’t need to modify dependencies in the package.json file manually. Run the ng update command, and all dependencies in package.json will be updated, assuming you have the latest version of Angular CLI installed. The process of updating your apps from one Angular version to another is described at https://update.angular.io

4.

ng g c— Generates a new component.

ng g s— Generates a new service.

ng g d— Generates a new directive.

ng g m— Generates a new module.

ng g application— Generates a new app within the same project. This command was introduced in Angular 6.

ng g library— Starting with Angular 6, you can generate a library project.

5.

For cleaner code separation, we usually don’t use a component for code that fetches or manipulates data. An injectable service is the right place for handling data. 

Note that the generated ProductService class is annotated with the @Injectable() decorator. To have Angular instantiate and inject this service into any component, add the following argument to the component’s constructor:

constructor(productService: ProductService){

  // start using the service, e.g. productService.getMyData();

}

Starting from Angular 6, provideIn: 'root' allows you to skip the step of specifying the service in the providers property of the NgModule() decorator.

6.

A directive can’t have its own UI, but can be attached to a component or a regular HTML element to change their visual representation. There are two types of directives in Angular:

Structural— The directive changes the structure of the component’s template. (like *ngFor, *ngIf)

Attribute— The directive changes the behavior or visual representation of an individual component or HTML element.

7.

Angular supports two types of data binding: unidirectional (default) and two-way. With unidirectional data binding, the data is synchronized in one direction: either from the class member variable (property) to the view or from the view event to the class variable or a method that handles the event.

Use square brackets to bind the value from a class variable to a property of an HTML element or an Angular component. 

<span [hidden]="isValid">This field is required</span>

This is unidirectional binding from the class variable to the view.

Remember, square brackets represent property binding, and parentheses represent event binding. To denote two-way binding, surround a template element’s ngModel with both square brackets and parentheses. 

[(ngModel)]="shippingAddress"

8.

In SPAs, you need the ability to modify the URL without forcing the browser to make a server-side request so the application can locate the proper view on the client. Angular offers two location strategies for implementing client-side navigation:

HashLocationStrategy. Changing any character to the right of the hash sign doesn’t cause a direct server-side request

PathLocationStrategy. This is the default location strategy in Angular.

To use hash-based navigation, @NgModule() has to include the providers value:

providers:[{provide: LocationStrategy, useClass: HashLocationStrategy}]

The <router-outlet> specifies the area on the page where the router will render the components (one at a time)


9.

By default the address bar of the browser changes as the user navigates with the router. If you don’t want to show the URL of the current route, use the skipLocationChange directive:

<a [routerLink]="['/product']" skipLocationChange>Product Details</a>


10.

A provider is an instruction to Angular about how to create an instance of an object for future injection into a target component, service, or directive. 

The long version would look like this: providers:[{provide: ProductService, useClass: ProductService}]. You say to Angular, “If you see a class with a constructor that uses the ProductService token, inject the instance of the ProductService class.”

@Injectable() is required only when the service itself has its own dependencies. It instructs Angular to generate additional metadata for this service. 

Providers declared in the @NgModule() decorator of a lazy-loaded module are available within such a module, but not to the entire application. 

providers of eagerly loaded modules are merged with providers of the root module. In other words, Angular has a single injector for all eagerly loaded modules.

11.

    of(1,2,3).subscribe(

      value=>console.log(value),

      err=>console.log(err),

      ()=>console.log("Streaming is over")

    );

    from(beers).pipe(

      map(beer=>beer.price),

      reduce((total,price)=>total+price,10)

    ).subscribe(

      beer=>console.log(beer),

      err=>console.log(err)

    );

12.

In a regular JavaScript app, to get a reference to the DOM element, you use a DOM selector API, document.querySelector(). In Angular, you can use the @ViewChild() decorator to get a reference to an element from a component template.

 <input type="text" #stockSymbol placeholder="Enter stock" >

   @ViewChild('stockSymbol') myInputField: ElementRef;

  constructor(){

  }

  ngAfterViewInit(): void {

    let keyup$ = fromEvent(this.myInputField.nativeElement, 'keyup');

    let keyupValue$ = keyup$.pipe(

      debounceTime(500),

      map(event => event['target'].value)

    ).subscribe(

      stock => this.getStockQuoteFromServer(stock)

    );

  }


  getStockQuoteFromServer(stock: string) {

    console.log(`The price of ${stock} is ${(100 * Math.random()).toFixed(4)}`);

  }

13.

In Angular, HTTP requests return observables. 

Angular doesn’t offer an API to support event bubbling. If event bubbling is important to your app, don’t use EventEmitter; use native DOM events instead.

14.

There are two approaches to working with forms in Angular: template-driven and reactive. 

Because you’re limited to HTML syntax while defining the form, the template-driven approach suits only simple forms.

With the reactive API, You construct the form model object explicitly using the FormControl, FormGroup, and FormArray classes.

To enable reactive forms, add ReactiveFormsModule from @angular/forms to the imports list of NgModule. For template-driven forms, import FormsModule

15.

NgForm is the directive that represents the entire form. It’s automatically attached to every <form> element.

16.

FormControl is an atomic form unit. FormGroup is a collection of FormControl objects and represents either the entire form or its part. When you need to programmatically add (or remove) controls to a form, use FormArray. It’s similar to FormGroup but has a length variable.

17.

[ngModelOptions]= "{updateOn:'blur'}" change/submit

18.

To notify BehaviorSubject about the new value, you use next(), and to notify the store about the new state, you use dispatch(). To get the new state, subscribe to the observable in both cases.

In ngrx apps, the Store service always remains a single source of truth, which may have multiple slices of state.

even though actions can be handled in both a reducer and an effect, only a reducer can change the state of an app.

Thursday, March 11, 2021

OAuth2 and Open Connect ID


OAuth2 and Open Connect ID in plain English, easy to understand 

https://www.youtube.com/watch?v=996OiexHze0

https://oauthdebugger.com





Wednesday, March 10, 2021

ng-book2-angular-6-r68 reading note

 


1. 

you can type the following commands to run any example:

npm install

npm start


2. Make sure node.js, typescript and Angular CLI are installed

npm -v

tsc -v

ng --version

ng    #to show the command list and get help


3. Run the below to create a new project from scratch

ng new angular-hello-world


4.

use the --port flag when running ng serve like this:

ng serve --port 9001


5. To create a new component using Angular CLI

ng generate component hello-world


6.

the ng serve command live-compiles our .ts to a .js file automatically.

Angular uses a concept called “style-encapsulation” which means that styles

specified for a particular component only apply to that component.

@Input() userId!: string; 

Now, the compiler understands that this variable, although not defined at compile time, shall be defined at run-time, and in time, before it is being used.

    <li *ngFor="let lolname of names">

        <app-user-item [name]="lolname"></app-user-item>

    </li>

define template between backticks(`...`) or sepearte file. 

Apostrophe

7. When we run "ng serve", ng will look at the file angular.json to find the entry point to our app.

angular.json specifies a "main" file, which in this case is main.ts

main.ts is the entry-point for our app and it bootstraps our application

We use the AppModule to bootstrap the app. AppModule is specified in src/app/app.module.ts


8. The methods

return a boolean value of false (tells the browser not to propagate the event upwards)


9. deploy

ng build --prod --base-href /

hosting on now:

install now: npm install -g now


10.

any is the default type if we omit typing for a given variable. Having a variable of type any allows

it to receive any kind of value:

var something: any = 'as string';

something = 1;


11.

When methods don’t declare an explicit returning type and return a value, it’s assumed they can

return anything (any type).

In TypeScript you can have only one constructor per class.

.forEach is a method on Array that accepts a function as an argument and calls that

function for each element in the Array.

var data = ['Alice Green', 'Paul Pfifer', 'Louis Blakenship'];

data.forEach(function(line) { console.log(line); });

Fat arrow => functions are a shorthand notation for writing functions.

data.forEach( (line) => console.log(line) );


12.

@Input('shortName') name: string;

@Input('oldAge') age: number;

<my-component [shortName]="myName" [oldAge]="myAge"></my-component>


13.

To create a custom output event we do three things:

1. Specify outputs in the @Component configuration

2. Attach an EventEmitter to the output property

3. Emit an event from the EventEmitter, at the right time


14.

The line [class.selected]="isSelected(myProduct)" is a fun one: Angular allows us to set

classes conditionally on an element using this syntax. This syntax says “add the CSS class selected

if isSelected(myProduct) returns true.” This is a really handy way for us to mark the currently

selected product.


15.

Here when we say @HostBinding('attr.class')

cssClass = 'item'; we’re saying that we want to attach the CSS class item to the host element. The host is the

element this component is attached to.


16.

<span *ngFor="let name of product.department; let i=index">


17.

<div [style.background-color]="'yellow'">

Uses fixed yellow background

</div>

<div [ngStyle]="{color: 'white', 'background-color': 'blue'}">


18.

A FormControl represents a single input field - it is the smallest unit of an Angular form.

FormControls encapsulate the field’s value, and states such as being valid, dirty (changed), or has errors.

<input type="text" [formControl]="name" />


19.

if you import FormsModule, NgForm will get automatically attached to any <form> tags you have in your view.

This is really useful but potentially confusing because it happens behind the scenes.

Learning Angular third edition reading note

 Learning Angular


1. Source code:

https://github.com/PacktPublishing/Learning-Angular--Third-Edition

2.

install VS Code extension "Angular Essentials"

In public methods and properties, we can omit the keyword public.

Remember, no more var; use the let keyword wherever possible.

number defines a floating-point number, as well as hexadecimal, decimal, binary, and octal literals.

you can come up with your own type:

type Animal = 'Cheetah' | 'Lion';

const animal: Animal = 'Cheetah';

3.

function sayHello(name: string): string {

    return 'Hello, ' + name;

}

to annoymous function:

const sayHello = function(name: string): string {

    return 'Hello, ' + name;

}

4.

TypeScript defines that a parameter is optional by adding the ? symbol as a postfix to the parameter name we want to make optional (place last):

function greetMe(name: string, greeting?: string): string {

    if(!greeting) {

        greeting = 'Hello';

    }

    return greeting + ', ' + name;

}

5.

default parameter (put last)

function greetMe(name: string, greeting: string = 'Hello'): string {

    return `${greeting}, ${name}`;

}

6.

rest parameter (put last)

function greetPeople(greeting:string,...names: string[]): string {

    return greeting + "," + names.join(" and ") + "!";

}

console.log(greetPeople("Hello","Ahri","Ashe"));

7.

const oldPerson = { name : 'John' };

const newPerson = { ...oldPerson, age : 20 };

9.

class Car {

    make: string;

    model: string;

    constructor(make: string, model: string) {

        this.make = make;

        this.model = model;

    }

}

TypeScript eliminates this boilerplate by using accessors on the constructor parameters.

class Car {

    constructor(public make: string, public model: string) {}

}

TypeScript will create the respective public fields and make the assignment automatically. 

10.

Can create an instance from an interface

interface A {

    a

}

const instance = <A> { a: 3 };

instance.a = 5;

console.log(instance.a);

This means you can create a mocking library very easily.

11.

To use it, we need to place the ? postfix in the nullable property, as follows:

for (let i = 0; i < hero.powers?.length; i++) {

}

Now, the if-else statement to check for nullable values is not needed anymore.

12.

Each member marked with the export keyword becomes part of the module's public API.

my-service.ts

export class MyService {

    getData() {}

}

export const PI = 3.14;

To use this module and its exported class, we need to import it:

import { MyService, PI } from './my-service';

13.

<span>{{ title }}</span>

same as 

<span [innerText]="title"></span>

while <span [innerText]="'My title'"></span> innerText property is a static string, not a component property.

14.

<p [class.star]="isLiked"></p>

The star class will be added to the paragraph element when the isLiked expression is true. Otherwise, it will be removed from the element. 

15.

template referance variable

<app-hero [name]="hero" #heroCmp (liked)="onLike(true)"></app-hero>

<span {{heroCmp.name}}></span>

16.

When using expressions that evaluate to a boolean value, it is best to use triple equality, ===, over the usual == because === checks not only whether values are equal but also whether types match. For example, 0 == '0' is truthy, whereas 0 === '0' is falsy.

17.

When we define an observable variable, we tend to append the $ sign to the name of the variable. This is a convention that we follow so that we can identify observables in our code efficiently and quickly.

18.

https://github.com/PacktPublishing/Learning-Angular--Third-Edition/tree/master/ch07

npm install angular-in-memory-web-api --save-dev

19.

By default it's for development.

ng build --prod