From a84115cd903660ed8943d8365c00405cb160aba8 Mon Sep 17 00:00:00 2001 From: monkeyWzr Date: Tue, 12 Mar 2024 08:49:25 +0000 Subject: [PATCH] deploy: a5df1d6bed256689eea9ab3617e331484427e986 --- about/index.html | 78 +- categories/index.html | 97 +- categories/index.xml | 2 +- categories/life/index.html | 85 +- categories/life/index.xml | 4 +- categories/life/page/1/index.html | 3 +- categories/notes/index.html | 134 +- categories/notes/index.xml | 10 +- categories/notes/page/1/index.html | 3 +- categories/tech/index.html | 85 +- categories/tech/index.xml | 2 +- categories/tech/page/1/index.html | 3 +- index.html | 148 +- index.xml | 80 +- posts/2016-10-22-z/index.html | 342 +---- .../index.html | 325 +---- posts/2016-11-29-iptables-usage/index.html | 414 +----- posts/2016-12-08-ruby-notes/index.html | 640 ++------- posts/2017-01-11-php-lambada/index.html | 433 ++---- posts/2017-02-18-hash/index.html | 350 +---- posts/2019-01-18-es6/index.html | 874 ++++-------- .../index.html | 429 +----- posts/2019-03-08-es6-bind-trick/index.html | 319 +---- .../index.html | 383 +----- posts/2019-03-22-js-tips/index.html | 457 ++----- .../index.html | 314 +---- posts/2019-10-27-uipath/index.html | 568 +------- .../2019-11-10-encodeuricomponent/index.html | 384 +----- .../index.html | 390 +----- .../2019-11-23-uipath-orchestrator/index.html | 355 +---- posts/2019-12-30-standardml-notes/index.html | 694 ++-------- posts/2020-02-29-racket/index.html | 604 ++------ posts/2020-04-29-subtyping/index.html | 282 +--- posts/2020-05-01-algorithms-graphs/index.html | 1214 ++++------------- .../index.html | 602 +++----- posts/code-block-test/index.html | 555 +++----- posts/index.html | 165 +-- posts/index.xml | 80 +- posts/page/1/index.html | 3 +- posts/page/2/index.html | 164 +-- posts/page/3/index.html | 97 +- tags/algorithms/index.html | 102 +- tags/algorithms/index.xml | 4 +- tags/algorithms/page/1/index.html | 3 +- tags/index.html | 93 +- tags/index.xml | 2 +- tags/javascript/index.html | 133 +- tags/javascript/index.xml | 64 +- tags/javascript/page/1/index.html | 3 +- tags/linux/index.html | 85 +- tags/linux/page/1/index.html | 3 +- tags/php/index.html | 94 +- tags/php/index.xml | 4 +- tags/php/page/1/index.html | 3 +- tags/programming-language/index.html | 85 +- tags/programming-language/index.xml | 2 +- tags/programming-language/page/1/index.html | 3 +- tags/racket/index.html | 85 +- tags/racket/index.xml | 2 +- tags/racket/page/1/index.html | 3 +- tags/rpa/index.html | 101 +- tags/rpa/index.xml | 2 +- tags/rpa/page/1/index.html | 3 +- tags/ruby/index.html | 85 +- tags/ruby/index.xml | 6 +- tags/ruby/page/1/index.html | 3 +- tags/sml/index.html | 85 +- tags/sml/index.xml | 2 +- tags/sml/page/1/index.html | 3 +- tags/test/index.html | 85 +- tags/test/index.xml | 2 +- tags/test/page/1/index.html | 3 +- tags/vue.js/index.html | 85 +- tags/vue.js/index.xml | 2 +- tags/vue.js/page/1/index.html | 3 +- 75 files changed, 1995 insertions(+), 11419 deletions(-) diff --git a/about/index.html b/about/index.html index d2e3b610..04b2a47f 100644 --- a/about/index.html +++ b/about/index.html @@ -1,76 +1,2 @@ - - - - - - - - - - - About me | Cactus theme example - - - - - - - - - - - - - - - - - - -
- - - -
- - - - - \ No newline at end of file +About me | Cactus theme example +
\ No newline at end of file diff --git a/categories/index.html b/categories/index.html index d2f6885e..4f3e5256 100644 --- a/categories/index.html +++ b/categories/index.html @@ -1,92 +1,5 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- - - -
- - - - - \ No newline at end of file +Cactus theme example +
\ No newline at end of file diff --git a/categories/index.xml b/categories/index.xml index beb90d69..55722556 100644 --- a/categories/index.xml +++ b/categories/index.xml @@ -1 +1 @@ -Categories on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/categories/Recent content in Categories on Cactus theme exampleHugo -- gohugo.ioen-usYouSun, 27 Jun 2021 09:00:00 +0000techhttps://www.takuzen.me/hugo-theme-cactus/categories/tech/Sun, 27 Jun 2021 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/categories/tech/noteshttps://www.takuzen.me/hugo-theme-cactus/categories/notes/Sat, 06 Jun 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/categories/notes/lifehttps://www.takuzen.me/hugo-theme-cactus/categories/life/Sat, 22 Oct 2016 16:56:54 +0000https://www.takuzen.me/hugo-theme-cactus/categories/life/ \ No newline at end of file +Categories on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/categories/Recent content in Categories on Cactus theme exampleHugo -- gohugo.ioen-usYouSun, 27 Jun 2021 09:00:00 +0000Techhttps://www.takuzen.me/hugo-theme-cactus/categories/tech/Sun, 27 Jun 2021 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/categories/tech/Noteshttps://www.takuzen.me/hugo-theme-cactus/categories/notes/Sat, 06 Jun 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/categories/notes/Lifehttps://www.takuzen.me/hugo-theme-cactus/categories/life/Sat, 22 Oct 2016 16:56:54 +0000https://www.takuzen.me/hugo-theme-cactus/categories/life/ \ No newline at end of file diff --git a/categories/life/index.html b/categories/life/index.html index bbd4413d..9d4ce6ef 100644 --- a/categories/life/index.html +++ b/categories/life/index.html @@ -1,83 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
-
    -

    2016

    -
  • -
    - -
    - - 幸せ - -
  • -
-
- -
- - - - - \ No newline at end of file +Cactus theme example +
\ No newline at end of file diff --git a/categories/life/index.xml b/categories/life/index.xml index 9ba2bfc1..8e14bdf7 100644 --- a/categories/life/index.xml +++ b/categories/life/index.xml @@ -1,11 +1,11 @@ -life on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/categories/life/Recent content in life on Cactus theme exampleHugo -- gohugo.ioen-usYouSat, 22 Oct 2016 16:56:54 +0000幸せhttps://www.takuzen.me/hugo-theme-cactus/posts/2016-10-22-z/Sat, 22 Oct 2016 16:56:54 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2016-10-22-z/:-) +Life on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/categories/life/Recent content in Life on Cactus theme exampleHugo -- gohugo.ioen-usYouSat, 22 Oct 2016 16:56:54 +0000幸せhttps://www.takuzen.me/hugo-theme-cactus/posts/2016-10-22-z/Sat, 22 Oct 2016 16:56:54 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2016-10-22-z/:-) Look at the stars 抬头仰望满天繁星 Look how they shine for you 看它们为你绽放着 闪烁不息 And everything you do 而你的一颦一举 -Yeah' they were all Yellow +Yeah’ they were all Yellow 却满含胆怯和羞意 I came along 我追随着你的气息 diff --git a/categories/life/page/1/index.html b/categories/life/page/1/index.html index 35211cee..d3ca1b4e 100644 --- a/categories/life/page/1/index.html +++ b/categories/life/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/categories/life/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/categories/life/ + \ No newline at end of file diff --git a/categories/notes/index.html b/categories/notes/index.html index 1ff5a745..d176bd56 100644 --- a/categories/notes/index.html +++ b/categories/notes/index.html @@ -1,132 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/categories/notes/index.xml b/categories/notes/index.xml index 1793cd18..cfb813be 100644 --- a/categories/notes/index.xml +++ b/categories/notes/index.xml @@ -1,8 +1,8 @@ -notes on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/categories/notes/Recent content in notes on Cactus theme exampleHugo -- gohugo.ioen-usYouSat, 06 Jun 2020 09:00:00 +0000Changes to String in java (from 1.7.0_06)https://www.takuzen.me/hugo-theme-cactus/posts/2020-06-06-changes-in-java-string/Sat, 06 Jun 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-06-06-changes-in-java-string/Before 1.7.0_06, String has 4 non static field: +Notes on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/categories/notes/Recent content in Notes on Cactus theme exampleHugo -- gohugo.ioen-usYouSat, 06 Jun 2020 09:00:00 +0000Changes to String in java (from 1.7.0_06)https://www.takuzen.me/hugo-theme-cactus/posts/2020-06-06-changes-in-java-string/Sat, 06 Jun 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-06-06-changes-in-java-string/Before 1.7.0_06, String has 4 non static field: char[] value int[] offset int count int hash Subing.substring create a String by sharing the original String’s internal char[] value and setting offset. This saves memory and makes String.substring run in a constant time($O(1)$). Meanwhile, this feature may cause memory leak1. http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/8deef18bb749/src/share/classes/java/lang/String.java -1public final class String 2 implements java.io.Serializable, Comparable<String>, CharSequence 3{ 4 /** The value is used for character storage.Racket noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Sat, 29 Feb 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Basic 1#lang racket 2(provide (all-defined-out)) 3 4;this is a comment 5 6(define s "hello") 7 8(define x 3) 9(define y (+ x 2)) 10 11(define cube1 12 (lambda (x) 13 (* x (* x x)))) 14 15(define cube2 16 (lambda (x) 17 (* x x x))) 18 19(define (cube3 x) 20 (* x x x)) 21 22(define (pow1 x y) 23 (if (=y 0) 24 1 25 (* x (pow1 x (- y 1))))) 26 27; currying 28(define pow2 29 (lambda (x) 30 (lambda (y) 31 (pow1 x y)))) 32 List Empty list: null () doesn"t work for null but '() does build a list: (list e1 .Standard ML noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Mon, 30 Dec 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Basics Comments (* SML comment *) Variable bindings and Expressions val x = 34; (* static environment: x : int *) (* dynamic environment: x --> 34 *) val y = x + 1; (* Use tilde character instead of minus to reprsent negation *) val z = ~1; (* Integer Division *) val w = y div x Strings: -(* `\n`のようなエスケープシーケンスが利用できる *) val x = "hello\n"; (* 文字列の連結には'^'を使う *) val y = "hello " ^ "world"; An ML program is a sequence of bindings.uipath ノート(三)- uipath orchestratorhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-11-23-uipath-orchestrator/Sat, 23 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-11-23-uipath-orchestrator/利用手順 Official doc: https://docs.uipath.com/robot/docs/from-orchestrator-and-the-orchestrator-settings-window +1public final class String 2 implements java.io.Serializable, Comparable<String>, CharSequence 3{ 4 /** The value is used for character storage. */ 5 private final char value[]; 6 7 /** The offset is the first index of the storage that is used.Racket noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Sat, 29 Feb 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Basic 1#lang racket 2(provide (all-defined-out)) 3 4;this is a comment 5 6(define s "hello") 7 8(define x 3) 9(define y (+ x 2)) 10 11(define cube1 12 (lambda (x) 13 (* x (* x x)))) 14 15(define cube2 16 (lambda (x) 17 (* x x x))) 18 19(define (cube3 x) 20 (* x x x)) 21 22(define (pow1 x y) 23 (if (=y 0) 24 1 25 (* x (pow1 x (- y 1))))) 26 27; currying 28(define pow2 29 (lambda (x) 30 (lambda (y) 31 (pow1 x y)))) List Empty list: null () doesn"t work for null but '() does build a list: (list e1 .Standard ML noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Mon, 30 Dec 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Basics Comments (* SML comment *) Variable bindings and Expressions val x = 34; (* static environment: x : int *) (* dynamic environment: x --> 34 *) val y = x + 1; (* Use tilde character instead of minus to reprsent negation *) val z = ~1; (* Integer Division *) val w = y div x Strings: +(* `\n`のようなエスケープシーケンスが利用できる *) val x = "hello\n"; (* 文字列の連結には'^'を使う *) val y = "hello " ^ "world"; An ML program is a sequence of bindings.uipath ノート(三)- uipath orchestratorhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-11-23-uipath-orchestrator/Sat, 23 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-11-23-uipath-orchestrator/利用手順 Official doc: https://docs.uipath.com/robot/docs/from-orchestrator-and-the-orchestrator-settings-window マシンを追加 マシン側でマシン名とユーザ名を確認 C:\Users\user>hostname DESKTOP-ABCDE5F C:\Users\user>whoami desktop-abcde5f\user C:\Users\user> 追加完了後、マシンキーを取得する。 ロボットを登録 Type: studio (開発用?) Domain/Username: 上記のユーザ名 ローカルのorchestrator設定 Uipath Robotを開き⇒orchestratorの設定で、上記のマシンキーを入力する。 orchestrator URLに https://platform.uipath.com/ を入力する. Invalid machine keyというエラーが出たら、下記のようなURLを試す: @@ -26,7 +26,7 @@ UI インタラクション: シーケンス 環境設定を Config ファイルに格納 不要になったアプリケーションを終了させることで、常にクリーンな状態を維持しましょう。JavaScript URI エンコーディングhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-11-10-encodeuricomponent/Sun, 10 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-11-10-encodeuricomponent/まとめ encodeURI()とencodeURIComponent()はRFC 2396準拠である。 encodeURI() は完全な URI を表すのに必要な文字 (Reserved Characters) はエンコードしません。 また、予約されていないが “そのまま” URI に使用できる(Unreserved Marks) 文字をエンコードしません。 encodeURIComponent() は “Unreserved Marks” 文字をエンコードしません。 1var set1 = ";,/?:@&=+$#"; // Reserved Characters 2var set2 = "-_.!~*'()"; // Unreserved Marks 3 4console.log(encodeURI(set1)); // ;,/?:@&=+$ 5console.log(encodeURI(set2)); // -_.!~*'() 6 7console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24 8console.log(encodeURIComponent(set2)); // -_.!~*'() rfc2396 appendix-A https://tools.ietf.org/html/rfc2396#appendix-A -URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] absoluteURI = scheme ":" ( hier_part | opaque_part ) relativeURI = ( net_path | abs_path | rel_path ) [ "?uipath ノート(一)https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/Sun, 27 Oct 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/変数 Int32 String Boolean GenericValue 参照 UiPath Studio には GenericValue 変数の自動変換メカニズムがあり、式を正しく定義することで、目的の結果を得ることができます。式の最初の要素は、Studio から操作するガイドラインとして使用されることを考慮してください。例えば、2 つの GenericValue 変数を追加し、式の最初の変数が String として定義されてた場合、最初に代入された値を元に 2 つの値を結合し、文字列となります。 Integer として定義した場合の結果は、合計の値となります。 +URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] absoluteURI = scheme ":" ( hier_part | opaque_part ) relativeURI = ( net_path | abs_path | rel_path ) [ "?uipath ノート(一)https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/Sun, 27 Oct 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/変数 Int32 String Boolean GenericValue 参照 UiPath Studio には GenericValue 変数の自動変換メカニズムがあり、式を正しく定義することで、目的の結果を得ることができます。式の最初の要素は、Studio から操作するガイドラインとして使用されることを考慮してください。例えば、2 つの GenericValue 変数を追加し、式の最初の変数が String として定義されてた場合、最初に代入された値を元に 2 つの値を結合し、文字列となります。 Integer として定義した場合の結果は、合計の値となります。 Array DataTime DataTable .Net 変数型を参照して探す方法 アクティビティ レイアウトダイアグラム シーエンス: より高度で複雑な自動化に向こう フローチャート: シンプルな自動化プロジェクトに適している ステートマシン Global Exception Handler (グローバル例外ハンドラー) 参照:https://docs.uipath.com/studio/lang-ja/docs/workflow-design -選択肢 条件分岐(If): シーケンス用条件分岐 フロー条件分岐(flow desicion): フローチャート用条件分岐 フロースイッチ (Flow Switch) 繰り返し 繰り返し(前判定)(While) 繰り返し(後判定)(Do While) 繰り返し(コレクションの各要素)(For Each) データ操作 CSVを読み込み(Read CSV) オプションにエンコーディングを指定できる(日本語データがある場合、"SHIFT-JIS"を指定する) 列名を含める(IncludeColumnNames)を指定できる 出力タイプ:System. \ No newline at end of file +選択肢 条件分岐(If): シーケンス用条件分岐 フロー条件分岐(flow desicion): フローチャート用条件分岐 フロースイッチ (Flow Switch) 繰り返し 繰り返し(前判定)(While) 繰り返し(後判定)(Do While) 繰り返し(コレクションの各要素)(For Each) データ操作 CSVを読み込み(Read CSV) オプションにエンコーディングを指定できる(日本語データがある場合、"SHIFT-JIS"を指定する) 列名を含める(IncludeColumnNames)を指定できる 出力タイプ:System.Data.DataTable Microsoft Docs Selectメソッドで半角スペースを含む列名で指定する場合、半角スペースが特殊文字ではなく文字列として認識されるため、[]で列名を囲う Names.Select("[メンバー ステータス] = 'Yes'") その他 メッセージボックス 代入(assign) 待機 (Delay) 入力ダイアログ(input dialog): フォルダーを選択(Select Folder) 一行を書き込み(Write Line): Debug用? アプリケーションを開く(Open Application) ブラウザを開く(Open Browser) ブラウザーにアタッチ(Attach Browser) 文字を入力(Type Into) ハイライト(Highlight) アンカーベース(Anchor Base) スクリーンショットをと撮る(Take Screenshot) 要素の有無を検出(Element Exists) 要素の消滅を待つ(Wait Element Vanish) レコーディング機能 [○]レコーディング可 \ No newline at end of file diff --git a/categories/notes/page/1/index.html b/categories/notes/page/1/index.html index 14a76fd4..904f5410 100644 --- a/categories/notes/page/1/index.html +++ b/categories/notes/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/categories/notes/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/categories/notes/ + \ No newline at end of file diff --git a/categories/tech/index.html b/categories/tech/index.html index 49e7456c..807d35ce 100644 --- a/categories/tech/index.html +++ b/categories/tech/index.html @@ -1,83 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/categories/tech/index.xml b/categories/tech/index.xml index b3225841..10f46f97 100644 --- a/categories/tech/index.xml +++ b/categories/tech/index.xml @@ -1,4 +1,4 @@ -tech on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/categories/tech/Recent content in tech on Cactus theme exampleHugo -- gohugo.ioen-usYouSun, 27 Jun 2021 09:00:00 +0000Code Block Testhttps://www.takuzen.me/hugo-theme-cactus/posts/code-block-test/Sun, 27 Jun 2021 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/code-block-test/String +Tech on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/categories/tech/Recent content in Tech on Cactus theme exampleHugo -- gohugo.ioen-usYouSun, 27 Jun 2021 09:00:00 +0000Code Block Testhttps://www.takuzen.me/hugo-theme-cactus/posts/code-block-test/Sun, 27 Jun 2021 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/code-block-test/String Using indents: text text text Fenced code block: text text <tag> Fenced code block with language (lineNumbersInTable = false): diff --git a/categories/tech/page/1/index.html b/categories/tech/page/1/index.html index 3b91a8f0..6f2a21ab 100644 --- a/categories/tech/page/1/index.html +++ b/categories/tech/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/categories/tech/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/categories/tech/ + \ No newline at end of file diff --git a/index.html b/index.html index 431af54c..91bc5e23 100644 --- a/index.html +++ b/index.html @@ -1,139 +1,21 @@ - - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
-Hugo is a general-purpose website framework. Technically speaking, Hugo is a static site generator. Unlike systems that dynamically build a page with each visitor request, Hugo builds pages when you create or update your content. Since websites are viewed far more often than they are edited, Hugo is designed to provide an optimal viewing experience for your website’s end users and an ideal writing experience for website authors. -

Find me on - - - -, - - - -and - - - -. -

-
-
-Writings +Cactus theme example +
Hugo is a general-purpose website framework. Technically speaking, Hugo is a static site generator. Unlike systems that dynamically build a page with each visitor request, Hugo builds pages when you create or update your content. Since websites are viewed far more often than they are edited, Hugo is designed to provide an optimal viewing experience for your website’s end users and an ideal writing experience for website authors.

Find me on + +, + +and + +.

Writings Topics - -Algorithms +Algorithms JavaScript Linux -php -programming language -racket +Php +Programming Language +Racket RPA -ruby +Ruby SML -test +Test Vue.js - -Most recent - -
-
-Projects -
    -
  • -Hugo: The world’s fastest framework for building websites. -
  • -
  • -Hugo Themes: A curated directory of Hugo themes -
  • -
-
- -
- - - - - \ No newline at end of file +Most recent
Projects
  • Hugo: The world’s fastest framework for building websites.
  • Hugo Themes: A curated directory of Hugo themes
\ No newline at end of file diff --git a/index.xml b/index.xml index f5dafbd8..8ab42459 100644 --- a/index.xml +++ b/index.xml @@ -5,8 +5,8 @@ text text <tag> Fenced code block with language (lineNumbersInTabl 1// JavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJava 2public final class String 3 implements java.io.Serializable, Comparable<String>, CharSequence 4{ 5 /** The value is used for character storage. */ 6 private final char value[]; 7 8 /** The offset is the first index of the storage that is used. */ 9 private final int offset; 10 11 /** The count is the number of characters in the String.
Changes to String in java (from 1.7.0_06)https://www.takuzen.me/hugo-theme-cactus/posts/2020-06-06-changes-in-java-string/Sat, 06 Jun 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-06-06-changes-in-java-string/Before 1.7.0_06, String has 4 non static field: char[] value int[] offset int count int hash Subing.substring create a String by sharing the original String&rsquo;s internal char[] value and setting offset. This saves memory and makes String.substring run in a constant time($O(1)$). Meanwhile, this feature may cause memory leak1. http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/8deef18bb749/src/share/classes/java/lang/String.java -1public final class String 2 implements java.io.Serializable, Comparable&lt;String&gt;, CharSequence 3{ 4 /** The value is used for character storage.Algorithms - Graphshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-05-01-algorithms-graphs/Fri, 01 May 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-05-01-algorithms-graphs/Undirected Graphs Some problems Path Shortest path Cycle Ehler tour: A cycle that uses each edge excatly once. Hamilton tour: A cycle that uses each vertex exactly once classical NP-complete problem. Connectivity MST: Biconnectivity: A vertex whose removal disconnects the graph Planarity Graph isomorphism: Are two graphs identical? No one knows so far. A lonstanding open problem Representations Real-world graphs tend to be sparse (huge number of vertices, small average vertex degree).Programming Language - Subtypinghttps://www.takuzen.me/hugo-theme-cactus/posts/2020-04-29-subtyping/Wed, 29 Apr 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-04-29-subtyping/Some Good Subtyping Rules Width subtyping: A supertype can have a subset of fields with the same types, i.e., a subtype can have extra fields. Permutation subtypings: A supertype can have the same set of fields with the same types in a different order. Transitivity: if t1 is subtype of t2, and t2 is subtype of t3, then t1 is subtype of t3. Reflexivity: Every type is a subtype of itself.Racket noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Sat, 29 Feb 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Basic 1#lang racket 2(provide (all-defined-out)) 3 4;this is a comment 5 6(define s &#34;hello&#34;) 7 8(define x 3) 9(define y (+ x 2)) 10 11(define cube1 12 (lambda (x) 13 (* x (* x x)))) 14 15(define cube2 16 (lambda (x) 17 (* x x x))) 18 19(define (cube3 x) 20 (* x x x)) 21 22(define (pow1 x y) 23 (if (=y 0) 24 1 25 (* x (pow1 x (- y 1))))) 26 27; currying 28(define pow2 29 (lambda (x) 30 (lambda (y) 31 (pow1 x y)))) 32 List Empty list: null () doesn&quot;t work for null but '() does build a list: (list e1 .Standard ML noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Mon, 30 Dec 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Basics Comments (* SML comment *) Variable bindings and Expressions val x = 34; (* static environment: x : int *) (* dynamic environment: x --&gt; 34 *) val y = x + 1; (* Use tilde character instead of minus to reprsent negation *) val z = ~1; (* Integer Division *) val w = y div x Strings: -(* `\n`のようなエスケープシーケンスが利用できる *) val x = &quot;hello\n&quot;; (* 文字列の連結には'^'を使う *) val y = &quot;hello &quot; ^ &quot;world&quot;; An ML program is a sequence of bindings.uipath ノート(三)- uipath orchestratorhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-11-23-uipath-orchestrator/Sat, 23 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-11-23-uipath-orchestrator/利用手順 Official doc: https://docs.uipath.com/robot/docs/from-orchestrator-and-the-orchestrator-settings-window +1public final class String 2 implements java.io.Serializable, Comparable&lt;String&gt;, CharSequence 3{ 4 /** The value is used for character storage. */ 5 private final char value[]; 6 7 /** The offset is the first index of the storage that is used.Algorithms - Graphshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-05-01-algorithms-graphs/Fri, 01 May 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-05-01-algorithms-graphs/Undirected Graphs Some problems Path Shortest path Cycle Ehler tour: A cycle that uses each edge excatly once. Hamilton tour: A cycle that uses each vertex exactly once classical NP-complete problem. Connectivity MST: Biconnectivity: A vertex whose removal disconnects the graph Planarity Graph isomorphism: Are two graphs identical? No one knows so far. A lonstanding open problem Representations Real-world graphs tend to be sparse (huge number of vertices, small average vertex degree).Programming Language - Subtypinghttps://www.takuzen.me/hugo-theme-cactus/posts/2020-04-29-subtyping/Wed, 29 Apr 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-04-29-subtyping/Some Good Subtyping Rules Width subtyping: A supertype can have a subset of fields with the same types, i.e., a subtype can have extra fields. Permutation subtypings: A supertype can have the same set of fields with the same types in a different order. Transitivity: if t1 is subtype of t2, and t2 is subtype of t3, then t1 is subtype of t3. Reflexivity: Every type is a subtype of itself.Racket noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Sat, 29 Feb 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Basic 1#lang racket 2(provide (all-defined-out)) 3 4;this is a comment 5 6(define s &#34;hello&#34;) 7 8(define x 3) 9(define y (+ x 2)) 10 11(define cube1 12 (lambda (x) 13 (* x (* x x)))) 14 15(define cube2 16 (lambda (x) 17 (* x x x))) 18 19(define (cube3 x) 20 (* x x x)) 21 22(define (pow1 x y) 23 (if (=y 0) 24 1 25 (* x (pow1 x (- y 1))))) 26 27; currying 28(define pow2 29 (lambda (x) 30 (lambda (y) 31 (pow1 x y)))) List Empty list: null () doesn&quot;t work for null but '() does build a list: (list e1 .Standard ML noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Mon, 30 Dec 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Basics Comments (* SML comment *) Variable bindings and Expressions val x = 34; (* static environment: x : int *) (* dynamic environment: x --&gt; 34 *) val y = x + 1; (* Use tilde character instead of minus to reprsent negation *) val z = ~1; (* Integer Division *) val w = y div x Strings: +(* `\n`のようなエスケープシーケンスが利用できる *) val x = &#34;hello\n&#34;; (* 文字列の連結には&#39;^&#39;を使う *) val y = &#34;hello &#34; ^ &#34;world&#34;; An ML program is a sequence of bindings.uipath ノート(三)- uipath orchestratorhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-11-23-uipath-orchestrator/Sat, 23 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-11-23-uipath-orchestrator/利用手順 Official doc: https://docs.uipath.com/robot/docs/from-orchestrator-and-the-orchestrator-settings-window マシンを追加 マシン側でマシン名とユーザ名を確認 C:\Users\user&gt;hostname DESKTOP-ABCDE5F C:\Users\user&gt;whoami desktop-abcde5f\user C:\Users\user&gt; 追加完了後、マシンキーを取得する。 ロボットを登録 Type: studio (開発用?) Domain/Username: 上記のユーザ名 ローカルのorchestrator設定 Uipath Robotを開き⇒orchestratorの設定で、上記のマシンキーを入力する。 orchestrator URLに https://platform.uipath.com/ を入力する. Invalid machine keyというエラーが出たら、下記のようなURLを試す: @@ -30,10 +30,10 @@ UI インタラクション: シーケンス 環境設定を Config ファイルに格納 不要になったアプリケーションを終了させることで、常にクリーンな状態を維持しましょう。JavaScript URI エンコーディングhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-11-10-encodeuricomponent/Sun, 10 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-11-10-encodeuricomponent/まとめ encodeURI()とencodeURIComponent()はRFC 2396準拠である。 encodeURI() は完全な URI を表すのに必要な文字 (Reserved Characters) はエンコードしません。 また、予約されていないが &ldquo;そのまま&rdquo; URI に使用できる(Unreserved Marks) 文字をエンコードしません。 encodeURIComponent() は &ldquo;Unreserved Marks&rdquo; 文字をエンコードしません。 1var set1 = &#34;;,/?:@&amp;=+$#&#34;; // Reserved Characters 2var set2 = &#34;-_.!~*&#39;()&#34;; // Unreserved Marks 3 4console.log(encodeURI(set1)); // ;,/?:@&amp;=+$ 5console.log(encodeURI(set2)); // -_.!~*&#39;() 6 7console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24 8console.log(encodeURIComponent(set2)); // -_.!~*&#39;() rfc2396 appendix-A https://tools.ietf.org/html/rfc2396#appendix-A -URI-reference = [ absoluteURI | relativeURI ] [ &quot;#&quot; fragment ] absoluteURI = scheme &quot;:&quot; ( hier_part | opaque_part ) relativeURI = ( net_path | abs_path | rel_path ) [ &quot;?uipath ノート(一)https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/Sun, 27 Oct 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/変数 Int32 String Boolean GenericValue 参照 UiPath Studio には GenericValue 変数の自動変換メカニズムがあり、式を正しく定義することで、目的の結果を得ることができます。式の最初の要素は、Studio から操作するガイドラインとして使用されることを考慮してください。例えば、2 つの GenericValue 変数を追加し、式の最初の変数が String として定義されてた場合、最初に代入された値を元に 2 つの値を結合し、文字列となります。 Integer として定義した場合の結果は、合計の値となります。 +URI-reference = [ absoluteURI | relativeURI ] [ &#34;#&#34; fragment ] absoluteURI = scheme &#34;:&#34; ( hier_part | opaque_part ) relativeURI = ( net_path | abs_path | rel_path ) [ &#34;?uipath ノート(一)https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/Sun, 27 Oct 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/変数 Int32 String Boolean GenericValue 参照 UiPath Studio には GenericValue 変数の自動変換メカニズムがあり、式を正しく定義することで、目的の結果を得ることができます。式の最初の要素は、Studio から操作するガイドラインとして使用されることを考慮してください。例えば、2 つの GenericValue 変数を追加し、式の最初の変数が String として定義されてた場合、最初に代入された値を元に 2 つの値を結合し、文字列となります。 Integer として定義した場合の結果は、合計の値となります。 Array DataTime DataTable .Net 変数型を参照して探す方法 アクティビティ レイアウトダイアグラム シーエンス: より高度で複雑な自動化に向こう フローチャート: シンプルな自動化プロジェクトに適している ステートマシン Global Exception Handler (グローバル例外ハンドラー) 参照:https://docs.uipath.com/studio/lang-ja/docs/workflow-design -選択肢 条件分岐(If): シーケンス用条件分岐 フロー条件分岐(flow desicion): フローチャート用条件分岐 フロースイッチ (Flow Switch) 繰り返し 繰り返し(前判定)(While) 繰り返し(後判定)(Do While) 繰り返し(コレクションの各要素)(For Each) データ操作 CSVを読み込み(Read CSV) オプションにエンコーディングを指定できる(日本語データがある場合、&quot;SHIFT-JIS&quot;を指定する) 列名を含める(IncludeColumnNames)を指定できる 出力タイプ:System.JavaScript Comparison operation at a glancehttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-28-javascript-comparison/Thu, 28 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-28-javascript-comparison/When given a scenario like: +選択肢 条件分岐(If): シーケンス用条件分岐 フロー条件分岐(flow desicion): フローチャート用条件分岐 フロースイッチ (Flow Switch) 繰り返し 繰り返し(前判定)(While) 繰り返し(後判定)(Do While) 繰り返し(コレクションの各要素)(For Each) データ操作 CSVを読み込み(Read CSV) オプションにエンコーディングを指定できる(日本語データがある場合、&quot;SHIFT-JIS&quot;を指定する) 列名を含める(IncludeColumnNames)を指定できる 出力タイプ:System.Data.DataTable Microsoft Docs Selectメソッドで半角スペースを含む列名で指定する場合、半角スペースが特殊文字ではなく文字列として認識されるため、[]で列名を囲う Names.Select(&#34;[メンバー ステータス] = &#39;Yes&#39;&#34;) その他 メッセージボックス 代入(assign) 待機 (Delay) 入力ダイアログ(input dialog): フォルダーを選択(Select Folder) 一行を書き込み(Write Line): Debug用? アプリケーションを開く(Open Application) ブラウザを開く(Open Browser) ブラウザーにアタッチ(Attach Browser) 文字を入力(Type Into) ハイライト(Highlight) アンカーベース(Anchor Base) スクリーンショットをと撮る(Take Screenshot) 要素の有無を検出(Element Exists) 要素の消滅を待つ(Wait Element Vanish) レコーディング機能 [○]レコーディング可JavaScript Comparison operation at a glancehttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-28-javascript-comparison/Thu, 28 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-28-javascript-comparison/When given a scenario like: 1console.log(null &gt; -1) //true It produces true, which makes me think null is treated as 0. But when I run: 1console.log(null == 0) // false 2console.log(null &gt; 0) // false 3console.log(null &lt; 0) // false They all output false! I googled a lot and finally found answers in Ecma-262 Specification. @@ -45,61 +45,61 @@ The comparison x == y, where x and y are values, produces true or false. Such a <p>The &ldquo;cool kids&rdquo; in JavaScript would generally pronounce <code>__proto__</code> as &ldquo;<strong>dunder proto</strong>&rdquo;.</p> </blockquote> <p><a href="https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript">https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript</a></p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span>( <span style="color:#ff79c6">new</span> Foo ).<span style="color:#bd93f9">__</span>proto__ <span style="color:#ff79c6">===</span> Foo.prototype; <span style="color:#6272a4">// true -</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span style="color:#6272a4"></span>( <span style="color:#ff79c6">new</span> Foo ).prototype <span style="color:#ff79c6">===</span> <span style="color:#ff79c6">undefined</span>; <span style="color:#6272a4">// true -</span></code></pre></div>Bind specific arguments of a functionhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-es6-bind-trick/Fri, 08 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-es6-bind-trick/To bind specific (nth) arguments of a function, we can write a decorator instead of using Function.bind(): +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span>( <span style="color:#ff79c6">new</span> Foo ).__proto__ <span style="color:#ff79c6">===</span> Foo.prototype; <span style="color:#6272a4">// true +</span></span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span><span style="color:#6272a4"></span>( <span style="color:#ff79c6">new</span> Foo ).prototype <span style="color:#ff79c6">===</span> <span style="color:#ff79c6">undefined</span>; <span style="color:#6272a4">// true +</span></span></span></code></pre></div>Bind specific arguments of a functionhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-es6-bind-trick/Fri, 08 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-es6-bind-trick/To bind specific (nth) arguments of a function, we can write a decorator instead of using Function.bind(): 1function func(p1, p2, p3) { 2 console.log(p1, p2, p3); 3} 4// the binding starts after however many are passed in. 5function decorator(...bound_args) { 6 return function(...args) { 7 return func(...args, ...bound_args); 8 }; 9} 10 11// bind the last parameter 12let f = decorator(&#34;3&#34;); 13f(&#34;a&#34;, &#34;b&#34;); // a b 3 14 15// bind the last two parameter 16let f2 = decorator(&#34;2&#34;, &#34;3&#34;) 17f2(&#34;a&#34;); // a 2 3 Even if we want to bind just the nth argument, we can do as follows:Object.assign() with accessor descriptorhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-object-assign-with-accessor-descriptor/Fri, 08 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-object-assign-with-accessor-descriptor/<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Copying_accessors">MDN docs:</a></p> <blockquote> <p>The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties versus just copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.</p> </blockquote> <p>For example</p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 1</span><span style="color:#ff79c6">class</span> Cat { -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 2</span> constructor(name) { -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 3</span> <span style="color:#ff79c6">this</span>.<span style="color:#bd93f9">_</span>name <span style="color:#ff79c6">=</span> name; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 4</span> } -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 5</span> -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 6</span> get name() { -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 7</span> <span style="color:#ff79c6">return</span> <span style="color:#ff79c6">this</span>.<span style="color:#bd93f9">_</span>name; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 8</span> } -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 9</span> set name(value) { -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">10</span> <span style="color:#ff79c6">this</span>.<span style="color:#bd93f9">_</span>name <span style="color:#ff79c6">=</span> value; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">11</span> } -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">12</span>} -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">13</span> -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">14</span><span style="color:#8be9fd;font-style:italic">let</span> nyannko <span style="color:#ff79c6">=</span> <span style="color:#ff79c6">new</span> Cat(<span style="color:#f1fa8c">&#34;nyannko&#34;</span>); -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">15</span><span style="color:#8be9fd;font-style:italic">let</span> copy <span style="color:#ff79c6">=</span> <span style="color:#8be9fd;font-style:italic">Object</span>.assign({}, nyannko) -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">16</span> -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">17</span>console.log(nyannko.name) <span style="color:#6272a4">// nyannko -</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">18</span><span style="color:#6272a4"></span>console.log(copy.name) <span style="color:#6272a4">// undefined -</span></code></pre></div><p>The <code>name</code> property is lost.</p>VueのNavigation Guardshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Fri, 25 Jan 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Navigation guards are provided by vue-router. Three ways to hook: +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-js" data-lang="js"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 1</span><span><span style="color:#ff79c6">class</span> Cat { +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 2</span><span> constructor(name) { +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 3</span><span> <span style="color:#ff79c6">this</span>._name <span style="color:#ff79c6">=</span> name; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 4</span><span> } +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 5</span><span> +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 6</span><span> get name() { +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 7</span><span> <span style="color:#ff79c6">return</span> <span style="color:#ff79c6">this</span>._name; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 8</span><span> } +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 9</span><span> set name(value) { +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">10</span><span> <span style="color:#ff79c6">this</span>._name <span style="color:#ff79c6">=</span> value; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">11</span><span> } +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">12</span><span>} +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">13</span><span> +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">14</span><span><span style="color:#8be9fd;font-style:italic">let</span> nyannko <span style="color:#ff79c6">=</span> <span style="color:#ff79c6">new</span> Cat(<span style="color:#f1fa8c">&#34;nyannko&#34;</span>); +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">15</span><span><span style="color:#8be9fd;font-style:italic">let</span> copy <span style="color:#ff79c6">=</span> <span style="color:#8be9fd;font-style:italic">Object</span>.assign({}, nyannko) +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">16</span><span> +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">17</span><span>console.log(nyannko.name) <span style="color:#6272a4">// nyannko +</span></span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">18</span><span><span style="color:#6272a4"></span>console.log(copy.name) <span style="color:#6272a4">// undefined +</span></span></span></code></pre></div><p>The <code>name</code> property is lost.</p>VueのNavigation Guardshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Fri, 25 Jan 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Navigation guards are provided by vue-router. Three ways to hook: globally per-route in-component NOTE: -Params or query changes won&rsquo;t trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard. Make sure to always call the next function, otherwise the hook will never be resolved. Global 1const router = new VueRouter({ ... }) 2 3// Before Guards 4router.ES6についてhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-01-18-es6/Fri, 18 Jan 2019 16:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-01-18-es6/<h2 id="overview">Overview</h2> +Params or query changes won&rsquo;t trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard. Make sure to always call the next function, otherwise the hook will never be resolved. Global 1const router = new VueRouter({ ... }) 2 3// Before Guards 4router.beforeEach((to, from, next) =&gt; { 5 // .ES6についてhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-01-18-es6/Fri, 18 Jan 2019 16:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-01-18-es6/<h2 id="overview">Overview</h2> <p><a href="https://github.com/lukehoban/es6features#readme">https://github.com/lukehoban/es6features#readme</a></p> <p><a href="http://help.wtf/es6">http://help.wtf/es6</a></p> <p><a href="http://es6-features.org">http://es6-features.org</a></p> <h2 id="string">String</h2> <h3 id="stringx-is-deprecated-use-stringprototypex-instead">String.x is deprecated; use String.prototype.x instead.</h3> <p>非推奨の構文:</p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Javascript" data-lang="Javascript"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span style="color:#8be9fd;font-style:italic">var</span> num <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">15</span>; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span style="color:#8be9fd;font-style:italic">String</span>.replace(num, <span style="color:#f1fa8c">/5/</span>, <span style="color:#f1fa8c">&#39;2&#39;</span>); -</code></pre></div><p>標準の構文:</p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Javascript" data-lang="Javascript"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span style="color:#8be9fd;font-style:italic">var</span> num <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">15</span>; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span style="color:#8be9fd;font-style:italic">String</span>(num).replace(<span style="color:#f1fa8c">/5/</span>, <span style="color:#f1fa8c">&#39;2&#39;</span>); -</code></pre></div><h3 id="template-literal">Template literal</h3> +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-Javascript" data-lang="Javascript"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span><span style="color:#8be9fd;font-style:italic">var</span> num <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">15</span>; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span><span style="color:#8be9fd;font-style:italic">String</span>.replace(num, <span style="color:#f1fa8c">/5/</span>, <span style="color:#f1fa8c">&#39;2&#39;</span>); +</span></span></code></pre></div><p>標準の構文:</p> +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-Javascript" data-lang="Javascript"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span><span style="color:#8be9fd;font-style:italic">var</span> num <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">15</span>; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span><span style="color:#8be9fd;font-style:italic">String</span>(num).replace(<span style="color:#f1fa8c">/5/</span>, <span style="color:#f1fa8c">&#39;2&#39;</span>); +</span></span></code></pre></div><h3 id="template-literal">Template literal</h3> <p>Nesting templates:</p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Javascript" data-lang="Javascript"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span style="color:#ff79c6">const</span> classes <span style="color:#ff79c6">=</span> <span style="color:#f1fa8c">`header </span><span style="color:#f1fa8c">${</span> isLargeScreen() <span style="color:#ff79c6">?</span> <span style="color:#f1fa8c">&#39;&#39;</span> <span style="color:#ff79c6">:</span> <span style="color:#f1fa8c">`icon-</span><span style="color:#f1fa8c">${</span>item.isCollapsed <span style="color:#ff79c6">?</span> <span style="color:#f1fa8c">&#39;expander&#39;</span> <span style="color:#ff79c6">:</span> <span style="color:#f1fa8c">&#39;collapser&#39;</span><span style="color:#f1fa8c">}</span><span style="color:#f1fa8c">`</span> <span style="color:#f1fa8c">}</span><span style="color:#f1fa8c">`</span>; -</code></pre></div>java散列知识点总结https://www.takuzen.me/hugo-theme-cactus/posts/2017-02-18-hash/Sat, 18 Feb 2017 19:19:01 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2017-02-18-hash/java 的根类 Object 具有 hashcode 方法。当 equal 方法被重写时也应当重写 hashcode 方法。 +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-Javascript" data-lang="Javascript"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span><span style="color:#ff79c6">const</span> classes <span style="color:#ff79c6">=</span> <span style="color:#f1fa8c">`header </span><span style="color:#f1fa8c">${</span> isLargeScreen() <span style="color:#ff79c6">?</span> <span style="color:#f1fa8c">&#39;&#39;</span> <span style="color:#ff79c6">:</span> <span style="color:#f1fa8c">`icon-</span><span style="color:#f1fa8c">${</span>item.isCollapsed <span style="color:#ff79c6">?</span> <span style="color:#f1fa8c">&#39;expander&#39;</span> <span style="color:#ff79c6">:</span> <span style="color:#f1fa8c">&#39;collapser&#39;</span><span style="color:#f1fa8c">}</span><span style="color:#f1fa8c">`</span> <span style="color:#f1fa8c">}</span><span style="color:#f1fa8c">`</span>; +</span></span></code></pre></div>java散列知识点总结https://www.takuzen.me/hugo-theme-cactus/posts/2017-02-18-hash/Sat, 18 Feb 2017 19:19:01 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2017-02-18-hash/java 的根类 Object 具有 hashcode 方法。当 equal 方法被重写时也应当重写 hashcode 方法。 基本数据类型的散列码 byte short int char 类型的搜索键将会转换为 int。 float 类型的搜索键使用 Float.floatToIntBits(key) 作为散列码。 long 类型的搜索键会进行折叠操作,如下: 1iny hashCode = (int) (key ^ (key &gt;&gt; 32)); double 类型的搜索键会使用 Double.doubleToLongBits(key) 方法转换为 long 类型然后再进行折叠。 字符串类型的散列码 对于字符串一般使用多项式散列码进行计算, 这里放个公式的图 b的较好取值为31,33,37,39,41。在 java String 类中 b 取31。 -1public static int hash(String key, int tableSize) 2{ 3 int hashVal = 0; 4 5 for (int i = 0; i &lt; key.php的闭包特性https://www.takuzen.me/hugo-theme-cactus/posts/2017-01-11-php-lambada/Wed, 11 Jan 2017 18:39:17 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2017-01-11-php-lambada/闭包和匿名函数在PHP 5.3.0引入,并且PHP将两者视为相同的概念。闭包其实是伪装成函数的对象,它的实质其实是Closure实例。 +1public static int hash(String key, int tableSize) 2{ 3 int hashVal = 0; 4 5 for (int i = 0; i &lt; key.length(); i++) 6 hashVal = 37*hashVal + key.php的闭包特性https://www.takuzen.me/hugo-theme-cactus/posts/2017-01-11-php-lambada/Wed, 11 Jan 2017 18:39:17 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2017-01-11-php-lambada/闭包和匿名函数在PHP 5.3.0引入,并且PHP将两者视为相同的概念。闭包其实是伪装成函数的对象,它的实质其实是Closure实例。 创建闭包非常简单: 1$c = function($name) { 2 return sprintf(&#34;Hello World! Hello %s!&#34;, $name); 3}; 4 5echo $c(&#39;PHP&#39;); 使用use对闭包附加状态,多个参数使用,分隔: -1function callPerson($name) { 2 return function($about) use ($name) { 3 return sprintf(&#34;%s, %s&#34;, $name, $about); 4 } 5} 6 7$triver = callPerson(&#39;Triver&#39;); 8echo $triver(&#34;slow down, please!!&#34;); 9 附加的变量会被封装到闭包内,即使返回的闭包队形已经跳出了callPerson()的作用域也仍然会记住$name的值。 +1function callPerson($name) { 2 return function($about) use ($name) { 3 return sprintf(&#34;%s, %s&#34;, $name, $about); 4 } 5} 6 7$triver = callPerson(&#39;Triver&#39;); 8echo $triver(&#34;slow down, please!!&#34;); 附加的变量会被封装到闭包内,即使返回的闭包队形已经跳出了callPerson()的作用域也仍然会记住$name的值。 闭包有一个有趣的bindTo()方法,可以将闭包的内部状态绑定到其他对象上,第二个参数指定了绑定闭包的对象所属的类,从而实现在闭包中访问绑定对象的私有方法和属性。 1class Bind { 2 protected $name = &#39;no name&#39;; 3 public $change; 4 5 public function addAction($action) { 6 $this-&gt;change = $action-&gt;bindTo($this, __CLASS__); 7 } 8} 9 10$bind = new Bind(); 11$bind-&gt;addAction(function() { 12 $this-&gt;name = &#34;php&#34;; 13 return $this-&gt;name; 14 }); 15 16$change = $bind-&gt;change; 17echo $change(); 使用这个特性可以方便的为类添加方法并绑定:ruby学习笔记https://www.takuzen.me/hugo-theme-cactus/posts/2016-12-08-ruby-notes/Thu, 08 Dec 2016 22:54:49 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2016-12-08-ruby-notes/regular expressions =~是用于正则表达式的匹配操作符。返回匹配到的字符串位置或nil。 -1&#34;abcdef&#34; =~ /d/ # return 3 2&#34;aaaaaa&#34; =~ /d/ # return nil !和? The exclamation point (!, sometimes pronounced aloud as &ldquo;bang!&quot;) indicates something potentially destructive, that is to say, something that can change the value of what it touches. -ruby&gt; s1 = &quot;forth&quot; &quot;forth&quot; ruby&gt; s1.chop! # This changes s1. &quot;fort&quot; ruby&gt; s2 = s1.chop # This puts a changed copy in s2, &quot;for&quot; ruby&gt; s1 # .netfilter/iptables 笔记https://www.takuzen.me/hugo-theme-cactus/posts/2016-11-29-iptables-usage/Tue, 29 Nov 2016 21:08:52 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2016-11-29-iptables-usage/netfilter 与 iptables netfilter是linux默认的防火墙,在2.4之后的版本正式进入内核。netfilter 使用四个表(Table)来存放控制信息包过滤处理的规则集。每张表由链(Chain)组成,每条链又包含了多条规则(rule)。 +1&#34;abcdef&#34; =~ /d/ # return 3 2&#34;aaaaaa&#34; =~ /d/ # return nil !和? The exclamation point (!, sometimes pronounced aloud as &ldquo;bang!&rdquo;) indicates something potentially destructive, that is to say, something that can change the value of what it touches. +ruby&gt; s1 = &#34;forth&#34; &#34;forth&#34; ruby&gt; s1.chop! # This changes s1. &#34;fort&#34; ruby&gt; s2 = s1.chop # This puts a changed copy in s2, &#34;for&#34; ruby&gt; s1 # .netfilter/iptables 笔记https://www.takuzen.me/hugo-theme-cactus/posts/2016-11-29-iptables-usage/Tue, 29 Nov 2016 21:08:52 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2016-11-29-iptables-usage/netfilter 与 iptables netfilter是linux默认的防火墙,在2.4之后的版本正式进入内核。netfilter 使用四个表(Table)来存放控制信息包过滤处理的规则集。每张表由链(Chain)组成,每条链又包含了多条规则(rule)。 iptables是用来编辑操作这些表的一个工具。iptables包中也包含了针对IPv6的工具ip6tables。 四个表及其包含的链: filter INPUT FORWARD OUTPUT nat PREROUTING POSTROUTING OUTPUT mangle PREROUTING INPUT FORWARD OUTPUT POSTROUTING raw PREROUTING OUTPUT filter机制 filter是netfilter中最重要的机制,其任务是执行数据包的过滤操作。具有三种内建链: @@ -113,7 +113,7 @@ Look how they shine for you 看它们为你绽放着 闪烁不息 And everything you do 而你的一颦一举 -Yeah' they were all Yellow +Yeah&rsquo; they were all Yellow 却满含胆怯和羞意 I came along 我追随着你的气息 diff --git a/posts/2016-10-22-z/index.html b/posts/2016-10-22-z/index.html index c275a1db..a3c0db92 100644 --- a/posts/2016-10-22-z/index.html +++ b/posts/2016-10-22-z/index.html @@ -1,28 +1,12 @@ - - - - - - - - - - - 幸せ | Cactus theme example - - - - - - -幸せ | Cactus theme example + - - - - - - - - - - - -
-
- +Your skin">
- - - - - -
- - - + +
- -
-
- -
- -
-
-
-
-
-

-幸せ -

-
- -
- -3 minute read -
-
-
-
-

:-)

-

Look at the stars

-

抬头仰望满天繁星

-

Look how they shine for you

-

看它们为你绽放着 闪烁不息

-

And everything you do

-

而你的一颦一举

-

Yeah' they were all Yellow

-

却满含胆怯和羞意

-

I came along

-

我追随着你的气息

-

I wrote a song for you

-

为你写下一首歌曲

-

And all the things you do

-

回想着你的所有举动和笑意

-

it was called Yellow

-

并用Yellow为这首歌命名

-

So then I took my turn

-

我耗尽心力

-

Oh what a thing to have done

-

用行动表达我的爱意

-

And it was all Yellow

-

噢这过程充满不安羞怯和点滴暖意

-

Your skin

-

你的每寸肌肤

-

Oh yeah' your skin and bones

-

你的冰肌玉骨

-

Turn into something beautiful

-

是那般美好 在我心永驻

-

Do you know? you know I love you so

-

你可知道 我已深深爱上了你

-

You know I love you so

-

你知道我已深深为你着迷

-

I swam across

-

我曾为你横越海洋

-

I jumped across for you

-

也曾为你翻越高山

-

Oh what a thing to do

-

而这一切行动的意义

-

Cos you were all Yellow

-

只为你满含羞怯的笑意

-

I drew a line

-

我拿起笔 小心翼翼

-

I drew a line for you

-

画着我脑海中美好的你

-

Oh what a thing to do

-

为你做这样一件事情

-

And it was all Yellow

-

心中却也充满暖意

-

Your skin

-

你的每寸肌肤

-

Oh yeah your skin and bones

-

你的冰肌玉骨

-

Turn into something beautiful

-

是那般美好 在我心永驻

-

Do you know?

-

你可知道

-

For you I’d bleed myself dry

-

为你我愿意付出一切

-

For you I’d bleed myself dry

-

直到生命燃尽 也甘心如饴

-

It’s true

-

这就是我的真心

-

Look how they shine for you

-

看那漫天繁星正为你闪耀不已

-

Look how they shine for you

-

仿佛亦惊叹于你的美丽

-

Look how they shine for

-

看那漫天繁星正为你闪耀不已

-

Look how they shine for you

-

仿佛亦能读懂我此刻心情

-

Look how they shine for you

-

看那漫天繁星正为你闪耀不已

-

Look how they shine

-

那漫天的璀璨 皆是为你

-

Look at the stars

-

抬头仰望那满天繁星

-

Look how they shine for you

-

看它们正为你绽放着 闪烁不息

-

And all the things that you do

-

皆是因为你的一颦一举

-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

幸せ

+3 minute read

:-)

Look at the stars

抬头仰望满天繁星

Look how they shine for you

看它们为你绽放着 闪烁不息

And everything you do

而你的一颦一举

Yeah’ they were all Yellow

却满含胆怯和羞意

I came along

我追随着你的气息

I wrote a song for you

为你写下一首歌曲

And all the things you do

回想着你的所有举动和笑意

it was called Yellow

并用Yellow为这首歌命名

So then I took my turn

我耗尽心力

Oh what a thing to have done

用行动表达我的爱意

And it was all Yellow

噢这过程充满不安羞怯和点滴暖意

Your skin

你的每寸肌肤

Oh yeah’ your skin and bones

你的冰肌玉骨

Turn into something beautiful

是那般美好 在我心永驻

Do you know? you know I love you so

你可知道 我已深深爱上了你

You know I love you so

你知道我已深深为你着迷

I swam across

我曾为你横越海洋

I jumped across for you

也曾为你翻越高山

Oh what a thing to do

而这一切行动的意义

Cos you were all Yellow

只为你满含羞怯的笑意

I drew a line

我拿起笔 小心翼翼

I drew a line for you

画着我脑海中美好的你

Oh what a thing to do

为你做这样一件事情

And it was all Yellow

心中却也充满暖意

Your skin

你的每寸肌肤

Oh yeah your skin and bones

你的冰肌玉骨

Turn into something beautiful

是那般美好 在我心永驻

Do you know?

你可知道

For you I’d bleed myself dry

为你我愿意付出一切

For you I’d bleed myself dry

直到生命燃尽 也甘心如饴

It’s true

这就是我的真心

Look how they shine for you

看那漫天繁星正为你闪耀不已

Look how they shine for you

仿佛亦惊叹于你的美丽

Look how they shine for

看那漫天繁星正为你闪耀不已

Look how they shine for you

仿佛亦能读懂我此刻心情

Look how they shine for you

看那漫天繁星正为你闪耀不已

Look how they shine

那漫天的璀璨 皆是为你

Look at the stars

抬头仰望那满天繁星

Look how they shine for you

看它们正为你绽放着 闪烁不息

And all the things that you do

皆是因为你的一颦一举

\ No newline at end of file diff --git a/posts/2016-11-05-php-composer-autoload/index.html b/posts/2016-11-05-php-composer-autoload/index.html index fd206f50..06f27009 100644 --- a/posts/2016-11-05-php-composer-autoload/index.html +++ b/posts/2016-11-05-php-composer-autoload/index.html @@ -1,311 +1,38 @@ - - - - - - - - - - - composer中的autoload | Cactus theme example - - - - - - - - - - - - - - - - - - -
-
- +composer中的autoload | Cactus theme example +
- - - - - -
- - - + +
- -
-
- -
- -
-
-
-
-
-

-composer中的autoload -

-
- -
- -2 minute read -
- -
-
-
-

composer的autoload可以轻松的实现php的自动加载。在composer.json中添加autoload字段即可。当前支持 PSR-0 PSR-4 classmap解析和files包含。官方推荐PSR-4标准(添加类时不需要重新生成加载器)。

-

PSR-4

-

Under the psr-4 key you define a mapping from namespaces to paths, relative to the package root. When autoloading a class like Foo\\Bar\\Baz a namespace prefix Foo\\ pointing to a directory src/ means that the autoloader will look for a file named src/Bar/Baz.php and include it if present. Note that as opposed to the older PSR-0 style, the prefix (Foo\\) is not present in the file path.

-

Namespace prefixes must end in \\ to avoid conflicts between similar prefixes. For example Foo would match classes in the FooBar namespace so the trailing backslashes solve the problem: Foo\\ and FooBar\\ are distinct.

-

The PSR-4 references are all combined, during install/update, into a single key => value array which may be found in the generated file vendor/composer/autoload_psr4.php.

-

实例:

-
{
-    "autoload": {
-        "psr-4": {
-            "Monolog\\": "src/",
-            "Vendor\\Namespace\\": ""
+

composer中的autoload

+2 minute read

composer的autoload可以轻松的实现php的自动加载。在composer.json中添加autoload字段即可。当前支持 PSR-0 PSR-4 classmap解析和files包含。官方推荐PSR-4标准(添加类时不需要重新生成加载器)。

PSR-4

Under the psr-4 key you define a mapping from namespaces to paths, relative to the package root. When autoloading a class like Foo\\Bar\\Baz a namespace prefix Foo\\ pointing to a directory src/ means that the autoloader will look for a file named src/Bar/Baz.php and include it if present. Note that as opposed to the older PSR-0 style, the prefix (Foo\\) is not present in the file path.

Namespace prefixes must end in \\ to avoid conflicts between similar prefixes. For example Foo would match classes in the FooBar namespace so the trailing backslashes solve the problem: Foo\\ and FooBar\\ are distinct.

The PSR-4 references are all combined, during install/update, into a single key => value array which may be found in the generated file vendor/composer/autoload_psr4.php.

实例:

{
+    "autoload": {
+        "psr-4": {
+            "Monolog\\": "src/",
+            "Vendor\\Namespace\\": ""
         }
     }
 }
-

如果需要在多个目录下搜索相同前缀,可以以数组的形式指定。

-
{
-    "autoload": {
-        "psr-4": { "Monolog\\": ["src/", "lib/"] }
+

如果需要在多个目录下搜索相同前缀,可以以数组的形式指定。

{
+    "autoload": {
+        "psr-4": { "Monolog\\": ["src/", "lib/"] }
     }
 }
-

也可为所有命名空间指定默认文件夹:

-
{
-    "autoload": {
-        "psr-4": { "": "src/" }
+

也可为所有命名空间指定默认文件夹:

{
+    "autoload": {
+        "psr-4": { "": "src/" }
     }
 }
-

classmap

-

classmap 引用的所有组合,都会在 install/update 过程中生成,并存储到 vendor/composer/autoload_classmap.php 文件中。这个 map 是经过扫描指定目录(同样支持直接精确到文件)中所有的 .php.inc 文件里内置的类而得到的。

-

你可以用 classmap 生成支持支持自定义加载的不遵循 PSR-0/4 规范的类库。要配置它指向需要的目录,以便能够准确搜索到类文件。

-

实例:

-
{
-    "autoload": {
-        "classmap": ["src/", "lib/", "Something.php"]
+

classmap

classmap 引用的所有组合,都会在 install/update 过程中生成,并存储到 vendor/composer/autoload_classmap.php 文件中。这个 map 是经过扫描指定目录(同样支持直接精确到文件)中所有的 .php.inc 文件里内置的类而得到的。

你可以用 classmap 生成支持支持自定义加载的不遵循 PSR-0/4 规范的类库。要配置它指向需要的目录,以便能够准确搜索到类文件。

实例:

{
+    "autoload": {
+        "classmap": ["src/", "lib/", "Something.php"]
     }
 }
-

相关链接

-

Example Implementations of PSR-4

-

The composer.json Schema

-

如何使用composer的autoload来自动加载自己编写的函数库与类库

-

使用composer中的autoload

-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

相关链接

Example Implementations of PSR-4

The composer.json Schema

如何使用composer的autoload来自动加载自己编写的函数库与类库

使用composer中的autoload

\ No newline at end of file diff --git a/posts/2016-11-29-iptables-usage/index.html b/posts/2016-11-29-iptables-usage/index.html index f798895b..ee448bf0 100644 --- a/posts/2016-11-29-iptables-usage/index.html +++ b/posts/2016-11-29-iptables-usage/index.html @@ -1,234 +1,26 @@ - - - - - - - - - - - netfilter/iptables 笔记 | Cactus theme example - - - - - - -netfilter/iptables 笔记 | Cactus theme example + - - - - - - - - - - - -
-
- +iptables -操作方式 [链名] [条件匹配] [选项] iptables -[ACD] chain rule-specification [options] iptables -I chain [rulenum] rule-specification [options] iptables -R chain rulenum rule-specification [options] iptables -D chain rulenum [options] iptables -[LS] [chain [rulenum]] [options] iptables -[FZ] [chain] [options] iptables -[NX] chain iptables -E old-chain-name new-chain-name iptables -P chain target [options] iptables -h (print this help information) 常用操作方式:">
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-netfilter/iptables 笔记 -

-
- -
- -7 minute read -
- -
-
-
-

netfilter 与 iptables

-

netfilter是linux默认的防火墙,在2.4之后的版本正式进入内核。netfilter 使用四个表(Table)来存放控制信息包过滤处理的规则集。每张表由链(Chain)组成,每条链又包含了多条规则(rule)。

-

iptables是用来编辑操作这些表的一个工具。iptables包中也包含了针对IPv6的工具ip6tables

-

四个表及其包含的链:

-
    -
  • filter -
      -
    • INPUT
    • -
    • FORWARD
    • -
    • OUTPUT
    • -
    -
  • -
  • nat -
      -
    • PREROUTING
    • -
    • POSTROUTING
    • -
    • OUTPUT
    • -
    -
  • -
  • mangle -
      -
    • PREROUTING
    • -
    • INPUT
    • -
    • FORWARD
    • -
    • OUTPUT
    • -
    • POSTROUTING
    • -
    -
  • -
  • raw -
      -
    • PREROUTING
    • -
    • OUTPUT
    • -
    -
  • -
-

img

-

filter机制

-

filternetfilter中最重要的机制,其任务是执行数据包的过滤操作。具有三种内建链:

-
    -
  • INPUT - 来自外部的数据包(访问本机)
  • -
  • OUTPUT - 发往外部的数据包(本机访问外部)
  • -
  • FORWORD - “路过”本机的数据包,转发到其他设备
  • -
-

链中规则的匹配方式遵循first matchfilter会根据数据包特征从相应链中的第一条规则开始逐一进行匹配。只要遇到满足特征的规则后便不再继续。 -每条链在最底端都定义了默认规则。默认规则只会有一种状态:ACCEPT或者DROP。默认为ACCEPT

-

iptables命令参数

-

格式:

-
iptables -操作方式 [链名] [条件匹配] [选项]
+

netfilter/iptables 笔记

+7 minute read

netfilter 与 iptables

netfilter是linux默认的防火墙,在2.4之后的版本正式进入内核。netfilter 使用四个表(Table)来存放控制信息包过滤处理的规则集。每张表由链(Chain)组成,每条链又包含了多条规则(rule)。

iptables是用来编辑操作这些表的一个工具。iptables包中也包含了针对IPv6的工具ip6tables

四个表及其包含的链:

  • filter
    • INPUT
    • FORWARD
    • OUTPUT
  • nat
    • PREROUTING
    • POSTROUTING
    • OUTPUT
  • mangle
    • PREROUTING
    • INPUT
    • FORWARD
    • OUTPUT
    • POSTROUTING
  • raw
    • PREROUTING
    • OUTPUT

img

filter机制

filternetfilter中最重要的机制,其任务是执行数据包的过滤操作。具有三种内建链:

  • INPUT - 来自外部的数据包(访问本机)
  • OUTPUT - 发往外部的数据包(本机访问外部)
  • FORWORD - “路过”本机的数据包,转发到其他设备

链中规则的匹配方式遵循first matchfilter会根据数据包特征从相应链中的第一条规则开始逐一进行匹配。只要遇到满足特征的规则后便不再继续。 +每条链在最底端都定义了默认规则。默认规则只会有一种状态:ACCEPT或者DROP。默认为ACCEPT

iptables命令参数

格式:

iptables -操作方式 [链名] [条件匹配] [选项]
 
 iptables -[ACD] chain rule-specification [options]
 iptables -I chain [rulenum] rule-specification [options]
@@ -240,174 +32,10 @@ 

iptables命令参数

iptables -E old-chain-name new-chain-name iptables -P chain target [options] iptables -h (print this help information) - -

常用操作方式:

-
    -
  • -L(--list) [chain] 列出所有规则或指定链的规则
  • -
  • -A(--append) chain 在指定链中添加新规则
  • -
  • -C(--check) chain 检查规则是否存在
  • -
  • -D(--delete) chain rule_num 删除链中匹配的规则
  • -
  • -F(--flush) [chain] 清除指定链或者全部链中的规则
  • -
  • -P(--policy) chain 设置指定链的默认策略
  • -
  • -R(--replace) chain rule_num 替换指定链中特定行的规则,第一行行数为1
  • -
-

常用选项:

-
    -
  • -p(--protocol) proto 指定协议,如tcp udp icmp
  • -
  • -j(--jump) target 规则的目标(??),如ACCEPT DROP REJECT
  • -
  • -s(--source) address[/mask] 数据包源IP,可为单IP或CIDR网段或域名
  • -
  • -d(--destination) address[/mask] 数据包目的IP,可为单IP或CIDR网段或域名
  • -
  • --dport port 目的端口,必须指明-p
  • -
  • --sport port 来源端口,必须指明-p
  • -
  • --line-numbers 显示行号
  • -
-
-

关于-p配置的上层协议,可参考/etc/protocols

-
-

state模块

-

state模块实现了“连接跟踪”功能,用来解决某些情况下防火墙内主机对外建立链接的问题。 -state模块定义了四种数据包链接状态,分别为ESTABLISHED NEW RELATED INVALID 四种。在TCP/IP标准的定义中,UDP和ICMP数据包是没有链接状态的,但是在state模块的定义中,任何数据包都有连接状态。

-

ESTABLISHED状态

-

只要数据包能够成功穿过防火墙,则之后的所有数据包(包括响应数据包)都会被标记为是ESTABLISHED状态。

-

当我们设置防火墙INPUT链的默认策略为DROP时,防火墙内主机很多服务,如ssh客户端基本上就无法与外面的ssh服务端建立连接了。原因很简单,ssh客户端使用的端口是随机的,防火墙无法预知客户端会使用哪一个端口发起链接。因此即使客户端发出了请求,ssh服务端返回的相应数据包也会被防火墙的默认策略拦截。

-

ESTABLISHED状态可以很轻易的解决此问题,见#解决应用程序无法从防火墙主机上对外建立新连接的问题

-

NEW状态

-

每一条链接中的地一个数据包的状态定义为NEW

-

RELATED状态

-

RELATED状态的数据包其含义是指,被动产成的应答数据包,且此数据包不属于当前任何链接。换一种说法就是,只要应答的数据包是因为本机发起的连接送出vhu一个数据包,导致了另一条连接的产生,那么这个新连接的所有数据包都属于RELATED状态。

-

以ubuntu上上的tracepath工具为例,在检测本机与目的主机间跳数时,tracepath是通过发送TTL值从1递增的tcp数据包来检测每一跳。路径中的路由器因TTL减为0而回送了一个ICMP数据包(ICMP Type 11),该数据包就属于RELATED状态。

-

INVALID状态

-

INVALID状态指的是状态不明的数据包,即不属于ESTABLISHED NEW RELATED三种类型的数据包。所有的INVALID数据包都应该视为恶意数据包。

-

实例

-

丢弃icmp协议包(禁止ping)

-

通过此规则实现禁止ping本机的效果

-
iptables -A INPUT -p icmp -j DROP
-

解决应用程序无法从防火墙主机上对外建立新连接的问题

-
iptables -A INPUT -p tcp -m state ESTABLISHED -j ACCEPT
-
-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

常用操作方式:

  • -L(--list) [chain] 列出所有规则或指定链的规则
  • -A(--append) chain 在指定链中添加新规则
  • -C(--check) chain 检查规则是否存在
  • -D(--delete) chain rule_num 删除链中匹配的规则
  • -F(--flush) [chain] 清除指定链或者全部链中的规则
  • -P(--policy) chain 设置指定链的默认策略
  • -R(--replace) chain rule_num 替换指定链中特定行的规则,第一行行数为1

常用选项:

  • -p(--protocol) proto 指定协议,如tcp udp icmp
  • -j(--jump) target 规则的目标(??),如ACCEPT DROP REJECT
  • -s(--source) address[/mask] 数据包源IP,可为单IP或CIDR网段或域名
  • -d(--destination) address[/mask] 数据包目的IP,可为单IP或CIDR网段或域名
  • --dport port 目的端口,必须指明-p
  • --sport port 来源端口,必须指明-p
  • --line-numbers 显示行号

关于-p配置的上层协议,可参考/etc/protocols

state模块

state模块实现了“连接跟踪”功能,用来解决某些情况下防火墙内主机对外建立链接的问题。 +state模块定义了四种数据包链接状态,分别为ESTABLISHED NEW RELATED INVALID 四种。在TCP/IP标准的定义中,UDP和ICMP数据包是没有链接状态的,但是在state模块的定义中,任何数据包都有连接状态。

ESTABLISHED状态

只要数据包能够成功穿过防火墙,则之后的所有数据包(包括响应数据包)都会被标记为是ESTABLISHED状态。

当我们设置防火墙INPUT链的默认策略为DROP时,防火墙内主机很多服务,如ssh客户端基本上就无法与外面的ssh服务端建立连接了。原因很简单,ssh客户端使用的端口是随机的,防火墙无法预知客户端会使用哪一个端口发起链接。因此即使客户端发出了请求,ssh服务端返回的相应数据包也会被防火墙的默认策略拦截。

ESTABLISHED状态可以很轻易的解决此问题,见#解决应用程序无法从防火墙主机上对外建立新连接的问题

NEW状态

每一条链接中的地一个数据包的状态定义为NEW

RELATED状态

RELATED状态的数据包其含义是指,被动产成的应答数据包,且此数据包不属于当前任何链接。换一种说法就是,只要应答的数据包是因为本机发起的连接送出vhu一个数据包,导致了另一条连接的产生,那么这个新连接的所有数据包都属于RELATED状态。

以ubuntu上上的tracepath工具为例,在检测本机与目的主机间跳数时,tracepath是通过发送TTL值从1递增的tcp数据包来检测每一跳。路径中的路由器因TTL减为0而回送了一个ICMP数据包(ICMP Type 11),该数据包就属于RELATED状态。

INVALID状态

INVALID状态指的是状态不明的数据包,即不属于ESTABLISHED NEW RELATED三种类型的数据包。所有的INVALID数据包都应该视为恶意数据包。

实例

丢弃icmp协议包(禁止ping)

通过此规则实现禁止ping本机的效果

iptables -A INPUT -p icmp -j DROP
+

解决应用程序无法从防火墙主机上对外建立新连接的问题

iptables -A INPUT -p tcp -m state ESTABLISHED -j ACCEPT
+
\ No newline at end of file diff --git a/posts/2016-12-08-ruby-notes/index.html b/posts/2016-12-08-ruby-notes/index.html index b3df600a..aaa1ac9c 100644 --- a/posts/2016-12-08-ruby-notes/index.html +++ b/posts/2016-12-08-ruby-notes/index.html @@ -1,535 +1,117 @@ - - - - - - - - - - - ruby学习笔记 | Cactus theme example - - - - - - - - - - - - - - - - - - -
-
- +ruby学习笔记 | Cactus theme example +
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-ruby学习笔记 -

-
- -
- -6 minute read -
- -
-
-
-

regular expressions

-

=~是用于正则表达式的匹配操作符。返回匹配到的字符串位置或nil。

-
1"abcdef" =~ /d/ # return 3
-2"aaaaaa" =~ /d/ # return nil
-
-

!和?

-

The exclamation point (!, sometimes pronounced aloud as “bang!") indicates something potentially destructive, that is to say, something that can change the value of what it touches.

-
ruby> s1 = "forth"
-  "forth"
+

ruby学习笔记

+6 minute read

regular expressions

=~是用于正则表达式的匹配操作符。返回匹配到的字符串位置或nil。

1"abcdef" =~ /d/ # return 3
+2"aaaaaa" =~ /d/ # return nil
+

!和?

The exclamation point (!, sometimes pronounced aloud as “bang!”) indicates something potentially destructive, that is to say, something that can change the value of what it touches.

ruby> s1 = "forth"
+  "forth"
 ruby> s1.chop!       # This changes s1.
-  "fort"
+  "fort"
 ruby> s2 = s1.chop   # This puts a changed copy in s2,
-  "for"
+  "for"
 ruby> s1             # ... without disturbing s1.
-  "fort"
-

You’ll also sometimes see chomp and chomp! used. These are more selective: the end of a string gets bit off only if it happens to be a newline.

-

The other method naming convention is the question mark (?, sometimes pronounced aloud as “huh?") indicates a “predicate” method, one that can return either true or false.

-

四种内部中断循环的方式

-
    -
  • break
  • -
  • next 等同与continue
  • -
  • redo restarts the current iteration
  • -
  • return
  • -
-

迭代器 iterator

-

Ruby’s String type has some useful iterators. each_byte is an iterator for each character in the string.

-
1irb(main):001:0> "abc".each_byte{|c| printf "<%c>", c}; print "\n"
-2<a><b><c>
-3=> nil
-

Another iterator of String is each_line.

-
1irb(main):002:0> "a\nb\nc\n".each_line{|l| print l}
-2a
-3b
-4c
-5=> "a\nb\nc\n"
-

ruby的 for in 也是一种迭代。We can use a control structure retry in conjunction with an iterated loop, and it will retry the loop from the beginning.

-

yield

-

yield occurs sometimes in a definition of an iterator. yield moves control to the block of code that is passed to the iterator (this will be explored in more detail in the chapter about procedure objects). The following example defines an iterator repeat, which repeats a block of code the number of times specified in an argument.

-
 1irb(main):003:0> def repeat(num)
- 2irb(main):004:1>     while num > 0
- 3irb(main):005:2>         yield
- 4irb(main):006:2>         num -= 1
- 5irb(main):007:2>     end
- 6irb(main):008:1> end
- 7=> :repeat
- 8irb(main):009:0> repeat(3) { puts "foo" }
- 9foo
-10foo
-11foo
-12=> nil
-

class

-

继承

-

继承的格式为:

-
 1class Superclass
- 2    def breathe
- 3        puts "inhale and exhale"
- 4    end
- 5    def identify
- 6        puts "I'm super"
- 7    end
- 8    def speak(word)
- 9        puts word
-10    end
-11end
-12
-13class Subclass<Superclass
-14    # code...
-15end
-

可在在子类中重新声明基类方法,也可以使用super关键字来扩展基类方法。super也允许我们传递参数给基类方法。

-
 1class Subclass<Superclass
- 2    def identify
- 3        super
- 4        puts "I'm sub too"
- 5    end
- 6    def speak(word)
- 7        super("this is from Superclass")
- 8        puts "now it's from Subclass: #{word}"
- 9    end
-10end
-

初始化(构造函数)

-

ruby使用initialize关键字来实现构造函数的功能。

-
1class Fruit
-2    def initialize( k="apple")
-3        @kind = k
-4        @condition = "ripe"
-5    end
-6end
-7
-8apple = Fruit.new "apple"
-

variables

-
    -
  • [a-z] or _ 本地变量
  • -
  • $ 全局变量
  • -
  • @ 实例变量 instance variable
  • -
  • [A-Z] 常量
  • -
-

全局变量

-

全局变量以 $ 开头。初始化之前,全局变量的值为nil。可定义一段procedure来追踪全局变量。

-
1$x #return nil
-2trace_var :$x, proc{puts "$x is now #{$x}"}
-3$x = 5 #return $x is now 5
-

一些特殊的变量(不一定是全局作用域):

-
    -
  • $! latest error message
  • -
  • $@ location of error
  • -
  • $_ 上一次由gets读入的字符串
  • -
  • $. line number last read by interpreter
  • -
  • $& string last matched by regexp
  • -
  • $~ the last regexp match, as an array of subexpressions
  • -
  • $n the nth subexpression in the last match (same as $~[n])
  • -
  • $= case-insensitivity flag
  • -
  • $/ input record separator
  • -
  • $\ output record separator
  • -
  • $0 the name of the ruby script file
  • -
  • $* 命令行参数
  • -
  • $$ 当前解释器的进程id
  • -
  • $? 上一次子进程的退出状态码
  • -
-

实例变量

-

An instance variable has a name beginning with @, and its scope is confined to whatever object self refers to. Two different objects, even if they belong to the same class, are allowed to have different values for their instance variables. From outside the object, instance variables cannot be altered or even observed (i.e., ruby’s instance variables are never public) except by whatever methods are explicitly provided by the programmer. As with globals, instance variables have the nil value until they are initialized.

-

Instance variables do not need to be declared. This indicates a flexible object structure; in fact, each instance variable is dynamically appended to an object when it is first assigned.

-

常量

-

常量名以大写字母开头。给常量重新赋值会得到警告。

-
1irb(main):009:0> Wzr=1222
-2=> 1222
-3irb(main):010:0> Wzr=1223
-4(irb):10: warning: already initialized constant Wzr
-5(irb):9: warning: previous definition of Wzr was here
-6=> 1223
-

常量可以在类和模块中定义,并允许外部访问。

-
1class ConstClass
-2   C1=120
-3end
-4
-5ConstClass::C1 # return 120
-

访问器(accessor)

-

实例属性需要通过属性访问器访问。常规访问器有简化写法:

-
1class Fruit
-2   def kind=(k)
-3       @kind = k
-4   end
-5   def kind
-6       @kind
-7   end
-8 end
-

inspect方法

-

当创建一个对象时解释器会返回一些信息:

-
1irb(main):009:0> apple = Fruit.new
-2=> #<Fruit:0x00000000a34f58>
-3irb(main):010:0>
-

可以通过inspect关键字来改变这种默认行为。

-
1class Fruit
-2    def inspect
-3        "a fruit is created"
-4    end
-5end
-

inspect方法常用来调试,可通过下面两种方式显示调用:

-
1p anObject
-2puts anObject.inspect
-

shortcuts

-

Ruby提供了访问器的一些简写形式:

- - - - - - - - - - - - - - - - - - - - - - - - - -
缩写效果
attr_reader :vdef v; @v; end
attr_writer :vdef v=(value); @v=value; end
attr_accessor :vattr_reader :v; attr_writer :v
attr_accessor :v, :wattr_accessor :v; attr_accessor :w
-

注释

-

单行注释以#开头。 -块注释可使用=begin =end来标记。

-
1=begin
-2这是一段注释块。This is a comment block.
-3Egg, I dreamed I was old.
-4=end
-

Dynamic Dispatch

-

Mixins

-

Ruby has no multiple inheritance. But it has mixins.

-

Lookup rulres

-

When looking for receiver obj’s method m,

-
    -
  • look in obj’s class
  • -
  • look in mixins the class includes(later includes shadow)
  • -
  • look in obj’s superclass
  • -
  • look in mixins the superclass inculdes
  • -
  • -
-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file + "fort" +

You’ll also sometimes see chomp and chomp! used. These are more selective: the end of a string gets bit off only if it happens to be a newline.

The other method naming convention is the question mark (?, sometimes pronounced aloud as “huh?”) indicates a “predicate” method, one that can return either true or false.

四种内部中断循环的方式

  • break
  • next 等同与continue
  • redo restarts the current iteration
  • return

迭代器 iterator

Ruby’s String type has some useful iterators. each_byte is an iterator for each character in the string.

1irb(main):001:0> "abc".each_byte{|c| printf "<%c>", c}; print "\n"
+2<a><b><c>
+3=> nil
+

Another iterator of String is each_line.

1irb(main):002:0> "a\nb\nc\n".each_line{|l| print l}
+2a
+3b
+4c
+5=> "a\nb\nc\n"
+

ruby的 for in 也是一种迭代。We can use a control structure retry in conjunction with an iterated loop, and it will retry the loop from the beginning.

yield

yield occurs sometimes in a definition of an iterator. yield moves control to the block of code that is passed to the iterator (this will be explored in more detail in the chapter about procedure objects). The following example defines an iterator repeat, which repeats a block of code the number of times specified in an argument.

 1irb(main):003:0> def repeat(num)
+ 2irb(main):004:1>     while num > 0
+ 3irb(main):005:2>         yield
+ 4irb(main):006:2>         num -= 1
+ 5irb(main):007:2>     end
+ 6irb(main):008:1> end
+ 7=> :repeat
+ 8irb(main):009:0> repeat(3) { puts "foo" }
+ 9foo
+10foo
+11foo
+12=> nil
+

class

继承

继承的格式为:

 1class Superclass
+ 2    def breathe
+ 3        puts "inhale and exhale"
+ 4    end
+ 5    def identify
+ 6        puts "I'm super"
+ 7    end
+ 8    def speak(word)
+ 9        puts word
+10    end
+11end
+12
+13class Subclass<Superclass
+14    # code...
+15end
+

可在在子类中重新声明基类方法,也可以使用super关键字来扩展基类方法。super也允许我们传递参数给基类方法。

 1class Subclass<Superclass
+ 2    def identify
+ 3        super
+ 4        puts "I'm sub too"
+ 5    end
+ 6    def speak(word)
+ 7        super("this is from Superclass")
+ 8        puts "now it's from Subclass: #{word}"
+ 9    end
+10end
+

初始化(构造函数)

ruby使用initialize关键字来实现构造函数的功能。

1class Fruit
+2    def initialize( k="apple")
+3        @kind = k
+4        @condition = "ripe"
+5    end
+6end
+7
+8apple = Fruit.new "apple"
+

variables

  • [a-z] or _ 本地变量
  • $ 全局变量
  • @ 实例变量 instance variable
  • [A-Z] 常量

全局变量

全局变量以 $ 开头。初始化之前,全局变量的值为nil。可定义一段procedure来追踪全局变量。

1$x #return nil
+2trace_var :$x, proc{puts "$x is now #{$x}"}
+3$x = 5 #return $x is now 5
+

一些特殊的变量(不一定是全局作用域):

  • $! latest error message
  • $@ location of error
  • $_ 上一次由gets读入的字符串
  • $. line number last read by interpreter
  • $& string last matched by regexp
  • $~ the last regexp match, as an array of subexpressions
  • $n the nth subexpression in the last match (same as $~[n])
  • $= case-insensitivity flag
  • $/ input record separator
  • $\ output record separator
  • $0 the name of the ruby script file
  • $* 命令行参数
  • $$ 当前解释器的进程id
  • $? 上一次子进程的退出状态码

实例变量

An instance variable has a name beginning with @, and its scope is confined to whatever object self refers to. Two different objects, even if they belong to the same class, are allowed to have different values for their instance variables. From outside the object, instance variables cannot be altered or even observed (i.e., ruby’s instance variables are never public) except by whatever methods are explicitly provided by the programmer. As with globals, instance variables have the nil value until they are initialized.

Instance variables do not need to be declared. This indicates a flexible object structure; in fact, each instance variable is dynamically appended to an object when it is first assigned.

常量

常量名以大写字母开头。给常量重新赋值会得到警告。

1irb(main):009:0> Wzr=1222
+2=> 1222
+3irb(main):010:0> Wzr=1223
+4(irb):10: warning: already initialized constant Wzr
+5(irb):9: warning: previous definition of Wzr was here
+6=> 1223
+

常量可以在类和模块中定义,并允许外部访问。

1class ConstClass
+2   C1=120
+3end
+4
+5ConstClass::C1 # return 120
+

访问器(accessor)

实例属性需要通过属性访问器访问。常规访问器有简化写法:

1class Fruit
+2   def kind=(k)
+3       @kind = k
+4   end
+5   def kind
+6       @kind
+7   end
+8 end
+

inspect方法

当创建一个对象时解释器会返回一些信息:

1irb(main):009:0> apple = Fruit.new
+2=> #<Fruit:0x00000000a34f58>
+3irb(main):010:0>
+

可以通过inspect关键字来改变这种默认行为。

1class Fruit
+2    def inspect
+3        "a fruit is created"
+4    end
+5end
+

inspect方法常用来调试,可通过下面两种方式显示调用:

1p anObject
+2puts anObject.inspect
+

shortcuts

Ruby提供了访问器的一些简写形式:

缩写效果
attr_reader :vdef v; @v; end
attr_writer :vdef v=(value); @v=value; end
attr_accessor :vattr_reader :v; attr_writer :v
attr_accessor :v, :wattr_accessor :v; attr_accessor :w

注释

单行注释以#开头。 +块注释可使用=begin =end来标记。

1=begin
+2这是一段注释块。This is a comment block.
+3Egg, I dreamed I was old.
+4=end
+

Dynamic Dispatch

Mixins

Ruby has no multiple inheritance. But it has mixins.

Lookup rulres

When looking for receiver obj’s method m,

  • look in obj’s class
  • look in mixins the class includes(later includes shadow)
  • look in obj’s superclass
  • look in mixins the superclass inculdes
\ No newline at end of file diff --git a/posts/2017-01-11-php-lambada/index.html b/posts/2017-01-11-php-lambada/index.html index 41d7ce2c..1209e7f9 100644 --- a/posts/2017-01-11-php-lambada/index.html +++ b/posts/2017-01-11-php-lambada/index.html @@ -1,347 +1,100 @@ - - - - - - - - - - - php的闭包特性 | Cactus theme example - - - - - - -php的闭包特性 | Cactus theme example +change = $action->bindTo($this, __CLASS__); 7 } 8} 9 10$bind = new Bind(); 11$bind->addAction(function() { 12 $this->name = "php"; 13 return $this->name; 14 }); 15 16$change = $bind->change; 17echo $change(); 使用这个特性可以方便的为类添加方法并绑定:"> - - - - - - -name; 14 }); 15 16$change = $bind->change; 17echo $change(); 使用这个特性可以方便的为类添加方法并绑定:'>change = $action->bindTo($this, __CLASS__); 7 } 8} 9 10$bind = new Bind(); 11$bind->addAction(function() { 12 $this->name = "php"; 13 return $this->name; 14 }); 15 16$change = $bind->change; 17echo $change(); 使用这个特性可以方便的为类添加方法并绑定:"> - - - - -
-
- +1class Bind { 2 protected $name = 'no name'; 3 public $change; 4 5 public function addAction($action) { 6 $this->change = $action->bindTo($this, __CLASS__); 7 } 8} 9 10$bind = new Bind(); 11$bind->addAction(function() { 12 $this->name = "php"; 13 return $this->name; 14 }); 15 16$change = $bind->change; 17echo $change(); 使用这个特性可以方便的为类添加方法并绑定:'>
- - - - - -
- - - + +
- -
-
- -
- -
-
-
-
-
-

-php的闭包特性 -

-
- -
- -3 minute read -
- -
-
-
-

闭包和匿名函数在PHP 5.3.0引入,并且PHP将两者视为相同的概念。闭包其实是伪装成函数的对象,它的实质其实是Closure实例。

-

创建闭包非常简单:

-
1$c = function($name) {
-2    return sprintf("Hello World! Hello %s!", $name);
-3};
-4
-5echo $c('PHP');
-

使用use对闭包附加状态,多个参数使用,分隔:

-
1function callPerson($name) {
-2    return function($about) use ($name) {
-3        return sprintf("%s, %s", $name, $about);
-4    }
-5}
-6
-7$triver = callPerson('Triver');
-8echo $triver("slow down, please!!");
-9
-

附加的变量会被封装到闭包内,即使返回的闭包队形已经跳出了callPerson()的作用域也仍然会记住$name的值。

-

闭包有一个有趣的bindTo()方法,可以将闭包的内部状态绑定到其他对象上,第二个参数指定了绑定闭包的对象所属的类,从而实现在闭包中访问绑定对象的私有方法和属性。

-
 1class Bind {
- 2    protected $name = 'no name';
- 3    public $change;
- 4
- 5    public function addAction($action) {
- 6        $this->change = $action->bindTo($this, __CLASS__);
- 7    }
- 8}
- 9
-10$bind = new Bind();
-11$bind->addAction(function() {
-12    $this->name = "php";
-13    return $this->name;
-14    });
-15
-16$change = $bind->change;
-17echo $change();
-

使用这个特性可以方便的为类添加方法并绑定:

-
 1trait MetaTrait
- 2{
- 3    //定义$methods数组,用于保存方法(函数)的名字和地址。
- 4    private $methods = array();
- 5    //定义addMethod方法,使用闭包类绑定匿名函数。
- 6    public function addMethod($methodName, $methodCallable)
- 7    {
- 8        if (!is_callable($methodCallable)) {
- 9            throw new InvalidArgumentException('Second param must be callable');
-10        }
-11        $this->methods[$methodName] = Closure::bind($methodCallable, $this, get_class());
-12    }
-13    //方法重载。为了避免当调用的方法不存在时产生错误,
-14    //可以使用 __call() 方法来避免。
-15    public function __call($methodName, array $args)
-16    {
-17        if (isset($this->methods[$methodName])) {
-18            return call_user_func_array($this->methods[$methodName], $args);
-19        }
-20
-21        throw RunTimeException('There is no method with the given name to call');
-22    }
-23}
-24
-25class HackThursday {
-26    use MetaTrait;
-27
-28    private $dayOfWeek = 'Thursday';
-29
-30}
-31
-32$test = new HackThursday();
-33$test->addMethod('when', function () {
-34    return $this->dayOfWeek;
-35});
-36
-37echo $test->when();
-

php7 中增加了 Closure::call() 方法,可以更高效的绑定对象作用域并调用。

-
 1class A {private $x = 1;}
- 2
- 3// Pre PHP 7 code
- 4$getXCB = function() {return $this->x;};
- 5$getX = $getXCB->bindTo(new A, 'A'); // intermediate closure
- 6echo $getX();
- 7
- 8// PHP 7+ code
- 9$getX = function() {return $this->x;};
-10echo $getX->call(new A);
-
-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

php的闭包特性

+3 minute read

闭包和匿名函数在PHP 5.3.0引入,并且PHP将两者视为相同的概念。闭包其实是伪装成函数的对象,它的实质其实是Closure实例。

创建闭包非常简单:

1$c = function($name) {
+2    return sprintf("Hello World! Hello %s!", $name);
+3};
+4
+5echo $c('PHP');
+

使用use对闭包附加状态,多个参数使用,分隔:

1function callPerson($name) {
+2    return function($about) use ($name) {
+3        return sprintf("%s, %s", $name, $about);
+4    }
+5}
+6
+7$triver = callPerson('Triver');
+8echo $triver("slow down, please!!");
+

附加的变量会被封装到闭包内,即使返回的闭包队形已经跳出了callPerson()的作用域也仍然会记住$name的值。

闭包有一个有趣的bindTo()方法,可以将闭包的内部状态绑定到其他对象上,第二个参数指定了绑定闭包的对象所属的类,从而实现在闭包中访问绑定对象的私有方法和属性。

 1class Bind {
+ 2    protected $name = 'no name';
+ 3    public $change;
+ 4
+ 5    public function addAction($action) {
+ 6        $this->change = $action->bindTo($this, __CLASS__);
+ 7    }
+ 8}
+ 9
+10$bind = new Bind();
+11$bind->addAction(function() {
+12    $this->name = "php";
+13    return $this->name;
+14    });
+15
+16$change = $bind->change;
+17echo $change();
+

使用这个特性可以方便的为类添加方法并绑定:

 1trait MetaTrait
+ 2{
+ 3    //定义$methods数组,用于保存方法(函数)的名字和地址。
+ 4    private $methods = array();
+ 5    //定义addMethod方法,使用闭包类绑定匿名函数。
+ 6    public function addMethod($methodName, $methodCallable)
+ 7    {
+ 8        if (!is_callable($methodCallable)) {
+ 9            throw new InvalidArgumentException('Second param must be callable');
+10        }
+11        $this->methods[$methodName] = Closure::bind($methodCallable, $this, get_class());
+12    }
+13    //方法重载。为了避免当调用的方法不存在时产生错误,
+14    //可以使用 __call() 方法来避免。
+15    public function __call($methodName, array $args)
+16    {
+17        if (isset($this->methods[$methodName])) {
+18            return call_user_func_array($this->methods[$methodName], $args);
+19        }
+20
+21        throw RunTimeException('There is no method with the given name to call');
+22    }
+23}
+24
+25class HackThursday {
+26    use MetaTrait;
+27
+28    private $dayOfWeek = 'Thursday';
+29
+30}
+31
+32$test = new HackThursday();
+33$test->addMethod('when', function () {
+34    return $this->dayOfWeek;
+35});
+36
+37echo $test->when();
+

php7 中增加了 Closure::call() 方法,可以更高效的绑定对象作用域并调用。

 1class A {private $x = 1;}
+ 2
+ 3// Pre PHP 7 code
+ 4$getXCB = function() {return $this->x;};
+ 5$getX = $getXCB->bindTo(new A, 'A'); // intermediate closure
+ 6echo $getX();
+ 7
+ 8// PHP 7+ code
+ 9$getX = function() {return $this->x;};
+10echo $getX->call(new A);
+
\ No newline at end of file diff --git a/posts/2017-02-18-hash/index.html b/posts/2017-02-18-hash/index.html index ed03326d..8a948d40 100644 --- a/posts/2017-02-18-hash/index.html +++ b/posts/2017-02-18-hash/index.html @@ -1,328 +1,36 @@ - - - - - - - - - - - java散列知识点总结 | Cactus theme example - - - - - - -java散列知识点总结 | Cactus theme example + - - - - - - - - - - - -
-
- +1public static int hash(String key, int tableSize) 2{ 3 int hashVal = 0; 4 5 for (int i = 0; i < key.length(); i++) 6 hashVal = 37*hashVal + key.">
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-java散列知识点总结 -

-
- -
- -3 minute read -
- -
-
-
-

java 的根类 Object 具有 hashcode 方法。当 equal 方法被重写时也应当重写 hashcode 方法。

-

基本数据类型的散列码

-
    -
  • byte short int char 类型的搜索键将会转换为 int
  • -
  • float 类型的搜索键使用 Float.floatToIntBits(key) 作为散列码。
  • -
  • long 类型的搜索键会进行折叠操作,如下:
  • -
-
1iny hashCode = (int) (key ^ (key >> 32));
-
    -
  • double 类型的搜索键会使用 Double.doubleToLongBits(key) 方法转换为 long 类型然后再进行折叠。
  • -
-

字符串类型的散列码

-

对于字符串一般使用多项式散列码进行计算,

-

这里放个公式的图

-

b的较好取值为31,33,37,39,41。在 java String 类中 b 取31。

-
 1public static int hash(String key, int tableSize)
- 2{
- 3    int hashVal = 0;
- 4
- 5    for (int i = 0; i < key.length(); i++)
- 6        hashVal = 37*hashVal + key.charAt(i);
- 7
- 8    hashVal %= tableSize;
- 9    if (hashVal < 0)
-10        hashVal += tableSize;
-11
-12    return hashVal;
-13}
-

压缩散列码

-

由于散列码可能是很大的正数,通常应该对其进行压缩以防止超出索引的范围。若索引范围为 0 ~ n - 1 ,通常的做法是 h(hashCode) = hashCode % N ,选择N为大于2的素数。 -java.util.HashMap 的实现中,将N设置为2的幂值,这样可以使用位运算代替上述的取模:h(hashCode) = hashCode & (N - 1) ,两者是完全等价的。

-

处理冲突

-

开放地址法

-

开放地址法是在冲突发生时,在散列表中找到一个开放位置的过程。

-
    -
  • 线性探测,存在成簇问题
  • -
  • 二次探测,存在二次成簇问题,并且不能保证一个开放的单元总是可以被找到。
  • -
  • 再哈希法
  • -
-

链地址法

-

链地址法是将具有同样索引的条目放在同一位置,每个位置使用一个桶(ArrayList or LinkedList)来放置多个条目。

-

装填因子

-

装填因子衡量一个散列表有多满。lamda = n / N 。对于开放地址法,装填因子介于 0 ~ 1,对于链地址法,装填因子可能为任意值。通常开放地址法需要将装填因子维持在0.5以下,而链地址法为0.9以下。java.util.HashMap 采用了阈值0.75。

-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

java散列知识点总结

+3 minute read

java 的根类 Object 具有 hashcode 方法。当 equal 方法被重写时也应当重写 hashcode 方法。

基本数据类型的散列码

  • byte short int char 类型的搜索键将会转换为 int
  • float 类型的搜索键使用 Float.floatToIntBits(key) 作为散列码。
  • long 类型的搜索键会进行折叠操作,如下:
1iny hashCode = (int) (key ^ (key >> 32));
+
  • double 类型的搜索键会使用 Double.doubleToLongBits(key) 方法转换为 long 类型然后再进行折叠。

字符串类型的散列码

对于字符串一般使用多项式散列码进行计算,

这里放个公式的图

b的较好取值为31,33,37,39,41。在 java String 类中 b 取31。

 1public static int hash(String key, int tableSize)
+ 2{
+ 3    int hashVal = 0;
+ 4
+ 5    for (int i = 0; i < key.length(); i++)
+ 6        hashVal = 37*hashVal + key.charAt(i);
+ 7
+ 8    hashVal %= tableSize;
+ 9    if (hashVal < 0)
+10        hashVal += tableSize;
+11
+12    return hashVal;
+13}
+

压缩散列码

由于散列码可能是很大的正数,通常应该对其进行压缩以防止超出索引的范围。若索引范围为 0 ~ n - 1 ,通常的做法是 h(hashCode) = hashCode % N ,选择N为大于2的素数。 +java.util.HashMap 的实现中,将N设置为2的幂值,这样可以使用位运算代替上述的取模:h(hashCode) = hashCode & (N - 1) ,两者是完全等价的。

处理冲突

开放地址法

开放地址法是在冲突发生时,在散列表中找到一个开放位置的过程。

  • 线性探测,存在成簇问题
  • 二次探测,存在二次成簇问题,并且不能保证一个开放的单元总是可以被找到。
  • 再哈希法

链地址法

链地址法是将具有同样索引的条目放在同一位置,每个位置使用一个桶(ArrayList or LinkedList)来放置多个条目。

装填因子

装填因子衡量一个散列表有多满。lamda = n / N 。对于开放地址法,装填因子介于 0 ~ 1,对于链地址法,装填因子可能为任意值。通常开放地址法需要将装填因子维持在0.5以下,而链地址法为0.9以下。java.util.HashMap 采用了阈值0.75。

\ No newline at end of file diff --git a/posts/2019-01-18-es6/index.html b/posts/2019-01-18-es6/index.html index 2be34c38..a2da1de9 100644 --- a/posts/2019-01-18-es6/index.html +++ b/posts/2019-01-18-es6/index.html @@ -1,21 +1,5 @@ - - - - - - - - - - - ES6について | Cactus theme example - - - - - - -ES6について | Cactus theme example + - - - - - - - - - - - -
-
- +">
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-ES6について -

-
- -
- -7 minute read -
- -
-
-
-

Overview

-

https://github.com/lukehoban/es6features#readme

-

http://help.wtf/es6

-

http://es6-features.org

-

String

-

String.x is deprecated; use String.prototype.x instead.

-

非推奨の構文:

-
1var num = 15; 
-2String.replace(num, /5/, '2');
-

標準の構文:

-
1var num = 15;
-2String(num).replace(/5/, '2');
-

Template literal

-

Nesting templates:

-
1const classes = `header ${ isLargeScreen() ? '' : `icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`;
-

タグ付けされたtemplate

-
 1var a = 5;
- 2var b = 10;
- 3
- 4function tag(strings, ...values) {
- 5  console.log(strings[0]); // "Hello "
- 6  console.log(strings[1]); // " world"
- 7  console.log(values[0]);  // 15
- 8  console.log(values[1]);  // 50
- 9
-10  return "Bazinga!";
-11}
-12
-13tag`Hello ${ a + b } world ${ a * b}`;
-14// "Bazinga!"
-

http://help.wtf/es6#template_literals

-
 1// Backticks enclose a template literal; ${} interpolates arbitrary expressions
- 2let num = 99; // see block scope
- 3console.log(`${num} bottles of beer on the wall, ${num} bottles of beer
- 4Take one down and pass it around, ${--num} bottles of beer!`);
- 5
- 6// Tagged form: Attach a function that processes string fragments and evaluated
- 7// expressions
- 8function celsius(strings, ...values) {
- 9  let rv = '';
-10  strings.forEach((string, index) => { // See arrow functions
-11    rv += string;
-12    if (typeof values[index] !== 'undefined')
-13      rv += Math.round((values[index] - 32) / 1.8);
-14  });
-15  return rv;
-16}
-17
-18// Converts all the interpolated numbers to the proper unit
-19console.log(celsius `Today temperatures ranged from ${60} to ${65} degrees.`);
-

var and let

-

https://eslint.org/docs/rules/no-var

-
-

ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let and const keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes.

-
-
1if (true) {
-2    var i = 1;
-3    let j = 2;
-4}
-5
-6console.log(i) // 1
-7console.log(j) // ReferenceError: not defined
-

Default function parameters

-
1function multiply(a, b = 1) {
-2  return a * b;
-3}
-

Iterators and for…of

-
 1let fibonacci = {
- 2  [Symbol.iterator]() {
- 3    let pre = 0, cur = 1;
- 4    return {
- 5      next() {
- 6        [pre, cur] = [cur, pre + cur];
- 7        return { done: false, value: cur }
- 8      }
- 9    }
-10  }
-11}
-12
-13for (var n of fibonacci) {
-14  // truncate the sequence at 1000
-15  if (n > 1000)
-16    break;
-17  console.log(n);
-18}
-

More: Duck Typing

-

Modules

-

import and export

-

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

-

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

-

Module Loaders

-

Module loaders support:

-
    -
  • Dynamic loading
  • -
  • State isolation
  • -
  • Global namespace isolation
  • -
  • Compilation hooks
  • -
  • Nested virtualization
  • -
-

The default module loader can be configured, and new loaders can be constructed to evaluate and load code in isolated or constrained contexts.

-
 1// Dynamic loading – ‘System’ is default loader
- 2System.import('lib/math').then(function(m) {
- 3  alert("2π = " + m.sum(m.pi, m.pi));
- 4});
- 5
- 6// Create execution sandboxes – new Loaders
- 7var loader = new Loader({
- 8  global: fixup(window) // replace ‘console.log’
- 9});
-10loader.eval("console.log('hello world!');");
-11
-12// Directly manipulate module cache
-13System.get('jquery');
-14System.set('jquery', Module({$: $})); // WARNING: not yet finalized
-

Promises

-

JavaScript Promiseの本

-
 1function asyncFunction() {
- 2    
- 3    return new Promise(function (resolve, reject) {
- 4        setTimeout(function () {
- 5            resolve('Async Hello world');
- 6        }, 16);
- 7    });
- 8}
- 9
-10asyncFunction().then(function (value) {
-11    console.log(value);    // => 'Async Hello world'
-12}).catch(function (error) {
-13    console.error(error);
-14});
-

Generators

-

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

-
 1// A generator function will return an object that implements the iteration
- 2// protocol, i.e., it has a next() method that returns
- 3// { value: < some value>, done: <true or false> }
- 4function* incRand(max) { // Asterisk defines this as a generator function
- 5  while (true) {
- 6    // Pause execution after the yield, resume when next(<something>) is called
- 7    // and assign <something> to x
- 8    let x = yield Math.floor(Math.random() * max + 1);
- 9    max += x;
-10  }
-11}
-12var rng = incRand(2); // Now we have a generator object to work with
-13console.log(rng.next()); // { value: <between 1 and 2>, done: false }
-14console.log(rng.next(3)); // as above, but between 1 and 5
-15console.log(rng.next()); // as above, but NaN since 5 + undefined results in NaN
-16console.log(rng.next(20)); // Oops, looks like we broke it! NaN again.
-17rng.throw(new Error('Unrecoverable generator state.')); // Will be thrown from yield
-

shorthand of Object initializer

-

https://ariya.io/2013/02/es6-and-object-literal-property-value-shorthand

-
 1// Shorthand property names (ES2015)
- 2var a = 'foo', b = 42, c = {};
- 3var o = {a, b, c};
- 4
- 5// Shorthand method names (ES2015)
- 6var o = {
- 7  property(parameters) {}
- 8};
- 9
-10// Computed property names (ES2015)
-11var prop = 'foo';
-12var o = {
-13  [prop]: 'hey',
-14  ['b' + 'ar']: 'there'
-15};
-

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

-

Destructuring

-

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

-

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Destructuring is fail-soft, similar to standard object lookup foo[“bar”], producing undefined values when not found.

-
1let [n1, n2, n3, n4, ...r] = [100, 'three', 34, {number: 23}, 694, 'eighteen'];
-2console.log(n1, n2, n3, n4); // "100 'three' 34 { number: 23 }"
-3console.log(r); // "[ 694, 'eighteen' ]"
-

Two variables values can be swapped in one destructuring expression

-
1var a = 1;
-2var b = 3;
-3
-4[a, b] = [b, a];
-5console.log(a); // 3
-6console.log(b); // 1
-

Object Destructuring

-
1var o = {p: 42, q: true};
-2var {p, q} = o;
-3
-4console.log(p); // 42
-5console.log(q); // true
-

Works for function parameters

-
1var fmt = ({id = 0, name}) => `${id}: ${name}`;
-2console.log(fmt({ id: 1, name: 'joe'}));
-

symbol

-

https://developer.mozilla.org/en-US/docs/Glossary/Symbol

-

sympol is a primitive data type. The Symbol() function returns a value of type symbol and every returned value is unique. It does not support new Symbol()

-
1var sym1 = Symbol();
-2var sym2 = Symbol('foo');
-3var sym3 = Symbol('foo');
-4
-5Symbol('foo') === Symbol('foo'); // false
-6var sym = new Symbol(); // TypeError
-

Map + Set + WeakMap + WeakSet

-

Reference: Why WeakMap?

-
-

Native WeakMaps hold “weak” references to key objects, which means that they do not prevent garbage collection in case there would be no other reference to the key object. This also avoids preventing garbage collection of values in the map.

-
-
 1/ Sets
- 2var s = new Set();
- 3s.add("hello").add("goodbye").add("hello");
- 4s.size === 2;
- 5s.has("hello") === true;
- 6
- 7// Maps
- 8var m = new Map();
- 9m.set("hello", 42);
-10m.set(s, 34);
-11m.get(s) == 34;
-12
-13// Weak Maps
-14var wm = new WeakMap();
-15wm.set(s, { extra: 42 });
-16wm.size === undefined
-17
-18// Weak Sets
-19var ws = new WeakSet();
-20ws.add({ data: 42 });
-21// Because the added object has no other references, it will not be held in the set
-

New APIs in core libraries

-
 1// Number
- 2Number.EPSILON
- 3Number.isInteger(Infinity) // false
- 4Number.isNaN("NaN") // false
- 5
- 6// Math
- 7Math.acosh(3) // 1.762747174039086
- 8Math.hypot(3, 4) // 5
- 9Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
-10
-11// String
-12"abcde".includes("cd") // true
-13"abc".repeat(3) // "abcabcabc"
-14
-15// Array
-16Array.from(document.querySelectorAll('*')) // Returns a real Array
-17Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
-18[0, 0, 0].fill(7, 1) // [0,7,7]
-19[1, 2, 3].find(x => x == 3) // 3
-20[1, 2, 3].findIndex(x => x == 2) // 1
-21[1, 2, 3, 4, 5].copyWithin(3, 0) // [1, 2, 3, 1, 2]
-22["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
-23["a", "b", "c"].keys() // iterator 0, 1, 2
-24["a", "b", "c"].values() // iterator "a", "b", "c"
-25
-26// Object
-27Object.assign(Point, { origin: new Point(0,0) })
-

Proxies

-

The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).

-

See more examples at MDN Proxy doc

-

No-op forwarding proxy

-
1var target = {};
-2var p = new Proxy(target, {});
-3
-4p.a = 37; // operation forwarded to the target
-5
-6console.log(target.a); // 37. The operation has been properly forwarded
-

Validation

-
 1let validator = {
- 2  set: function(obj, prop, value) {
- 3    if (prop === 'age') {
- 4      if (!Number.isInteger(value)) {
- 5        throw new TypeError('The age is not an integer');
- 6      }
- 7      if (value > 200) {
- 8        throw new RangeError('The age seems invalid');
- 9      }
-10    }
-11
-12    // The default behavior to store the value
-13    obj[prop] = value;
-14
-15    // Indicate success
-16    return true;
-17  }
-18};
-19
-20let person = new Proxy({}, validator);
-21
-22person.age = 100;
-23console.log(person.age); // 100
-24person.age = 'young'; // Throws an exception
-25person.age = 300; // Throws an exception
-

Binary and Octal Literals

-
0b111110111 === 503 // true
+

ES6について

+7 minute read

Overview

https://github.com/lukehoban/es6features#readme

http://help.wtf/es6

http://es6-features.org

String

String.x is deprecated; use String.prototype.x instead.

非推奨の構文:

1var num = 15; 
+2String.replace(num, /5/, '2');
+

標準の構文:

1var num = 15;
+2String(num).replace(/5/, '2');
+

Template literal

Nesting templates:

1const classes = `header ${ isLargeScreen() ? '' : `icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`;
+

タグ付けされたtemplate

 1var a = 5;
+ 2var b = 10;
+ 3
+ 4function tag(strings, ...values) {
+ 5  console.log(strings[0]); // "Hello "
+ 6  console.log(strings[1]); // " world"
+ 7  console.log(values[0]);  // 15
+ 8  console.log(values[1]);  // 50
+ 9
+10  return "Bazinga!";
+11}
+12
+13tag`Hello ${ a + b } world ${ a * b}`;
+14// "Bazinga!"
+

http://help.wtf/es6#template_literals

 1// Backticks enclose a template literal; ${} interpolates arbitrary expressions
+ 2let num = 99; // see block scope
+ 3console.log(`${num} bottles of beer on the wall, ${num} bottles of beer
+ 4Take one down and pass it around, ${--num} bottles of beer!`);
+ 5
+ 6// Tagged form: Attach a function that processes string fragments and evaluated
+ 7// expressions
+ 8function celsius(strings, ...values) {
+ 9  let rv = '';
+10  strings.forEach((string, index) => { // See arrow functions
+11    rv += string;
+12    if (typeof values[index] !== 'undefined')
+13      rv += Math.round((values[index] - 32) / 1.8);
+14  });
+15  return rv;
+16}
+17
+18// Converts all the interpolated numbers to the proper unit
+19console.log(celsius `Today temperatures ranged from ${60} to ${65} degrees.`);
+

var and let

https://eslint.org/docs/rules/no-var

ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let and const keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes.

1if (true) {
+2    var i = 1;
+3    let j = 2;
+4}
+5
+6console.log(i) // 1
+7console.log(j) // ReferenceError: not defined
+

Default function parameters

1function multiply(a, b = 1) {
+2  return a * b;
+3}
+

Iterators and for…of

 1let fibonacci = {
+ 2  [Symbol.iterator]() {
+ 3    let pre = 0, cur = 1;
+ 4    return {
+ 5      next() {
+ 6        [pre, cur] = [cur, pre + cur];
+ 7        return { done: false, value: cur }
+ 8      }
+ 9    }
+10  }
+11}
+12
+13for (var n of fibonacci) {
+14  // truncate the sequence at 1000
+15  if (n > 1000)
+16    break;
+17  console.log(n);
+18}
+

More: Duck Typing

Modules

import and export

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

Module Loaders

Module loaders support:

  • Dynamic loading
  • State isolation
  • Global namespace isolation
  • Compilation hooks
  • Nested virtualization

The default module loader can be configured, and new loaders can be constructed to evaluate and load code in isolated or constrained contexts.

 1// Dynamic loading – ‘System’ is default loader
+ 2System.import('lib/math').then(function(m) {
+ 3  alert("2π = " + m.sum(m.pi, m.pi));
+ 4});
+ 5
+ 6// Create execution sandboxes – new Loaders
+ 7var loader = new Loader({
+ 8  global: fixup(window) // replace ‘console.log’
+ 9});
+10loader.eval("console.log('hello world!');");
+11
+12// Directly manipulate module cache
+13System.get('jquery');
+14System.set('jquery', Module({$: $})); // WARNING: not yet finalized
+

Promises

JavaScript Promiseの本

 1function asyncFunction() {
+ 2    
+ 3    return new Promise(function (resolve, reject) {
+ 4        setTimeout(function () {
+ 5            resolve('Async Hello world');
+ 6        }, 16);
+ 7    });
+ 8}
+ 9
+10asyncFunction().then(function (value) {
+11    console.log(value);    // => 'Async Hello world'
+12}).catch(function (error) {
+13    console.error(error);
+14});
+

Generators

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

 1// A generator function will return an object that implements the iteration
+ 2// protocol, i.e., it has a next() method that returns
+ 3// { value: < some value>, done: <true or false> }
+ 4function* incRand(max) { // Asterisk defines this as a generator function
+ 5  while (true) {
+ 6    // Pause execution after the yield, resume when next(<something>) is called
+ 7    // and assign <something> to x
+ 8    let x = yield Math.floor(Math.random() * max + 1);
+ 9    max += x;
+10  }
+11}
+12var rng = incRand(2); // Now we have a generator object to work with
+13console.log(rng.next()); // { value: <between 1 and 2>, done: false }
+14console.log(rng.next(3)); // as above, but between 1 and 5
+15console.log(rng.next()); // as above, but NaN since 5 + undefined results in NaN
+16console.log(rng.next(20)); // Oops, looks like we broke it! NaN again.
+17rng.throw(new Error('Unrecoverable generator state.')); // Will be thrown from yield
+

shorthand of Object initializer

https://ariya.io/2013/02/es6-and-object-literal-property-value-shorthand

 1// Shorthand property names (ES2015)
+ 2var a = 'foo', b = 42, c = {};
+ 3var o = {a, b, c};
+ 4
+ 5// Shorthand method names (ES2015)
+ 6var o = {
+ 7  property(parameters) {}
+ 8};
+ 9
+10// Computed property names (ES2015)
+11var prop = 'foo';
+12var o = {
+13  [prop]: 'hey',
+14  ['b' + 'ar']: 'there'
+15};
+

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Destructuring

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Destructuring is fail-soft, similar to standard object lookup foo[“bar”], producing undefined values when not found.

1let [n1, n2, n3, n4, ...r] = [100, 'three', 34, {number: 23}, 694, 'eighteen'];
+2console.log(n1, n2, n3, n4); // "100 'three' 34 { number: 23 }"
+3console.log(r); // "[ 694, 'eighteen' ]"
+

Two variables values can be swapped in one destructuring expression

1var a = 1;
+2var b = 3;
+3
+4[a, b] = [b, a];
+5console.log(a); // 3
+6console.log(b); // 1
+

Object Destructuring

1var o = {p: 42, q: true};
+2var {p, q} = o;
+3
+4console.log(p); // 42
+5console.log(q); // true
+

Works for function parameters

1var fmt = ({id = 0, name}) => `${id}: ${name}`;
+2console.log(fmt({ id: 1, name: 'joe'}));
+

symbol

https://developer.mozilla.org/en-US/docs/Glossary/Symbol

sympol is a primitive data type. The Symbol() function returns a value of type symbol and every returned value is unique. It does not support new Symbol()

1var sym1 = Symbol();
+2var sym2 = Symbol('foo');
+3var sym3 = Symbol('foo');
+4
+5Symbol('foo') === Symbol('foo'); // false
+6var sym = new Symbol(); // TypeError
+

Map + Set + WeakMap + WeakSet

Reference: Why WeakMap?

Native WeakMaps hold “weak” references to key objects, which means that they do not prevent garbage collection in case there would be no other reference to the key object. This also avoids preventing garbage collection of values in the map.

 1/ Sets
+ 2var s = new Set();
+ 3s.add("hello").add("goodbye").add("hello");
+ 4s.size === 2;
+ 5s.has("hello") === true;
+ 6
+ 7// Maps
+ 8var m = new Map();
+ 9m.set("hello", 42);
+10m.set(s, 34);
+11m.get(s) == 34;
+12
+13// Weak Maps
+14var wm = new WeakMap();
+15wm.set(s, { extra: 42 });
+16wm.size === undefined
+17
+18// Weak Sets
+19var ws = new WeakSet();
+20ws.add({ data: 42 });
+21// Because the added object has no other references, it will not be held in the set
+

New APIs in core libraries

 1// Number
+ 2Number.EPSILON
+ 3Number.isInteger(Infinity) // false
+ 4Number.isNaN("NaN") // false
+ 5
+ 6// Math
+ 7Math.acosh(3) // 1.762747174039086
+ 8Math.hypot(3, 4) // 5
+ 9Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
+10
+11// String
+12"abcde".includes("cd") // true
+13"abc".repeat(3) // "abcabcabc"
+14
+15// Array
+16Array.from(document.querySelectorAll('*')) // Returns a real Array
+17Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
+18[0, 0, 0].fill(7, 1) // [0,7,7]
+19[1, 2, 3].find(x => x == 3) // 3
+20[1, 2, 3].findIndex(x => x == 2) // 1
+21[1, 2, 3, 4, 5].copyWithin(3, 0) // [1, 2, 3, 1, 2]
+22["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
+23["a", "b", "c"].keys() // iterator 0, 1, 2
+24["a", "b", "c"].values() // iterator "a", "b", "c"
+25
+26// Object
+27Object.assign(Point, { origin: new Point(0,0) })
+

Proxies

The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).

See more examples at MDN Proxy doc

No-op forwarding proxy

1var target = {};
+2var p = new Proxy(target, {});
+3
+4p.a = 37; // operation forwarded to the target
+5
+6console.log(target.a); // 37. The operation has been properly forwarded
+

Validation

 1let validator = {
+ 2  set: function(obj, prop, value) {
+ 3    if (prop === 'age') {
+ 4      if (!Number.isInteger(value)) {
+ 5        throw new TypeError('The age is not an integer');
+ 6      }
+ 7      if (value > 200) {
+ 8        throw new RangeError('The age seems invalid');
+ 9      }
+10    }
+11
+12    // The default behavior to store the value
+13    obj[prop] = value;
+14
+15    // Indicate success
+16    return true;
+17  }
+18};
+19
+20let person = new Proxy({}, validator);
+21
+22person.age = 100;
+23console.log(person.age); // 100
+24person.age = 'young'; // Throws an exception
+25person.age = 300; // Throws an exception
+

Binary and Octal Literals

0b111110111 === 503 // true
 0o767 === 503 // true
-

その他

-

Reflect API

-

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect

-

Tail calls

-
1function factorial(n, acc = 1) {
-2    'use strict';
-3    if (n <= 1) return acc;
-4    return factorial(n - 1, n * acc);
-5}
-6
-7// Stack overflow in most implementations today,
-8// but safe on arbitrary inputs in ES6
-9factorial(100000)
-

Unicode

-

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode

-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

その他

Reflect API

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect

Tail calls

1function factorial(n, acc = 1) {
+2    'use strict';
+3    if (n <= 1) return acc;
+4    return factorial(n - 1, n * acc);
+5}
+6
+7// Stack overflow in most implementations today,
+8// but safe on arbitrary inputs in ES6
+9factorial(100000)
+

Unicode

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode

\ No newline at end of file diff --git a/posts/2019-01-19-vue-navigation-guards/index.html b/posts/2019-01-19-vue-navigation-guards/index.html index 40371cc3..2118273d 100644 --- a/posts/2019-01-19-vue-navigation-guards/index.html +++ b/posts/2019-01-19-vue-navigation-guards/index.html @@ -1,359 +1,78 @@ - - - - - - - - - - - VueのNavigation Guards | Cactus theme example - - - - - - - - - - - - - - - - - - -
-
- +VueのNavigation Guards | Cactus theme example +
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-VueのNavigation Guards -

-
- -
- -2 minute read -
-

VueのNavigation Guards

+2 minute read
-
-
-
-

Navigation guards are provided by vue-router. -Three ways to hook:

-
    -
  • globally
  • -
  • per-route
  • -
  • in-component
  • -
-

NOTE:

-
    -
  1. Params or query changes won’t trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard.
  2. -
  3. Make sure to always call the next function, otherwise the hook will never be resolved.
  4. -
-

Global

-
 1const router = new VueRouter({ ... })
- 2
- 3// Before Guards
- 4router.beforeEach((to, from, next) => {
- 5  // ...
- 6})
- 7
- 8// Resolve Guards
- 9// beforeResolve guards will be called right before the navigation is confirmed
-10// after all in-component guards and async route components are resolved
-11router.beforeResolve((to, from, next) => {
-12  // ...
-13})
-14
-15// After Hooks
-16router.afterEach((to, from) => {
-17  // ...
-18})
-

Pre-reoute

-
 1const router = new VueRouter({
- 2  routes: [
- 3    {
- 4      path: '/foo',
- 5      component: Foo,
- 6      beforeEnter: (to, from, next) => {
- 7        // ...
- 8      }
- 9    }
-10  ]
-11})
-

In-component

-
 1const Foo = {
- 2  template: `...`,
- 3  beforeRouteEnter (to, from, next) {
- 4    // called before the route that renders this component is confirmed.
- 5    // does NOT have access to `this` component instance,
- 6    // because it has not been created yet when this guard is called!
- 7    // However, you can access the instance by passing a callback to next. 
- 8    // The callback will be called when the navigation is confirmed
- 9    // and the component instance will be passed to the callback as the argument
-10    beforeRouteEnter (to, from, next) {
-11      next(vm => {
-12        // access to component instance via `vm`
-13      })
-14    }
-15  },
-16  beforeRouteUpdate (to, from, next) {
-17    // called when the route that renders this component has changed,
-18    // but this component is reused in the new route.
-19    // For example, for a route with dynamic params `/foo/:id`, when we
-20    // navigate between `/foo/1` and `/foo/2`, the same `Foo` component instance
-21    // will be reused, and this hook will be called when that happens.
-22    // has access to `this` component instance.
-23  },
-24  beforeRouteLeave (to, from, next) {
-25    // called when the route that renders this component is about to
-26    // be navigated away from.
-27    // has access to `this` component instance.
-28  }
-29}
-

Resolve flow

-
    -
  • Navigation triggered.
  • -
  • Call leave guards in deactivated components.
  • -
  • Call global beforeEach guards.
  • -
  • Call beforeRouteUpdate guards in reused components.
  • -
  • Call beforeEnter in route configs.
  • -
  • Resolve async route components.
  • -
  • Call beforeRouteEnter in activated components.
  • -
  • Call global beforeResolve guards.
  • -
  • Navigation confirmed.
  • -
  • Call global afterEach hooks.
  • -
  • DOM updates triggered.
  • -
  • Call callbacks passed to next in beforeRouteEnter guards with instantiated instances.
  • -
-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

Navigation guards are provided by vue-router. +Three ways to hook:

  • globally
  • per-route
  • in-component

NOTE:

  1. Params or query changes won’t trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard.
  2. Make sure to always call the next function, otherwise the hook will never be resolved.

Global

 1const router = new VueRouter({ ... })
+ 2
+ 3// Before Guards
+ 4router.beforeEach((to, from, next) => {
+ 5  // ...
+ 6})
+ 7
+ 8// Resolve Guards
+ 9// beforeResolve guards will be called right before the navigation is confirmed
+10// after all in-component guards and async route components are resolved
+11router.beforeResolve((to, from, next) => {
+12  // ...
+13})
+14
+15// After Hooks
+16router.afterEach((to, from) => {
+17  // ...
+18})
+

Pre-reoute

 1const router = new VueRouter({
+ 2  routes: [
+ 3    {
+ 4      path: '/foo',
+ 5      component: Foo,
+ 6      beforeEnter: (to, from, next) => {
+ 7        // ...
+ 8      }
+ 9    }
+10  ]
+11})
+

In-component

 1const Foo = {
+ 2  template: `...`,
+ 3  beforeRouteEnter (to, from, next) {
+ 4    // called before the route that renders this component is confirmed.
+ 5    // does NOT have access to `this` component instance,
+ 6    // because it has not been created yet when this guard is called!
+ 7    // However, you can access the instance by passing a callback to next. 
+ 8    // The callback will be called when the navigation is confirmed
+ 9    // and the component instance will be passed to the callback as the argument
+10    beforeRouteEnter (to, from, next) {
+11      next(vm => {
+12        // access to component instance via `vm`
+13      })
+14    }
+15  },
+16  beforeRouteUpdate (to, from, next) {
+17    // called when the route that renders this component has changed,
+18    // but this component is reused in the new route.
+19    // For example, for a route with dynamic params `/foo/:id`, when we
+20    // navigate between `/foo/1` and `/foo/2`, the same `Foo` component instance
+21    // will be reused, and this hook will be called when that happens.
+22    // has access to `this` component instance.
+23  },
+24  beforeRouteLeave (to, from, next) {
+25    // called when the route that renders this component is about to
+26    // be navigated away from.
+27    // has access to `this` component instance.
+28  }
+29}
+

Resolve flow

  • Navigation triggered.
  • Call leave guards in deactivated components.
  • Call global beforeEach guards.
  • Call beforeRouteUpdate guards in reused components.
  • Call beforeEnter in route configs.
  • Resolve async route components.
  • Call beforeRouteEnter in activated components.
  • Call global beforeResolve guards.
  • Navigation confirmed.
  • Call global afterEach hooks.
  • DOM updates triggered.
  • Call callbacks passed to next in beforeRouteEnter guards with instantiated instances.
\ No newline at end of file diff --git a/posts/2019-03-08-es6-bind-trick/index.html b/posts/2019-03-08-es6-bind-trick/index.html index 5c6e70b2..0fbec8ad 100644 --- a/posts/2019-03-08-es6-bind-trick/index.html +++ b/posts/2019-03-08-es6-bind-trick/index.html @@ -1,283 +1,42 @@ - - - - - - - - - - - Bind specific arguments of a function | Cactus theme example - - - - - - - - - - - - - - - - - - -
-
- +Bind specific arguments of a function | Cactus theme example +
- - - - - -
- - - + +
- -
-
- -
- -
-
-
-
-
-

-Bind specific arguments of a function -

-
- -
- -1 minute read -
- -
-
-
-

To bind specific (nth) arguments of a function, we can write a decorator instead of using Function.bind():

-
 1function func(p1, p2, p3) {
- 2    console.log(p1, p2, p3);
- 3}
- 4// the binding starts after however many are passed in.
- 5function decorator(...bound_args) {
- 6    return function(...args) {
- 7        return func(...args, ...bound_args);
- 8    };
- 9}
-10
-11// bind the last parameter
-12let f = decorator("3");
-13f("a", "b");  // a b 3
-14
-15// bind the last two parameter
-16let f2 = decorator("2", "3")
-17f2("a");  // a 2 3
-

Even if we want to bind just the nth argument, we can do as follows:

-
 1// bind a specific (nth) argument
- 2function decoratorN(n, bound_arg) {
- 3    return function(...args) {
- 4        args[n-1] = bound_arg;
- 5        return func(...args);
- 6    }
- 7}
- 8
- 9let fN = decoratorN(2, "2");
-10fN("a","b","c"); // a 2 c
-

https://stackoverflow.com/questions/27699493/javascript-partially-applied-function-how-to-bind-only-the-2nd-parameter

-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

Bind specific arguments of a function

+1 minute read

To bind specific (nth) arguments of a function, we can write a decorator instead of using Function.bind():

 1function func(p1, p2, p3) {
+ 2    console.log(p1, p2, p3);
+ 3}
+ 4// the binding starts after however many are passed in.
+ 5function decorator(...bound_args) {
+ 6    return function(...args) {
+ 7        return func(...args, ...bound_args);
+ 8    };
+ 9}
+10
+11// bind the last parameter
+12let f = decorator("3");
+13f("a", "b");  // a b 3
+14
+15// bind the last two parameter
+16let f2 = decorator("2", "3")
+17f2("a");  // a 2 3
+

Even if we want to bind just the nth argument, we can do as follows:

 1// bind a specific (nth) argument
+ 2function decoratorN(n, bound_arg) {
+ 3    return function(...args) {
+ 4        args[n-1] = bound_arg;
+ 5        return func(...args);
+ 6    }
+ 7}
+ 8
+ 9let fN = decoratorN(2, "2");
+10fN("a","b","c"); // a 2 c
+

https://stackoverflow.com/questions/27699493/javascript-partially-applied-function-how-to-bind-only-the-2nd-parameter

\ No newline at end of file diff --git a/posts/2019-03-08-object-assign-with-accessor-descriptor/index.html b/posts/2019-03-08-object-assign-with-accessor-descriptor/index.html index 0c8d9782..a47f811f 100644 --- a/posts/2019-03-08-object-assign-with-accessor-descriptor/index.html +++ b/posts/2019-03-08-object-assign-with-accessor-descriptor/index.html @@ -1,21 +1,5 @@ - - - - - - - - - - - Object.assign() with accessor descriptor | Cactus theme example - - - - - - -Object.assign() with accessor descriptor | Cactus theme example +
- - - - - -
- - - + +
- -
-
- -
- -
-
-
-
-
-

-Object.assign() with accessor descriptor -

-
- -
- -1 minute read -
- -
-
-
-

MDN docs:

-
-

The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties versus just copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.

-
-

For example

-
 1class Cat {
- 2    constructor(name) {
- 3        this._name = name;
- 4    }
- 5
- 6    get name() {
- 7        return this._name;
- 8    }
- 9    set name(value) {
-10        this._name = value;
-11    }
-12}
-13
-14let nyannko = new Cat("nyannko");
-15let copy = Object.assign({}, nyannko)
-16
-17console.log(nyannko.name) // nyannko
-18console.log(copy.name) // undefined
-

The name property is lost.

-

To copy accessors, we can use Object.getOwnPropertyDescriptor() and Object.defineProperty() as the MDN docs recommend:

-
 1var obj = {
- 2  foo: 1,
- 3  get bar() {
- 4    return 2;
- 5  }
- 6};
- 7
- 8var copy = Object.assign({}, obj); 
- 9console.log(copy); 
-10// { foo: 1, bar: 2 }, the value of copy.bar is obj.bar's getter's return value.
-11
-12// This is an assign function that copies full descriptors
-13function completeAssign(target, ...sources) {
-14  sources.forEach(source => {
-15    let descriptors = Object.keys(source).reduce((descriptors, key) => {
-16      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
-17      return descriptors;
-18    }, {});
-19    // by default, Object.assign copies enumerable Symbols too
-20    Object.getOwnPropertySymbols(source).forEach(sym => {
-21      let descriptor = Object.getOwnPropertyDescriptor(source, sym);
-22      if (descriptor.enumerable) {
-23        descriptors[sym] = descriptor;
-24      }
-25    });
-26    Object.defineProperties(target, descriptors);
-27  });
-28  return target;
-29}
-30
-31var copy = completeAssign({}, obj);
-32console.log(copy);
-33// { foo:1, get bar() { return 2 } }
-

The other way is Object.prototype.__proto__ (but not recommended):

-
1let completeCopy = Object.assign({__proto__: nyannko.__proto__}, nyannko);
-2console.log(completeCopy.name); // nyannko
-

Object.prototype.__proto__ is deprecated so be aware that this may cease to work at any time. -https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto

-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

Object.assign() with accessor descriptor

+1 minute read

MDN docs:

The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties versus just copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.

For example

 1class Cat {
+ 2    constructor(name) {
+ 3        this._name = name;
+ 4    }
+ 5
+ 6    get name() {
+ 7        return this._name;
+ 8    }
+ 9    set name(value) {
+10        this._name = value;
+11    }
+12}
+13
+14let nyannko = new Cat("nyannko");
+15let copy = Object.assign({}, nyannko)
+16
+17console.log(nyannko.name) // nyannko
+18console.log(copy.name) // undefined
+

The name property is lost.

To copy accessors, we can use Object.getOwnPropertyDescriptor() and Object.defineProperty() as the MDN docs recommend:

 1var obj = {
+ 2  foo: 1,
+ 3  get bar() {
+ 4    return 2;
+ 5  }
+ 6};
+ 7
+ 8var copy = Object.assign({}, obj); 
+ 9console.log(copy); 
+10// { foo: 1, bar: 2 }, the value of copy.bar is obj.bar's getter's return value.
+11
+12// This is an assign function that copies full descriptors
+13function completeAssign(target, ...sources) {
+14  sources.forEach(source => {
+15    let descriptors = Object.keys(source).reduce((descriptors, key) => {
+16      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
+17      return descriptors;
+18    }, {});
+19    // by default, Object.assign copies enumerable Symbols too
+20    Object.getOwnPropertySymbols(source).forEach(sym => {
+21      let descriptor = Object.getOwnPropertyDescriptor(source, sym);
+22      if (descriptor.enumerable) {
+23        descriptors[sym] = descriptor;
+24      }
+25    });
+26    Object.defineProperties(target, descriptors);
+27  });
+28  return target;
+29}
+30
+31var copy = completeAssign({}, obj);
+32console.log(copy);
+33// { foo:1, get bar() { return 2 } }
+

The other way is Object.prototype.__proto__ (but not recommended):

1let completeCopy = Object.assign({__proto__: nyannko.__proto__}, nyannko);
+2console.log(completeCopy.name); // nyannko
+

Object.prototype.__proto__ is deprecated so be aware that this may cease to work at any time. +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto

\ No newline at end of file diff --git a/posts/2019-03-22-js-tips/index.html b/posts/2019-03-22-js-tips/index.html index 0bef3389..e7c4b456 100644 --- a/posts/2019-03-22-js-tips/index.html +++ b/posts/2019-03-22-js-tips/index.html @@ -1,21 +1,5 @@ - - - - - - - - - - - Js tips I can't remember | Cactus theme example - - - - - - -Js tips I can't remember | Cactus theme example + - - - - - - - - - - - -
-
- +">
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-Js tips I can't remember -

-
- -
- -3 minute read -
- -
-
-
-

__proto__ VS prototype

-
-

__proto__ is the actual object that is used in the lookup chain to resolve methods and others. prototype is the object that is used to build __proto__ when creating an object with new.

-
-
-

The “cool kids” in JavaScript would generally pronounce __proto__ as “dunder proto”.

-
-

https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript

-
1( new Foo ).__proto__ === Foo.prototype; // true
-2( new Foo ).prototype === undefined; // true
-

{} VS Object.create(null)

-

Object.create(null) can create a ‘pure’ empty object that is without the delegation to Object.prototype.

-
1let obj1 = {};
-2let obj2 = Object.create(null);
-3console.log(obj1.__proto__); // {constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
-4console.log(obj2.__proto__); // undefined
-

Computed Property Names

-

ES6 adds computed property names, which is helpful when declaring objects using the object-literal syntax.

-
1var prefix = "foo";
-2
-3var myObject = {
-4	[prefix + "bar"]: "hello",
-5	[prefix + "baz"]: "world"
-6};
-7
-8myObject["foobar"]; // hello
-9myObject["foobaz"]; // world
-

Dangerous Function.prototype.name comparison

-

Sometimes we may spectify a function by comparing the function name:

-
1function Foo() {};
-2let foo = new Foo();
-3
-4if (foo.constructor.name === 'Foo') {
-5  console.log("'foo' is an instance of 'Foo'");
-6} else {
-7  console.log('Oops!');
-8}
-

It may behave unexpectedly after building because most build tools compress the code to forms like:

-
1function a() {};
-2let b = new a();
-3if (b.constructor.name === 'Foo') {
-4  console.log("'foo' is an instance of 'Foo'");
-5} else {
-6  console.log('Oops!');
-7}
-

A more robust way of performing object property check

-

Normally we use hasOwnProperty() checks to see if object has the property or not. But consider objects created by:

-
1// this will not consult the [[Prototype]] chain
-2let obj = Object.create(null)
-

Such object does not link to Object.prototype, thus obj.hasOwnProperty(...) would fail and raise error.

-

We can use a more robust way to perform property check:

-
1Object.prototype.hasOwnProperty.call(obj,"a") //false
-

Or:

-
1// this will check the current object or any higher level of the [[Prototype]] chain
-2"a" in obj
-

for...in vs for...of

-

The for..in loop iterates over the list of enumerable properties on an object (including its [[Prototype]] chain).The for...of iterate over the values directly instead of the array indices (or object properties). It asks built-in or custom @@iterator of the thing to be iterated.

-
 1let arr = ['a', 'b', 'c']
- 2arr.name = 'foo'
- 3
- 4arr // ["a", "b", "c", name: "foo"]
- 5
- 6for (key in arr)
- 7  console.log(key) // 0 1 2 name
- 8
- 9for (value of arr)
-10  console.log(value) // a b c
-

“(Prototypal) Inheritance”

-

When writing “prototype style” code like implementing Parent-Child class inheritance:

-
 1function Foo(name) {
- 2	this.name = name;
- 3}
- 4
- 5Foo.prototype.myName = function() {
- 6	return this.name;
- 7};
- 8
- 9function Bar(name,label) {
-10	Foo.call( this, name );
-11	this.label = label;
-12}
-13
-14// Then trying to build a family with Foo and Bar
-15// ...
-

A common mis-conception/confusion here is that either of the following approaches would also work, but they do not work as you’d expect:

-
1// doesn't work like you want!
-2Bar.prototype = Foo.prototype;
-3
-4// works kinda like you want, but with
-5// side-effects you probably don't want :(
-6Bar.prototype = new Foo();
-

the right way is:

-
1// "make a new 'Bar dot prototype' object that's linked to 'Foo dot prototype'."
-2// pre-ES6
-3// throws away default existing `Bar.prototype`
-4Bar.prototype = Object.create( Foo.prototype );
-5
-6// ES6+
-7// modifies existing `Bar.prototype`
-8Object.setPrototypeOf( Bar.prototype, Foo.prototype );
-

reference: You-Dont-Know-JS: “(Prototypal) Inheritance”

-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

Js tips I can't remember

+3 minute read

__proto__ VS prototype

__proto__ is the actual object that is used in the lookup chain to resolve methods and others. prototype is the object that is used to build __proto__ when creating an object with new.

The “cool kids” in JavaScript would generally pronounce __proto__ as “dunder proto”.

https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript

1( new Foo ).__proto__ === Foo.prototype; // true
+2( new Foo ).prototype === undefined; // true
+

{} VS Object.create(null)

Object.create(null) can create a ‘pure’ empty object that is without the delegation to Object.prototype.

1let obj1 = {};
+2let obj2 = Object.create(null);
+3console.log(obj1.__proto__); // {constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
+4console.log(obj2.__proto__); // undefined
+

Computed Property Names

ES6 adds computed property names, which is helpful when declaring objects using the object-literal syntax.

1var prefix = "foo";
+2
+3var myObject = {
+4	[prefix + "bar"]: "hello",
+5	[prefix + "baz"]: "world"
+6};
+7
+8myObject["foobar"]; // hello
+9myObject["foobaz"]; // world
+

Dangerous Function.prototype.name comparison

Sometimes we may spectify a function by comparing the function name:

1function Foo() {};
+2let foo = new Foo();
+3
+4if (foo.constructor.name === 'Foo') {
+5  console.log("'foo' is an instance of 'Foo'");
+6} else {
+7  console.log('Oops!');
+8}
+

It may behave unexpectedly after building because most build tools compress the code to forms like:

1function a() {};
+2let b = new a();
+3if (b.constructor.name === 'Foo') {
+4  console.log("'foo' is an instance of 'Foo'");
+5} else {
+6  console.log('Oops!');
+7}
+

A more robust way of performing object property check

Normally we use hasOwnProperty() checks to see if object has the property or not. But consider objects created by:

1// this will not consult the [[Prototype]] chain
+2let obj = Object.create(null)
+

Such object does not link to Object.prototype, thus obj.hasOwnProperty(...) would fail and raise error.

We can use a more robust way to perform property check:

1Object.prototype.hasOwnProperty.call(obj,"a") //false
+

Or:

1// this will check the current object or any higher level of the [[Prototype]] chain
+2"a" in obj
+

for...in vs for...of

The for..in loop iterates over the list of enumerable properties on an object (including its [[Prototype]] chain).The for...of iterate over the values directly instead of the array indices (or object properties). It asks built-in or custom @@iterator of the thing to be iterated.

 1let arr = ['a', 'b', 'c']
+ 2arr.name = 'foo'
+ 3
+ 4arr // ["a", "b", "c", name: "foo"]
+ 5
+ 6for (key in arr)
+ 7  console.log(key) // 0 1 2 name
+ 8
+ 9for (value of arr)
+10  console.log(value) // a b c
+

“(Prototypal) Inheritance”

When writing “prototype style” code like implementing Parent-Child class inheritance:

 1function Foo(name) {
+ 2	this.name = name;
+ 3}
+ 4
+ 5Foo.prototype.myName = function() {
+ 6	return this.name;
+ 7};
+ 8
+ 9function Bar(name,label) {
+10	Foo.call( this, name );
+11	this.label = label;
+12}
+13
+14// Then trying to build a family with Foo and Bar
+15// ...
+

A common mis-conception/confusion here is that either of the following approaches would also work, but they do not work as you’d expect:

1// doesn't work like you want!
+2Bar.prototype = Foo.prototype;
+3
+4// works kinda like you want, but with
+5// side-effects you probably don't want :(
+6Bar.prototype = new Foo();
+

the right way is:

1// "make a new 'Bar dot prototype' object that's linked to 'Foo dot prototype'."
+2// pre-ES6
+3// throws away default existing `Bar.prototype`
+4Bar.prototype = Object.create( Foo.prototype );
+5
+6// ES6+
+7// modifies existing `Bar.prototype`
+8Object.setPrototypeOf( Bar.prototype, Foo.prototype );
+

reference: You-Dont-Know-JS: “(Prototypal) Inheritance”

\ No newline at end of file diff --git a/posts/2019-03-28-javascript-comparison/index.html b/posts/2019-03-28-javascript-comparison/index.html index 59c4e9cf..48865cff 100644 --- a/posts/2019-03-28-javascript-comparison/index.html +++ b/posts/2019-03-28-javascript-comparison/index.html @@ -1,296 +1,36 @@ - - - - - - - - - - - JavaScript Comparison operation at a glance | Cactus theme example - - - - - - -JavaScript Comparison operation at a glance | Cactus theme example + - - - - - - - - - - - -
-
- +The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:">
- - - - - -
- - - + +
- -
-
- -
- -
-
-
-
-
-

-JavaScript Comparison operation at a glance -

-
- -
- -1 minute read -
- -
-
-
-

When given a scenario like:

-
1console.log(null > -1) //true
-

It produces true, which makes me think null is treated as 0. But when I run:

-
1console.log(null == 0) // false
-2console.log(null > 0) // false
-3console.log(null < 0) // false
-

They all output false!

-

I googled a lot and finally found answers in Ecma-262 Specification.

-

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

-
 11. If Type(x) is the same as Type(y), then return the result of performing Strict Equality Comparison x === y.
- 22. If x is null and y is undefined, return true.
- 33. If x is undefined and y is null, return true.
- 44. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
- 55. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
- 66. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
- 77. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
- 88. If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
- 99. If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
-1010. Return false.
-

Relational comparison is much more complex so I’m not copying that section. Read at the spec website.

-

TL;DR

-

Anyway it seems that in null == 0, null is treated just as is, and equality comparison between null and Number always return false (No 10). -But when it comes null > -1, null is conversed to 0 using ToNumber() algorithm.

-

Read more:

- -
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

JavaScript Comparison operation at a glance

+1 minute read

When given a scenario like:

1console.log(null > -1) //true
+

It produces true, which makes me think null is treated as 0. But when I run:

1console.log(null == 0) // false
+2console.log(null > 0) // false
+3console.log(null < 0) // false
+

They all output false!

I googled a lot and finally found answers in Ecma-262 Specification.

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

 11. If Type(x) is the same as Type(y), then return the result of performing Strict Equality Comparison x === y.
+ 22. If x is null and y is undefined, return true.
+ 33. If x is undefined and y is null, return true.
+ 44. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
+ 55. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
+ 66. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
+ 77. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
+ 88. If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
+ 99. If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
+1010. Return false.
+

Relational comparison is much more complex so I’m not copying that section. Read at the spec website.

TL;DR

Anyway it seems that in null == 0, null is treated just as is, and equality comparison between null and Number always return false (No 10). +But when it comes null > -1, null is conversed to 0 using ToNumber() algorithm.

Read more:

\ No newline at end of file diff --git a/posts/2019-10-27-uipath/index.html b/posts/2019-10-27-uipath/index.html index dd2bf2bf..5f45c256 100644 --- a/posts/2019-10-27-uipath/index.html +++ b/posts/2019-10-27-uipath/index.html @@ -1,552 +1,24 @@ - - - - - - - - - - - uipath ノート(一) | Cactus theme example - - - - - - - - - - - - - - - - - - -
-
- +uipath ノート(一) | Cactus theme example +
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-uipath ノート(一) -

-
- -
- -9 minute read -
- - -
-
-
-

変数

-
    -
  • Int32
  • -
  • String
  • -
  • Boolean
  • -
  • GenericValue 参照
  • -
-
-

UiPath Studio には GenericValue 変数の自動変換メカニズムがあり、式を正しく定義することで、目的の結果を得ることができます。式の最初の要素は、Studio から操作するガイドラインとして使用されることを考慮してください。例えば、2 つの GenericValue 変数を追加し、式の最初の変数が String として定義されてた場合、最初に代入された値を元に 2 つの値を結合し、文字列となります。 Integer として定義した場合の結果は、合計の値となります。

-
-
    -
  • Array
  • -
  • DataTime
  • -
  • DataTable
  • -
-

.Net 変数型を参照して探す方法

-

アクティビティ

-

レイアウトダイアグラム

-
    -
  • シーエンス: より高度で複雑な自動化に向こう
  • -
  • フローチャート: シンプルな自動化プロジェクトに適している
  • -
  • ステートマシン
  • -
  • Global Exception Handler (グローバル例外ハンドラー)
  • -
-
-

参照:https://docs.uipath.com/studio/lang-ja/docs/workflow-design

-
-

選択肢

-
    -
  • 条件分岐(If): シーケンス用条件分岐
  • -
  • フロー条件分岐(flow desicion): フローチャート用条件分岐
  • -
  • フロースイッチ (Flow Switch)
  • -
-

繰り返し

-
    -
  • 繰り返し(前判定)(While)
  • -
  • 繰り返し(後判定)(Do While)
  • -
  • 繰り返し(コレクションの各要素)(For Each)
  • -
-

データ操作

-
    -
  • CSVを読み込み(Read CSV) -
      -
    • オプションにエンコーディングを指定できる(日本語データがある場合、"SHIFT-JIS"を指定する)
    • -
    • 列名を含める(IncludeColumnNames)を指定できる
    • -
    • 出力タイプ:System.Data.DataTable Microsoft Docs
    • -
    • Selectメソッドで半角スペースを含む列名で指定する場合、半角スペースが特殊文字ではなく文字列として認識されるため、[]で列名を囲う
    • -
    -
  • -
-
Names.Select("[メンバー ステータス] = 'Yes'")
-

その他

-
    -
  • メッセージボックス
  • -
  • 代入(assign)
  • -
  • 待機 (Delay)
  • -
  • 入力ダイアログ(input dialog):
  • -
  • フォルダーを選択(Select Folder)
  • -
  • 一行を書き込み(Write Line): Debug用?
  • -
  • アプリケーションを開く(Open Application)
  • -
  • ブラウザを開く(Open Browser)
  • -
  • ブラウザーにアタッチ(Attach Browser)
  • -
  • 文字を入力(Type Into)
  • -
  • ハイライト(Highlight)
  • -
  • アンカーベース(Anchor Base)
  • -
  • スクリーンショットをと撮る(Take Screenshot)
  • -
  • 要素の有無を検出(Element Exists)
  • -
  • 要素の消滅を待つ(Wait Element Vanish)
  • -
-

レコーディング機能

-

[○]レコーディング可

-
    -
  • 左クリック -
      -
    • ボタン
    • -
    • チェックボックス
    • -
    • ドロップダウン
    • -
    • -
    -
  • -
  • 文字入力
  • -
-

[×]レコーディング不可

-
    -
  • ショットカットキー
  • -
  • 修飾キー(ctrl + cなど)
  • -
  • 右クリック
  • -
  • マウスホバー
  • -
-

ショットカット

-
    -
  • F2 - 時間差で選択
  • -
  • F3 - 領域を選択
  • -
-

ベーシック

-
    -
  • 適する操作内容:複数ウィンドウ上の単一の操作
  • -
  • 生成されるワークフローがシンプル
  • -
-

デスクトップ

-
    -
  • 適する操作内容:同一ウィンドウ上の連続した操作
  • -
  • 生成されるワークフローが複雑
  • -
  • セレクターの保守性が良い
  • -
-

ウェブ

-

ウェブアプリとブラウザーでレコーディングを行うためのものです。コンテナーを生成し、既定で 入力をシミュレート (Simulate Type)/クリック (Click) の入力メソッドを使用します。

-

入力/出力方法まとめ

-

入力

-
    -
  • デフォルト(Default) -
      -
    • 互換性が高い
    • -
    • キーボード対応
    • -
    -
  • -
  • ウィンドウメッセージ(Windows Message) -
      -
    • バックグラウンド処理
    • -
    • キーボード対応
    • -
    -
  • -
  • シミュレート(Simulate Type/Click) -
      -
    • 互換性が低い
    • -
    • バックグラウンド処理
    • -
    • フィールド内自動削除
    • -
    -
  • -
-

出力

-
    -
  • フルテキスト(FullText) -
      -
    • スピード:★★★★★
    • -
    • 正確さ:100%
    • -
    • バックグラウンド処理
    • -
    • 非表示の項目を取得
    • -
    -
  • -
  • ネイティブ(Native) -
      -
    • スピード:★★★★
    • -
    • 正確さ:100%
    • -
    • 文字情報を取得
    • -
    -
  • -
  • OCR -
      -
    • スピード:★★
    • -
    • 正確さ:98%(?)
    • -
    • 文字情報を取得
    • -
    • CITRIX対応
    • -
    -
  • -
-

セレクター

-
    -
  • 部分セレクター
  • -
  • 完全セレクター
  • -
  • 動的なセレクター:ワイルドカードを使ってる
  • -
  • アンカーベース(Anchor Base)
  • -
  • 相対的なアンカー(Select Relative Element)
  • -
-
-

セレクターがあまり安定しないと考えられるときには、[Anchor Base(アンカーベース)] アクティビティや、UiPath Explorer の [Select Relative Element(相対的なアンカーを選択してください)] を使用することで、信頼性の高い自動化を構築できる場合があります。

-
-

アンカーベース(Anchor Base)

-

アンカーとして使用できるアクティビティ:

-
    -
  • 要素を探す(Find Element)
  • -
  • 画像を探す(Find Image)
  • -
-

EXCEL操作

-
    -
  • EXCELアプリケーションスコープ(Excel Application Scope)
  • -
  • 範囲を追加(Append Range)
  • -
  • データテーブルを並べ替え(Sort Data Table)
  • -
  • データテーブルをフィルタリング(Filter Data Table)
  • -
  • Build Data Table
  • -
  • Generate Data Table
  • -
  • Output Data Table
  • -
-

PDF操作

-

PDF Activities Pack -UiPath.PDF.Activities

-
    -
  • PDFのテキストを読み込み(Read PDf Text) -
      -
    • 範囲(Range):ページ範囲を指定する。ディフォルトは"ALL"。例: 1 3-5
    • -
    -
  • -
  • OCRでPDFを読み込み(Read PDF With OCR)
  • -
  • 画面スクレイピング(Screen Scraping)も適用
  • -
-

MAIL操作

-

MailMessageの型:

-
System.Net.Mail.MailMessage
+

uipath ノート(一)

+9 minute read

変数

  • Int32
  • String
  • Boolean
  • GenericValue 参照

UiPath Studio には GenericValue 変数の自動変換メカニズムがあり、式を正しく定義することで、目的の結果を得ることができます。式の最初の要素は、Studio から操作するガイドラインとして使用されることを考慮してください。例えば、2 つの GenericValue 変数を追加し、式の最初の変数が String として定義されてた場合、最初に代入された値を元に 2 つの値を結合し、文字列となります。 Integer として定義した場合の結果は、合計の値となります。

  • Array
  • DataTime
  • DataTable

.Net 変数型を参照して探す方法

アクティビティ

レイアウトダイアグラム

  • シーエンス: より高度で複雑な自動化に向こう
  • フローチャート: シンプルな自動化プロジェクトに適している
  • ステートマシン
  • Global Exception Handler (グローバル例外ハンドラー)

参照:https://docs.uipath.com/studio/lang-ja/docs/workflow-design

選択肢

  • 条件分岐(If): シーケンス用条件分岐
  • フロー条件分岐(flow desicion): フローチャート用条件分岐
  • フロースイッチ (Flow Switch)

繰り返し

  • 繰り返し(前判定)(While)
  • 繰り返し(後判定)(Do While)
  • 繰り返し(コレクションの各要素)(For Each)

データ操作

  • CSVを読み込み(Read CSV)
    • オプションにエンコーディングを指定できる(日本語データがある場合、"SHIFT-JIS"を指定する)
    • 列名を含める(IncludeColumnNames)を指定できる
    • 出力タイプ:System.Data.DataTable Microsoft Docs
    • Selectメソッドで半角スペースを含む列名で指定する場合、半角スペースが特殊文字ではなく文字列として認識されるため、[]で列名を囲う
Names.Select("[メンバー ステータス] = 'Yes'")
+

その他

  • メッセージボックス
  • 代入(assign)
  • 待機 (Delay)
  • 入力ダイアログ(input dialog):
  • フォルダーを選択(Select Folder)
  • 一行を書き込み(Write Line): Debug用?
  • アプリケーションを開く(Open Application)
  • ブラウザを開く(Open Browser)
  • ブラウザーにアタッチ(Attach Browser)
  • 文字を入力(Type Into)
  • ハイライト(Highlight)
  • アンカーベース(Anchor Base)
  • スクリーンショットをと撮る(Take Screenshot)
  • 要素の有無を検出(Element Exists)
  • 要素の消滅を待つ(Wait Element Vanish)

レコーディング機能

[○]レコーディング可

  • 左クリック
    • ボタン
    • チェックボックス
    • ドロップダウン
  • 文字入力

[×]レコーディング不可

  • ショットカットキー
  • 修飾キー(ctrl + cなど)
  • 右クリック
  • マウスホバー

ショットカット

  • F2 - 時間差で選択
  • F3 - 領域を選択

ベーシック

  • 適する操作内容:複数ウィンドウ上の単一の操作
  • 生成されるワークフローがシンプル

デスクトップ

  • 適する操作内容:同一ウィンドウ上の連続した操作
  • 生成されるワークフローが複雑
  • セレクターの保守性が良い

ウェブ

ウェブアプリとブラウザーでレコーディングを行うためのものです。コンテナーを生成し、既定で 入力をシミュレート (Simulate Type)/クリック (Click) の入力メソッドを使用します。

入力/出力方法まとめ

入力

  • デフォルト(Default)
    • 互換性が高い
    • キーボード対応
  • ウィンドウメッセージ(Windows Message)
    • バックグラウンド処理
    • キーボード対応
  • シミュレート(Simulate Type/Click)
    • 互換性が低い
    • バックグラウンド処理
    • フィールド内自動削除

出力

  • フルテキスト(FullText)
    • スピード:★★★★★
    • 正確さ:100%
    • バックグラウンド処理
    • 非表示の項目を取得
  • ネイティブ(Native)
    • スピード:★★★★
    • 正確さ:100%
    • 文字情報を取得
  • OCR
    • スピード:★★
    • 正確さ:98%(?)
    • 文字情報を取得
    • CITRIX対応

セレクター

  • 部分セレクター
  • 完全セレクター
  • 動的なセレクター:ワイルドカードを使ってる
  • アンカーベース(Anchor Base)
  • 相対的なアンカー(Select Relative Element)

セレクターがあまり安定しないと考えられるときには、[Anchor Base(アンカーベース)] アクティビティや、UiPath Explorer の [Select Relative Element(相対的なアンカーを選択してください)] を使用することで、信頼性の高い自動化を構築できる場合があります。

アンカーベース(Anchor Base)

アンカーとして使用できるアクティビティ:

  • 要素を探す(Find Element)
  • 画像を探す(Find Image)

EXCEL操作

  • EXCELアプリケーションスコープ(Excel Application Scope)
  • 範囲を追加(Append Range)
  • データテーブルを並べ替え(Sort Data Table)
  • データテーブルをフィルタリング(Filter Data Table)
  • Build Data Table
  • Generate Data Table
  • Output Data Table

PDF操作

PDF Activities Pack +UiPath.PDF.Activities

  • PDFのテキストを読み込み(Read PDf Text)
    • 範囲(Range):ページ範囲を指定する。ディフォルトは"ALL"。例: 1 3-5
  • OCRでPDFを読み込み(Read PDF With OCR)
  • 画面スクレイピング(Screen Scraping)も適用

MAIL操作

MailMessageの型:

System.Net.Mail.MailMessage
 System.Web.Mail.MailMessage
-
    -
  • SMTP
  • -
  • POP3
  • -
  • IMAP
  • -
  • Outlook
  • -
  • Exchange
  • -
  • IBM Notes
  • -
-

Debug

-
    -
  • トライキャッチ(Try Catch)
  • -
  • メッセージをログ(Log Message) -
      -
    • Critical
    • -
    • Error
    • -
    • Warning
    • -
    • Information
    • -
    • Trace
    • -
    • Verbose: Traceと同じレベルだが、アクティビティ start および end の両方のメッセージと、使用される変数および引数の値を記録する
    • -
    -
  • -
-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +
  • SMTP
  • POP3
  • IMAP
  • Outlook
  • Exchange
  • IBM Notes

Debug

  • トライキャッチ(Try Catch)
  • メッセージをログ(Log Message)
    • Critical
    • Error
    • Warning
    • Information
    • Trace
    • Verbose: Traceと同じレベルだが、アクティビティ start および end の両方のメッセージと、使用される変数および引数の値を記録する
\ No newline at end of file diff --git a/posts/2019-11-10-encodeuricomponent/index.html b/posts/2019-11-10-encodeuricomponent/index.html index d4fde6bc..37b8a103 100644 --- a/posts/2019-11-10-encodeuricomponent/index.html +++ b/posts/2019-11-10-encodeuricomponent/index.html @@ -1,360 +1,98 @@ - - - - - - - - - - - JavaScript URI エンコーディング | Cactus theme example - - - - - - - - - - - - - - - - - - -
-
- +JavaScript URI エンコーディング | Cactus theme example +
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-JavaScript URI エンコーディング -

-
- -
- -3 minute read -
- - -
-
-
-

まとめ

-

encodeURI()encodeURIComponent()はRFC 2396準拠である。 +

JavaScript URI エンコーディング

+3 minute read

まとめ

encodeURI()encodeURIComponent()はRFC 2396準拠である。 encodeURI() は完全な URI を表すのに必要な文字 (Reserved Characters) はエンコードしません。 また、予約されていないが “そのまま” URI に使用できる(Unreserved Marks) 文字をエンコードしません。 -encodeURIComponent() は “Unreserved Marks” 文字をエンコードしません。

-
1var set1 = ";,/?:@&=+$#"; // Reserved Characters
-2var set2 = "-_.!~*'()";   // Unreserved Marks
-3
-4console.log(encodeURI(set1)); // ;,/?:@&=+$
-5console.log(encodeURI(set2)); // -_.!~*'()
-6
-7console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24
-8console.log(encodeURIComponent(set2)); // -_.!~*'()
-

rfc2396 appendix-A

-

https://tools.ietf.org/html/rfc2396#appendix-A

-
URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
-      absoluteURI   = scheme ":" ( hier_part | opaque_part )
-      relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
+encodeURIComponent() は “Unreserved Marks” 文字をエンコードしません。

1var set1 = ";,/?:@&=+$#"; // Reserved Characters
+2var set2 = "-_.!~*'()";   // Unreserved Marks
+3
+4console.log(encodeURI(set1)); // ;,/?:@&=+$
+5console.log(encodeURI(set2)); // -_.!~*'()
+6
+7console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24
+8console.log(encodeURIComponent(set2)); // -_.!~*'()
+

rfc2396 appendix-A

https://tools.ietf.org/html/rfc2396#appendix-A

URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
+      absoluteURI   = scheme ":" ( hier_part | opaque_part )
+      relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
 
-      hier_part     = ( net_path | abs_path ) [ "?" query ]
+      hier_part     = ( net_path | abs_path ) [ "?" query ]
       opaque_part   = uric_no_slash *uric
 
-      uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
-                      "&" | "=" | "+" | "$" | ","
+      uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
+                      "&" | "=" | "+" | "$" | ","
 
-      net_path      = "//" authority [ abs_path ]
-      abs_path      = "/"  path_segments
+      net_path      = "//" authority [ abs_path ]
+      abs_path      = "/"  path_segments
       rel_path      = rel_segment [ abs_path ]
 
       rel_segment   = 1*( unreserved | escaped |
-                          ";" | "@" | "&" | "=" | "+" | "$" | "," )
+                          ";" | "@" | "&" | "=" | "+" | "$" | "," )
 
-      scheme        = alpha *( alpha | digit | "+" | "-" | "." )
+      scheme        = alpha *( alpha | digit | "+" | "-" | "." )
 
       authority     = server | reg_name
 
-      reg_name      = 1*( unreserved | escaped | "$" | "," |
-                          ";" | ":" | "@" | "&" | "=" | "+" )
+      reg_name      = 1*( unreserved | escaped | "$" | "," |
+                          ";" | ":" | "@" | "&" | "=" | "+" )
 
-      server        = [ [ userinfo "@" ] hostport ]
+      server        = [ [ userinfo "@" ] hostport ]
       userinfo      = *( unreserved | escaped |
-                         ";" | ":" | "&" | "=" | "+" | "$" | "," )
+                         ";" | ":" | "&" | "=" | "+" | "$" | "," )
 
-      hostport      = host [ ":" port ]
+      hostport      = host [ ":" port ]
       host          = hostname | IPv4address
-      hostname      = *( domainlabel "." ) toplabel [ "." ]
-      domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
-      toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
-      IPv4address   = 1*digit "." 1*digit "." 1*digit "." 1*digit
+      hostname      = *( domainlabel "." ) toplabel [ "." ]
+      domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
+      toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
+      IPv4address   = 1*digit "." 1*digit "." 1*digit "." 1*digit
       port          = *digit
 
       path          = [ abs_path | opaque_part ]
-      path_segments = segment *( "/" segment )
-      segment       = *pchar *( ";" param )
+      path_segments = segment *( "/" segment )
+      segment       = *pchar *( ";" param )
       param         = *pchar
       pchar         = unreserved | escaped |
-                      ":" | "@" | "&" | "=" | "+" | "$" | ","
+                      ":" | "@" | "&" | "=" | "+" | "$" | ","
 
       query         = *uric
 
       fragment      = *uric
       
       uric          = reserved | unreserved | escaped
-      reserved      = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
-                      "$" | ","
+      reserved      = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
+                      "$" | ","
       unreserved    = alphanum | mark
-      mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
-                      "(" | ")"
+      mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
+                      "(" | ")"
 
-      escaped       = "%" hex hex
-      hex           = digit | "A" | "B" | "C" | "D" | "E" | "F" |
-                              "a" | "b" | "c" | "d" | "e" | "f"
+      escaped       = "%" hex hex
+      hex           = digit | "A" | "B" | "C" | "D" | "E" | "F" |
+                              "a" | "b" | "c" | "d" | "e" | "f"
 
       alphanum      = alpha | digit
       alpha         = lowalpha | upalpha
 
-      lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" |
-                 "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" |
-                 "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
-      upalpha  = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
-                 "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
-                 "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"
-      digit    = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
-                 "8" | "9"
-

参考

-

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

-

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

-

https://qiita.com/aosho235/items/0581fc82f8ce2c5ac055

-

https://tools.ietf.org/html/rfc2396

-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file + lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | + "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | + "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" + upalpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | + "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | + "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" + digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | + "8" | "9" +

参考

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

https://qiita.com/aosho235/items/0581fc82f8ce2c5ac055

https://tools.ietf.org/html/rfc2396

\ No newline at end of file diff --git a/posts/2019-11-18-uipath-best-practice/index.html b/posts/2019-11-18-uipath-best-practice/index.html index c3b7d70e..327341ac 100644 --- a/posts/2019-11-18-uipath-best-practice/index.html +++ b/posts/2019-11-18-uipath-best-practice/index.html @@ -1,354 +1,42 @@ - - - - - - - - - - - uipath ノート(二)- Best Practice | Cactus theme example - - - - - - - - - - - - - - - - - - -
-
- +uipath ノート(二)- Best Practice | Cactus theme example +
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-uipath ノート(二)- Best Practice -

-
- -
- -2 minute read -
- - -
-
-
-

時間をかけて各ワークフローに適したレイアウトを選択しましょう。

-
    -
  • -

    メイン: フローチャートまたはステートマシン

    -
  • -
  • -

    ビジネスロジック: フローチャート

    -
  • -
  • -

    UI インタラクション: シーケンス

    -
  • -
  • -

    フローチャートを使用することで、入れ子状の IF を回避

    -
  • -
-

プロセスを小さなワークフローに分割しましょう。

-
    -
  • -

    分割したものを個別に開発、テスト

    -
  • -
  • -

    ワークフローの再利用

    -
  • -
  • -

    分割ファイルで作業することによる、より効率的な共同作業

    -
  • -
-

必ず例外を処理しましょう。

-
    -
  • -

    例外が発生しやすいワークフローを [Try Catch (トライキャッチ)] ブロックに配置

    -
  • -
  • -

    外部から呼び出されたワークフローでも同様

    -
  • -
  • -

    リカバリシーケンスの設定

    -
  • -
-

ワークフローを読みやすいものにしましょう。

-
    -
  • -

    すべてのコンポーネントにわかりやすい名前を選択

    -
  • -
  • -

    注記やコメントの使用

    -
  • -
  • -

    リアルタイムの実行状況のログ取得

    -
  • -
  • -

    環境設定を Config ファイルに格納

    -
  • -
-

不要になったアプリケーションを終了させることで、常にクリーンな状態を維持しましょう。

-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

uipath ノート(二)- Best Practice

+2 minute read

時間をかけて各ワークフローに適したレイアウトを選択しましょう。

  • メイン: フローチャートまたはステートマシン

  • ビジネスロジック: フローチャート

  • UI インタラクション: シーケンス

  • フローチャートを使用することで、入れ子状の IF を回避

プロセスを小さなワークフローに分割しましょう。

  • 分割したものを個別に開発、テスト

  • ワークフローの再利用

  • 分割ファイルで作業することによる、より効率的な共同作業

必ず例外を処理しましょう。

  • 例外が発生しやすいワークフローを [Try Catch (トライキャッチ)] ブロックに配置

  • 外部から呼び出されたワークフローでも同様

  • リカバリシーケンスの設定

ワークフローを読みやすいものにしましょう。

  • すべてのコンポーネントにわかりやすい名前を選択

  • 注記やコメントの使用

  • リアルタイムの実行状況のログ取得

  • 環境設定を Config ファイルに格納

不要になったアプリケーションを終了させることで、常にクリーンな状態を維持しましょう。

\ No newline at end of file diff --git a/posts/2019-11-23-uipath-orchestrator/index.html b/posts/2019-11-23-uipath-orchestrator/index.html index 5036577d..e876d7ce 100644 --- a/posts/2019-11-23-uipath-orchestrator/index.html +++ b/posts/2019-11-23-uipath-orchestrator/index.html @@ -1,359 +1,40 @@ - - - - - - - - - - - uipath ノート(三)- uipath orchestrator | Cactus theme example - - - - - - -uipath ノート(三)- uipath orchestrator | Cactus theme example + - - - - - - - - - - - -
-
- +ジョブの停止 停止(Stop):必ずワークフロー内で「停止すべきか確認(Should Stop)」アクティビティを使用する 強制終了(Kill):処理中の内容に関わらず、ジョブを停止する アクティブなジョブは削除できない パラメーター変更の優先順位 ジョブ (Jobs) -> プロセス (Processes) -> パッケージ(UiPath Studio)">
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-uipath ノート(三)- uipath orchestrator -

-
- -
- -2 minute read -
- - -
-
-

uipath ノート(三)- uipath orchestrator

+2 minute read

利用手順

Official doc: https://docs.uipath.com/robot/docs/from-orchestrator-and-the-orchestrator-settings-window

マシンを追加

マシン側でマシン名とユーザ名を確認

C:\Users\user>hostname
 DESKTOP-ABCDE5F
 
 C:\Users\user>whoami
 desktop-abcde5f\user
 
 C:\Users\user>
-

追加完了後、マシンキーを取得する。

-

ロボットを登録

-
    -
  • Type: studio (開発用?)
  • -
  • Domain/Username: 上記のユーザ名
  • -
-

ローカルのorchestrator設定

-

Uipath Robotを開き⇒orchestratorの設定で、上記のマシンキーを入力する。 +

追加完了後、マシンキーを取得する。

ロボットを登録

  • Type: studio (開発用?)
  • Domain/Username: 上記のユーザ名

ローカルのorchestrator設定

Uipath Robotを開き⇒orchestratorの設定で、上記のマシンキーを入力する。 orchestrator URLに https://platform.uipath.com/ を入力する. -Invalid machine keyというエラーが出たら、下記のようなURLを試す:

-
https://platform.uipath.com/<account name>/<service name>
-

参照:Uipath orchestrator error : invalid machine key

-

ロボットグループ(Environment)作成

-

プロジェクトをパブリッシュ(Publish)

-

プロセスを追加

-

Automations ⇒ Processes

-

ジョブ(Jobs)の実行

-

Monitoring ⇒ Jobs

-

その他

-

再パブリッシュすると、Processが最新バージョンを使うため、変更作業が必要

-

Processes ⇒ More Options ⇒ View Process ⇒ 最新のバージョンに切り替える

-

ジョブの停止

-
    -
  • 停止(Stop):必ずワークフロー内で「停止すべきか確認(Should Stop)」アクティビティを使用する
  • -
  • 強制終了(Kill):処理中の内容に関わらず、ジョブを停止する
  • -
-

アクティブなジョブは削除できない

-

パラメーター変更の優先順位

-

ジョブ (Jobs) -> プロセス (Processes) -> パッケージ(UiPath Studio)

-

マシンテンプレート

-

Machine Templates only work for Active Directory users, Attended Floating Robots and Studio Floating Robots.

-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +Invalid machine keyというエラーが出たら、下記のようなURLを試す:

https://platform.uipath.com/<account name>/<service name>
+

参照:Uipath orchestrator error : invalid machine key

ロボットグループ(Environment)作成

プロジェクトをパブリッシュ(Publish)

プロセスを追加

Automations ⇒ Processes

ジョブ(Jobs)の実行

Monitoring ⇒ Jobs

その他

再パブリッシュすると、Processが最新バージョンを使うため、変更作業が必要

Processes ⇒ More Options ⇒ View Process ⇒ 最新のバージョンに切り替える

ジョブの停止

  • 停止(Stop):必ずワークフロー内で「停止すべきか確認(Should Stop)」アクティビティを使用する
  • 強制終了(Kill):処理中の内容に関わらず、ジョブを停止する

アクティブなジョブは削除できない

パラメーター変更の優先順位

ジョブ (Jobs) -> プロセス (Processes) -> パッケージ(UiPath Studio)

マシンテンプレート

Machine Templates only work for Active Directory users, Attended Floating Robots and Studio Floating Robots.

\ No newline at end of file diff --git a/posts/2019-12-30-standardml-notes/index.html b/posts/2019-12-30-standardml-notes/index.html index 9ad195e9..2928f238 100644 --- a/posts/2019-12-30-standardml-notes/index.html +++ b/posts/2019-12-30-standardml-notes/index.html @@ -1,215 +1,17 @@ - - - - - - - - - - - Standard ML notes | Cactus theme example - - - - - - - - - - - - - - - - - - -
-
- +Standard ML notes | Cactus theme example +
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-Standard ML notes -

-
- -
- -13 minute read -
- - -
-
-

Standard ML notes

+13 minute read

Basics

Comments

(* SML comment *)
+

Variable bindings and Expressions

val x = 34;
 (* static environment: x : int *)
 (* dynamic environment: x --> 34 *)
 val y = x + 1;
@@ -219,26 +21,16 @@ 

Comments

(* Integer Division *) val w = y div x -

Strings:

-
(* `\n`のようなエスケープシーケンスが利用できる *)
-val x = "hello\n"; 
-(* 文字列の連結には'^'を使う *)
-val y = "hello " ^ "world";
+

Strings:

(* `\n`のようなエスケープシーケンスが利用できる *)
+val x = "hello\n"; 
+(* 文字列の連結には'^'を使う *)
+val y = "hello " ^ "world";
 

An ML program is a sequence of bindings. Each binding gets type-checked and then evaluated. What type a binding has depends on a static environment. How a binding is evaluated depends on a dynamic environment. -Sometimes we use just environment to mean dynamic environment and use context as a synonym for static environment.

-
    -
  • Syntaxs : How to write it.
  • -
  • Semantics: How it type-checks and evaluates
  • -
  • Value: an expression that has no more computation to do
  • -
-

Shadowing

-

Bindings are immutable in SML. Given val x = 8 + 9; we produce a dynamic environment where x maps to 17. +Sometimes we use just environment to mean dynamic environment and use context as a synonym for static environment.

  • Syntaxs : How to write it.
  • Semantics: How it type-checks and evaluates
  • Value: an expression that has no more computation to do

Shadowing

Bindings are immutable in SML. Given val x = 8 + 9; we produce a dynamic environment where x maps to 17. In this environment x will always map to 17; there is no “assignment statement” in ML for changing what x maps to. You can have another binding later, say val x = 19;, but that just creates a differnt environment -where the later binding for x shadows the earlier one.

-

Function Bindings

-
fun pow (x:int, y:int) = (* correct only for y >= 0 *)
+where the later binding for x shadows the earlier one.

Function Bindings

fun pow (x:int, y:int) = (* correct only for y >= 0 *)
     if y = 0
     then 1
     else x * pow(x, y-1);
@@ -249,23 +41,7 @@ 

Function Bindings

val ans = cube(4); (* The parentheses are not necessary if there is only one argument val ans = cube 4; *) -
    -
  • Syntax: fun x0 (x1 : t1, ..., xn : tn) = e
  • -
  • Type-checking: -
      -
    • t1 * ... * tn -> t
    • -
    • The type of a function is “argument types” -> “reslut types”
    • -
    -
  • -
  • Evaluation: -
      -
    • A function is a value
    • -
    • The environment we extends arguments with is that “was current” when the function was defined, not the one where it is being called.
    • -
    -
  • -
-

Pairs and other Tuples

-
fun swap (pr : int*bool) =
+
  • Syntax: fun x0 (x1 : t1, ..., xn : tn) = e
  • Type-checking:
    • t1 * ... * tn -> t
    • The type of a function is “argument types” -> “reslut types”
  • Evaluation:
    • A function is a value
    • The environment we extends arguments with is that “was current” when the function was defined, not the one where it is being called.

Pairs and other Tuples

fun swap (pr : int*bool) =
     (#2 pr, #1 pr);
 
 fun sum_two_pairs (pr1 : int * int, pr2 : int * int) =
@@ -280,31 +56,23 @@ 

Pairs and other Tuples

pr else (#2 pr, #1 pr); -

ML supportstuplesby allowing any number of parts. Pairs and tuples can be nested however you want. For example, a 3-tuple (i.e., a triple) of integers has type intintint. An example is (7,9,11) and you retrieve the parts with #1 e, #2 e, and #3 e where e is an expression that evaluates to a triple.

-
val a = (7, 9, 11) (* int * int * int *)
+

ML supportstuplesby allowing any number of parts. Pairs and tuples can be nested however you want. For example, a 3-tuple (i.e., a triple) of integers has type intintint. An example is (7,9,11) and you retrieve the parts with #1 e, #2 e, and #3 e where e is an expression that evaluates to a triple.

val a = (7, 9, 11) (* int * int * int *)
 val x = (3, (4, (5,6))); (* int * (int * (int * int)) *)
 val y = (#2 x, (#1 x, #2 (#2 x))); (* (int * (int * int)) * (int * (int * int)) *)
 val ans = (#2 y, 4); (* (int * (int * int)) * int *)
-

Lists

-
val x = [7,8,9];
+

Lists

val x = [7,8,9];
 5::x; (* 5 consed onto x *)
 6::5::x;
 [6]::[[1,2],[3,4];
 

To append a list t a list, use list-append operator @: -Reference:# The Standard ML Basis Library

-
-

Interface: -val @ : ‘a list * ‘a list -> ‘a list

-
-
val x = [1,2] @ [3,4,5]; (* [1,2,3,4,5] *)
-

Accessing:

-
val x = [7,8,9];
+Reference:# The Standard ML Basis Library

Interface: +val @ : ‘a list * ‘a list -> ‘a list

val x = [1,2] @ [3,4,5]; (* [1,2,3,4,5] *)
+

Accessing:

val x = [7,8,9];
 null x; (* False *)
 null []; (* True *)
 hd x; (* 7 *)
 tl x; (* [8, 9] *)
-

List Functions

-
fun sum_list(xs : int list) =
+

List Functions

fun sum_list(xs : int list) =
     if null xs
     then 0
     else hd xs + sum_list(tl xs);
@@ -341,21 +109,7 @@ 

Pairs and other Tuples

fun sum_pair_list2 (xs : (int * int) list) = (sum_list(firsts xs)) + (sum_list(seconds xs)); - -

Functions that make and us lists are almost always recursice becasue a list has an unknown length. To write a recursive function the thought process involves two steps:

-
    -
  • think about the base case
  • -
  • think about the recursive case
  • -
-

Let Expressions

-
    -
  • Syntax: let b1 b2 ... bn in e end -
      -
    • Each bi is any binding an e is any expression
    • -
    -
  • -
-
let val x = 1
+

Functions that make and us lists are almost always recursice becasue a list has an unknown length. To write a recursive function the thought process involves two steps:

  • think about the base case
  • think about the recursive case

Let Expressions

  • Syntax: let b1 b2 ... bn in e end
    • Each bi is any binding an e is any expression
let val x = 1
 in
     (let val x = 2 in x+1 end) + (let val y = x+2 in y+1 end)
 end
@@ -368,14 +122,7 @@ 

Let Expressions

in count(1) end -

Options

-

An option value has either 0 or 1 thing: None is an option value carrying nothing whereas SOME e evaluates e to a value v and becomes the option carrying the one value v. The type of NONE is 'a option and the type of SOME e is t option if e has type t.

-

We have:

-
    -
  • isSome which evaluates to false if its argument is NONE
  • -
  • valOf to get the value carried by SOME(raising exception for NONE)
  • -
-
fun max1( xs : int list) =
+

Options

An option value has either 0 or 1 thing: None is an option value carrying nothing whereas SOME e evaluates e to a value v and becomes the option carrying the one value v. The type of NONE is 'a option and the type of SOME e is t option if e has type t.

We have:

  • isSome which evaluates to false if its argument is NONE
  • valOf to get the value carried by SOME(raising exception for NONE)
fun max1( xs : int list) =
     if null xs
     then NONE
     else
@@ -385,121 +132,64 @@ 

Let Expressions

then tl_ans else SOME (hd xs) end; -

Some More Expressions

-

Boolean operations:

-
    -
  • e1 andalso e2 -
      -
    • if result of e1 is false then false else result of e2
    • -
    -
  • -
  • e1 orelse e2
  • -
  • not e1
  • -
-

※Syntax && and || don’t exist in ML and ! means something different.

-

andalso and orelse are just keywords. not is a pre-defined function.

-

Comparisons:

-
    -
  • = <> > < >= <= -
      -
    • = and <> can be used with any “equality type” but not with real
    • -
    -
  • -
-

Build New Types

-

To Create a compound type, there are really only three essential building blocks:

-
    -
  • Each-of : A compound type t describes values that contain each of values of type t1 t2tn
  • -
  • One-of: A compound type t describes values that contain a value of one of the types t1 t2tn
  • -
  • Self-refenence: A compound type t may refer to itself in its definition in order to describe recursive data structures like lists and trees.
  • -
-

Records

-

Record types are “each-of” types where each component is a named field. The order of fields never matters.

-
val x = {bar = (1+2,true andalso true), foo = 3+4, baz = (false,9) }
+

Some More Expressions

Boolean operations:

  • e1 andalso e2
    • if result of e1 is false then false else result of e2
  • e1 orelse e2
  • not e1

※Syntax && and || don’t exist in ML and ! means something different.

andalso and orelse are just keywords. not is a pre-defined function.

Comparisons:

  • = <> > < >= <=
    • = and <> can be used with any “equality type” but not with real

Build New Types

To Create a compound type, there are really only three essential building blocks:

  • Each-of : A compound type t describes values that contain each of values of type t1 t2tn
  • One-of: A compound type t describes values that contain a value of one of the types t1 t2tn
  • Self-refenence: A compound type t may refer to itself in its definition in order to describe recursive data structures like lists and trees.

Records

Record types are “each-of” types where each component is a named field. The order of fields never matters.

val x = {bar = (1+2,true andalso true), foo = 3+4, baz = (false,9) }
 #bar x (* (3, true) *)
-

Tupels are actually syntactic sugar for records. #1 e, #2 e, etc. mean: get the contents of the field named 1, 2, etc.

-
- val x = {1="a",2="b"};
-val x = ("a","b") : string * string
-- val y = {1="a", 3="b"};
-val y = {1="a",3="b"} : {1:string, 3:string}
-

Datatype bindings

-
datatype mytype = TwoInts of int*int
+

Tupels are actually syntactic sugar for records. #1 e, #2 e, etc. mean: get the contents of the field named 1, 2, etc.

- val x = {1="a",2="b"};
+val x = ("a","b") : string * string
+- val y = {1="a", 3="b"};
+val y = {1="a",3="b"} : {1:string, 3:string}
+

Datatype bindings

datatype mytype = TwoInts of int*int
 		                       | Str of string
                                | Pizza;
-val a = Str "hi"; (* Str "hi" : mytype *)
+val a = Str "hi"; (* Str "hi" : mytype *)
 val b = Str; (* fn : string -> mytype *)
 val c = Pizza; (* Pizza : mytype *)
 val d = TwoInts(1+2, 3+4); (* TwoInts (3,7) : mytype *)
-val e = a; (* Str "hi" : mytype *)
-

The example above adds four things to the environment:

-
    -
  • A new type mytype that we can now use just like any other types
  • -
  • Three constructors TwoInts, Str, Pizza
  • -
-

We can also create a type synonmy which is entirely interchangeable with the existing type.

-
type foo = int
+val e = a; (* Str "hi" : mytype *)
+

The example above adds four things to the environment:

  • A new type mytype that we can now use just like any other types
  • Three constructors TwoInts, Str, Pizza

We can also create a type synonmy which is entirely interchangeable with the existing type.

type foo = int
 (* we can write foo wherever we write int and vice-versa *)
-

Case Expressions

-

To access to datatype values, we can use a case expression:

-
fun f (x : mytype) =
+

Case Expressions

To access to datatype values, we can use a case expression:

fun f (x : mytype) =
     case x of
 	    Pizza => 3
       | Str s => 8
       | TwoInts(i1, i2) => i1 + i2;
 
-f(Str("a")); (* val it = 8 : int *)
-

We separate the branches with the | character. Each branch has the form p => e where p is a pattern and e is an expression. Patterns are used to match against the result of evaluating the case’s first expression. This is why evaluating a case-expression is called pattern-matching.

-

Lists and Options are Datatypes too

-

SOME and NONE are actually constructors. So you can use them in a case like:

-
fun inc_or_zero intoption =
+f(Str("a")); (* val it = 8 : int *)
+

We separate the branches with the | character. Each branch has the form p => e where p is a pattern and e is an expression. Patterns are used to match against the result of evaluating the case’s first expression. This is why evaluating a case-expression is called pattern-matching.

Lists and Options are Datatypes too

SOME and NONE are actually constructors. So you can use them in a case like:

fun inc_or_zero intoption =
     case intoption of
 	    NONE => 0
       | SOME i => i+1;
-

As for list, [] and :: are also constructors. :: is a little unusual because it is an infix operator so when in patterns:

-
fun sum_list xs =
+

As for list, [] and :: are also constructors. :: is a little unusual because it is an infix operator so when in patterns:

fun sum_list xs =
     case xs of
 	    [] => 0
-      | x::xs' => x + sum_list xs';
+      | x::xs' => x + sum_list xs';
 
 fun append(xs, ys) =
     case xs of
 	    [] => ys
-      | x::xs' => x :: append(xs', ys);
-

Pattern-matching

-

Val-bindings are actually using pattern-matching.

-
val (x, y, z) = (1,2,3);
+      | x::xs' => x :: append(xs', ys);
+

Pattern-matching

Val-bindings are actually using pattern-matching.

val (x, y, z) = (1,2,3);
 (*
     val x = 1 : int
     val y = 2 : int
     val z = 3 : int
 *)
-

When defining a function, we can also use pattern-matching

-
fun sum_triple (x, y, z) =
+

When defining a function, we can also use pattern-matching

fun sum_triple (x, y, z) =
     x + y + z;
 

Actually, all functions in ML takes one tripple as an argument. There is no such thing as a mutli-argument function or zero-argument function in ML. -The binding fun () = e is using the unit-pattern () to match against calls that pass the unit value (), which is the only value fo a pre-defined datatype unit.

-

The definition of patterns is recursive. We can use nested patterns instead of nested cae expressions.

-

We can use wildcard pattern _ in patterns.

-
fun len xs =
+The binding fun () = e is using the unit-pattern () to match against calls that pass the unit value (), which is the only value fo a pre-defined datatype unit.

The definition of patterns is recursive. We can use nested patterns instead of nested cae expressions.

We can use wildcard pattern _ in patterns.

fun len xs =
     case xs of
 	[] => 0
-      | _::xs' => 1 + len xs';
-
-

Function Patterns

-

In a function binding, we can use a syntactic sugar instead of using case expressions:

-
fun f p1 = e1
+      | _::xs' => 1 + len xs';
+

Function Patterns

In a function binding, we can use a syntactic sugar instead of using case expressions:

fun f p1 = e1
   | f p2 = e2
   ...
   | f pn = en
-

for example

-
fun append ([], ys) = ys
-  | append (x::xs', ys) = x :: append(xs', ys);
-

Exceptions

-

To create new kinds of exceptions we can use exception bindings.

-
exception MyUndesirableCondition;
+

for example

fun append ([], ys) = ys
+  | append (x::xs', ys) = x :: append(xs', ys);
+

Exceptions

To create new kinds of exceptions we can use exception bindings.

exception MyUndesirableCondition;
 exception MyOtherException of int * int;
-

Use raise to raise exceptions. Use handle to catch exceptions.

-
fun hd xs =
+

Use raise to raise exceptions. Use handle to catch exceptions.

fun hd xs =
     case xs of
 	[] => raise List.Empty
       | x::_ => x;
@@ -509,33 +199,25 @@ 

Lists and Options are Datatypes too

Tail Recursion

-

There is a situation in a recursive call called tail call:

-
-

when f makes a recursive call to f, there is nothing more for the caller to do after the callee returns except return the callee’s result.

-
-

Consider a sum function:

-
fun sum1 xs =
+

Tail Recursion

There is a situation in a recursive call called tail call:

when f makes a recursive call to f, there is nothing more for the caller to do after the callee returns except return the callee’s result.

Consider a sum function:

fun sum1 xs =
     case xs of
         [] => 0
-      | i::xs' => i + sum1 xs'
-

When the function runs, it will keep a call-stack for each recursive call . But if we change a little bit using tail call :

-
fun sum2 xs =
+      | i::xs' => i + sum1 xs'
+

When the function runs, it will keep a call-stack for each recursive call . But if we change a little bit using tail call :

fun sum2 xs =
     let fun f (xs,acc) =
         case xs of
             [] => acc
-          | i::xs' => f(xs',i+acc)
+          | i::xs' => f(xs',i+acc)
     in
         f(xs,0)
     end
 

we use a local helper f and a accumulator acc so that the return value of f is just the return value of sum2 . As a result, there is no need to keep every call in stack, just the current f is enough. And that’s ML and most of other functional programming languages do. -Another example: when reversing a list:

-
fun rev1 lst =
+Another example: when reversing a list:

fun rev1 lst =
     case lst of
         [] => []
       | x::xs => (rev1 xs) @ [x]
@@ -548,80 +230,43 @@ 

Lists and Options are Datatypes too

rev1 is O(n^2) but rev2 is almost as simple as O(n).

-

To make sure which calls are tail calls, we can use a recursive defination of tail position like:

-
    -
  • In fun f(x) = e, e is in tail position.
  • -
  • If an expression is not in tail position, then none of its subexpressions are
  • -
  • If if e1 then e2 else e3 is in tail position, then e2 and e3 are in tail position (but not e1). (Case-expressions are similar.)
  • -
  • If let b1 ... bn in e end is in tail position, then e is in tail position (but no expressions in the bindings are).
  • -
  • Function-call arguments are not in tail position.
  • -
-

First-class Functions

-

The most common use of first class functions is passing them as arguments to other functions.

-
fun n_times (f, n, x) =
+

rev1 is O(n^2) but rev2 is almost as simple as O(n).

To make sure which calls are tail calls, we can use a recursive defination of tail position like:

  • In fun f(x) = e, e is in tail position.
  • If an expression is not in tail position, then none of its subexpressions are
  • If if e1 then e2 else e3 is in tail position, then e2 and e3 are in tail position (but not e1). (Case-expressions are similar.)
  • If let b1 ... bn in e end is in tail position, then e is in tail position (but no expressions in the bindings are).
  • Function-call arguments are not in tail position.

First-class Functions

The most common use of first class functions is passing them as arguments to other functions.

fun n_times (f, n, x) =
     if n=0
     then x
     else f (n_times(f, n-1,x))
-

The function n_times is called higher-order funciton. Its type is:

-
fn : ('a -> 'a) * int * 'a -> 'a
-

'a means they can be any type. This is called parametric polymorphism , or generic types .

-

Instead, consider a function that is not polymorphic:

-
(* (int -> int) * int -> int *)
+

The function n_times is called higher-order funciton. Its type is:

fn : ('a -> 'a) * int * 'a -> 'a
+

'a means they can be any type. This is called parametric polymorphism , or generic types .

Instead, consider a function that is not polymorphic:

(* (int -> int) * int -> int *)
 fun times_until_zero (f, x) =
     if x = 0
     then 0
     else 1 + times_until_zero(f, f x)
-

Anonymous Functions

-
fun triple_n_times (n, x) =
+

Anonymous Functions

fun triple_n_times (n, x) =
     n_times((fn x => 3*x), n, x)
-

Maps:

-
(* ('a -> 'b) * 'a list -> 'b list *)
+

Maps:

(* ('a -> 'b) * 'a list -> 'b list *)
 fun map (f, xs) =
     case xs of
 	[] => []
-      | x::xs' => (f x)::(map(f, xs'));
-

Filters:

-
(* ('a -> bool) * 'a list -> 'a list *)
+      | x::xs' => (f x)::(map(f, xs'));
+

Filters:

(* ('a -> bool) * 'a list -> 'a list *)
 fun filter (f, xs) =
     case xs of
 	[] => []
-      | x::xs' => if f x
-		  then x::(filter (f, xs'))
-		  else filter (f, xs');
-

Lexical scope VS dynamic scope

-

Combining Functions

-
 fun sqrt_of_abs i = (Math.sqrt o Real.fromInt o abs) i;
-

Use our own infix operator to define a left-to-right syntax.

-
infix |>
+      | x::xs' => if f x
+		  then x::(filter (f, xs'))
+		  else filter (f, xs');
+

Lexical scope VS dynamic scope

Combining Functions

 fun sqrt_of_abs i = (Math.sqrt o Real.fromInt o abs) i;
+

Use our own infix operator to define a left-to-right syntax.

infix |>
 fun x |> f = f x;
 fun sqrt_of_abs i = i |> abs |> Real.fromInt |> Math.sqrt;
-

Currying

-
(* fun sorted(x, y z) = z >= y andalso y >= x *)
+

Currying

(* fun sorted(x, y z) = z >= y andalso y >= x *)
 val sorted = fn x => fn y => fn z => z >= y andalso y >= x;
 
 (* just syntactic sugar for code above *)
 fun sorted_nicer x y z = z >= y andalso y >= x;
-

when calling curried the function:

-
(* ((sorted_nicer x) y) z *)
+

when calling curried the function:

(* ((sorted_nicer x) y) z *)
 (* or just: *)
 sorted_nicer x y z
-

-

Type Inference

-

Key steps in ML:

-
    -
  • Determine types of bindings in order
  • -
  • For each val of fun binding: -
      -
    • Analyze definition for all necessary facts
    • -
    • Type erro if no way for all facts to hold
    • -
    -
  • -
  • Use type variables like 'a for any unconstrained type
  • -
  • Enforce the value restriction
  • -
-

One example:

-
(*
+

Type Inference

Key steps in ML:

  • Determine types of bindings in order
  • For each val of fun binding:
    • Analyze definition for all necessary facts
    • Type erro if no way for all facts to hold
  • Use type variables like 'a for any unconstrained type
  • Enforce the value restriction

One example:

(*
 	compose : T1 * T2 -> T3
 	f : T1
 	g : T2
@@ -631,43 +276,33 @@ 

Combining Functions

from f being passed the result of g, T1=T6->T7 from call to f being body of anonymous function, T7 = T5 all together, (T6->T5) * (T4->T6) -> (T4->T5) - so ('a->'b) * ('c->'a) -> ('c->'b) + so ('a->'b) * ('c->'a) -> ('c->'b) *) fun compose (f, g) = fn x => f (g x) -

Value restriction

-

A variable-binding can have a polymorphic type only if the expression is a variable or value:

-
val r = ref NONE
-val _ = r := SOME "hi"
+

Value restriction

A variable-binding can have a polymorphic type only if the expression is a variable or value:

val r = ref NONE
+val _ = r := SOME "hi"
 val i - 1 + valOf (!r)
 

If there is is no value-restriction, the code above will type check, which shouldn’t. -With value restriction, ML will give a warning when type-checking:

-
- val r = ref NONE;
+With value restriction, ML will give a warning when type-checking:

- val r = ref NONE;
 stdIn:2.5-2.17 Warning: type vars not generalized because of
    value restriction are instantiated to dummy types (X1,X2,...)
 val r = ref NONE : ?.X1 option ref
-

Mutual Recursion

-

Mutual recursion allows f to call g and g to call f. -In ML, There is an and keyword to allow that:

-
fun p1 = e1
+

Mutual Recursion

Mutual recursion allows f to call g and g to call f. +In ML, There is an and keyword to allow that:

fun p1 = e1
 and p2 = e2
 and p3 = p3
-

Modules

-
structure MyMathLib =
+

Modules

structure MyMathLib =
 struct
 fun fact x = x
 val half_pi = Math.pi / 2.0
 fun doubler x = x * 2
 end
-

Signatures

-

A signature is a type for a module.

-
signature SIGNAME  =
+

Signatures

A signature is a type for a module.

signature SIGNAME  =
 sig types-for-bindings
 end
-

Ascribing a signature to a module:

-
structure myModule :> SIGNAME =
+

Ascribing a signature to a module:

structure myModule :> SIGNAME =
 struct bindings end;
-

Anything not in the signature cannot be used outside the module.

-
signature MATHLIB =
+

Anything not in the signature cannot be used outside the module.

signature MATHLIB =
 sig
     val fact : int -> int
     val half_pi : real
@@ -681,166 +316,7 @@ 

Combining Functions

val half_pi = Math.pi / 2.0 fun doubler x = x * 2 end -

Signature matching

-

Equivalence

-
    -
  • PL Equivalence
  • -
  • Asymptotic equivalence
  • -
  • System equivalence
  • -
-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

Signature matching

Equivalence

  • PL Equivalence
  • Asymptotic equivalence
  • System equivalence
\ No newline at end of file diff --git a/posts/2020-02-29-racket/index.html b/posts/2020-02-29-racket/index.html index 6506654e..076d4358 100644 --- a/posts/2020-02-29-racket/index.html +++ b/posts/2020-02-29-racket/index.html @@ -1,491 +1,119 @@ - - - - - - - - - - - Racket notes | Cactus theme example - - - - - - - - - - - - - - - - - - -
-
- +Racket notes | Cactus theme example +
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-Racket notes -

-
- -
- -4 minute read -
- - -
-
-
-

Basic

-
 1#lang racket
- 2(provide (all-defined-out))
- 3
- 4;this is a comment
- 5
- 6(define s "hello")
- 7
- 8(define x 3)
- 9(define y (+ x 2))
-10
-11(define cube1
-12  (lambda (x)
-13    (* x (* x x))))
-14
-15(define cube2
-16  (lambda (x)
-17    (* x x x)))
-18
-19(define (cube3 x)
-20  (* x x x))
-21
-22(define (pow1 x y)
-23  (if (=y 0)
-24      1
-25      (* x (pow1 x (- y 1)))))
-26
-27; currying
-28(define pow2
-29  (lambda (x)
-30    (lambda (y)
-31      (pow1 x y))))
-32
-

List

-
    -
  • Empty list: null -
      -
    • () doesn"t work for null but '() does
    • -
    -
  • -
  • build a list: (list e1 ... en)
  • -
  • Constructor: cons
  • -
  • Access head of list: car
  • -
  • Access tail of list: cdr
  • -
  • Check for empty: null?
  • -
-

Syntax

-

A term is either:

-
    -
  • An atom like #t, #f, 34, "hi", null, 4.0, x,...
  • -
  • A special form like define, lambda, if
  • -
  • A sequence of terms in parentheses: (t1 t2 t3)
  • -
  • Can use [ anything you use (
  • -
-

Remember parentheses matters! For example: -(e) means call e with 0 argument.

-

Dynamic typing

-
1(define lst (list #t "hi" 1 (list 2 3 4)))
-

Cond

-
1(define (sum3 xs)
-2  (cond [(null? xs) 0]
-3        [(number? (car xs)) (+ (car xs) (sum3 (cdr xs)))]
-4        [#t 0]))
-

What is true?

-

Anything that is not #f is true #t.

-

Local bindings

-

let/let*/letrec

-
1(let ([x1 e1]
-2      [x2 e2]
-3      ...
-4      [xn en])
-5  e)
-

Racket uses the environment before the let-expression to evaluate e1 e2 ... en, which means if en uses x1, x2, that would mean some outer variables of the same name. Instead, the expressions in let* are evaluated in the environment produced from the previous bindings (later ones shadow) .

-

The expressions in letrec are evaluated in the environment that includes all th bindings. It is needed for mutual recursion.

-

set!

-

Racket has assignment statements:

-
1(set! x e)
-

Once you have side-effects, sequences are useful:

-
1(begin e1 e2 e3)
-

cons/mcons

-

cons produces pairs or lists. (Actually lists are just extented pairs)

-
1(define pr (cons 1 (cons #t "hi"))) ; is a pair
-2(define lst (cons 1 (cons #t (cons "hi" null)))) ; is a list
-

mcons is another way to make pairs which allows you to change the value inside piars:

-
1(define mpr (mcons 1 (mcons #t "hi")))
-2(mcar mpr) ; 1
-3(mcdr mpr) ; (mcons (#t "hi"))
-4(set-mcdr! mpr 47) ; mpr becomes (mcons 1 47)
-

Related form:

-
    -
  • mcons
  • -
  • mcar
  • -
  • mcdr
  • -
  • mpair?
  • -
  • set-mcar!
  • -
  • set-mcdr!
  • -
-

Delayed Evaluation and Thunk

-

In most programming languages, given e1 e2 ... en, the function arguments e2, ..., en are evaluated once before the function body is executed. -So if we define a function like:

-
1(define (my-if-bad x y z) (if x y z))
-2
-3(define (factorial-wrong x)
-4  (my-if-bad (= x 0)
-5             1
-6             (* x (factorial-wrong (- x 1)))))
-

if we use if instead of my-if-bad, factorial-wrong acts just like we want. But with my-if-bad, the function never stops because the two branches evaluate at the same time.

-

Thanks to lambda, we can delay the evaluation, using the fact that function bodies are not evaluated until the function gets called.

-
1(define (my-if x y z) (if x (y) (z)))
-2
-3(define (factorial x)
-4  (my-if (= x 0)
-5         (lambda () 1)
-6         (lambda () (* x (factorial (- x 1))))))
-

The general idiom of using a zero-argument function to delay evaluation is also called a thunk (or, thunk the argument).

-

By the way,

-

Lazy-evaluation/Call-by-need/Promises

-

Streams

-

A stream is an infinite sequence of values.

-
 1#lang racket
- 2; 1 1 1 1 ...
- 3(define ones (lambda () (cons 1 ones)))
- 4
- 5; 1 2 3 4 ...
- 6(define nats
- 7  (letrec ([f (lambda (x) (cons x (lambda () (f (+ x 1)))))])
- 8     (lambda () (f 1))))
- 9
-10; 2 4 6 8 ...
-11(define power-of-two
-12  (letrec ([f (lambda (x) (cons x (lambda () (f (* x 2)))))])
-13    (lambda () (f 2))))
-14
-15; higher-order maker
-16(define (stream-maker fn arg)
-17  (letrec ([f (lambda (x) (cons x (lambda () (f (fn x arg)))))])
-18    (lambda () (f arg))))
-

Memoization (Not Memorization)

-

Memoization is another idiom related to lazy evaluation that does not actually use thunks. To implement memoization we do use mutation: Whenever the function is called with an argument we have not seen before, we compute the answer and then add the result to the table.

-
 1(define fibonacci
- 2  (letrec([memo null]
- 3          [f (lambda (x)
- 4               (let ([ans (assoc x memo)])
- 5                 (if ans
- 6                     (cdr ans)
- 7                     (let ([new-ans (if (or (= x 1) (= x 2))
- 8                                        1
- 9                                        (+ (f (- x 1))
-10                                           (f (- x 2))))])
-11                       (begin
-12                         (set! memo (cons (cons x new-ans) memo))
-13                         new-ans)))))])
-14    f))
-

Macros

-

Think about these things about macros and how Racket handles them better than other macro systems(notably C/C++)

-
    -
  • Tokenization
  • -
  • Parenthesization
  • -
  • Scope
  • -
-

Syntax

-
 1(define-syntax myif
- 2  (syntax-rules (then else)
- 3    [(my-if e1 then e2 else e3)
- 4     (if e1 e2 e3)]))
- 5
- 6(define-syntax my-delay
- 7  (syntax-rules ()
- 8    [(my-delay e)
- 9     (mcons #f (lambda () e))]))
-10
-

Hygiene

-

Recursive Datatypes Via Rackets’s struct

-

https://docs.racket-lang.org/reference/define-struct.html?q=struct#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29

-
1(struct foo (bar baz quux) #:transparent
-
-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

Racket notes

+4 minute read

Basic

 1#lang racket
+ 2(provide (all-defined-out))
+ 3
+ 4;this is a comment
+ 5
+ 6(define s "hello")
+ 7
+ 8(define x 3)
+ 9(define y (+ x 2))
+10
+11(define cube1
+12  (lambda (x)
+13    (* x (* x x))))
+14
+15(define cube2
+16  (lambda (x)
+17    (* x x x)))
+18
+19(define (cube3 x)
+20  (* x x x))
+21
+22(define (pow1 x y)
+23  (if (=y 0)
+24      1
+25      (* x (pow1 x (- y 1)))))
+26
+27; currying
+28(define pow2
+29  (lambda (x)
+30    (lambda (y)
+31      (pow1 x y))))
+

List

  • Empty list: null
    • () doesn"t work for null but '() does
  • build a list: (list e1 ... en)
  • Constructor: cons
  • Access head of list: car
  • Access tail of list: cdr
  • Check for empty: null?

Syntax

A term is either:

  • An atom like #t, #f, 34, "hi", null, 4.0, x,...
  • A special form like define, lambda, if
  • A sequence of terms in parentheses: (t1 t2 t3)
  • Can use [ anything you use (

Remember parentheses matters! For example: +(e) means call e with 0 argument.

Dynamic typing

1(define lst (list #t "hi" 1 (list 2 3 4)))
+

Cond

1(define (sum3 xs)
+2  (cond [(null? xs) 0]
+3        [(number? (car xs)) (+ (car xs) (sum3 (cdr xs)))]
+4        [#t 0]))
+

What is true?

Anything that is not #f is true #t.

Local bindings

let/let*/letrec

1(let ([x1 e1]
+2      [x2 e2]
+3      ...
+4      [xn en])
+5  e)
+

Racket uses the environment before the let-expression to evaluate e1 e2 ... en, which means if en uses x1, x2, that would mean some outer variables of the same name. Instead, the expressions in let* are evaluated in the environment produced from the previous bindings (later ones shadow) .

The expressions in letrec are evaluated in the environment that includes all th bindings. It is needed for mutual recursion.

set!

Racket has assignment statements:

1(set! x e)
+

Once you have side-effects, sequences are useful:

1(begin e1 e2 e3)
+

cons/mcons

cons produces pairs or lists. (Actually lists are just extented pairs)

1(define pr (cons 1 (cons #t "hi"))) ; is a pair
+2(define lst (cons 1 (cons #t (cons "hi" null)))) ; is a list
+

mcons is another way to make pairs which allows you to change the value inside piars:

1(define mpr (mcons 1 (mcons #t "hi")))
+2(mcar mpr) ; 1
+3(mcdr mpr) ; (mcons (#t "hi"))
+4(set-mcdr! mpr 47) ; mpr becomes (mcons 1 47)
+

Related form:

  • mcons
  • mcar
  • mcdr
  • mpair?
  • set-mcar!
  • set-mcdr!

Delayed Evaluation and Thunk

In most programming languages, given e1 e2 ... en, the function arguments e2, ..., en are evaluated once before the function body is executed. +So if we define a function like:

1(define (my-if-bad x y z) (if x y z))
+2
+3(define (factorial-wrong x)
+4  (my-if-bad (= x 0)
+5             1
+6             (* x (factorial-wrong (- x 1)))))
+

if we use if instead of my-if-bad, factorial-wrong acts just like we want. But with my-if-bad, the function never stops because the two branches evaluate at the same time.

Thanks to lambda, we can delay the evaluation, using the fact that function bodies are not evaluated until the function gets called.

1(define (my-if x y z) (if x (y) (z)))
+2
+3(define (factorial x)
+4  (my-if (= x 0)
+5         (lambda () 1)
+6         (lambda () (* x (factorial (- x 1))))))
+

The general idiom of using a zero-argument function to delay evaluation is also called a thunk (or, thunk the argument).

By the way,

Lazy-evaluation/Call-by-need/Promises

Streams

A stream is an infinite sequence of values.

 1#lang racket
+ 2; 1 1 1 1 ...
+ 3(define ones (lambda () (cons 1 ones)))
+ 4
+ 5; 1 2 3 4 ...
+ 6(define nats
+ 7  (letrec ([f (lambda (x) (cons x (lambda () (f (+ x 1)))))])
+ 8     (lambda () (f 1))))
+ 9
+10; 2 4 6 8 ...
+11(define power-of-two
+12  (letrec ([f (lambda (x) (cons x (lambda () (f (* x 2)))))])
+13    (lambda () (f 2))))
+14
+15; higher-order maker
+16(define (stream-maker fn arg)
+17  (letrec ([f (lambda (x) (cons x (lambda () (f (fn x arg)))))])
+18    (lambda () (f arg))))
+

Memoization (Not Memorization)

Memoization is another idiom related to lazy evaluation that does not actually use thunks. To implement memoization we do use mutation: Whenever the function is called with an argument we have not seen before, we compute the answer and then add the result to the table.

 1(define fibonacci
+ 2  (letrec([memo null]
+ 3          [f (lambda (x)
+ 4               (let ([ans (assoc x memo)])
+ 5                 (if ans
+ 6                     (cdr ans)
+ 7                     (let ([new-ans (if (or (= x 1) (= x 2))
+ 8                                        1
+ 9                                        (+ (f (- x 1))
+10                                           (f (- x 2))))])
+11                       (begin
+12                         (set! memo (cons (cons x new-ans) memo))
+13                         new-ans)))))])
+14    f))
+

Macros

Think about these things about macros and how Racket handles them better than other macro systems(notably C/C++)

  • Tokenization
  • Parenthesization
  • Scope

Syntax

1(define-syntax myif
+2  (syntax-rules (then else)
+3    [(my-if e1 then e2 else e3)
+4     (if e1 e2 e3)]))
+5
+6(define-syntax my-delay
+7  (syntax-rules ()
+8    [(my-delay e)
+9     (mcons #f (lambda () e))]))
+

Hygiene

Recursive Datatypes Via Rackets’s struct

https://docs.racket-lang.org/reference/define-struct.html?q=struct#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29

1(struct foo (bar baz quux) #:transparent
+
\ No newline at end of file diff --git a/posts/2020-04-29-subtyping/index.html b/posts/2020-04-29-subtyping/index.html index 9a36f4c5..f6472b0f 100644 --- a/posts/2020-04-29-subtyping/index.html +++ b/posts/2020-04-29-subtyping/index.html @@ -1,273 +1,15 @@ - - - - - - - - - - - Programming Language - Subtyping | Cactus theme example - - - - - - - - - - - - - - - - - - -
-
- +Programming Language - Subtyping | Cactus theme example +
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-Programming Language - Subtyping -

-
- -
- -1 minute read -
- -
-
-
-

Some Good Subtyping Rules

-
    -
  • Width subtyping: A supertype can have a subset of fields with the same types, i.e., a subtype can have extra fields.
  • -
  • Permutation subtypings: A supertype can have the same set of fields with the same types in a different order.
  • -
  • Transitivity: if t1 is subtype of t2, and t2 is subtype of t3, then t1 is subtype of t3.
  • -
  • Reflexivity: Every type is a subtype of itself.
  • -
-

Given the three features of (1) setting a field, (2) letting depth -subtyping change the type of a field, and (3) having a sound type system actually prevent field-missing errors, we can have any two of the three, but not all of them.

-

Function Subtyping

-

Function subtyping contravariant in argument(s) and covariant in results. -If t3 is subtype of t1, and t2 is a subtype of t4, then t1 -> t2 is a subtype of t3 -> t4.

-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

Programming Language - Subtyping

+1 minute read

Some Good Subtyping Rules

  • Width subtyping: A supertype can have a subset of fields with the same types, i.e., a subtype can have extra fields.
  • Permutation subtypings: A supertype can have the same set of fields with the same types in a different order.
  • Transitivity: if t1 is subtype of t2, and t2 is subtype of t3, then t1 is subtype of t3.
  • Reflexivity: Every type is a subtype of itself.

Given the three features of (1) setting a field, (2) letting depth +subtyping change the type of a field, and (3) having a sound type system actually prevent field-missing errors, we can have any two of the three, but not all of them.

Function Subtyping

Function subtyping contravariant in argument(s) and covariant in results. +If t3 is subtype of t1, and t2 is a subtype of t4, then t1 -> t2 is a subtype of t3 -> t4.

\ No newline at end of file diff --git a/posts/2020-05-01-algorithms-graphs/index.html b/posts/2020-05-01-algorithms-graphs/index.html index edc7a5e1..821db02e 100644 --- a/posts/2020-05-01-algorithms-graphs/index.html +++ b/posts/2020-05-01-algorithms-graphs/index.html @@ -1,970 +1,266 @@ - - - - - - - - - - - Algorithms - Graphs | Cactus theme example - - - - - - - - - - - - - - - - - - -
-
- +Algorithms - Graphs | Cactus theme example +
- - - - - -
- - - + +
- -
-
- - -
-
-
-
-

-Algorithms - Graphs -

-
- -
- -12 minute read -
- -
-
-
-

Undirected Graphs

-

Some problems

-
    -
  • Path
  • -
  • Shortest path
  • -
  • Cycle
  • -
  • Ehler tour: A cycle that uses each edge excatly once.
  • -
  • Hamilton tour: A cycle that uses each vertex exactly once -
      -
    • classical NP-complete problem.
    • -
    -
  • -
  • Connectivity
  • -
  • MST:
  • -
  • Biconnectivity: A vertex whose removal disconnects the graph
  • -
  • Planarity
  • -
  • Graph isomorphism: Are two graphs identical? -
      -
    • No one knows so far. A lonstanding open problem
    • -
    -
  • -
-

Representations

-

Real-world graphs tend to be sparse (huge number of vertices, small average vertex degree).

-
    -
  • Set-of-edges representation -
      -
    • unefficient
    • -
    -
  • -
  • Adjacency-matrix representation -
      -
    • space cost is prohibitive
    • -
    -
  • -
  • Adjacency-list array representation -
      -
    • GOOD
    • -
    -
  • -
-

Adjacency-list Data structure

-
    -
  • Space usage proportional to V + E
  • -
  • Constant time to add an edge
  • -
  • Time proportional to the degree of v to iterate through vertices adjacent to v
  • -
-

Depth-first Search (DFS)

-

Typical applications:

-
    -
  • Find all vertices connected to a given source vertex
  • -
  • Find a path between two vertices
  • -
-

Algorithm:

-
    -
  • Use recursion (a function-call stack) or an explicit stack.
  • -
  • Mark each visited vertex (and keep track of edge taken to visit it)
  • -
  • Return (retrace steps) when no unvisited options
  • -
-
 1public class DepthFirstPaths{
- 2    private blloean[] marked;
- 3    private int[] edgeTO;
- 4    private int s;
- 5    public DepthFirstPaths(Graph G, int s)
- 6    {
- 7        // ...
- 8        dfs(G, s);
- 9    }
-10
-11    private void dfs(Graph Gm int v)
-12    {
-13        marked[v] = true;
-14        for (int w : G.adj(v))
-15            if (!marked[v])
-16            {
-17                dfs(G, w)
-18                edgeTo[w] = v;
-19            }
-20    }
-21}
-

Propositions:

-
    -
  1. DFS marks all vertices connected to s in time proportional to the sum of their degrees.
  2. -
  3. After DFS, can find vertices connected to s in constant time and can find a path to s in time proportional to its length.
  4. -
-

Breadth-first Search (BFS)

-

Typical applications:

-
    -
  • shortest path
  • -
-

Algorithm:

-
    -
  • Put s onto a queue, and mark s as visited
  • -
  • Take the next vertex v from the queue and mark it
  • -
  • Put onto the queue all unmarked vertices that are adjacent to v
  • -
-
 1public class BreadthFirstPaths
- 2{
- 3    private boolean[] marked;
- 4    private int[] edgeTo;
- 5    // ...
- 6    private void bfs(Graph G, int s)
- 7    {
- 8        Queue<Integer> q = new Queue<>();
- 9        q.enqueue(s);
-10        marked[s] = ture;
-11        while (!q.isEmpty())
-12        {
-13            int v = q.dequeue();
-14            for (int w: G.adj(v))
-15            {
-16                if (!marked[w])
-17                {
-18                    q.enqueue(w);
-19                    marked[w] = true;
-20                    edgeTo[w] = v;
-21                }
-22            }
-23        }
-24    }
-25}
-

Proposition:

-
    -
  1. BFS computes shortest paths (fewest number of edges) from s to all other vertices in a graph in time proportional to E + V
  2. -
-

Applications of DFS

-

Connected components

-

The goal is to preprocess graph to answer queries of the form is v connected to w? in constant time.

-

The relation is connected to is an equivalence relation:

-
    -
  • Reflexive: v is connected to v
  • -
  • Symmetric: if v is connected to w, then w is connected to v
  • -
  • Transitive: if v connected to w and w connected to x, then v connected to x
  • -
-
 1public class CC {
- 2    private boolean[] marked;
- 3    private int[] id;
- 4    private int count;
- 5
- 6    public CC(Graph G) {
- 7        marked = new boolean[G.V()];
- 8        id = new int[G.V()];
- 9        for (int v = 0, v < G.V(); v++) {
-10            if (!marked[v]) {
-11                dfs(G, v);
-12                count++;
-13            }
-14        }
-15    }
-16
-17    // ...
-18
-19    private void dfs(Graph G, int v) {
-20        marked[v] = true;
-21        id[v] = count;
-22        for (int w : G.adj(v)) {
-23            if (!marked[w]) {
-24                dfs(G, w)
-25            }
-26        }
-27    }
-28}
-

Cycle detection

-

Problem: Is a given graph acylic?

-

TODO

-

Two-colorability

-

Problem: Is the graph bipartite?

-

TODO

-

Symbol graphs

-

TODO

-

Degrees of separation

-

TODO

-

Directed Graphs

-
-

A directed graph (or digraph) is a set of vertices and a collection of directed edges. Each directed edge connects an ordered pair of vertices.

-
-
    -
  • outdegree: the number of edges going from it
  • -
  • indegree: the number fo edges going into it
  • -
  • directed path: a sequence of vertices in which there is a (directed) edge pointing from each vertex in the sequence to its successor in the sequence
  • -
  • directed cycle
  • -
  • simple cycle: a cycle with no repeated edges or vertices
  • -
-

Representations

-

Again, use adjacency-lists representation

-
    -
  • Based on iterating over vertices pointing from v
  • -
  • Real-world digraphs tend to be sparse
  • -
-
 1public class Digraph {
- 2    private final int V;
- 3    private final Bag<Integer>[] adj;
- 4
- 5    public Digraph(int V) {
- 6        this.V = V;
- 7        adj = (Bag<Integer>[]) new Bag[V];
- 8        for (int v = 0; v < V; v++) {
- 9            adj[v] = new Bag<Integer>[];
-10        }
-11    }
-12
-13    public void addEdge(int v, int w) {
-14        adj[v].add(w);
-15    }
-16
-17    public Iterable<Integer> adj(int v) {
-18        return adj[v];
-19    }
-20}
-
-

Reachabiliity problem: Find all vertices reachable from s along a directed path.

-

We can use the same dfs method as for undirected graphs.

-
    -
  • Every undirected graph is a digraph with edges in both directions.
  • -
  • DFS is a digraph algorithm,
  • -
-

Reachability applications:

-
    -
  • program control-flow analysis -
      -
    • Dead-code elimination
    • -
    • infinite-loop detection
    • -
    -
  • -
  • mark-sweep garbage collector
  • -
-

Other DFS problems:

-
    -
  • Path findind
  • -
  • Topological sort
  • -
  • Directed cycle detection
  • -
  • -
-

BFS problems:

-
    -
  • shortest path
  • -
  • multiple-source shortest paths
  • -
  • web crawler application
  • -
-

Topological Sort

-
-

Topological sort: Given a digraph, put the vertices in order such that all its directed edges point from a vertix earlier in the order to a vertex later in the order (or report impossible).

-
-

A digraph has a topological order if and only if it is a directed acyclic graph (DAG). -Topological sort redraws DAG so all edges poitn upwards.

-

use DFS again. It can be proved that reverse postorder of a DAG is a topological order. -(check P578 for the definition of Preorder/Postorder)

-
 1public class DepthFirstOrder {
- 2    private boolean[] marked;
- 3    private Stack<Integer> reversePost;
- 4
- 5    publiv DepthFirstOrder(Digraph G) {
- 6        reversePost = new Stack<Integer>();
- 7        marked = new boolean[G.V()];
- 8        for (int v = 0; v < G.V(); v++) {
- 9            if (!marked[v]) dfs(G, v);
-10        }
-11    }
-12
-13    private void dfs(Digrapg G, int v) {
-14        marked[v] = true;
-15        for (int w : G.adj(v)) {
-16            if (!marked[w]) dfs(G, w)
-17        }
-18        reversePost.push(v);
-19    }
-20}
-

Directed cycle detection

-

To find out if a given digraph is a DAG, we can try to find a directec cycle in the digraph. -Use DFS and a stack to track the cycle.

-
1// TODO
-

Some very typical applications of directed cycle detection and topological sort: -(A directed cycle means the problem is infeasible)

-
    -
  • job schedule
  • -
  • course scuedule
  • -
  • inheritance
  • -
  • spreadsheet -
      -
    • vertex: cell
    • -
    • edge: formula
    • -
    -
  • -
  • symbolic links
  • -
-

Strong components

-

Vertices v and w are strongly connected if there is both a directed path from v to w and a directed path from w to v. -Strong connectivity is an equvicalence relation.

-

Kosaraju-Sharir Algorithm

-

Kosaraju-Sharir is easy to implement but difficutl to understand. It runs DFS twice:

-
    -
  • Given a digraph G, run DFS to compute the topological order of its reverse $G^R$
  • -
  • Run DFS on G in the order given by first DFS
  • -
-

TODO: ADD Proof

-

https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/KosarajuSharirSCC.java.html

-
 1public class KosarajuSharirSCC {
- 2    private boolean[] marked;     // marked[v] = has vertex v been visited?
- 3    private int[] id;             // id[v] = id of strong component containing v
- 4    private int count;            // number of strongly-connected components
- 5
- 6    /**
- 7     * Computes the strong components of the digraph {@code G}.
- 8     * @param G the digraph
- 9     */
-10    public KosarajuSharirSCC(Digraph G) {
-11
-12        // compute reverse postorder of reverse graph
-13        DepthFirstOrder dfs = new DepthFirstOrder(G.reverse());
-14
-15        // run DFS on G, using reverse postorder to guide calculation
-16        marked = new boolean[G.V()];
-17        id = new int[G.V()];
-18        for (int v : dfs.reversePost()) {
-19            if (!marked[v]) {
-20                dfs(G, v);
-21                count++;
-22            }
-23        }
-24    }
-25
-26    // DFS on graph G
-27    private void dfs(Digraph G, int v) { 
-28        marked[v] = true;
-29        id[v] = count;
-30        for (int w : G.adj(v)) {
-31            if (!marked[w]) dfs(G, w);
-32        }
-33    }
-34
-35    // ...
-36}
-

Minimum Spanning Trees

-

An edge-weighted-graph is a graph where we associate weight or costs with each edge. +

Algorithms - Graphs

+12 minute read

Undirected Graphs

Some problems

  • Path
  • Shortest path
  • Cycle
  • Ehler tour: A cycle that uses each edge excatly once.
  • Hamilton tour: A cycle that uses each vertex exactly once
    • classical NP-complete problem.
  • Connectivity
  • MST:
  • Biconnectivity: A vertex whose removal disconnects the graph
  • Planarity
  • Graph isomorphism: Are two graphs identical?
    • No one knows so far. A lonstanding open problem

Representations

Real-world graphs tend to be sparse (huge number of vertices, small average vertex degree).

  • Set-of-edges representation
    • unefficient
  • Adjacency-matrix representation
    • space cost is prohibitive
  • Adjacency-list array representation
    • GOOD

Adjacency-list Data structure

  • Space usage proportional to V + E
  • Constant time to add an edge
  • Time proportional to the degree of v to iterate through vertices adjacent to v

Depth-first Search (DFS)

Typical applications:

  • Find all vertices connected to a given source vertex
  • Find a path between two vertices

Algorithm:

  • Use recursion (a function-call stack) or an explicit stack.
  • Mark each visited vertex (and keep track of edge taken to visit it)
  • Return (retrace steps) when no unvisited options
 1public class DepthFirstPaths{
+ 2    private blloean[] marked;
+ 3    private int[] edgeTO;
+ 4    private int s;
+ 5    public DepthFirstPaths(Graph G, int s)
+ 6    {
+ 7        // ...
+ 8        dfs(G, s);
+ 9    }
+10
+11    private void dfs(Graph Gm int v)
+12    {
+13        marked[v] = true;
+14        for (int w : G.adj(v))
+15            if (!marked[v])
+16            {
+17                dfs(G, w)
+18                edgeTo[w] = v;
+19            }
+20    }
+21}
+

Propositions:

  1. DFS marks all vertices connected to s in time proportional to the sum of their degrees.
  2. After DFS, can find vertices connected to s in constant time and can find a path to s in time proportional to its length.

Breadth-first Search (BFS)

Typical applications:

  • shortest path

Algorithm:

  • Put s onto a queue, and mark s as visited
  • Take the next vertex v from the queue and mark it
  • Put onto the queue all unmarked vertices that are adjacent to v
 1public class BreadthFirstPaths
+ 2{
+ 3    private boolean[] marked;
+ 4    private int[] edgeTo;
+ 5    // ...
+ 6    private void bfs(Graph G, int s)
+ 7    {
+ 8        Queue<Integer> q = new Queue<>();
+ 9        q.enqueue(s);
+10        marked[s] = ture;
+11        while (!q.isEmpty())
+12        {
+13            int v = q.dequeue();
+14            for (int w: G.adj(v))
+15            {
+16                if (!marked[w])
+17                {
+18                    q.enqueue(w);
+19                    marked[w] = true;
+20                    edgeTo[w] = v;
+21                }
+22            }
+23        }
+24    }
+25}
+

Proposition:

  1. BFS computes shortest paths (fewest number of edges) from s to all other vertices in a graph in time proportional to E + V

Applications of DFS

Connected components

The goal is to preprocess graph to answer queries of the form is v connected to w? in constant time.

The relation is connected to is an equivalence relation:

  • Reflexive: v is connected to v
  • Symmetric: if v is connected to w, then w is connected to v
  • Transitive: if v connected to w and w connected to x, then v connected to x
 1public class CC {
+ 2    private boolean[] marked;
+ 3    private int[] id;
+ 4    private int count;
+ 5
+ 6    public CC(Graph G) {
+ 7        marked = new boolean[G.V()];
+ 8        id = new int[G.V()];
+ 9        for (int v = 0, v < G.V(); v++) {
+10            if (!marked[v]) {
+11                dfs(G, v);
+12                count++;
+13            }
+14        }
+15    }
+16
+17    // ...
+18
+19    private void dfs(Graph G, int v) {
+20        marked[v] = true;
+21        id[v] = count;
+22        for (int w : G.adj(v)) {
+23            if (!marked[w]) {
+24                dfs(G, w)
+25            }
+26        }
+27    }
+28}
+

Cycle detection

Problem: Is a given graph acylic?

TODO

Two-colorability

Problem: Is the graph bipartite?

TODO

Symbol graphs

TODO

Degrees of separation

TODO

Directed Graphs

A directed graph (or digraph) is a set of vertices and a collection of directed edges. Each directed edge connects an ordered pair of vertices.

  • outdegree: the number of edges going from it
  • indegree: the number fo edges going into it
  • directed path: a sequence of vertices in which there is a (directed) edge pointing from each vertex in the sequence to its successor in the sequence
  • directed cycle
  • simple cycle: a cycle with no repeated edges or vertices

Representations

Again, use adjacency-lists representation

  • Based on iterating over vertices pointing from v
  • Real-world digraphs tend to be sparse
 1public class Digraph {
+ 2    private final int V;
+ 3    private final Bag<Integer>[] adj;
+ 4
+ 5    public Digraph(int V) {
+ 6        this.V = V;
+ 7        adj = (Bag<Integer>[]) new Bag[V];
+ 8        for (int v = 0; v < V; v++) {
+ 9            adj[v] = new Bag<Integer>[];
+10        }
+11    }
+12
+13    public void addEdge(int v, int w) {
+14        adj[v].add(w);
+15    }
+16
+17    public Iterable<Integer> adj(int v) {
+18        return adj[v];
+19    }
+20}
+

Reachabiliity problem: Find all vertices reachable from s along a directed path.

We can use the same dfs method as for undirected graphs.

  • Every undirected graph is a digraph with edges in both directions.
  • DFS is a digraph algorithm,

Reachability applications:

  • program control-flow analysis
    • Dead-code elimination
    • infinite-loop detection
  • mark-sweep garbage collector

Other DFS problems:

  • Path findind
  • Topological sort
  • Directed cycle detection

BFS problems:

  • shortest path
  • multiple-source shortest paths
  • web crawler application

Topological Sort

Topological sort: Given a digraph, put the vertices in order such that all its directed edges point from a vertix earlier in the order to a vertex later in the order (or report impossible).

A digraph has a topological order if and only if it is a directed acyclic graph (DAG). +Topological sort redraws DAG so all edges poitn upwards.

use DFS again. It can be proved that reverse postorder of a DAG is a topological order. +(check P578 for the definition of Preorder/Postorder)

 1public class DepthFirstOrder {
+ 2    private boolean[] marked;
+ 3    private Stack<Integer> reversePost;
+ 4
+ 5    publiv DepthFirstOrder(Digraph G) {
+ 6        reversePost = new Stack<Integer>();
+ 7        marked = new boolean[G.V()];
+ 8        for (int v = 0; v < G.V(); v++) {
+ 9            if (!marked[v]) dfs(G, v);
+10        }
+11    }
+12
+13    private void dfs(Digrapg G, int v) {
+14        marked[v] = true;
+15        for (int w : G.adj(v)) {
+16            if (!marked[w]) dfs(G, w)
+17        }
+18        reversePost.push(v);
+19    }
+20}
+

Directed cycle detection

To find out if a given digraph is a DAG, we can try to find a directec cycle in the digraph. +Use DFS and a stack to track the cycle.

1// TODO
+

Some very typical applications of directed cycle detection and topological sort: +(A directed cycle means the problem is infeasible)

  • job schedule
  • course scuedule
  • inheritance
  • spreadsheet
    • vertex: cell
    • edge: formula
  • symbolic links

Strong components

Vertices v and w are strongly connected if there is both a directed path from v to w and a directed path from w to v. +Strong connectivity is an equvicalence relation.

Kosaraju-Sharir Algorithm

Kosaraju-Sharir is easy to implement but difficutl to understand. It runs DFS twice:

  • Given a digraph G, run DFS to compute the topological order of its reverse $G^R$
  • Run DFS on G in the order given by first DFS

TODO: ADD Proof

https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/KosarajuSharirSCC.java.html

 1public class KosarajuSharirSCC {
+ 2    private boolean[] marked;     // marked[v] = has vertex v been visited?
+ 3    private int[] id;             // id[v] = id of strong component containing v
+ 4    private int count;            // number of strongly-connected components
+ 5
+ 6    /**
+ 7     * Computes the strong components of the digraph {@code G}.
+ 8     * @param G the digraph
+ 9     */
+10    public KosarajuSharirSCC(Digraph G) {
+11
+12        // compute reverse postorder of reverse graph
+13        DepthFirstOrder dfs = new DepthFirstOrder(G.reverse());
+14
+15        // run DFS on G, using reverse postorder to guide calculation
+16        marked = new boolean[G.V()];
+17        id = new int[G.V()];
+18        for (int v : dfs.reversePost()) {
+19            if (!marked[v]) {
+20                dfs(G, v);
+21                count++;
+22            }
+23        }
+24    }
+25
+26    // DFS on graph G
+27    private void dfs(Digraph G, int v) { 
+28        marked[v] = true;
+29        id[v] = count;
+30        for (int w : G.adj(v)) {
+31            if (!marked[w]) dfs(G, w);
+32        }
+33    }
+34
+35    // ...
+36}
+

Minimum Spanning Trees

An edge-weighted-graph is a graph where we associate weight or costs with each edge. A spanning tree of an undirected edge-weighted graph G is a subgraph T that is both a tree (conneted and acyclic) and spanning (includes all of the vertices). Given an (connected) undirected edge-weighted graph G with V vertices and E edges, the MST of it must have V - 1 edges. -If the graph is not connceted, we compute minimum spanning forest (MST of each component).

-
    -
  • A cut in a graph is a partition of its vertices into two (nonempty) sets
  • -
  • A crossing edge connects a vertex in one set with a vertex in the other.
  • -
  • Cut property: Given any cut, the crossing edge of min weight is in the MST.
  • -
-

Edge-weight Graph Data Type

-

Edge: -https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Edge.java.html

-

EdgeWeigthedGraph: -https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/EdgeWeightedGraph.java.html

-

Greedy MST Algorithm:

-
    -
  • Start with all edges colored gray.
  • -
  • Find cut with no blacked crossing edges; color its min-weight edge black.
  • -
  • Repeat until V-1 edges are colored black.
  • -
-

Implementations 1: Kruskal’s algorithm

-

For edges in ascending order of weight:

-
    -
  • Add next edge to Tree unless doing so would create a cycle.
  • -
-

To efficiently solve this problem, use union-find :

-
    -
  1. use a priority queue to maintain all the edges in V
  2. -
  3. union-find data structure: -
      -
    • maintain a set for each connected component in T.
    • -
    • if v and w are in saome set, then adding v->w would create a cycle
    • -
    • to add v>w to T, merge sets containing v and w.
    • -
    -
  4. -
-

TODO: Add code

-

Implementations 2: Prim’s algorithm

-
    -
  • Start with vertex 0 and greedily grow tree T.
  • -
  • Add To T the min weight edge with exactly oue endpoint in T.
  • -
  • Reapeat unitl V - 1 edges.
  • -
-

The key to solve this problem is how do we find the crossing edge of minimal weight efficiently.

-

A lazy solution (in time proportional to $ElogE$, fair enough):

-
    -
  1. Maintain a PQ of edges with (at least) one endpoint in T -
      -
    • Key = edge, priority = weight
    • -
    -
  2. -
  3. Delete-min to determine next edge e = v->w to add to T
  4. -
  5. Disregard if both endpoints v and w are marked (both in T)
  6. -
  7. Otherwise, let w be the unmarked vertex (not in T) -
      -
    • add to PQ and edge incident to w (assuming other endpoint not in T)
    • -
    • add e to T and mark w
    • -
    -
  8. -
-

TODO: add code

-

A eager solution (in time proprotional to $ElogV$, better):

-
    -
  1. Maintain a PQ of vertices connected by an edge to T, where priority of v = weight of shortedt edge connecting v to T
  2. -
  3. Delete min vertex v and add its associated edge e = v->w to T
  4. -
  5. Update PQ by considering all edges e = v->x incident to v -
      -
    • ignore if x is already in T
    • -
    • add x to PQ if not alread on it
    • -
    • decrease priority of x if v->x becomes shortest edge connecting x to T
    • -
    -
  6. -
-

This solution uses an indexed priority queue data structure.

-

TODO: add code

-

Shortest Paths

-

Some variants:

-
    -
  • Which vertices? -
      -
    • Single source
    • -
    • Source-sink
    • -
    • All pairs
    • -
    -
  • -
  • Edge weights -
      -
    • Nonegative weights
    • -
    • Euclidean weights
    • -
    • Arbitrary weights
    • -
    -
  • -
  • Cycles? -
      -
    • No directed cycles
    • -
    • No negative cycles
    • -
    -
  • -
-

Edge-weighted digraph data strcuture

-

Weighted directed edge: -https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/DirectedEdge.java.html

-

Edge-weighted digraph: -https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/EdgeWeightedDigraph.java.html

-

Use adjacency-lists implementation same as EdgeWeightedGraph

-

Generic Single-source Shortest paths

-

Our goal is to find the shortest path from s to every other vertex. As a result, what we find will be the shortest-paths tree (SPT) for source s.

-

Relax edge e = v->w

-
    -
  • distTo[v] is length of shortest known path from s to v
  • -
  • distTo[w] is length of shortest known path from s to w
  • -
  • esgeTo[w] is last edge on shortest known pathh from s to w
  • -
  • if e = v->w gives shorter path to w through v, update both distTo[w] and edgeTo[w]
  • -
-
1private void relax(DirectedEdge e) {
-2    int v = e.from(), w = e.to();
-3    if (distTo[w] > distTo[v] + e.weight()) {
-4        distTo[w] = distTo[v] + e.weight();
-5        edgeTo[w] = e;
-6    }
-7}
-

Optimality conditions

-

Given an edge-weighted digraph G, distTo[] are the shortest path distances from s iff:

-
    -
  • distTo[s] = 0
  • -
  • For each vertex v, distTo[v] is the length of some path from s to v.
  • -
  • For each edge e = v->w, distTo[w] <= distTo[v] + e.weight()
  • -
-

Generic algorithm

-
Generic algorithm (to compute SPT from s) {
+If the graph is not connceted, we compute minimum spanning forest (MST of each component).

  • A cut in a graph is a partition of its vertices into two (nonempty) sets
  • A crossing edge connects a vertex in one set with a vertex in the other.
  • Cut property: Given any cut, the crossing edge of min weight is in the MST.

Edge-weight Graph Data Type

Edge: +https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Edge.java.html

EdgeWeigthedGraph: +https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/EdgeWeightedGraph.java.html

Greedy MST Algorithm:

  • Start with all edges colored gray.
  • Find cut with no blacked crossing edges; color its min-weight edge black.
  • Repeat until V-1 edges are colored black.

Implementations 1: Kruskal’s algorithm

For edges in ascending order of weight:

  • Add next edge to Tree unless doing so would create a cycle.

To efficiently solve this problem, use union-find :

  1. use a priority queue to maintain all the edges in V
  2. union-find data structure:
    • maintain a set for each connected component in T.
    • if v and w are in saome set, then adding v->w would create a cycle
    • to add v>w to T, merge sets containing v and w.

TODO: Add code

Implementations 2: Prim’s algorithm

  • Start with vertex 0 and greedily grow tree T.
  • Add To T the min weight edge with exactly oue endpoint in T.
  • Reapeat unitl V - 1 edges.

The key to solve this problem is how do we find the crossing edge of minimal weight efficiently.

A lazy solution (in time proportional to $ElogE$, fair enough):

  1. Maintain a PQ of edges with (at least) one endpoint in T
    • Key = edge, priority = weight
  2. Delete-min to determine next edge e = v->w to add to T
  3. Disregard if both endpoints v and w are marked (both in T)
  4. Otherwise, let w be the unmarked vertex (not in T)
    • add to PQ and edge incident to w (assuming other endpoint not in T)
    • add e to T and mark w

TODO: add code

A eager solution (in time proprotional to $ElogV$, better):

  1. Maintain a PQ of vertices connected by an edge to T, where priority of v = weight of shortedt edge connecting v to T
  2. Delete min vertex v and add its associated edge e = v->w to T
  3. Update PQ by considering all edges e = v->x incident to v
    • ignore if x is already in T
    • add x to PQ if not alread on it
    • decrease priority of x if v->x becomes shortest edge connecting x to T

This solution uses an indexed priority queue data structure.

TODO: add code

Shortest Paths

Some variants:

  • Which vertices?
    • Single source
    • Source-sink
    • All pairs
  • Edge weights
    • Nonegative weights
    • Euclidean weights
    • Arbitrary weights
  • Cycles?
    • No directed cycles
    • No negative cycles

Edge-weighted digraph data strcuture

Weighted directed edge: +https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/DirectedEdge.java.html

Edge-weighted digraph: +https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/EdgeWeightedDigraph.java.html

Use adjacency-lists implementation same as EdgeWeightedGraph

Generic Single-source Shortest paths

Our goal is to find the shortest path from s to every other vertex. As a result, what we find will be the shortest-paths tree (SPT) for source s.

Relax edge e = v->w

  • distTo[v] is length of shortest known path from s to v
  • distTo[w] is length of shortest known path from s to w
  • esgeTo[w] is last edge on shortest known pathh from s to w
  • if e = v->w gives shorter path to w through v, update both distTo[w] and edgeTo[w]
1private void relax(DirectedEdge e) {
+2    int v = e.from(), w = e.to();
+3    if (distTo[w] > distTo[v] + e.weight()) {
+4        distTo[w] = distTo[v] + e.weight();
+5        edgeTo[w] = e;
+6    }
+7}
+

Optimality conditions

Given an edge-weighted digraph G, distTo[] are the shortest path distances from s iff:

  • distTo[s] = 0
  • For each vertex v, distTo[v] is the length of some path from s to v.
  • For each edge e = v->w, distTo[w] <= distTo[v] + e.weight()

Generic algorithm

Generic algorithm (to compute SPT from s) {
     Initialize distTo[s] = 0 and distTo[v] = $\infty$
 
     Repeat until optimality conditions are satisfied:
         - Relax any edge
 }
-

Efficient implementations:

- -

Implement 1: Dijkstra’s algorithm

-

When there is no nonnegative weight exists, we can use Dijkstra’s algorithm.

-
    -
  • Consider vertices in increasing order of distance from s (non-tree vertex with the lowest distTo[] value)
  • -
  • add vertex to tree and relax all edges pointing from that vertex
  • -
-
 1public class DijkstraSP{
- 2        // ...
- 3    public DijkstraSP(EdgeWeightedDigraph G, int s) {
- 4        edgeTo = new DirectedEdge[G.V()];
- 5        distTo = new double[G.V()];
- 6        pq = new IndexMinPQ<Double>(G.V());
- 7
- 8        for (int v = 0; v < G.V(); v++) {
- 9            distTo[v] = Double.POSITIVE_INFINITY;
-10        }
-11        distTo[s] = 0;
-12
-13        pq.insert(s, 0.0);
-14        while(!pq.isEmpty()) {
-15            int v= pq.delMin();
-16            for (DirectedEdge e : G.adj(v)) {
-17                relax(e);
-18            }
-19        }
-20    }
-21
-22    private void relax(DirectedEdge e) {
-23        int v = e.from(), w = e.to();
-24        if (distTo[w] > distTo[v] + e.weight()) {
-25            distTo[w] = distTo[v] + e.weight();
-26            edgeTo[w] = e;
-27            if (pq.contains(w)) pq.decreaseKey(w, distTo[w]);
-28            else pq.insert(w, distTo[w]);
-29        }
-30    }
-31}
-

Compare to Prim’s algorithm:

-
    -
  • Both are computing a graph’s spanning tree
  • -
  • Prim’s algorithm choose closest vertex to tree as next vertex, while Dijkstra’s algorithm choose closest vertex to the source
  • -
-

Implement 2: Topological sort algorithm

-

When the graph is a DAG, we can consider vertices in topological order and do relaxing.

-
1    // ...
-2    Topological topological = new Topological(G);
-3    for (int v : topological.order()) {
-4        for (DirectedEdge e : G.adj(v)) {
-5            relax(e);
-6        }
-7    }
-

Seam carving: Resize an image without distortion.

-

Longest paths:

-
    -
  • Formuate as a shortest paths problem in edge-weighted DAGs -
      -
    • Negate all weights
    • -
    • Find shortest paths
    • -
    • Negate weights in result
    • -
    -
  • -
  • Allpication: Parallel job scheduling (Critical path method, CPM).
  • -
-

Implement 3: Bellman-Ford algorithm

-
-

A SPT exists iff no negative cycles (a directed cycle whose sum of edge weights is negative).

-
-

When we want to find shortest paths with nagative weights, Dijkstra’s algorithms doesn’t work. +

Efficient implementations:

Implement 1: Dijkstra’s algorithm

When there is no nonnegative weight exists, we can use Dijkstra’s algorithm.

  • Consider vertices in increasing order of distance from s (non-tree vertex with the lowest distTo[] value)
  • add vertex to tree and relax all edges pointing from that vertex
 1public class DijkstraSP{
+ 2        // ...
+ 3    public DijkstraSP(EdgeWeightedDigraph G, int s) {
+ 4        edgeTo = new DirectedEdge[G.V()];
+ 5        distTo = new double[G.V()];
+ 6        pq = new IndexMinPQ<Double>(G.V());
+ 7
+ 8        for (int v = 0; v < G.V(); v++) {
+ 9            distTo[v] = Double.POSITIVE_INFINITY;
+10        }
+11        distTo[s] = 0;
+12
+13        pq.insert(s, 0.0);
+14        while(!pq.isEmpty()) {
+15            int v= pq.delMin();
+16            for (DirectedEdge e : G.adj(v)) {
+17                relax(e);
+18            }
+19        }
+20    }
+21
+22    private void relax(DirectedEdge e) {
+23        int v = e.from(), w = e.to();
+24        if (distTo[w] > distTo[v] + e.weight()) {
+25            distTo[w] = distTo[v] + e.weight();
+26            edgeTo[w] = e;
+27            if (pq.contains(w)) pq.decreaseKey(w, distTo[w]);
+28            else pq.insert(w, distTo[w]);
+29        }
+30    }
+31}
+

Compare to Prim’s algorithm:

  • Both are computing a graph’s spanning tree
  • Prim’s algorithm choose closest vertex to tree as next vertex, while Dijkstra’s algorithm choose closest vertex to the source

Implement 2: Topological sort algorithm

When the graph is a DAG, we can consider vertices in topological order and do relaxing.

1    // ...
+2    Topological topological = new Topological(G);
+3    for (int v : topological.order()) {
+4        for (DirectedEdge e : G.adj(v)) {
+5            relax(e);
+6        }
+7    }
+

Seam carving: Resize an image without distortion.

Longest paths:

  • Formuate as a shortest paths problem in edge-weighted DAGs
    • Negate all weights
    • Find shortest paths
    • Negate weights in result
  • Allpication: Parallel job scheduling (Critical path method, CPM).

Implement 3: Bellman-Ford algorithm

A SPT exists iff no negative cycles (a directed cycle whose sum of edge weights is negative).

When we want to find shortest paths with nagative weights, Dijkstra’s algorithms doesn’t work. We can use Bellman-Ford algorithm as long as there is no negative cycle in the graph. -(Bellman-Ford algorithm is a dynamic programming algorithm)

-
    -
  • Initialize distTo[s] = 0 and distTo[v] = $\infty$
  • -
  • Maintain a queue and repeat until the queue is empty or find a cycle: -
      -
    • Pop vertex v from q
    • -
    • Relax each edge pointing from v to any vertex w: -
        -
      • if distTo[w] can be de decreased, update distTo[w] and add w to the queue
      • -
      -
    • -
    -
  • -
-
 1// ...
- 2    public BellmanFordSP(EdgeWeightedDigraph G, int s) {
- 3        distTo  = new double[G.V()];
- 4        edgeTo  = new DirectedEdge[G.V()];
- 5        onQueue = new boolean[G.V()];
- 6        for (int v = 0; v < G.V(); v++)
- 7            distTo[v] = Double.POSITIVE_INFINITY;
- 8        distTo[s] = 0.0;
- 9
-10        // Bellman-Ford algorithm
-11        queue = new Queue<Integer>();
-12        queue.enqueue(s);
-13        onQueue[s] = true;
-14        while (!queue.isEmpty() && !hasNegativeCycle()) {
-15            int v = queue.dequeue();
-16            onQueue[v] = false;
-17            relax(G, v);
-18        }
-19    }
-20
-21    private void relax(EdgeWeightedDigraph G, int v) {
-22        for (DirectedEdge e : G.adj(v)) {
-23            int w = e.to();
-24            if (distTo[w] > distTo[v] + e.weight()) {
-25                distTo[w] = distTo[v] + e.weight();
-26                edgeTo[w] = e;
-27                if (!onQueue[w]) {
-28                    queue.enqueue(w);
-29                    onQueue[w] = true;
-30                }
-31            }
-32            if (++cost % G.V() == 0) {
-33                findNegativeCycle();
-34                if (hasNegativeCycle()) return;  // found a negative cycle
-35            }
-36        }
-37    }
-38
-

Bellman-Ford algorithm can also be used for finding a negative cycle.

-

Negative cycle application: arbitrage detection.

-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - - - \ No newline at end of file +(Bellman-Ford algorithm is a dynamic programming algorithm)

  • Initialize distTo[s] = 0 and distTo[v] = $\infty$
  • Maintain a queue and repeat until the queue is empty or find a cycle:
    • Pop vertex v from q
    • Relax each edge pointing from v to any vertex w:
      • if distTo[w] can be de decreased, update distTo[w] and add w to the queue
 1// ...
+ 2    public BellmanFordSP(EdgeWeightedDigraph G, int s) {
+ 3        distTo  = new double[G.V()];
+ 4        edgeTo  = new DirectedEdge[G.V()];
+ 5        onQueue = new boolean[G.V()];
+ 6        for (int v = 0; v < G.V(); v++)
+ 7            distTo[v] = Double.POSITIVE_INFINITY;
+ 8        distTo[s] = 0.0;
+ 9
+10        // Bellman-Ford algorithm
+11        queue = new Queue<Integer>();
+12        queue.enqueue(s);
+13        onQueue[s] = true;
+14        while (!queue.isEmpty() && !hasNegativeCycle()) {
+15            int v = queue.dequeue();
+16            onQueue[v] = false;
+17            relax(G, v);
+18        }
+19    }
+20
+21    private void relax(EdgeWeightedDigraph G, int v) {
+22        for (DirectedEdge e : G.adj(v)) {
+23            int w = e.to();
+24            if (distTo[w] > distTo[v] + e.weight()) {
+25                distTo[w] = distTo[v] + e.weight();
+26                edgeTo[w] = e;
+27                if (!onQueue[w]) {
+28                    queue.enqueue(w);
+29                    onQueue[w] = true;
+30                }
+31            }
+32            if (++cost % G.V() == 0) {
+33                findNegativeCycle();
+34                if (hasNegativeCycle()) return;  // found a negative cycle
+35            }
+36        }
+37    }
+

Bellman-Ford algorithm can also be used for finding a negative cycle.

Negative cycle application: arbitrage detection.

\ No newline at end of file diff --git a/posts/2020-06-06-changes-in-java-string/index.html b/posts/2020-06-06-changes-in-java-string/index.html index 1101e9e9..0fc0cfeb 100644 --- a/posts/2020-06-06-changes-in-java-string/index.html +++ b/posts/2020-06-06-changes-in-java-string/index.html @@ -1,438 +1,174 @@ - - - - - - - - - - - Changes to String in java (from 1.7.0_06) | Cactus theme example - - - - - - -Changes to String in java (from 1.7.0_06) | Cactus theme example + - - - - - - - - - - - -
-
- +1public final class String 2 implements java.io.Serializable, Comparable, CharSequence 3{ 4 /** The value is used for character storage. */ 5 private final char value[]; 6 7 /** The offset is the first index of the storage that is used.">
- - - - - -
- - - + +
- -
-
- -
- -
-
-
-
-
-

-Changes to String in java (from 1.7.0_06) -

-
- -
- -4 minute read -
- - -
-
-
-

Before 1.7.0_06, String has 4 non static field:

-
    -
  • char[] value
  • -
  • int[] offset
  • -
  • int count
  • -
  • int hash
  • -
-

Subing.substring create a String by sharing the original String’s internal char[] value and setting offset. This saves memory and makes String.substring run in a constant time($O(1)$). -Meanwhile, this feature may cause memory leak1.

-

http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/8deef18bb749/src/share/classes/java/lang/String.java

-
 1public final class String
- 2    implements java.io.Serializable, Comparable<String>, CharSequence
- 3{
- 4    /** The value is used for character storage. */
- 5    private final char value[];
- 6
- 7    /** The offset is the first index of the storage that is used. */
- 8    private final int offset;
- 9
-10    /** The count is the number of characters in the String. */
-11    private final int count;
-12
-13    /** Cache the hash code for the string */
-14    private int hash; // Default to 0
-15
-16    // ...
-17
-18    // Package private constructor which shares value array for speed.
-19    String(int offset, int count, char value[]) {
-20        this.value = value;
-21        this.offset = offset;
-22        this.count = count;
-23    }
-24
-25    // ...
-26
-27    /**
-28     * Returns a new string that is a substring of this string. The
-29     * substring begins at the specified <code>beginIndex</code> and
-30     * extends to the character at index <code>endIndex - 1</code>.
-31     * Thus the length of the substring is <code>endIndex-beginIndex</code>.
-32     * <p>
-33     * Examples:
-34     * <blockquote><pre>
-35     * "hamburger".substring(4, 8) returns "urge"
-36     * "smiles".substring(1, 5) returns "mile"
-37     * </pre></blockquote>
-38     *
-39     * @param      beginIndex   the beginning index, inclusive.
-40     * @param      endIndex     the ending index, exclusive.
-41     * @return     the specified substring.
-42     * @exception  IndexOutOfBoundsException  if the
-43     *             <code>beginIndex</code> is negative, or
-44     *             <code>endIndex</code> is larger than the length of
-45     *             this <code>String</code> object, or
-46     *             <code>beginIndex</code> is larger than
-47     *             <code>endIndex</code>.
-48     */
-49    public String substring(int beginIndex, int endIndex) {
-50        if (beginIndex < 0) {
-51            throw new StringIndexOutOfBoundsException(beginIndex);
-52        }
-53        if (endIndex > count) {
-54            throw new StringIndexOutOfBoundsException(endIndex);
-55        }
-56        if (beginIndex > endIndex) {
-57            throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
-58        }
-59        return ((beginIndex == 0) && (endIndex == count)) ? this :
-60            new String(offset + beginIndex, endIndex - beginIndex, value);
-61    }
-62
-63    // ...
-64}
-

Since Java 1.7.0_06, offset and count fields were removed. String.substring makes new copies of value, which means we can forget about the memory leak but the runtime becomes $O(N)$ at the same time.

-

http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/String.java

-
 1
- 2public final class String
- 3    implements java.io.Serializable, Comparable<String>, CharSequence {
- 4    /** The value is used for character storage. */
- 5    private final char value[];
- 6
- 7    /** Cache the hash code for the string */
- 8    private int hash; // Default to 0
- 9
-10    // ...
-11
-12  /**
-13     * Allocates a new {@code String} that contains characters from a subarray
-14     * of the character array argument. The {@code offset} argument is the
-15     * index of the first character of the subarray and the {@code count}
-16     * argument specifies the length of the subarray. The contents of the
-17     * subarray are copied; subsequent modification of the character array does
-18     * not affect the newly created string.
-19     *
-20     * @param  value
-21     *         Array that is the source of characters
-22     *
-23     * @param  offset
-24     *         The initial offset
-25     *
-26     * @param  count
-27     *         The length
-28     *
-29     * @throws  IndexOutOfBoundsException
-30     *          If the {@code offset} and {@code count} arguments index
-31     *          characters outside the bounds of the {@code value} array
-32     */
-33    public String(char value[], int offset, int count) {
-34        if (offset < 0) {
-35            throw new StringIndexOutOfBoundsException(offset);
-36        }
-37        if (count < 0) {
-38            throw new StringIndexOutOfBoundsException(count);
-39        }
-40        // Note: offset or count might be near -1>>>1.
-41        if (offset > value.length - count) {
-42            throw new StringIndexOutOfBoundsException(offset + count);
-43        }
-44        this.value = Arrays.copyOfRange(value, offset, offset+count);
-45    }
-46
-47    // ...
-48
-49/**
-50     * Returns a string that is a substring of this string. The
-51     * substring begins at the specified {@code beginIndex} and
-52     * extends to the character at index {@code endIndex - 1}.
-53     * Thus the length of the substring is {@code endIndex-beginIndex}.
-54     * <p>
-55     * Examples:
-56     * <blockquote><pre>
-57     * "hamburger".substring(4, 8) returns "urge"
-58     * "smiles".substring(1, 5) returns "mile"
-59     * </pre></blockquote>
-60     *
-61     * @param      beginIndex   the beginning index, inclusive.
-62     * @param      endIndex     the ending index, exclusive.
-63     * @return     the specified substring.
-64     * @exception  IndexOutOfBoundsException  if the
-65     *             {@code beginIndex} is negative, or
-66     *             {@code endIndex} is larger than the length of
-67     *             this {@code String} object, or
-68     *             {@code beginIndex} is larger than
-69     *             {@code endIndex}.
-70     */
-71    public String substring(int beginIndex, int endIndex) {
-72        if (beginIndex < 0) {
-73            throw new StringIndexOutOfBoundsException(beginIndex);
-74        }
-75        if (endIndex > value.length) {
-76            throw new StringIndexOutOfBoundsException(endIndex);
-77        }
-78        int subLen = endIndex - beginIndex;
-79        if (subLen < 0) {
-80            throw new StringIndexOutOfBoundsException(subLen);
-81        }
-82        return ((beginIndex == 0) && (endIndex == value.length)) ? this
-83                : new String(value, beginIndex, subLen);
-84    }
-85
-86    // ...
-87
-88}
-

The auther’s comment2: -Card

-
-
-
    -
  1. -

    http://java-performance.info/changes-to-string-java-1-7-0_06/ ↩︎

    -
  2. -
  3. -

    https://www.reddit.com/r/programming/comments/1qw73v/til_oracle_changed_the_internal_string/cdhb77f/ ↩︎

    -
  4. -
-
-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

Changes to String in java (from 1.7.0_06)

+4 minute read

Before 1.7.0_06, String has 4 non static field:

  • char[] value
  • int[] offset
  • int count
  • int hash

Subing.substring create a String by sharing the original String’s internal char[] value and setting offset. This saves memory and makes String.substring run in a constant time($O(1)$). +Meanwhile, this feature may cause memory leak1.

http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/8deef18bb749/src/share/classes/java/lang/String.java

 1public final class String
+ 2    implements java.io.Serializable, Comparable<String>, CharSequence
+ 3{
+ 4    /** The value is used for character storage. */
+ 5    private final char value[];
+ 6
+ 7    /** The offset is the first index of the storage that is used. */
+ 8    private final int offset;
+ 9
+10    /** The count is the number of characters in the String. */
+11    private final int count;
+12
+13    /** Cache the hash code for the string */
+14    private int hash; // Default to 0
+15
+16    // ...
+17
+18    // Package private constructor which shares value array for speed.
+19    String(int offset, int count, char value[]) {
+20        this.value = value;
+21        this.offset = offset;
+22        this.count = count;
+23    }
+24
+25    // ...
+26
+27    /**
+28     * Returns a new string that is a substring of this string. The
+29     * substring begins at the specified <code>beginIndex</code> and
+30     * extends to the character at index <code>endIndex - 1</code>.
+31     * Thus the length of the substring is <code>endIndex-beginIndex</code>.
+32     * <p>
+33     * Examples:
+34     * <blockquote><pre>
+35     * "hamburger".substring(4, 8) returns "urge"
+36     * "smiles".substring(1, 5) returns "mile"
+37     * </pre></blockquote>
+38     *
+39     * @param      beginIndex   the beginning index, inclusive.
+40     * @param      endIndex     the ending index, exclusive.
+41     * @return     the specified substring.
+42     * @exception  IndexOutOfBoundsException  if the
+43     *             <code>beginIndex</code> is negative, or
+44     *             <code>endIndex</code> is larger than the length of
+45     *             this <code>String</code> object, or
+46     *             <code>beginIndex</code> is larger than
+47     *             <code>endIndex</code>.
+48     */
+49    public String substring(int beginIndex, int endIndex) {
+50        if (beginIndex < 0) {
+51            throw new StringIndexOutOfBoundsException(beginIndex);
+52        }
+53        if (endIndex > count) {
+54            throw new StringIndexOutOfBoundsException(endIndex);
+55        }
+56        if (beginIndex > endIndex) {
+57            throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
+58        }
+59        return ((beginIndex == 0) && (endIndex == count)) ? this :
+60            new String(offset + beginIndex, endIndex - beginIndex, value);
+61    }
+62
+63    // ...
+64}
+

Since Java 1.7.0_06, offset and count fields were removed. String.substring makes new copies of value, which means we can forget about the memory leak but the runtime becomes $O(N)$ at the same time.

http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/String.java

 1
+ 2public final class String
+ 3    implements java.io.Serializable, Comparable<String>, CharSequence {
+ 4    /** The value is used for character storage. */
+ 5    private final char value[];
+ 6
+ 7    /** Cache the hash code for the string */
+ 8    private int hash; // Default to 0
+ 9
+10    // ...
+11
+12  /**
+13     * Allocates a new {@code String} that contains characters from a subarray
+14     * of the character array argument. The {@code offset} argument is the
+15     * index of the first character of the subarray and the {@code count}
+16     * argument specifies the length of the subarray. The contents of the
+17     * subarray are copied; subsequent modification of the character array does
+18     * not affect the newly created string.
+19     *
+20     * @param  value
+21     *         Array that is the source of characters
+22     *
+23     * @param  offset
+24     *         The initial offset
+25     *
+26     * @param  count
+27     *         The length
+28     *
+29     * @throws  IndexOutOfBoundsException
+30     *          If the {@code offset} and {@code count} arguments index
+31     *          characters outside the bounds of the {@code value} array
+32     */
+33    public String(char value[], int offset, int count) {
+34        if (offset < 0) {
+35            throw new StringIndexOutOfBoundsException(offset);
+36        }
+37        if (count < 0) {
+38            throw new StringIndexOutOfBoundsException(count);
+39        }
+40        // Note: offset or count might be near -1>>>1.
+41        if (offset > value.length - count) {
+42            throw new StringIndexOutOfBoundsException(offset + count);
+43        }
+44        this.value = Arrays.copyOfRange(value, offset, offset+count);
+45    }
+46
+47    // ...
+48
+49/**
+50     * Returns a string that is a substring of this string. The
+51     * substring begins at the specified {@code beginIndex} and
+52     * extends to the character at index {@code endIndex - 1}.
+53     * Thus the length of the substring is {@code endIndex-beginIndex}.
+54     * <p>
+55     * Examples:
+56     * <blockquote><pre>
+57     * "hamburger".substring(4, 8) returns "urge"
+58     * "smiles".substring(1, 5) returns "mile"
+59     * </pre></blockquote>
+60     *
+61     * @param      beginIndex   the beginning index, inclusive.
+62     * @param      endIndex     the ending index, exclusive.
+63     * @return     the specified substring.
+64     * @exception  IndexOutOfBoundsException  if the
+65     *             {@code beginIndex} is negative, or
+66     *             {@code endIndex} is larger than the length of
+67     *             this {@code String} object, or
+68     *             {@code beginIndex} is larger than
+69     *             {@code endIndex}.
+70     */
+71    public String substring(int beginIndex, int endIndex) {
+72        if (beginIndex < 0) {
+73            throw new StringIndexOutOfBoundsException(beginIndex);
+74        }
+75        if (endIndex > value.length) {
+76            throw new StringIndexOutOfBoundsException(endIndex);
+77        }
+78        int subLen = endIndex - beginIndex;
+79        if (subLen < 0) {
+80            throw new StringIndexOutOfBoundsException(subLen);
+81        }
+82        return ((beginIndex == 0) && (endIndex == value.length)) ? this
+83                : new String(value, beginIndex, subLen);
+84    }
+85
+86    // ...
+87
+88}
+

The auther’s comment2: +Card

\ No newline at end of file diff --git a/posts/code-block-test/index.html b/posts/code-block-test/index.html index e9483182..90437483 100644 --- a/posts/code-block-test/index.html +++ b/posts/code-block-test/index.html @@ -1,414 +1,163 @@ - - - - - - - - - - - Code Block Test | Cactus theme example - - - - - - -Code Block Test | Cactus theme example + - - - - - - - - - - - -
-
- +1// JavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJava 2public final class String 3 implements java.io.Serializable, Comparable, CharSequence 4{ 5 /** The value is used for character storage. */ 6 private final char value[]; 7 8 /** The offset is the first index of the storage that is used. */ 9 private final int offset; 10 11 /** The count is the number of characters in the String.">
- - - - - -
- - - + +
- -
-
- -
- -
-
-
-
-
-

-Code Block Test -

-
- -
- -2 minute read -
- - -
-
-
-

String

-

Using indents:

-
text
+

Code Block Test

+2 minute read

String

Using indents:

text
 text
 text
-
-

Fenced code block:

-
text
+

Fenced code block:

text
 text
 <tag>
-

Fenced code block with language (lineNumbersInTable = false):

-
 1// JavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJava
- 2public final class String
- 3    implements java.io.Serializable, Comparable<String>, CharSequence
- 4{
- 5    /** The value is used for character storage. */
- 6    private final char value[];
- 7
- 8    /** The offset is the first index of the storage that is used. */
- 9    private final int offset;
-10
-11    /** The count is the number of characters in the String. */
-12    private final int count;
-13
-14    /** Cache the hash code for the string */
-15    private int hash; // Default to 0
-16
-17    // ...
-18
-19    // Package private constructor which shares value array for speed.
-20    String(int offset, int count, char value[]) {
-21        this.value = value;
-22        this.offset = offset;
-23        this.count = count;
-24    }
-25
-26    // ...
-27
-28    /**
-29     * Returns a new string that is a substring of this string. The
-30     * substring begins at the specified <code>beginIndex</code> and
-31     * extends to the character at index <code>endIndex - 1</code>.
-32     * Thus the length of the substring is <code>endIndex-beginIndex</code>.
-33     * <p>
-34     * Examples:
-35     * <blockquote><pre>
-36     * "hamburger".substring(4, 8) returns "urge"
-37     * "smiles".substring(1, 5) returns "mile"
-38     * </pre></blockquote>
-39     *
-40     * @param      beginIndex   the beginning index, inclusive.
-41     * @param      endIndex     the ending index, exclusive.
-42     * @return     the specified substring.
-43     * @exception  IndexOutOfBoundsException  if the
-44     *             <code>beginIndex</code> is negative, or
-45     *             <code>endIndex</code> is larger than the length of
-46     *             this <code>String</code> object, or
-47     *             <code>beginIndex</code> is larger than
-48     *             <code>endIndex</code>.
-49     */
-50    public String substring(int beginIndex, int endIndex) {
-51        if (beginIndex < 0) {
-52            throw new StringIndexOutOfBoundsException(beginIndex);
-53        }
-54        if (endIndex > count) {
-55            throw new StringIndexOutOfBoundsException(endIndex);
-56        }
-57        if (beginIndex > endIndex) {
-58            throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
-59        }
-60        return ((beginIndex == 0) && (endIndex == count)) ? this :
-61            new String(offset + beginIndex, endIndex - beginIndex, value);
-62    }
-63
-64    // ...
-65}
-

Using hugo’s highlight shortcode (lineNumbersInTable = true):

-
- -
-
 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
-10
-11
-12
-13
-14
-15
-16
-17
-18
-19
-20
-21
-
-
// TypeScript
-type OptionalUser = {
-    [K in keyof User]?: User[K]
-}
-
-// ! we can remove optional constraint
-type RequiredUser = {
-    [K in keyof OptionalUser]-?: User[K]
-}
-
-type NullableUser = {
-    [K in keyof User]: User[K] | null
-}
-type ReadonlyUser = {
-    readonly [K in keyof User]: User[K]
-}
-
-// ! we can remove readonly constraint
-type ModifiableUser = {
-    -readonly [K in keyof User]: User[K]
-}
-
-
-

Without line number

-
(() => {
-
-  function createCopyButton(codeNode) {
-    const copyBtn = document.createElement('button')
-    copyBtn.className = 'code-copy-btn'
-    copyBtn.type = 'button'
-    copyBtn.innerText = 'copy'
-    copyBtn.parentElement = codeNode.parentElement
-
-    let resetTimer
-    copyBtn.addEventListener('click', () => {
-      navigator.clipboard.writeText(codeNode.innerText).then(() => {
-        copyBtn.innerText = 'copied!'
-      }).then(() => {
-        clearTimeout(resetTimer)
-        resetTimer = setTimeout(() => {
-          copyBtn.innerText = 'copy'
-        }, 1000)
-      })
-    })
-
-    return copyBtn
-  }
-
-  document.querySelectorAll('pre > code').forEach((codeNode) => {
-    const copyBtn = createCopyButton(codeNode);
-    codeNode.parentNode.insertBefore(copyBtn, codeNode)
-  })
-
-})()
-
-
-
-
- -
-
-
-
- - - - -
-
- -
- - - - - - \ No newline at end of file +

Fenced code block with language (lineNumbersInTable = false):

 1// JavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJava
+ 2public final class String
+ 3    implements java.io.Serializable, Comparable<String>, CharSequence
+ 4{
+ 5    /** The value is used for character storage. */
+ 6    private final char value[];
+ 7
+ 8    /** The offset is the first index of the storage that is used. */
+ 9    private final int offset;
+10
+11    /** The count is the number of characters in the String. */
+12    private final int count;
+13
+14    /** Cache the hash code for the string */
+15    private int hash; // Default to 0
+16
+17    // ...
+18
+19    // Package private constructor which shares value array for speed.
+20    String(int offset, int count, char value[]) {
+21        this.value = value;
+22        this.offset = offset;
+23        this.count = count;
+24    }
+25
+26    // ...
+27
+28    /**
+29     * Returns a new string that is a substring of this string. The
+30     * substring begins at the specified <code>beginIndex</code> and
+31     * extends to the character at index <code>endIndex - 1</code>.
+32     * Thus the length of the substring is <code>endIndex-beginIndex</code>.
+33     * <p>
+34     * Examples:
+35     * <blockquote><pre>
+36     * "hamburger".substring(4, 8) returns "urge"
+37     * "smiles".substring(1, 5) returns "mile"
+38     * </pre></blockquote>
+39     *
+40     * @param      beginIndex   the beginning index, inclusive.
+41     * @param      endIndex     the ending index, exclusive.
+42     * @return     the specified substring.
+43     * @exception  IndexOutOfBoundsException  if the
+44     *             <code>beginIndex</code> is negative, or
+45     *             <code>endIndex</code> is larger than the length of
+46     *             this <code>String</code> object, or
+47     *             <code>beginIndex</code> is larger than
+48     *             <code>endIndex</code>.
+49     */
+50    public String substring(int beginIndex, int endIndex) {
+51        if (beginIndex < 0) {
+52            throw new StringIndexOutOfBoundsException(beginIndex);
+53        }
+54        if (endIndex > count) {
+55            throw new StringIndexOutOfBoundsException(endIndex);
+56        }
+57        if (beginIndex > endIndex) {
+58            throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
+59        }
+60        return ((beginIndex == 0) && (endIndex == count)) ? this :
+61            new String(offset + beginIndex, endIndex - beginIndex, value);
+62    }
+63
+64    // ...
+65}
+

Using hugo’s highlight shortcode (lineNumbersInTable = true):

 1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+ 8
+ 9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+
// TypeScript
+type OptionalUser = {
+    [K in keyof User]?: User[K]
+}
+
+// ! we can remove optional constraint
+type RequiredUser = {
+    [K in keyof OptionalUser]-?: User[K]
+}
+
+type NullableUser = {
+    [K in keyof User]: User[K] | null
+}
+type ReadonlyUser = {
+    readonly [K in keyof User]: User[K]
+}
+
+// ! we can remove readonly constraint
+type ModifiableUser = {
+    -readonly [K in keyof User]: User[K]
+}

Without line number

(() => {
+
+  function createCopyButton(codeNode) {
+    const copyBtn = document.createElement('button')
+    copyBtn.className = 'code-copy-btn'
+    copyBtn.type = 'button'
+    copyBtn.innerText = 'copy'
+    copyBtn.parentElement = codeNode.parentElement
+
+    let resetTimer
+    copyBtn.addEventListener('click', () => {
+      navigator.clipboard.writeText(codeNode.innerText).then(() => {
+        copyBtn.innerText = 'copied!'
+      }).then(() => {
+        clearTimeout(resetTimer)
+        resetTimer = setTimeout(() => {
+          copyBtn.innerText = 'copy'
+        }, 1000)
+      })
+    })
+
+    return copyBtn
+  }
+
+  document.querySelectorAll('pre > code').forEach((codeNode) => {
+    const copyBtn = createCopyButton(codeNode);
+    codeNode.parentNode.insertBefore(copyBtn, codeNode)
+  })
+
+})()
\ No newline at end of file diff --git a/posts/index.html b/posts/index.html index e5d817bd..d1a72ae6 100644 --- a/posts/index.html +++ b/posts/index.html @@ -1,162 +1,3 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- - -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/posts/index.xml b/posts/index.xml index 977f3da1..86e161fe 100644 --- a/posts/index.xml +++ b/posts/index.xml @@ -5,8 +5,8 @@ text text &lt;tag&gt; Fenced code block with language (lineNumbersInTabl 1// JavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJavaJava 2public final class String 3 implements java.io.Serializable, Comparable&lt;String&gt;, CharSequence 4{ 5 /** The value is used for character storage. */ 6 private final char value[]; 7 8 /** The offset is the first index of the storage that is used. */ 9 private final int offset; 10 11 /** The count is the number of characters in the String.
Changes to String in java (from 1.7.0_06)https://www.takuzen.me/hugo-theme-cactus/posts/2020-06-06-changes-in-java-string/Sat, 06 Jun 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-06-06-changes-in-java-string/Before 1.7.0_06, String has 4 non static field: char[] value int[] offset int count int hash Subing.substring create a String by sharing the original String&rsquo;s internal char[] value and setting offset. This saves memory and makes String.substring run in a constant time($O(1)$). Meanwhile, this feature may cause memory leak1. http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/8deef18bb749/src/share/classes/java/lang/String.java -1public final class String 2 implements java.io.Serializable, Comparable&lt;String&gt;, CharSequence 3{ 4 /** The value is used for character storage.Algorithms - Graphshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-05-01-algorithms-graphs/Fri, 01 May 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-05-01-algorithms-graphs/Undirected Graphs Some problems Path Shortest path Cycle Ehler tour: A cycle that uses each edge excatly once. Hamilton tour: A cycle that uses each vertex exactly once classical NP-complete problem. Connectivity MST: Biconnectivity: A vertex whose removal disconnects the graph Planarity Graph isomorphism: Are two graphs identical? No one knows so far. A lonstanding open problem Representations Real-world graphs tend to be sparse (huge number of vertices, small average vertex degree).Programming Language - Subtypinghttps://www.takuzen.me/hugo-theme-cactus/posts/2020-04-29-subtyping/Wed, 29 Apr 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-04-29-subtyping/Some Good Subtyping Rules Width subtyping: A supertype can have a subset of fields with the same types, i.e., a subtype can have extra fields. Permutation subtypings: A supertype can have the same set of fields with the same types in a different order. Transitivity: if t1 is subtype of t2, and t2 is subtype of t3, then t1 is subtype of t3. Reflexivity: Every type is a subtype of itself.Racket noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Sat, 29 Feb 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Basic 1#lang racket 2(provide (all-defined-out)) 3 4;this is a comment 5 6(define s &#34;hello&#34;) 7 8(define x 3) 9(define y (+ x 2)) 10 11(define cube1 12 (lambda (x) 13 (* x (* x x)))) 14 15(define cube2 16 (lambda (x) 17 (* x x x))) 18 19(define (cube3 x) 20 (* x x x)) 21 22(define (pow1 x y) 23 (if (=y 0) 24 1 25 (* x (pow1 x (- y 1))))) 26 27; currying 28(define pow2 29 (lambda (x) 30 (lambda (y) 31 (pow1 x y)))) 32 List Empty list: null () doesn&quot;t work for null but '() does build a list: (list e1 .Standard ML noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Mon, 30 Dec 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Basics Comments (* SML comment *) Variable bindings and Expressions val x = 34; (* static environment: x : int *) (* dynamic environment: x --&gt; 34 *) val y = x + 1; (* Use tilde character instead of minus to reprsent negation *) val z = ~1; (* Integer Division *) val w = y div x Strings: -(* `\n`のようなエスケープシーケンスが利用できる *) val x = &quot;hello\n&quot;; (* 文字列の連結には'^'を使う *) val y = &quot;hello &quot; ^ &quot;world&quot;; An ML program is a sequence of bindings.uipath ノート(三)- uipath orchestratorhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-11-23-uipath-orchestrator/Sat, 23 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-11-23-uipath-orchestrator/利用手順 Official doc: https://docs.uipath.com/robot/docs/from-orchestrator-and-the-orchestrator-settings-window +1public final class String 2 implements java.io.Serializable, Comparable&lt;String&gt;, CharSequence 3{ 4 /** The value is used for character storage. */ 5 private final char value[]; 6 7 /** The offset is the first index of the storage that is used.Algorithms - Graphshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-05-01-algorithms-graphs/Fri, 01 May 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-05-01-algorithms-graphs/Undirected Graphs Some problems Path Shortest path Cycle Ehler tour: A cycle that uses each edge excatly once. Hamilton tour: A cycle that uses each vertex exactly once classical NP-complete problem. Connectivity MST: Biconnectivity: A vertex whose removal disconnects the graph Planarity Graph isomorphism: Are two graphs identical? No one knows so far. A lonstanding open problem Representations Real-world graphs tend to be sparse (huge number of vertices, small average vertex degree).Programming Language - Subtypinghttps://www.takuzen.me/hugo-theme-cactus/posts/2020-04-29-subtyping/Wed, 29 Apr 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-04-29-subtyping/Some Good Subtyping Rules Width subtyping: A supertype can have a subset of fields with the same types, i.e., a subtype can have extra fields. Permutation subtypings: A supertype can have the same set of fields with the same types in a different order. Transitivity: if t1 is subtype of t2, and t2 is subtype of t3, then t1 is subtype of t3. Reflexivity: Every type is a subtype of itself.Racket noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Sat, 29 Feb 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Basic 1#lang racket 2(provide (all-defined-out)) 3 4;this is a comment 5 6(define s &#34;hello&#34;) 7 8(define x 3) 9(define y (+ x 2)) 10 11(define cube1 12 (lambda (x) 13 (* x (* x x)))) 14 15(define cube2 16 (lambda (x) 17 (* x x x))) 18 19(define (cube3 x) 20 (* x x x)) 21 22(define (pow1 x y) 23 (if (=y 0) 24 1 25 (* x (pow1 x (- y 1))))) 26 27; currying 28(define pow2 29 (lambda (x) 30 (lambda (y) 31 (pow1 x y)))) List Empty list: null () doesn&quot;t work for null but '() does build a list: (list e1 .Standard ML noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Mon, 30 Dec 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Basics Comments (* SML comment *) Variable bindings and Expressions val x = 34; (* static environment: x : int *) (* dynamic environment: x --&gt; 34 *) val y = x + 1; (* Use tilde character instead of minus to reprsent negation *) val z = ~1; (* Integer Division *) val w = y div x Strings: +(* `\n`のようなエスケープシーケンスが利用できる *) val x = &#34;hello\n&#34;; (* 文字列の連結には&#39;^&#39;を使う *) val y = &#34;hello &#34; ^ &#34;world&#34;; An ML program is a sequence of bindings.uipath ノート(三)- uipath orchestratorhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-11-23-uipath-orchestrator/Sat, 23 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-11-23-uipath-orchestrator/利用手順 Official doc: https://docs.uipath.com/robot/docs/from-orchestrator-and-the-orchestrator-settings-window マシンを追加 マシン側でマシン名とユーザ名を確認 C:\Users\user&gt;hostname DESKTOP-ABCDE5F C:\Users\user&gt;whoami desktop-abcde5f\user C:\Users\user&gt; 追加完了後、マシンキーを取得する。 ロボットを登録 Type: studio (開発用?) Domain/Username: 上記のユーザ名 ローカルのorchestrator設定 Uipath Robotを開き⇒orchestratorの設定で、上記のマシンキーを入力する。 orchestrator URLに https://platform.uipath.com/ を入力する. Invalid machine keyというエラーが出たら、下記のようなURLを試す: @@ -30,10 +30,10 @@ UI インタラクション: シーケンス 環境設定を Config ファイルに格納 不要になったアプリケーションを終了させることで、常にクリーンな状態を維持しましょう。JavaScript URI エンコーディングhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-11-10-encodeuricomponent/Sun, 10 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-11-10-encodeuricomponent/まとめ encodeURI()とencodeURIComponent()はRFC 2396準拠である。 encodeURI() は完全な URI を表すのに必要な文字 (Reserved Characters) はエンコードしません。 また、予約されていないが &ldquo;そのまま&rdquo; URI に使用できる(Unreserved Marks) 文字をエンコードしません。 encodeURIComponent() は &ldquo;Unreserved Marks&rdquo; 文字をエンコードしません。 1var set1 = &#34;;,/?:@&amp;=+$#&#34;; // Reserved Characters 2var set2 = &#34;-_.!~*&#39;()&#34;; // Unreserved Marks 3 4console.log(encodeURI(set1)); // ;,/?:@&amp;=+$ 5console.log(encodeURI(set2)); // -_.!~*&#39;() 6 7console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24 8console.log(encodeURIComponent(set2)); // -_.!~*&#39;() rfc2396 appendix-A https://tools.ietf.org/html/rfc2396#appendix-A -URI-reference = [ absoluteURI | relativeURI ] [ &quot;#&quot; fragment ] absoluteURI = scheme &quot;:&quot; ( hier_part | opaque_part ) relativeURI = ( net_path | abs_path | rel_path ) [ &quot;?uipath ノート(一)https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/Sun, 27 Oct 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/変数 Int32 String Boolean GenericValue 参照 UiPath Studio には GenericValue 変数の自動変換メカニズムがあり、式を正しく定義することで、目的の結果を得ることができます。式の最初の要素は、Studio から操作するガイドラインとして使用されることを考慮してください。例えば、2 つの GenericValue 変数を追加し、式の最初の変数が String として定義されてた場合、最初に代入された値を元に 2 つの値を結合し、文字列となります。 Integer として定義した場合の結果は、合計の値となります。 +URI-reference = [ absoluteURI | relativeURI ] [ &#34;#&#34; fragment ] absoluteURI = scheme &#34;:&#34; ( hier_part | opaque_part ) relativeURI = ( net_path | abs_path | rel_path ) [ &#34;?uipath ノート(一)https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/Sun, 27 Oct 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/変数 Int32 String Boolean GenericValue 参照 UiPath Studio には GenericValue 変数の自動変換メカニズムがあり、式を正しく定義することで、目的の結果を得ることができます。式の最初の要素は、Studio から操作するガイドラインとして使用されることを考慮してください。例えば、2 つの GenericValue 変数を追加し、式の最初の変数が String として定義されてた場合、最初に代入された値を元に 2 つの値を結合し、文字列となります。 Integer として定義した場合の結果は、合計の値となります。 Array DataTime DataTable .Net 変数型を参照して探す方法 アクティビティ レイアウトダイアグラム シーエンス: より高度で複雑な自動化に向こう フローチャート: シンプルな自動化プロジェクトに適している ステートマシン Global Exception Handler (グローバル例外ハンドラー) 参照:https://docs.uipath.com/studio/lang-ja/docs/workflow-design -選択肢 条件分岐(If): シーケンス用条件分岐 フロー条件分岐(flow desicion): フローチャート用条件分岐 フロースイッチ (Flow Switch) 繰り返し 繰り返し(前判定)(While) 繰り返し(後判定)(Do While) 繰り返し(コレクションの各要素)(For Each) データ操作 CSVを読み込み(Read CSV) オプションにエンコーディングを指定できる(日本語データがある場合、&quot;SHIFT-JIS&quot;を指定する) 列名を含める(IncludeColumnNames)を指定できる 出力タイプ:System.JavaScript Comparison operation at a glancehttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-28-javascript-comparison/Thu, 28 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-28-javascript-comparison/When given a scenario like: +選択肢 条件分岐(If): シーケンス用条件分岐 フロー条件分岐(flow desicion): フローチャート用条件分岐 フロースイッチ (Flow Switch) 繰り返し 繰り返し(前判定)(While) 繰り返し(後判定)(Do While) 繰り返し(コレクションの各要素)(For Each) データ操作 CSVを読み込み(Read CSV) オプションにエンコーディングを指定できる(日本語データがある場合、&quot;SHIFT-JIS&quot;を指定する) 列名を含める(IncludeColumnNames)を指定できる 出力タイプ:System.Data.DataTable Microsoft Docs Selectメソッドで半角スペースを含む列名で指定する場合、半角スペースが特殊文字ではなく文字列として認識されるため、[]で列名を囲う Names.Select(&#34;[メンバー ステータス] = &#39;Yes&#39;&#34;) その他 メッセージボックス 代入(assign) 待機 (Delay) 入力ダイアログ(input dialog): フォルダーを選択(Select Folder) 一行を書き込み(Write Line): Debug用? アプリケーションを開く(Open Application) ブラウザを開く(Open Browser) ブラウザーにアタッチ(Attach Browser) 文字を入力(Type Into) ハイライト(Highlight) アンカーベース(Anchor Base) スクリーンショットをと撮る(Take Screenshot) 要素の有無を検出(Element Exists) 要素の消滅を待つ(Wait Element Vanish) レコーディング機能 [○]レコーディング可JavaScript Comparison operation at a glancehttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-28-javascript-comparison/Thu, 28 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-28-javascript-comparison/When given a scenario like: 1console.log(null &gt; -1) //true It produces true, which makes me think null is treated as 0. But when I run: 1console.log(null == 0) // false 2console.log(null &gt; 0) // false 3console.log(null &lt; 0) // false They all output false! I googled a lot and finally found answers in Ecma-262 Specification. @@ -45,61 +45,61 @@ The comparison x == y, where x and y are values, produces true or false. Such a <p>The &ldquo;cool kids&rdquo; in JavaScript would generally pronounce <code>__proto__</code> as &ldquo;<strong>dunder proto</strong>&rdquo;.</p> </blockquote> <p><a href="https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript">https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript</a></p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span>( <span style="color:#ff79c6">new</span> Foo ).<span style="color:#bd93f9">__</span>proto__ <span style="color:#ff79c6">===</span> Foo.prototype; <span style="color:#6272a4">// true -</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span style="color:#6272a4"></span>( <span style="color:#ff79c6">new</span> Foo ).prototype <span style="color:#ff79c6">===</span> <span style="color:#ff79c6">undefined</span>; <span style="color:#6272a4">// true -</span></code></pre></div>Bind specific arguments of a functionhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-es6-bind-trick/Fri, 08 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-es6-bind-trick/To bind specific (nth) arguments of a function, we can write a decorator instead of using Function.bind(): +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span>( <span style="color:#ff79c6">new</span> Foo ).__proto__ <span style="color:#ff79c6">===</span> Foo.prototype; <span style="color:#6272a4">// true +</span></span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span><span style="color:#6272a4"></span>( <span style="color:#ff79c6">new</span> Foo ).prototype <span style="color:#ff79c6">===</span> <span style="color:#ff79c6">undefined</span>; <span style="color:#6272a4">// true +</span></span></span></code></pre></div>Bind specific arguments of a functionhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-es6-bind-trick/Fri, 08 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-es6-bind-trick/To bind specific (nth) arguments of a function, we can write a decorator instead of using Function.bind(): 1function func(p1, p2, p3) { 2 console.log(p1, p2, p3); 3} 4// the binding starts after however many are passed in. 5function decorator(...bound_args) { 6 return function(...args) { 7 return func(...args, ...bound_args); 8 }; 9} 10 11// bind the last parameter 12let f = decorator(&#34;3&#34;); 13f(&#34;a&#34;, &#34;b&#34;); // a b 3 14 15// bind the last two parameter 16let f2 = decorator(&#34;2&#34;, &#34;3&#34;) 17f2(&#34;a&#34;); // a 2 3 Even if we want to bind just the nth argument, we can do as follows:Object.assign() with accessor descriptorhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-object-assign-with-accessor-descriptor/Fri, 08 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-object-assign-with-accessor-descriptor/<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Copying_accessors">MDN docs:</a></p> <blockquote> <p>The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties versus just copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.</p> </blockquote> <p>For example</p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 1</span><span style="color:#ff79c6">class</span> Cat { -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 2</span> constructor(name) { -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 3</span> <span style="color:#ff79c6">this</span>.<span style="color:#bd93f9">_</span>name <span style="color:#ff79c6">=</span> name; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 4</span> } -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 5</span> -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 6</span> get name() { -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 7</span> <span style="color:#ff79c6">return</span> <span style="color:#ff79c6">this</span>.<span style="color:#bd93f9">_</span>name; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 8</span> } -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 9</span> set name(value) { -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">10</span> <span style="color:#ff79c6">this</span>.<span style="color:#bd93f9">_</span>name <span style="color:#ff79c6">=</span> value; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">11</span> } -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">12</span>} -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">13</span> -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">14</span><span style="color:#8be9fd;font-style:italic">let</span> nyannko <span style="color:#ff79c6">=</span> <span style="color:#ff79c6">new</span> Cat(<span style="color:#f1fa8c">&#34;nyannko&#34;</span>); -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">15</span><span style="color:#8be9fd;font-style:italic">let</span> copy <span style="color:#ff79c6">=</span> <span style="color:#8be9fd;font-style:italic">Object</span>.assign({}, nyannko) -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">16</span> -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">17</span>console.log(nyannko.name) <span style="color:#6272a4">// nyannko -</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">18</span><span style="color:#6272a4"></span>console.log(copy.name) <span style="color:#6272a4">// undefined -</span></code></pre></div><p>The <code>name</code> property is lost.</p>VueのNavigation Guardshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Fri, 25 Jan 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Navigation guards are provided by vue-router. Three ways to hook: +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-js" data-lang="js"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 1</span><span><span style="color:#ff79c6">class</span> Cat { +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 2</span><span> constructor(name) { +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 3</span><span> <span style="color:#ff79c6">this</span>._name <span style="color:#ff79c6">=</span> name; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 4</span><span> } +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 5</span><span> +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 6</span><span> get name() { +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 7</span><span> <span style="color:#ff79c6">return</span> <span style="color:#ff79c6">this</span>._name; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 8</span><span> } +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 9</span><span> set name(value) { +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">10</span><span> <span style="color:#ff79c6">this</span>._name <span style="color:#ff79c6">=</span> value; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">11</span><span> } +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">12</span><span>} +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">13</span><span> +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">14</span><span><span style="color:#8be9fd;font-style:italic">let</span> nyannko <span style="color:#ff79c6">=</span> <span style="color:#ff79c6">new</span> Cat(<span style="color:#f1fa8c">&#34;nyannko&#34;</span>); +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">15</span><span><span style="color:#8be9fd;font-style:italic">let</span> copy <span style="color:#ff79c6">=</span> <span style="color:#8be9fd;font-style:italic">Object</span>.assign({}, nyannko) +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">16</span><span> +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">17</span><span>console.log(nyannko.name) <span style="color:#6272a4">// nyannko +</span></span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">18</span><span><span style="color:#6272a4"></span>console.log(copy.name) <span style="color:#6272a4">// undefined +</span></span></span></code></pre></div><p>The <code>name</code> property is lost.</p>VueのNavigation Guardshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Fri, 25 Jan 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Navigation guards are provided by vue-router. Three ways to hook: globally per-route in-component NOTE: -Params or query changes won&rsquo;t trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard. Make sure to always call the next function, otherwise the hook will never be resolved. Global 1const router = new VueRouter({ ... }) 2 3// Before Guards 4router.ES6についてhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-01-18-es6/Fri, 18 Jan 2019 16:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-01-18-es6/<h2 id="overview">Overview</h2> +Params or query changes won&rsquo;t trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard. Make sure to always call the next function, otherwise the hook will never be resolved. Global 1const router = new VueRouter({ ... }) 2 3// Before Guards 4router.beforeEach((to, from, next) =&gt; { 5 // .ES6についてhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-01-18-es6/Fri, 18 Jan 2019 16:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-01-18-es6/<h2 id="overview">Overview</h2> <p><a href="https://github.com/lukehoban/es6features#readme">https://github.com/lukehoban/es6features#readme</a></p> <p><a href="http://help.wtf/es6">http://help.wtf/es6</a></p> <p><a href="http://es6-features.org">http://es6-features.org</a></p> <h2 id="string">String</h2> <h3 id="stringx-is-deprecated-use-stringprototypex-instead">String.x is deprecated; use String.prototype.x instead.</h3> <p>非推奨の構文:</p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Javascript" data-lang="Javascript"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span style="color:#8be9fd;font-style:italic">var</span> num <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">15</span>; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span style="color:#8be9fd;font-style:italic">String</span>.replace(num, <span style="color:#f1fa8c">/5/</span>, <span style="color:#f1fa8c">&#39;2&#39;</span>); -</code></pre></div><p>標準の構文:</p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Javascript" data-lang="Javascript"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span style="color:#8be9fd;font-style:italic">var</span> num <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">15</span>; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span style="color:#8be9fd;font-style:italic">String</span>(num).replace(<span style="color:#f1fa8c">/5/</span>, <span style="color:#f1fa8c">&#39;2&#39;</span>); -</code></pre></div><h3 id="template-literal">Template literal</h3> +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-Javascript" data-lang="Javascript"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span><span style="color:#8be9fd;font-style:italic">var</span> num <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">15</span>; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span><span style="color:#8be9fd;font-style:italic">String</span>.replace(num, <span style="color:#f1fa8c">/5/</span>, <span style="color:#f1fa8c">&#39;2&#39;</span>); +</span></span></code></pre></div><p>標準の構文:</p> +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-Javascript" data-lang="Javascript"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span><span style="color:#8be9fd;font-style:italic">var</span> num <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">15</span>; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span><span style="color:#8be9fd;font-style:italic">String</span>(num).replace(<span style="color:#f1fa8c">/5/</span>, <span style="color:#f1fa8c">&#39;2&#39;</span>); +</span></span></code></pre></div><h3 id="template-literal">Template literal</h3> <p>Nesting templates:</p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Javascript" data-lang="Javascript"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span style="color:#ff79c6">const</span> classes <span style="color:#ff79c6">=</span> <span style="color:#f1fa8c">`header </span><span style="color:#f1fa8c">${</span> isLargeScreen() <span style="color:#ff79c6">?</span> <span style="color:#f1fa8c">&#39;&#39;</span> <span style="color:#ff79c6">:</span> <span style="color:#f1fa8c">`icon-</span><span style="color:#f1fa8c">${</span>item.isCollapsed <span style="color:#ff79c6">?</span> <span style="color:#f1fa8c">&#39;expander&#39;</span> <span style="color:#ff79c6">:</span> <span style="color:#f1fa8c">&#39;collapser&#39;</span><span style="color:#f1fa8c">}</span><span style="color:#f1fa8c">`</span> <span style="color:#f1fa8c">}</span><span style="color:#f1fa8c">`</span>; -</code></pre></div>java散列知识点总结https://www.takuzen.me/hugo-theme-cactus/posts/2017-02-18-hash/Sat, 18 Feb 2017 19:19:01 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2017-02-18-hash/java 的根类 Object 具有 hashcode 方法。当 equal 方法被重写时也应当重写 hashcode 方法。 +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-Javascript" data-lang="Javascript"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span><span style="color:#ff79c6">const</span> classes <span style="color:#ff79c6">=</span> <span style="color:#f1fa8c">`header </span><span style="color:#f1fa8c">${</span> isLargeScreen() <span style="color:#ff79c6">?</span> <span style="color:#f1fa8c">&#39;&#39;</span> <span style="color:#ff79c6">:</span> <span style="color:#f1fa8c">`icon-</span><span style="color:#f1fa8c">${</span>item.isCollapsed <span style="color:#ff79c6">?</span> <span style="color:#f1fa8c">&#39;expander&#39;</span> <span style="color:#ff79c6">:</span> <span style="color:#f1fa8c">&#39;collapser&#39;</span><span style="color:#f1fa8c">}</span><span style="color:#f1fa8c">`</span> <span style="color:#f1fa8c">}</span><span style="color:#f1fa8c">`</span>; +</span></span></code></pre></div>java散列知识点总结https://www.takuzen.me/hugo-theme-cactus/posts/2017-02-18-hash/Sat, 18 Feb 2017 19:19:01 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2017-02-18-hash/java 的根类 Object 具有 hashcode 方法。当 equal 方法被重写时也应当重写 hashcode 方法。 基本数据类型的散列码 byte short int char 类型的搜索键将会转换为 int。 float 类型的搜索键使用 Float.floatToIntBits(key) 作为散列码。 long 类型的搜索键会进行折叠操作,如下: 1iny hashCode = (int) (key ^ (key &gt;&gt; 32)); double 类型的搜索键会使用 Double.doubleToLongBits(key) 方法转换为 long 类型然后再进行折叠。 字符串类型的散列码 对于字符串一般使用多项式散列码进行计算, 这里放个公式的图 b的较好取值为31,33,37,39,41。在 java String 类中 b 取31。 -1public static int hash(String key, int tableSize) 2{ 3 int hashVal = 0; 4 5 for (int i = 0; i &lt; key.php的闭包特性https://www.takuzen.me/hugo-theme-cactus/posts/2017-01-11-php-lambada/Wed, 11 Jan 2017 18:39:17 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2017-01-11-php-lambada/闭包和匿名函数在PHP 5.3.0引入,并且PHP将两者视为相同的概念。闭包其实是伪装成函数的对象,它的实质其实是Closure实例。 +1public static int hash(String key, int tableSize) 2{ 3 int hashVal = 0; 4 5 for (int i = 0; i &lt; key.length(); i++) 6 hashVal = 37*hashVal + key.php的闭包特性https://www.takuzen.me/hugo-theme-cactus/posts/2017-01-11-php-lambada/Wed, 11 Jan 2017 18:39:17 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2017-01-11-php-lambada/闭包和匿名函数在PHP 5.3.0引入,并且PHP将两者视为相同的概念。闭包其实是伪装成函数的对象,它的实质其实是Closure实例。 创建闭包非常简单: 1$c = function($name) { 2 return sprintf(&#34;Hello World! Hello %s!&#34;, $name); 3}; 4 5echo $c(&#39;PHP&#39;); 使用use对闭包附加状态,多个参数使用,分隔: -1function callPerson($name) { 2 return function($about) use ($name) { 3 return sprintf(&#34;%s, %s&#34;, $name, $about); 4 } 5} 6 7$triver = callPerson(&#39;Triver&#39;); 8echo $triver(&#34;slow down, please!!&#34;); 9 附加的变量会被封装到闭包内,即使返回的闭包队形已经跳出了callPerson()的作用域也仍然会记住$name的值。 +1function callPerson($name) { 2 return function($about) use ($name) { 3 return sprintf(&#34;%s, %s&#34;, $name, $about); 4 } 5} 6 7$triver = callPerson(&#39;Triver&#39;); 8echo $triver(&#34;slow down, please!!&#34;); 附加的变量会被封装到闭包内,即使返回的闭包队形已经跳出了callPerson()的作用域也仍然会记住$name的值。 闭包有一个有趣的bindTo()方法,可以将闭包的内部状态绑定到其他对象上,第二个参数指定了绑定闭包的对象所属的类,从而实现在闭包中访问绑定对象的私有方法和属性。 1class Bind { 2 protected $name = &#39;no name&#39;; 3 public $change; 4 5 public function addAction($action) { 6 $this-&gt;change = $action-&gt;bindTo($this, __CLASS__); 7 } 8} 9 10$bind = new Bind(); 11$bind-&gt;addAction(function() { 12 $this-&gt;name = &#34;php&#34;; 13 return $this-&gt;name; 14 }); 15 16$change = $bind-&gt;change; 17echo $change(); 使用这个特性可以方便的为类添加方法并绑定:ruby学习笔记https://www.takuzen.me/hugo-theme-cactus/posts/2016-12-08-ruby-notes/Thu, 08 Dec 2016 22:54:49 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2016-12-08-ruby-notes/regular expressions =~是用于正则表达式的匹配操作符。返回匹配到的字符串位置或nil。 -1&#34;abcdef&#34; =~ /d/ # return 3 2&#34;aaaaaa&#34; =~ /d/ # return nil !和? The exclamation point (!, sometimes pronounced aloud as &ldquo;bang!&quot;) indicates something potentially destructive, that is to say, something that can change the value of what it touches. -ruby&gt; s1 = &quot;forth&quot; &quot;forth&quot; ruby&gt; s1.chop! # This changes s1. &quot;fort&quot; ruby&gt; s2 = s1.chop # This puts a changed copy in s2, &quot;for&quot; ruby&gt; s1 # .netfilter/iptables 笔记https://www.takuzen.me/hugo-theme-cactus/posts/2016-11-29-iptables-usage/Tue, 29 Nov 2016 21:08:52 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2016-11-29-iptables-usage/netfilter 与 iptables netfilter是linux默认的防火墙,在2.4之后的版本正式进入内核。netfilter 使用四个表(Table)来存放控制信息包过滤处理的规则集。每张表由链(Chain)组成,每条链又包含了多条规则(rule)。 +1&#34;abcdef&#34; =~ /d/ # return 3 2&#34;aaaaaa&#34; =~ /d/ # return nil !和? The exclamation point (!, sometimes pronounced aloud as &ldquo;bang!&rdquo;) indicates something potentially destructive, that is to say, something that can change the value of what it touches. +ruby&gt; s1 = &#34;forth&#34; &#34;forth&#34; ruby&gt; s1.chop! # This changes s1. &#34;fort&#34; ruby&gt; s2 = s1.chop # This puts a changed copy in s2, &#34;for&#34; ruby&gt; s1 # .netfilter/iptables 笔记https://www.takuzen.me/hugo-theme-cactus/posts/2016-11-29-iptables-usage/Tue, 29 Nov 2016 21:08:52 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2016-11-29-iptables-usage/netfilter 与 iptables netfilter是linux默认的防火墙,在2.4之后的版本正式进入内核。netfilter 使用四个表(Table)来存放控制信息包过滤处理的规则集。每张表由链(Chain)组成,每条链又包含了多条规则(rule)。 iptables是用来编辑操作这些表的一个工具。iptables包中也包含了针对IPv6的工具ip6tables。 四个表及其包含的链: filter INPUT FORWARD OUTPUT nat PREROUTING POSTROUTING OUTPUT mangle PREROUTING INPUT FORWARD OUTPUT POSTROUTING raw PREROUTING OUTPUT filter机制 filter是netfilter中最重要的机制,其任务是执行数据包的过滤操作。具有三种内建链: @@ -113,7 +113,7 @@ Look how they shine for you 看它们为你绽放着 闪烁不息 And everything you do 而你的一颦一举 -Yeah' they were all Yellow +Yeah&rsquo; they were all Yellow 却满含胆怯和羞意 I came along 我追随着你的气息 diff --git a/posts/page/1/index.html b/posts/page/1/index.html index ea56d4c0..1b7b5525 100644 --- a/posts/page/1/index.html +++ b/posts/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/posts/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/posts/ + \ No newline at end of file diff --git a/posts/page/2/index.html b/posts/page/2/index.html index 66e6ac92..ad2f2d97 100644 --- a/posts/page/2/index.html +++ b/posts/page/2/index.html @@ -1,162 +1,4 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
\ No newline at end of file diff --git a/posts/page/3/index.html b/posts/page/3/index.html index d75d5746..e48dad39 100644 --- a/posts/page/3/index.html +++ b/posts/page/3/index.html @@ -1,94 +1,3 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- - -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/tags/algorithms/index.html b/tags/algorithms/index.html index 39ed712f..5c235885 100644 --- a/tags/algorithms/index.html +++ b/tags/algorithms/index.html @@ -1,100 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/tags/algorithms/index.xml b/tags/algorithms/index.xml index 5164ef2d..097b5eea 100644 --- a/tags/algorithms/index.xml +++ b/tags/algorithms/index.xml @@ -1,8 +1,8 @@ Algorithms on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/algorithms/Recent content in Algorithms on Cactus theme exampleHugo -- gohugo.ioen-usYouSat, 06 Jun 2020 09:00:00 +0000Changes to String in java (from 1.7.0_06)https://www.takuzen.me/hugo-theme-cactus/posts/2020-06-06-changes-in-java-string/Sat, 06 Jun 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-06-06-changes-in-java-string/Before 1.7.0_06, String has 4 non static field: char[] value int[] offset int count int hash Subing.substring create a String by sharing the original String&rsquo;s internal char[] value and setting offset. This saves memory and makes String.substring run in a constant time($O(1)$). Meanwhile, this feature may cause memory leak1. http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/8deef18bb749/src/share/classes/java/lang/String.java -1public final class String 2 implements java.io.Serializable, Comparable&lt;String&gt;, CharSequence 3{ 4 /** The value is used for character storage.Algorithms - Graphshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-05-01-algorithms-graphs/Fri, 01 May 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-05-01-algorithms-graphs/Undirected Graphs Some problems Path Shortest path Cycle Ehler tour: A cycle that uses each edge excatly once. Hamilton tour: A cycle that uses each vertex exactly once classical NP-complete problem. Connectivity MST: Biconnectivity: A vertex whose removal disconnects the graph Planarity Graph isomorphism: Are two graphs identical? No one knows so far. A lonstanding open problem Representations Real-world graphs tend to be sparse (huge number of vertices, small average vertex degree).java散列知识点总结https://www.takuzen.me/hugo-theme-cactus/posts/2017-02-18-hash/Sat, 18 Feb 2017 19:19:01 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2017-02-18-hash/java 的根类 Object 具有 hashcode 方法。当 equal 方法被重写时也应当重写 hashcode 方法。 +1public final class String 2 implements java.io.Serializable, Comparable&lt;String&gt;, CharSequence 3{ 4 /** The value is used for character storage. */ 5 private final char value[]; 6 7 /** The offset is the first index of the storage that is used.Algorithms - Graphshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-05-01-algorithms-graphs/Fri, 01 May 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-05-01-algorithms-graphs/Undirected Graphs Some problems Path Shortest path Cycle Ehler tour: A cycle that uses each edge excatly once. Hamilton tour: A cycle that uses each vertex exactly once classical NP-complete problem. Connectivity MST: Biconnectivity: A vertex whose removal disconnects the graph Planarity Graph isomorphism: Are two graphs identical? No one knows so far. A lonstanding open problem Representations Real-world graphs tend to be sparse (huge number of vertices, small average vertex degree).java散列知识点总结https://www.takuzen.me/hugo-theme-cactus/posts/2017-02-18-hash/Sat, 18 Feb 2017 19:19:01 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2017-02-18-hash/java 的根类 Object 具有 hashcode 方法。当 equal 方法被重写时也应当重写 hashcode 方法。 基本数据类型的散列码 byte short int char 类型的搜索键将会转换为 int。 float 类型的搜索键使用 Float.floatToIntBits(key) 作为散列码。 long 类型的搜索键会进行折叠操作,如下: 1iny hashCode = (int) (key ^ (key &gt;&gt; 32)); double 类型的搜索键会使用 Double.doubleToLongBits(key) 方法转换为 long 类型然后再进行折叠。 字符串类型的散列码 对于字符串一般使用多项式散列码进行计算, 这里放个公式的图 b的较好取值为31,33,37,39,41。在 java String 类中 b 取31。 -1public static int hash(String key, int tableSize) 2{ 3 int hashVal = 0; 4 5 for (int i = 0; i &lt; key. \ No newline at end of file +1public static int hash(String key, int tableSize) 2{ 3 int hashVal = 0; 4 5 for (int i = 0; i &lt; key.length(); i++) 6 hashVal = 37*hashVal + key.
\ No newline at end of file diff --git a/tags/algorithms/page/1/index.html b/tags/algorithms/page/1/index.html index 634b8ee3..c2ed477c 100644 --- a/tags/algorithms/page/1/index.html +++ b/tags/algorithms/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/tags/algorithms/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/tags/algorithms/ + \ No newline at end of file diff --git a/tags/index.html b/tags/index.html index e9e23f6d..7aa3d00a 100644 --- a/tags/index.html +++ b/tags/index.html @@ -1,89 +1,12 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
\ No newline at end of file diff --git a/tags/index.xml b/tags/index.xml index ea81057e..9e8a0c5c 100644 --- a/tags/index.xml +++ b/tags/index.xml @@ -1 +1 @@ -Tags on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/Recent content in Tags on Cactus theme exampleHugo -- gohugo.ioen-usYouSun, 27 Jun 2021 09:00:00 +0000testhttps://www.takuzen.me/hugo-theme-cactus/tags/test/Sun, 27 Jun 2021 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/test/Algorithmshttps://www.takuzen.me/hugo-theme-cactus/tags/algorithms/Sat, 06 Jun 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/algorithms/programming languagehttps://www.takuzen.me/hugo-theme-cactus/tags/programming-language/Wed, 29 Apr 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/programming-language/rackethttps://www.takuzen.me/hugo-theme-cactus/tags/racket/Sat, 29 Feb 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/racket/SMLhttps://www.takuzen.me/hugo-theme-cactus/tags/sml/Mon, 30 Dec 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/sml/RPAhttps://www.takuzen.me/hugo-theme-cactus/tags/rpa/Sat, 23 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/rpa/JavaScripthttps://www.takuzen.me/hugo-theme-cactus/tags/javascript/Sun, 10 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/javascript/Vue.jshttps://www.takuzen.me/hugo-theme-cactus/tags/vue.js/Fri, 25 Jan 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/vue.js/phphttps://www.takuzen.me/hugo-theme-cactus/tags/php/Wed, 11 Jan 2017 18:39:17 +0000https://www.takuzen.me/hugo-theme-cactus/tags/php/rubyhttps://www.takuzen.me/hugo-theme-cactus/tags/ruby/Thu, 08 Dec 2016 22:54:49 +0000https://www.takuzen.me/hugo-theme-cactus/tags/ruby/Linuxhttps://www.takuzen.me/hugo-theme-cactus/tags/linux/Tue, 29 Nov 2016 21:08:52 +0000https://www.takuzen.me/hugo-theme-cactus/tags/linux/ \ No newline at end of file +Tags on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/Recent content in Tags on Cactus theme exampleHugo -- gohugo.ioen-usYouSun, 27 Jun 2021 09:00:00 +0000Testhttps://www.takuzen.me/hugo-theme-cactus/tags/test/Sun, 27 Jun 2021 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/test/Algorithmshttps://www.takuzen.me/hugo-theme-cactus/tags/algorithms/Sat, 06 Jun 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/algorithms/Programming Languagehttps://www.takuzen.me/hugo-theme-cactus/tags/programming-language/Wed, 29 Apr 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/programming-language/Rackethttps://www.takuzen.me/hugo-theme-cactus/tags/racket/Sat, 29 Feb 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/racket/SMLhttps://www.takuzen.me/hugo-theme-cactus/tags/sml/Mon, 30 Dec 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/sml/RPAhttps://www.takuzen.me/hugo-theme-cactus/tags/rpa/Sat, 23 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/rpa/JavaScripthttps://www.takuzen.me/hugo-theme-cactus/tags/javascript/Sun, 10 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/javascript/Vue.jshttps://www.takuzen.me/hugo-theme-cactus/tags/vue.js/Fri, 25 Jan 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/tags/vue.js/Phphttps://www.takuzen.me/hugo-theme-cactus/tags/php/Wed, 11 Jan 2017 18:39:17 +0000https://www.takuzen.me/hugo-theme-cactus/tags/php/Rubyhttps://www.takuzen.me/hugo-theme-cactus/tags/ruby/Thu, 08 Dec 2016 22:54:49 +0000https://www.takuzen.me/hugo-theme-cactus/tags/ruby/Linuxhttps://www.takuzen.me/hugo-theme-cactus/tags/linux/Tue, 29 Nov 2016 21:08:52 +0000https://www.takuzen.me/hugo-theme-cactus/tags/linux/ \ No newline at end of file diff --git a/tags/javascript/index.html b/tags/javascript/index.html index 4d0bb71c..eb094364 100644 --- a/tags/javascript/index.html +++ b/tags/javascript/index.html @@ -1,131 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/tags/javascript/index.xml b/tags/javascript/index.xml index 8f0df03d..4a033a2e 100644 --- a/tags/javascript/index.xml +++ b/tags/javascript/index.xml @@ -1,6 +1,6 @@ JavaScript on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/javascript/Recent content in JavaScript on Cactus theme exampleHugo -- gohugo.ioen-usYouSun, 10 Nov 2019 09:00:00 +0000JavaScript URI エンコーディングhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-11-10-encodeuricomponent/Sun, 10 Nov 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-11-10-encodeuricomponent/まとめ encodeURI()とencodeURIComponent()はRFC 2396準拠である。 encodeURI() は完全な URI を表すのに必要な文字 (Reserved Characters) はエンコードしません。 また、予約されていないが &ldquo;そのまま&rdquo; URI に使用できる(Unreserved Marks) 文字をエンコードしません。 encodeURIComponent() は &ldquo;Unreserved Marks&rdquo; 文字をエンコードしません。 1var set1 = &#34;;,/?:@&amp;=+$#&#34;; // Reserved Characters 2var set2 = &#34;-_.!~*&#39;()&#34;; // Unreserved Marks 3 4console.log(encodeURI(set1)); // ;,/?:@&amp;=+$ 5console.log(encodeURI(set2)); // -_.!~*&#39;() 6 7console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24 8console.log(encodeURIComponent(set2)); // -_.!~*&#39;() rfc2396 appendix-A https://tools.ietf.org/html/rfc2396#appendix-A -URI-reference = [ absoluteURI | relativeURI ] [ &quot;#&quot; fragment ] absoluteURI = scheme &quot;:&quot; ( hier_part | opaque_part ) relativeURI = ( net_path | abs_path | rel_path ) [ &quot;?JavaScript Comparison operation at a glancehttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-28-javascript-comparison/Thu, 28 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-28-javascript-comparison/When given a scenario like: +URI-reference = [ absoluteURI | relativeURI ] [ &#34;#&#34; fragment ] absoluteURI = scheme &#34;:&#34; ( hier_part | opaque_part ) relativeURI = ( net_path | abs_path | rel_path ) [ &#34;?JavaScript Comparison operation at a glancehttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-28-javascript-comparison/Thu, 28 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-28-javascript-comparison/When given a scenario like: 1console.log(null &gt; -1) //true It produces true, which makes me think null is treated as 0. But when I run: 1console.log(null == 0) // false 2console.log(null &gt; 0) // false 3console.log(null &lt; 0) // false They all output false! I googled a lot and finally found answers in Ecma-262 Specification. @@ -12,47 +12,47 @@ The comparison x == y, where x and y are values, produces true or false. Such a <p>The &ldquo;cool kids&rdquo; in JavaScript would generally pronounce <code>__proto__</code> as &ldquo;<strong>dunder proto</strong>&rdquo;.</p> </blockquote> <p><a href="https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript">https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript</a></p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span>( <span style="color:#ff79c6">new</span> Foo ).<span style="color:#bd93f9">__</span>proto__ <span style="color:#ff79c6">===</span> Foo.prototype; <span style="color:#6272a4">// true -</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span style="color:#6272a4"></span>( <span style="color:#ff79c6">new</span> Foo ).prototype <span style="color:#ff79c6">===</span> <span style="color:#ff79c6">undefined</span>; <span style="color:#6272a4">// true -</span></code></pre></div>Bind specific arguments of a functionhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-es6-bind-trick/Fri, 08 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-es6-bind-trick/To bind specific (nth) arguments of a function, we can write a decorator instead of using Function.bind(): +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span>( <span style="color:#ff79c6">new</span> Foo ).__proto__ <span style="color:#ff79c6">===</span> Foo.prototype; <span style="color:#6272a4">// true +</span></span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span><span style="color:#6272a4"></span>( <span style="color:#ff79c6">new</span> Foo ).prototype <span style="color:#ff79c6">===</span> <span style="color:#ff79c6">undefined</span>; <span style="color:#6272a4">// true +</span></span></span></code></pre></div>Bind specific arguments of a functionhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-es6-bind-trick/Fri, 08 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-es6-bind-trick/To bind specific (nth) arguments of a function, we can write a decorator instead of using Function.bind(): 1function func(p1, p2, p3) { 2 console.log(p1, p2, p3); 3} 4// the binding starts after however many are passed in. 5function decorator(...bound_args) { 6 return function(...args) { 7 return func(...args, ...bound_args); 8 }; 9} 10 11// bind the last parameter 12let f = decorator(&#34;3&#34;); 13f(&#34;a&#34;, &#34;b&#34;); // a b 3 14 15// bind the last two parameter 16let f2 = decorator(&#34;2&#34;, &#34;3&#34;) 17f2(&#34;a&#34;); // a 2 3 Even if we want to bind just the nth argument, we can do as follows:Object.assign() with accessor descriptorhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-object-assign-with-accessor-descriptor/Fri, 08 Mar 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-03-08-object-assign-with-accessor-descriptor/<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Copying_accessors">MDN docs:</a></p> <blockquote> <p>The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties versus just copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.</p> </blockquote> <p>For example</p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 1</span><span style="color:#ff79c6">class</span> Cat { -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 2</span> constructor(name) { -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 3</span> <span style="color:#ff79c6">this</span>.<span style="color:#bd93f9">_</span>name <span style="color:#ff79c6">=</span> name; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 4</span> } -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 5</span> -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 6</span> get name() { -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 7</span> <span style="color:#ff79c6">return</span> <span style="color:#ff79c6">this</span>.<span style="color:#bd93f9">_</span>name; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 8</span> } -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 9</span> set name(value) { -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">10</span> <span style="color:#ff79c6">this</span>.<span style="color:#bd93f9">_</span>name <span style="color:#ff79c6">=</span> value; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">11</span> } -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">12</span>} -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">13</span> -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">14</span><span style="color:#8be9fd;font-style:italic">let</span> nyannko <span style="color:#ff79c6">=</span> <span style="color:#ff79c6">new</span> Cat(<span style="color:#f1fa8c">&#34;nyannko&#34;</span>); -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">15</span><span style="color:#8be9fd;font-style:italic">let</span> copy <span style="color:#ff79c6">=</span> <span style="color:#8be9fd;font-style:italic">Object</span>.assign({}, nyannko) -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">16</span> -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">17</span>console.log(nyannko.name) <span style="color:#6272a4">// nyannko -</span><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">18</span><span style="color:#6272a4"></span>console.log(copy.name) <span style="color:#6272a4">// undefined -</span></code></pre></div><p>The <code>name</code> property is lost.</p>VueのNavigation Guardshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Fri, 25 Jan 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Navigation guards are provided by vue-router. Three ways to hook: +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-js" data-lang="js"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 1</span><span><span style="color:#ff79c6">class</span> Cat { +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 2</span><span> constructor(name) { +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 3</span><span> <span style="color:#ff79c6">this</span>._name <span style="color:#ff79c6">=</span> name; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 4</span><span> } +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 5</span><span> +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 6</span><span> get name() { +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 7</span><span> <span style="color:#ff79c6">return</span> <span style="color:#ff79c6">this</span>._name; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 8</span><span> } +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f"> 9</span><span> set name(value) { +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">10</span><span> <span style="color:#ff79c6">this</span>._name <span style="color:#ff79c6">=</span> value; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">11</span><span> } +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">12</span><span>} +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">13</span><span> +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">14</span><span><span style="color:#8be9fd;font-style:italic">let</span> nyannko <span style="color:#ff79c6">=</span> <span style="color:#ff79c6">new</span> Cat(<span style="color:#f1fa8c">&#34;nyannko&#34;</span>); +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">15</span><span><span style="color:#8be9fd;font-style:italic">let</span> copy <span style="color:#ff79c6">=</span> <span style="color:#8be9fd;font-style:italic">Object</span>.assign({}, nyannko) +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">16</span><span> +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">17</span><span>console.log(nyannko.name) <span style="color:#6272a4">// nyannko +</span></span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">18</span><span><span style="color:#6272a4"></span>console.log(copy.name) <span style="color:#6272a4">// undefined +</span></span></span></code></pre></div><p>The <code>name</code> property is lost.</p>VueのNavigation Guardshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Fri, 25 Jan 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Navigation guards are provided by vue-router. Three ways to hook: globally per-route in-component NOTE: -Params or query changes won&rsquo;t trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard. Make sure to always call the next function, otherwise the hook will never be resolved. Global 1const router = new VueRouter({ ... }) 2 3// Before Guards 4router.ES6についてhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-01-18-es6/Fri, 18 Jan 2019 16:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-01-18-es6/<h2 id="overview">Overview</h2> +Params or query changes won&rsquo;t trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard. Make sure to always call the next function, otherwise the hook will never be resolved. Global 1const router = new VueRouter({ ... }) 2 3// Before Guards 4router.beforeEach((to, from, next) =&gt; { 5 // .ES6についてhttps://www.takuzen.me/hugo-theme-cactus/posts/2019-01-18-es6/Fri, 18 Jan 2019 16:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-01-18-es6/<h2 id="overview">Overview</h2> <p><a href="https://github.com/lukehoban/es6features#readme">https://github.com/lukehoban/es6features#readme</a></p> <p><a href="http://help.wtf/es6">http://help.wtf/es6</a></p> <p><a href="http://es6-features.org">http://es6-features.org</a></p> <h2 id="string">String</h2> <h3 id="stringx-is-deprecated-use-stringprototypex-instead">String.x is deprecated; use String.prototype.x instead.</h3> <p>非推奨の構文:</p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Javascript" data-lang="Javascript"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span style="color:#8be9fd;font-style:italic">var</span> num <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">15</span>; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span style="color:#8be9fd;font-style:italic">String</span>.replace(num, <span style="color:#f1fa8c">/5/</span>, <span style="color:#f1fa8c">&#39;2&#39;</span>); -</code></pre></div><p>標準の構文:</p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Javascript" data-lang="Javascript"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span style="color:#8be9fd;font-style:italic">var</span> num <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">15</span>; -<span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span style="color:#8be9fd;font-style:italic">String</span>(num).replace(<span style="color:#f1fa8c">/5/</span>, <span style="color:#f1fa8c">&#39;2&#39;</span>); -</code></pre></div><h3 id="template-literal">Template literal</h3> +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-Javascript" data-lang="Javascript"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span><span style="color:#8be9fd;font-style:italic">var</span> num <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">15</span>; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span><span style="color:#8be9fd;font-style:italic">String</span>.replace(num, <span style="color:#f1fa8c">/5/</span>, <span style="color:#f1fa8c">&#39;2&#39;</span>); +</span></span></code></pre></div><p>標準の構文:</p> +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-Javascript" data-lang="Javascript"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span><span style="color:#8be9fd;font-style:italic">var</span> num <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">15</span>; +</span></span><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">2</span><span><span style="color:#8be9fd;font-style:italic">String</span>(num).replace(<span style="color:#f1fa8c">/5/</span>, <span style="color:#f1fa8c">&#39;2&#39;</span>); +</span></span></code></pre></div><h3 id="template-literal">Template literal</h3> <p>Nesting templates:</p> -<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-Javascript" data-lang="Javascript"><span style="margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span style="color:#ff79c6">const</span> classes <span style="color:#ff79c6">=</span> <span style="color:#f1fa8c">`header </span><span style="color:#f1fa8c">${</span> isLargeScreen() <span style="color:#ff79c6">?</span> <span style="color:#f1fa8c">&#39;&#39;</span> <span style="color:#ff79c6">:</span> <span style="color:#f1fa8c">`icon-</span><span style="color:#f1fa8c">${</span>item.isCollapsed <span style="color:#ff79c6">?</span> <span style="color:#f1fa8c">&#39;expander&#39;</span> <span style="color:#ff79c6">:</span> <span style="color:#f1fa8c">&#39;collapser&#39;</span><span style="color:#f1fa8c">}</span><span style="color:#f1fa8c">`</span> <span style="color:#f1fa8c">}</span><span style="color:#f1fa8c">`</span>; -</code></pre></div> \ No newline at end of file +<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-Javascript" data-lang="Javascript"><span style="display:flex;"><span style="white-space:pre;-webkit-user-select:none;user-select:none;margin-right:0.4em;padding:0 0.4em 0 0.4em;color:#7f7f7f">1</span><span><span style="color:#ff79c6">const</span> classes <span style="color:#ff79c6">=</span> <span style="color:#f1fa8c">`header </span><span style="color:#f1fa8c">${</span> isLargeScreen() <span style="color:#ff79c6">?</span> <span style="color:#f1fa8c">&#39;&#39;</span> <span style="color:#ff79c6">:</span> <span style="color:#f1fa8c">`icon-</span><span style="color:#f1fa8c">${</span>item.isCollapsed <span style="color:#ff79c6">?</span> <span style="color:#f1fa8c">&#39;expander&#39;</span> <span style="color:#ff79c6">:</span> <span style="color:#f1fa8c">&#39;collapser&#39;</span><span style="color:#f1fa8c">}</span><span style="color:#f1fa8c">`</span> <span style="color:#f1fa8c">}</span><span style="color:#f1fa8c">`</span>; +</span></span></code></pre></div>
\ No newline at end of file diff --git a/tags/javascript/page/1/index.html b/tags/javascript/page/1/index.html index 74383c8a..4a6e3fde 100644 --- a/tags/javascript/page/1/index.html +++ b/tags/javascript/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/tags/javascript/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/tags/javascript/ + \ No newline at end of file diff --git a/tags/linux/index.html b/tags/linux/index.html index fbbc3efc..ad3bcd0e 100644 --- a/tags/linux/index.html +++ b/tags/linux/index.html @@ -1,83 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/tags/linux/page/1/index.html b/tags/linux/page/1/index.html index 70a07b1f..5604479d 100644 --- a/tags/linux/page/1/index.html +++ b/tags/linux/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/tags/linux/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/tags/linux/ + \ No newline at end of file diff --git a/tags/php/index.html b/tags/php/index.html index 516b151c..fe82bebe 100644 --- a/tags/php/index.html +++ b/tags/php/index.html @@ -1,92 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/tags/php/index.xml b/tags/php/index.xml index 04cfc784..81d2a1d8 100644 --- a/tags/php/index.xml +++ b/tags/php/index.xml @@ -1,7 +1,7 @@ -php on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/php/Recent content in php on Cactus theme exampleHugo -- gohugo.ioen-usYouWed, 11 Jan 2017 18:39:17 +0000php的闭包特性https://www.takuzen.me/hugo-theme-cactus/posts/2017-01-11-php-lambada/Wed, 11 Jan 2017 18:39:17 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2017-01-11-php-lambada/闭包和匿名函数在PHP 5.3.0引入,并且PHP将两者视为相同的概念。闭包其实是伪装成函数的对象,它的实质其实是Closure实例。 +Php on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/php/Recent content in Php on Cactus theme exampleHugo -- gohugo.ioen-usYouWed, 11 Jan 2017 18:39:17 +0000php的闭包特性https://www.takuzen.me/hugo-theme-cactus/posts/2017-01-11-php-lambada/Wed, 11 Jan 2017 18:39:17 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2017-01-11-php-lambada/闭包和匿名函数在PHP 5.3.0引入,并且PHP将两者视为相同的概念。闭包其实是伪装成函数的对象,它的实质其实是Closure实例。 创建闭包非常简单: 1$c = function($name) { 2 return sprintf(&#34;Hello World! Hello %s!&#34;, $name); 3}; 4 5echo $c(&#39;PHP&#39;); 使用use对闭包附加状态,多个参数使用,分隔: -1function callPerson($name) { 2 return function($about) use ($name) { 3 return sprintf(&#34;%s, %s&#34;, $name, $about); 4 } 5} 6 7$triver = callPerson(&#39;Triver&#39;); 8echo $triver(&#34;slow down, please!!&#34;); 9 附加的变量会被封装到闭包内,即使返回的闭包队形已经跳出了callPerson()的作用域也仍然会记住$name的值。 +1function callPerson($name) { 2 return function($about) use ($name) { 3 return sprintf(&#34;%s, %s&#34;, $name, $about); 4 } 5} 6 7$triver = callPerson(&#39;Triver&#39;); 8echo $triver(&#34;slow down, please!!&#34;); 附加的变量会被封装到闭包内,即使返回的闭包队形已经跳出了callPerson()的作用域也仍然会记住$name的值。 闭包有一个有趣的bindTo()方法,可以将闭包的内部状态绑定到其他对象上,第二个参数指定了绑定闭包的对象所属的类,从而实现在闭包中访问绑定对象的私有方法和属性。 1class Bind { 2 protected $name = &#39;no name&#39;; 3 public $change; 4 5 public function addAction($action) { 6 $this-&gt;change = $action-&gt;bindTo($this, __CLASS__); 7 } 8} 9 10$bind = new Bind(); 11$bind-&gt;addAction(function() { 12 $this-&gt;name = &#34;php&#34;; 13 return $this-&gt;name; 14 }); 15 16$change = $bind-&gt;change; 17echo $change(); 使用这个特性可以方便的为类添加方法并绑定:composer中的autoloadhttps://www.takuzen.me/hugo-theme-cactus/posts/2016-11-05-php-composer-autoload/Sat, 05 Nov 2016 02:42:06 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2016-11-05-php-composer-autoload/composer的autoload可以轻松的实现php的自动加载。在composer.json中添加autoload字段即可。当前支持 PSR-0 PSR-4 classmap解析和files包含。官方推荐PSR-4标准(添加类时不需要重新生成加载器)。 PSR-4 Under the psr-4 key you define a mapping from namespaces to paths, relative to the package root. When autoloading a class like Foo\\Bar\\Baz a namespace prefix Foo\\ pointing to a directory src/ means that the autoloader will look for a file named src/Bar/Baz.php and include it if present. Note that as opposed to the older PSR-0 style, the prefix (Foo\\) is not present in the file path. \ No newline at end of file diff --git a/tags/php/page/1/index.html b/tags/php/page/1/index.html index f8f37a43..2d79c72b 100644 --- a/tags/php/page/1/index.html +++ b/tags/php/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/tags/php/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/tags/php/ + \ No newline at end of file diff --git a/tags/programming-language/index.html b/tags/programming-language/index.html index f453aa6d..1b7e4ccf 100644 --- a/tags/programming-language/index.html +++ b/tags/programming-language/index.html @@ -1,83 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/tags/programming-language/index.xml b/tags/programming-language/index.xml index ad4b7411..f6e95b7d 100644 --- a/tags/programming-language/index.xml +++ b/tags/programming-language/index.xml @@ -1 +1 @@ -programming language on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/programming-language/Recent content in programming language on Cactus theme exampleHugo -- gohugo.ioen-usYouWed, 29 Apr 2020 09:00:00 +0000Programming Language - Subtypinghttps://www.takuzen.me/hugo-theme-cactus/posts/2020-04-29-subtyping/Wed, 29 Apr 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-04-29-subtyping/Some Good Subtyping Rules Width subtyping: A supertype can have a subset of fields with the same types, i.e., a subtype can have extra fields. Permutation subtypings: A supertype can have the same set of fields with the same types in a different order. Transitivity: if t1 is subtype of t2, and t2 is subtype of t3, then t1 is subtype of t3. Reflexivity: Every type is a subtype of itself. \ No newline at end of file +Programming Language on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/programming-language/Recent content in Programming Language on Cactus theme exampleHugo -- gohugo.ioen-usYouWed, 29 Apr 2020 09:00:00 +0000Programming Language - Subtypinghttps://www.takuzen.me/hugo-theme-cactus/posts/2020-04-29-subtyping/Wed, 29 Apr 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-04-29-subtyping/Some Good Subtyping Rules Width subtyping: A supertype can have a subset of fields with the same types, i.e., a subtype can have extra fields. Permutation subtypings: A supertype can have the same set of fields with the same types in a different order. Transitivity: if t1 is subtype of t2, and t2 is subtype of t3, then t1 is subtype of t3. Reflexivity: Every type is a subtype of itself. \ No newline at end of file diff --git a/tags/programming-language/page/1/index.html b/tags/programming-language/page/1/index.html index 2e3fd74a..8204f1f3 100644 --- a/tags/programming-language/page/1/index.html +++ b/tags/programming-language/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/tags/programming-language/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/tags/programming-language/ + \ No newline at end of file diff --git a/tags/racket/index.html b/tags/racket/index.html index 4b1c429f..52e9fd79 100644 --- a/tags/racket/index.html +++ b/tags/racket/index.html @@ -1,83 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/tags/racket/index.xml b/tags/racket/index.xml index 1386e762..e9952721 100644 --- a/tags/racket/index.xml +++ b/tags/racket/index.xml @@ -1 +1 @@ -racket on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/racket/Recent content in racket on Cactus theme exampleHugo -- gohugo.ioen-usYouSat, 29 Feb 2020 09:00:00 +0000Racket noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Sat, 29 Feb 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Basic 1#lang racket 2(provide (all-defined-out)) 3 4;this is a comment 5 6(define s &#34;hello&#34;) 7 8(define x 3) 9(define y (+ x 2)) 10 11(define cube1 12 (lambda (x) 13 (* x (* x x)))) 14 15(define cube2 16 (lambda (x) 17 (* x x x))) 18 19(define (cube3 x) 20 (* x x x)) 21 22(define (pow1 x y) 23 (if (=y 0) 24 1 25 (* x (pow1 x (- y 1))))) 26 27; currying 28(define pow2 29 (lambda (x) 30 (lambda (y) 31 (pow1 x y)))) 32 List Empty list: null () doesn&quot;t work for null but '() does build a list: (list e1 . \ No newline at end of file +Racket on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/racket/Recent content in Racket on Cactus theme exampleHugo -- gohugo.ioen-usYouSat, 29 Feb 2020 09:00:00 +0000Racket noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Sat, 29 Feb 2020 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2020-02-29-racket/Basic 1#lang racket 2(provide (all-defined-out)) 3 4;this is a comment 5 6(define s &#34;hello&#34;) 7 8(define x 3) 9(define y (+ x 2)) 10 11(define cube1 12 (lambda (x) 13 (* x (* x x)))) 14 15(define cube2 16 (lambda (x) 17 (* x x x))) 18 19(define (cube3 x) 20 (* x x x)) 21 22(define (pow1 x y) 23 (if (=y 0) 24 1 25 (* x (pow1 x (- y 1))))) 26 27; currying 28(define pow2 29 (lambda (x) 30 (lambda (y) 31 (pow1 x y)))) List Empty list: null () doesn&quot;t work for null but '() does build a list: (list e1 . \ No newline at end of file diff --git a/tags/racket/page/1/index.html b/tags/racket/page/1/index.html index 045d5121..4ffb7a75 100644 --- a/tags/racket/page/1/index.html +++ b/tags/racket/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/tags/racket/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/tags/racket/ + \ No newline at end of file diff --git a/tags/rpa/index.html b/tags/rpa/index.html index f22c867d..794c9af2 100644 --- a/tags/rpa/index.html +++ b/tags/rpa/index.html @@ -1,99 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/tags/rpa/index.xml b/tags/rpa/index.xml index 18216adf..eee4adc0 100644 --- a/tags/rpa/index.xml +++ b/tags/rpa/index.xml @@ -23,4 +23,4 @@ UI インタラクション: シーケンス 不要になったアプリケーションを終了させることで、常にクリーンな状態を維持しましょう。
uipath ノート(一)https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/Sun, 27 Oct 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-10-27-uipath/変数 Int32 String Boolean GenericValue 参照 UiPath Studio には GenericValue 変数の自動変換メカニズムがあり、式を正しく定義することで、目的の結果を得ることができます。式の最初の要素は、Studio から操作するガイドラインとして使用されることを考慮してください。例えば、2 つの GenericValue 変数を追加し、式の最初の変数が String として定義されてた場合、最初に代入された値を元に 2 つの値を結合し、文字列となります。 Integer として定義した場合の結果は、合計の値となります。 Array DataTime DataTable .Net 変数型を参照して探す方法 アクティビティ レイアウトダイアグラム シーエンス: より高度で複雑な自動化に向こう フローチャート: シンプルな自動化プロジェクトに適している ステートマシン Global Exception Handler (グローバル例外ハンドラー) 参照:https://docs.uipath.com/studio/lang-ja/docs/workflow-design -選択肢 条件分岐(If): シーケンス用条件分岐 フロー条件分岐(flow desicion): フローチャート用条件分岐 フロースイッチ (Flow Switch) 繰り返し 繰り返し(前判定)(While) 繰り返し(後判定)(Do While) 繰り返し(コレクションの各要素)(For Each) データ操作 CSVを読み込み(Read CSV) オプションにエンコーディングを指定できる(日本語データがある場合、&quot;SHIFT-JIS&quot;を指定する) 列名を含める(IncludeColumnNames)を指定できる 出力タイプ:System.
\ No newline at end of file +選択肢 条件分岐(If): シーケンス用条件分岐 フロー条件分岐(flow desicion): フローチャート用条件分岐 フロースイッチ (Flow Switch) 繰り返し 繰り返し(前判定)(While) 繰り返し(後判定)(Do While) 繰り返し(コレクションの各要素)(For Each) データ操作 CSVを読み込み(Read CSV) オプションにエンコーディングを指定できる(日本語データがある場合、&quot;SHIFT-JIS&quot;を指定する) 列名を含める(IncludeColumnNames)を指定できる 出力タイプ:System.Data.DataTable Microsoft Docs Selectメソッドで半角スペースを含む列名で指定する場合、半角スペースが特殊文字ではなく文字列として認識されるため、[]で列名を囲う Names.Select(&#34;[メンバー ステータス] = &#39;Yes&#39;&#34;) その他 メッセージボックス 代入(assign) 待機 (Delay) 入力ダイアログ(input dialog): フォルダーを選択(Select Folder) 一行を書き込み(Write Line): Debug用? アプリケーションを開く(Open Application) ブラウザを開く(Open Browser) ブラウザーにアタッチ(Attach Browser) 文字を入力(Type Into) ハイライト(Highlight) アンカーベース(Anchor Base) スクリーンショットをと撮る(Take Screenshot) 要素の有無を検出(Element Exists) 要素の消滅を待つ(Wait Element Vanish) レコーディング機能 [○]レコーディング可
\ No newline at end of file diff --git a/tags/rpa/page/1/index.html b/tags/rpa/page/1/index.html index 13df74b2..97357976 100644 --- a/tags/rpa/page/1/index.html +++ b/tags/rpa/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/tags/rpa/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/tags/rpa/ + \ No newline at end of file diff --git a/tags/ruby/index.html b/tags/ruby/index.html index ae87abf1..e5ae0d74 100644 --- a/tags/ruby/index.html +++ b/tags/ruby/index.html @@ -1,83 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/tags/ruby/index.xml b/tags/ruby/index.xml index c8a63c8c..dc527330 100644 --- a/tags/ruby/index.xml +++ b/tags/ruby/index.xml @@ -1,3 +1,3 @@ -ruby on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/ruby/Recent content in ruby on Cactus theme exampleHugo -- gohugo.ioen-usYouThu, 08 Dec 2016 22:54:49 +0000ruby学习笔记https://www.takuzen.me/hugo-theme-cactus/posts/2016-12-08-ruby-notes/Thu, 08 Dec 2016 22:54:49 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2016-12-08-ruby-notes/regular expressions =~是用于正则表达式的匹配操作符。返回匹配到的字符串位置或nil。 -1&#34;abcdef&#34; =~ /d/ # return 3 2&#34;aaaaaa&#34; =~ /d/ # return nil !和? The exclamation point (!, sometimes pronounced aloud as &ldquo;bang!&quot;) indicates something potentially destructive, that is to say, something that can change the value of what it touches. -ruby&gt; s1 = &quot;forth&quot; &quot;forth&quot; ruby&gt; s1.chop! # This changes s1. &quot;fort&quot; ruby&gt; s2 = s1.chop # This puts a changed copy in s2, &quot;for&quot; ruby&gt; s1 # . \ No newline at end of file +Ruby on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/ruby/Recent content in Ruby on Cactus theme exampleHugo -- gohugo.ioen-usYouThu, 08 Dec 2016 22:54:49 +0000ruby学习笔记https://www.takuzen.me/hugo-theme-cactus/posts/2016-12-08-ruby-notes/Thu, 08 Dec 2016 22:54:49 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2016-12-08-ruby-notes/regular expressions =~是用于正则表达式的匹配操作符。返回匹配到的字符串位置或nil。 +1&#34;abcdef&#34; =~ /d/ # return 3 2&#34;aaaaaa&#34; =~ /d/ # return nil !和? The exclamation point (!, sometimes pronounced aloud as &ldquo;bang!&rdquo;) indicates something potentially destructive, that is to say, something that can change the value of what it touches. +ruby&gt; s1 = &#34;forth&#34; &#34;forth&#34; ruby&gt; s1.chop! # This changes s1. &#34;fort&#34; ruby&gt; s2 = s1.chop # This puts a changed copy in s2, &#34;for&#34; ruby&gt; s1 # . \ No newline at end of file diff --git a/tags/ruby/page/1/index.html b/tags/ruby/page/1/index.html index 8b7a80d2..07d4e736 100644 --- a/tags/ruby/page/1/index.html +++ b/tags/ruby/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/tags/ruby/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/tags/ruby/ + \ No newline at end of file diff --git a/tags/sml/index.html b/tags/sml/index.html index 1492ea5c..c44f7519 100644 --- a/tags/sml/index.html +++ b/tags/sml/index.html @@ -1,83 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/tags/sml/index.xml b/tags/sml/index.xml index a1e83c70..71402073 100644 --- a/tags/sml/index.xml +++ b/tags/sml/index.xml @@ -1,2 +1,2 @@ SML on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/sml/Recent content in SML on Cactus theme exampleHugo -- gohugo.ioen-usYouMon, 30 Dec 2019 09:00:00 +0000Standard ML noteshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Mon, 30 Dec 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-12-30-standardml-notes/Basics Comments (* SML comment *) Variable bindings and Expressions val x = 34; (* static environment: x : int *) (* dynamic environment: x --&gt; 34 *) val y = x + 1; (* Use tilde character instead of minus to reprsent negation *) val z = ~1; (* Integer Division *) val w = y div x Strings: -(* `\n`のようなエスケープシーケンスが利用できる *) val x = &quot;hello\n&quot;; (* 文字列の連結には'^'を使う *) val y = &quot;hello &quot; ^ &quot;world&quot;; An ML program is a sequence of bindings. \ No newline at end of file +(* `\n`のようなエスケープシーケンスが利用できる *) val x = &#34;hello\n&#34;; (* 文字列の連結には&#39;^&#39;を使う *) val y = &#34;hello &#34; ^ &#34;world&#34;; An ML program is a sequence of bindings.
\ No newline at end of file diff --git a/tags/sml/page/1/index.html b/tags/sml/page/1/index.html index 7bb10fb9..8b783fc7 100644 --- a/tags/sml/page/1/index.html +++ b/tags/sml/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/tags/sml/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/tags/sml/ + \ No newline at end of file diff --git a/tags/test/index.html b/tags/test/index.html index 1c51af3a..acf7bd41 100644 --- a/tags/test/index.html +++ b/tags/test/index.html @@ -1,83 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/tags/test/index.xml b/tags/test/index.xml index 786976e7..15370c15 100644 --- a/tags/test/index.xml +++ b/tags/test/index.xml @@ -1,4 +1,4 @@ -test on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/test/Recent content in test on Cactus theme exampleHugo -- gohugo.ioen-usYouSun, 27 Jun 2021 09:00:00 +0000Code Block Testhttps://www.takuzen.me/hugo-theme-cactus/posts/code-block-test/Sun, 27 Jun 2021 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/code-block-test/String +Test on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/test/Recent content in Test on Cactus theme exampleHugo -- gohugo.ioen-usYouSun, 27 Jun 2021 09:00:00 +0000Code Block Testhttps://www.takuzen.me/hugo-theme-cactus/posts/code-block-test/Sun, 27 Jun 2021 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/code-block-test/String Using indents: text text text Fenced code block: text text &lt;tag&gt; Fenced code block with language (lineNumbersInTable = false): diff --git a/tags/test/page/1/index.html b/tags/test/page/1/index.html index b521fbd4..844d8b0c 100644 --- a/tags/test/page/1/index.html +++ b/tags/test/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/tags/test/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/tags/test/ + \ No newline at end of file diff --git a/tags/vue.js/index.html b/tags/vue.js/index.html index a2580cd5..8b5a83d8 100644 --- a/tags/vue.js/index.html +++ b/tags/vue.js/index.html @@ -1,83 +1,2 @@ - - - - - - - - - - -Cactus theme example - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - \ No newline at end of file +Cactus theme example + \ No newline at end of file diff --git a/tags/vue.js/index.xml b/tags/vue.js/index.xml index 550a1c1f..6f7f45d6 100644 --- a/tags/vue.js/index.xml +++ b/tags/vue.js/index.xml @@ -1,3 +1,3 @@ Vue.js on Cactus theme examplehttps://www.takuzen.me/hugo-theme-cactus/tags/vue.js/Recent content in Vue.js on Cactus theme exampleHugo -- gohugo.ioen-usYouFri, 25 Jan 2019 09:00:00 +0000VueのNavigation Guardshttps://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Fri, 25 Jan 2019 09:00:00 +0000https://www.takuzen.me/hugo-theme-cactus/posts/2019-01-19-vue-navigation-guards/Navigation guards are provided by vue-router. Three ways to hook: globally per-route in-component NOTE: -Params or query changes won&rsquo;t trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard. Make sure to always call the next function, otherwise the hook will never be resolved. Global 1const router = new VueRouter({ ... }) 2 3// Before Guards 4router. \ No newline at end of file +Params or query changes won&rsquo;t trigger enter/leave navigation guards. You can either watch the $route object to react to those changes, or use the beforeRouteUpdate in-component guard. Make sure to always call the next function, otherwise the hook will never be resolved. Global 1const router = new VueRouter({ ... }) 2 3// Before Guards 4router.beforeEach((to, from, next) =&gt; { 5 // .
\ No newline at end of file diff --git a/tags/vue.js/page/1/index.html b/tags/vue.js/page/1/index.html index 8cdbd66b..127d127e 100644 --- a/tags/vue.js/page/1/index.html +++ b/tags/vue.js/page/1/index.html @@ -1 +1,2 @@ -https://www.takuzen.me/hugo-theme-cactus/tags/vue.js/ \ No newline at end of file +https://www.takuzen.me/hugo-theme-cactus/tags/vue.js/ + \ No newline at end of file