Total Pageviews

2018/05/01

[閱讀筆記] Thinking, Fast and Slow (2/9)


  1. 若你在意是否被視為有信用與有智慧的人,你應該用比較簡單的語言,而非用複雜的語言。除了語言要簡單,也要試著讓訊息容易被記憶。容易被記憶,就容易被引用,人們就會認為這是真的
  2. 若你所接收到的訊息,與你的想法、邏輯、偏好產生某種連結,或是訊息來源是你信任或喜歡的,你就會感到 cognitive ease (認知放鬆)。但問題是,還有其他因素會造成你感到 cognitive ease (認知放鬆),如印刷的字體精美、看起來很舒服、訊息內容有押韻且容易被記憶等。你很難去追蹤讓你感到 cognitive ease (認知放鬆) 的來源,但是當你是 cognitive ease (認知放鬆) 的狀態,你就會傾向用 System 1 來做思考與判斷,懶惰的 System 2 也會採用 System 1 的建議
  3. 當你在做測驗時,若測驗題目的印刷字體不是很容易閱讀,你就會比較容易產生 cognitive stained (認知緊張),所以會動用 System 2 來思考、作答,也比較容易剃除 System 1 建議的直覺的答案。相反地,若是測驗題目印刷精美、容易閱讀,System 2 就比較容易接受 System 1 的建議,採取直覺的答案
  4. Switzerland 有針對投資人與公司名稱做一份研究,投資人相信比較容易發音的公司名稱會擁有較好的投報率 (如 Emmi, Comet, Swissfirst 等),一些較不好發音的公司就不受投資人青睞 (如 Geberit, Ypsomed 等)
  5. 單純曝光效應,又譯重複曝光效應(英文:Mere Exposure Effect)是一種心理學現象——人們會單純因為自己熟悉某個事物而產生好感。社會心理學中,這一效果也被稱為「熟悉定律」(familiarity principle)。這一現象所囊括的事物十分廣泛,例如文字,畫作,人像照片,多邊形及聲音等。在人際關係的研究中,一個人在自己的眼前出現的次數越多,自己越容易對其產生偏好和喜愛。
  6. The Mere Exposure Effect 發生的原因是,若不斷重複發生且無害,此類的刺激會變成一個安全的信號,安全的就是好的、正面的,人們就會對其產生偏好和喜愛
  7. 一個人的情緒會影響 System 1 的運作,當我們感覺的不舒服與不開心時,我們會與直覺失去聯繫。好心情、直覺、創造力等,相當仰賴 System 1
  8. 當一個人處於好心情的狀態,就會降低 System 2 的運作,人會變成更仰賴直覺,更有創造力,警戒心也會降低,更容易犯下邏輯錯。若你今天的心情非常愉悅,你要注意你的 System 2 可能會比平常的時候更脆弱,你需要格外謹慎
  9. 以Kahneman 和Tversky 為代表的學者認為,個體在進行決策時依據的不是決策方案各種可能結果的絕對效用值,而是以某個既存的心理中立基點(即參照點, reference point)為基準,把決策結果理解為實際損益量與心理參照點的偏離方向和程度。他們在“展望理論”(Prospect theory)中首次提出了“參照點”的概念,認為參照點潛在決定了被試將某特定結果編碼為收益或損失,進而影響其隨後的決策過程。有關參照點的理論可以解釋許多非理性決策行為和決策偏差
  10. 展望理論(prospect theory)引申的四個基本結論
    1. 確定效應:處於收益(gains)狀態時,多數人是風險厭惡者(risk aversion)。
    2. 反射效應:處於損失(losses)狀態時,多數人是風險喜好者(risk seeking)。
    3. 損失規避:多數人對損失比對收益敏感。
    4. 參照依賴:多數人對得失的判斷往往由參照點(reference points)決定。簡言之,人在面臨獲利時,不願冒風險;而在面臨損失時,人人都成了冒險家。而損失和獲利是相對於參照點而言的,改變評價事物時的參照點,就會改變對風險的態度。
  11. 一個重大事件的發生會導致一些後果,後果就需要一些原因來解釋他們。我們對於今天發生的事情擁有有限的資訊,System 1 卻可以根據這些有限的資訊拼湊起來,解釋為什麼發生這些事情,如同財經專家總是在收盤後在講解今天漲跌的原因,別忘了,那些財經專家跟你一樣只擁有有限的資訊而已
  12. System 1 沒有具備推理的能力;System 2 則可以學習統計性的思考,但是很少人受過必要的訓練
  13. 我們的腦袋像是一個強大的電腦,能將腦袋中各種想法建立起有相互關聯的網絡。啟動這個關聯機制是自動自發的,我們 (System 2) 也有能力控制在記憶中搜尋的能力,並能偵測所處的事件或環境該注意的地方
  14. The Wisdom of Crowds (群眾智慧) 一書中提到,一群被測試者目視一個糖果罐裏頭,預測有多少個一元硬幣。有些人會高估、有些人會低估,但是將其平均,卻相當準確。這個機制相當直接,所有人看著相同的糖果罐,每個人的判斷都有偏差,有的人偏差較多,有的人偏差較少,將其平均以後,偏差比率接近 0。但是群眾智慧的準確有其條件,「每個人都是獨立互不影響的」、「每個人的偏誤都是互無關聯的的」。若觀察者分享了偏誤,就無法達成預期的效用,如同在金融市場,整群的看好買進、看壞殺出,形成了一個又一個的泡沫與過去悲觀的深谷。但在某些條件下,群眾可以做出非常好的估算
  15. 在工作中,很長的時間都會花在開會上,但是與會人員很少能做好獨立判斷 (independent judgement),大部分的狀況都是被較早發言的人所影響,導致後面發言的人都是跟著前面的人的意見。比較好的做法是,在開會討論前,要求每個人將其想法與意見寫下來 (要獨立思考、不要跟其他成員討論),開會時就依據所收集的意見與想法進行討論,如此才能有效運用群組成員間不同的知識與意見,並且獲得更多的獨立評估的資訊
  16. 知道有限的資訊或證據就直接跳到結論,是非常典型的直覺式思考,這是 System 1 常做的事情。System 1 對於資訊或證據的質與量非常地不敏感,常常一下子就產生既定印象與直覺,然後就產生結論 (WYSIATI, What You See Is All There Is)
  17. 在心理學中,框架效應(Framing effect)是一種認知偏差,意義為面對同一個的問題,使用不同的描述但描述後的答案跟結果都是一樣的,人們會選擇乍聽之下較有利或順耳的描述作為方案。當以獲利的方式提問時,人們傾向於避免風險;當以損失的方式提問時,人們傾向於冒風險。如經過此手術後一個月的存活率達 90%,與經過此手術後一個月的死亡率達 10%,此二資訊是一樣的,但是感受完全不同,人們傾向只接受一種,不會再去反思
  18. 框架效應(Framing effect)能夠解釋,為何人們比較喜歡購買標明「85%瘦肉」的肉品,勝過標明「15%肥肉」的肉品;以及為什麼願意接受「有80%存活機率的手術」的病人數目,是願意接受「有20%死亡機率的手術」的病人數目的兩倍。
  19. 比較理性的人所感知的情緒並沒有比較少,他們只是比較會調節情緒而已。我們要怎樣調節自己的情緒呢?答案簡單得讓人吃驚:去思考它即可
  20. 基本比率謬誤(base rate fallacy)是一種機率謬誤,係因不明統計學的基本比率導致的推論謬誤。如看到一位貌似紳士、穿著乾乾淨淨的男士,你會覺得他是圖書館管理員還是農夫?儘管你已知這個地區的農夫與圖書館管理員的比率是5 : 1,你還是不會理會這樣的比率,直接猜是圖書館管理員,這就是 What You See Is All There Is (WYSIATI)
  21. 人們對於某人的管理技能一無所知,但是卻有可能因為對方做了一個很好的簡報,而產生光環效應 (Halo Effect),認為其具備良好的管理技能
  22. 人們可能會根據一位顧問的報告來做重大的決定,他們似乎不知道他們擁有的資訊是多麼有限
  23. System 1 一直在運轉,對周圍情況進行估算。這種估算,比我們實際需要的要多。這種過量的估算體現了“思維的發散性” (The Mental Shotgun),好像System 1 是一支散彈槍(shotgun),不管需不需要都會向主要目標發射出大量的子彈,有些是會擊中目標,有些則是不必要的。想控制 System 1 不去做這種過量評估是不可能的。評估一個問題,會激發對另一個問題的評估。這種評估是沒有必要的,而且影響對正確問題的評估。
  24. “思維的發散性” (The Mental Shotgun) 的例子:當某人被問及他認為這家公司的財務狀況是否健全時,此人不會忘記他喜歡這家公司的產品。這就是常發生的,你在評估一個問題時,又激發另外一個評估,但是另外一個評估常是沒有必要的,且會影響正確性
  25. 評估一個人是否具有吸引力是一個很基本的評價。無論你是否要做這的行為,你的腦袋會自動去做評估,並影響你





2018/04/15

[Spring Boot] How turn off debug log in spring boot?

Problem
I am using spring boot to implement Neo4j, but the log file contains lots of debug message


How-To
Add the following configuration in your application.yml:
spring:
  data:
    neo4j:
      uri: bolt://localhost
      username: neo4j
      password: secret

logging:
  level:
    root: INFO
    org:
      springframework: 
        web: WARN
      hibernate: ERROR

Get rid of debug level log successfully:


2018/04/14

[Mac] 透過 Welly 連 ptt 出現亂碼

Problem
透過 Welly 連 ptt 出現亂碼


已在偏好設定,將預設編碼設定為 Big5 仍舊是亂碼


How-To
點選選單 "顯示方式" => "編碼" => 選擇 "Big5"


亂碼問題即可獲得解決


2018/04/13

[Mac] 如何變更截圖存放位置

Problem
在 Mac 中,可以透過 command(⌘)+ shift + 3​ 來截取整個桌面的圖


可透過 command(⌘)+ shift + 4 來截取所選定區域的圖


但是,系統預設會將截圖的圖檔放在桌面,如
 /Users/albert/Desktop  

若想要把它變更到某一特定目錄,如
 /Users/albert/Desktop/截圖  

該如何設定?


How-To
修改流程如下:

語法:
 defaults write com.apple.screencapture location /Users/albert/Desktop/截圖  


2018/04/12

[snakeyaml] How to hide bean type in snakeyaml?

Problem
I try to serialize a Java object into a YAML String, the expected YAML content looks like:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
  intents:
  - greet
  - inform
  - others
  - question
  entities:
  - userid
  - is_account_locked
  - pass_company_check
  actions:
  - utter_default
  - utter_greet
  - confirm:
      dependency:
        slots:
        - userid
  - unlock:
      dependency:
        slots:
        - userid
        - is_account_locked

But the actual YAML content is:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
  intents:
  - greet
  - inform
  - others
  - question
  entities:
  - userid
  - is_account_locked
  - pass_company_check
  actions:
  - utter_default
  - utter_greet
  - confirm: !!test.albert.snakeyaml.SnakeYamlTest$ActionAttribute
      dependency:
        slots:
        - userid
  - unlock: !!test.albert.snakeyaml.SnakeYamlTest$ActionAttribute
      dependency:
        slots:
        - userid
        - is_account_locked

How to hide bean type in snakeyaml?


Here has sample code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
  package test.albert.snakeyaml;
  
  import java.util.Arrays;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  
  import org.yaml.snakeyaml.DumperOptions;
  import org.yaml.snakeyaml.Yaml;
  import org.yaml.snakeyaml.representer.Representer;
  
  import lombok.AllArgsConstructor;
  import lombok.Data;
  import lombok.extern.slf4j.Slf4j;
  
  @Slf4j
  public class SnakeYamlTest {
  
      public static void main(String[] args) {
          // Set DumperOptions options
          DumperOptions options = new DumperOptions();
          options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
          options.setPrettyFlow(true);
            
          // Create Yaml instance with DumperOptions
          Yaml yaml = new Yaml(options);
  
          // Prepare map data for YAML
          Map<String, Object> actionMap1 = new HashMap<>();
          actionMap1.put("confirm", new ActionAttribute(new Dependency(Arrays.asList("userid"))));
  
          Map<String, Object> actionMap2 = new HashMap<>();
          actionMap2.put("unlock", new ActionAttribute(new Dependency(Arrays.asList("userid", "is_account_locked"))));
  
          Map<String, Object> map = new HashMap<>();
          map.put("intents", Arrays.asList("greet", "inform", "others", "question"));
          map.put("entities", Arrays.asList("userid", "is_account_locked", "pass_company_check"));
          map.put("actions", Arrays.asList("utter_default", "utter_greet", actionMap1, actionMap2));
  
          // Serialize a Java object into a YAML String
          String output = yaml.dump(map);
          log.info("\n" + output);
      }
  
      @Data
      @AllArgsConstructor
      private static class ActionAttribute {
          Dependency dependency;
      }
  
      @Data
      @AllArgsConstructor
      private static class Dependency {
          private List<String> slots;
      }
  }



How-To
Here has updated source code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
  package test.albert.snakeyaml;
  
  import java.util.Arrays;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  
  import org.yaml.snakeyaml.DumperOptions;
  import org.yaml.snakeyaml.Yaml;
  import org.yaml.snakeyaml.nodes.Tag;
  import org.yaml.snakeyaml.representer.Representer;
  
  import lombok.AllArgsConstructor;
  import lombok.Data;
  import lombok.extern.slf4j.Slf4j;
  
  @Slf4j
  public class SnakeYamlTest {
  
      public static void main(String[] args) {
          // Set DumperOptions options
          DumperOptions options = new DumperOptions();
          options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
          options.setPrettyFlow(true);
          
          // overwrite Representer
          Representer representer = new Representer();
          representer.addClassTag(ActionAttribute.class, Tag.MAP);
  
          // Create Yaml instance with Representer and DumperOptions
          Yaml yaml = new Yaml(representer, options);
  
          // Prepare map data for YAML
          Map<String, Object> actionMap1 = new HashMap<>();
          actionMap1.put("confirm", new ActionAttribute(new Dependency(Arrays.asList("userid"))));
  
          Map<String, Object> actionMap2 = new HashMap<>();
          actionMap2.put("unlock", new ActionAttribute(new Dependency(Arrays.asList("userid", "is_account_locked"))));
  
          Map<String, Object> map = new HashMap<>();
          map.put("intents", Arrays.asList("greet", "inform", "others", "question"));
          map.put("entities", Arrays.asList("userid", "is_account_locked", "pass_company_check"));
          map.put("actions", Arrays.asList("utter_default", "utter_greet", actionMap1, actionMap2));
  
          // Serialize a Java object into a YAML String
          String output = yaml.dump(map);
          log.info("\n" + output);
      }
  
      @Data
      @AllArgsConstructor
      private static class ActionAttribute {
          Dependency dependency;
      }
  
      @Data
      @AllArgsConstructor
      private static class Dependency {
          private List<String> slots;
      }
  }

2018/04/11

[Java 8] Using lambda instead of Comparator in Collections.sort

Assume I have a Java Bean class which named Sentence
import java.io.Serializable;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(of = "id", callSuper = false)
public class Sentence implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer id;

    private Integer projectId;
   
    private String text;

    private Integer intentId;

}


Assume I have a List of Sentence which named result:
List<Sentence> result = new ArrayList<>();


If I would like to sort result by intendId, we can using Comparator to fulfill this requirement before Java 8
    Collections.sort(result, new Comparator<Sentence>() {
        @Override
        public int compare(Sentence o1, Sentence o2) {
            return o1.getIntentId().compareTo(o2.getIntentId());
        }
    });


In Java 8, we can take advantage of Lambda to cope with this requirement easily:     
    Collections.sort(result, (s1, s2) -> s1.getIntentId().compareTo(s2.getIntentId()));


Reference
[1] https://dzone.com/articles/dont-fear-the-lambda

2018/04/10

[JavaScript] Remove an item from array

Scenario
Assume I have an array of data in $scope.tab2.sentence.entities
I would like to remove an item from array based on the value which I provide, how to do it?


How-To

You can utilize splice to fulfill the requirement.
Here has the code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
 $scope.removeTab2Entity = function(entity) {
      var index;
      for (var i = 0; i < $scope.tab2.sentence.entities.length; i++) {
          if ($scope.tab2.sentence.entities[i].value == entity.value) {
              index = i;
              break;
          }
      }
      $scope.tab2.sentence.entities.splice(index, 1);
  }

splice syntax and its parameter information are as bellows:

Reference
[1] https://www.w3schools.com/jsref/jsref_splice.asp

2018/04/09

[Spring] Using RestTemplate to do HTTP Post and Get

Problem
How to use Spring RestTemplate to implement HTTP Post and Get.
The requirement is:
1. Using HTTP Get to get JSON string
2. Using HTTP Post to post JSON string to server




How-To

The example is as bellows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    @Autowired
    private RestTemplate restTemplate;
    
    // example for HTTP Get
    String getUrl = "http://192.168.0.1:8080/status";
    try {
       String statusJSONString = restTemplate.getForObject(new URI(getUrl), String.class);
    } catch (RestClientException | URISyntaxException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
    
    // example for HTTP Post
    String postUrl = "http://192.168.0.1:8080/train?name=test1";
        
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
  
    HttpEntity<String> entity = new HttpEntity<String>(jsonString, headers);
  
    try {
          restTemplate.postForEntity(new URI(url), entity, String.class);
    } catch (RestClientException | URISyntaxException e) {
        throw new IllegalArgumentException(e.getMessage());
    }


2018/04/08

[Angular] [Bootbox] File Upload Example

Problem
How to implement file upload function via Angular and Bootbox?

How-To

Here has sample code.
Code snippet in JavaScript:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    $scope.importJson = function() {
     $scope.attachment = undefined;
     
     bootbox.dialog({
      message: "<input class='form-control' type='file' id='jsonFile' name='jsonFile' /> ",
      title: '匯入 JSON',
      buttons: {
       upload: {
           label: '上傳',
           callback: function() {
               cResource().uploadFile({
                   url: '/api/projects/' + $scope.project.id + '/importJSON',
                   file: $scope.attachment
               }).success(function(res, status, headers, config) {
                   cAlerter.success('上傳成功');
               }).error(function(res, status, headers, config) {
               });
           }
       },
       cancel: {
             label: '取消'
       }
      }
     });
     var jsonFile = document.getElementById("jsonFile");
     jsonFile.addEventListener("change", function (e) {
         $scope.attachment = this.files[0];
     }, false);
    };


Code snippet in controller class:

1
2
3
4
5
6
    @Transactional
    @PostMapping(value = "/{projectId}/importJSON", produces = MediaType.APPLICATION_JSON_VALUE)
    public void importJSON(@PathVariable Integer projectId,
      @RequestParam(value = "file") MultipartFile jsonFile) throws IOException {
  
    }





2018/04/07

[Maven] How to specify JDK version for Maven?

Problem
I have multiple JDK version in my computer, how to specify JDK version for Maven?

How-to

Add the two properties in your pom.xml
 <properties>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
 </properties>


2018/04/06

[Python] namedtuple

Assume I create a Dog class as bellows:
class Dog():
    def __init__(self, size, name):
        self.size = size
        self.name = name

If I would like to set values into Dog class, the code snippet looks like:
pug = Dog('小型犬', '巴哥犬')
shiba = Dog('中型犬', '柴犬')
print('size = {}, name = {}'.format(pug.size, pug.name))
print('size = {}, name = {}'.format(shiba.size, shiba.name))


We can use namedtuple instead of Class.The code snippet are the following:
from collections import namedtuple
# namedtuple instances are just as memory efficient as regular tuples 
# because they do not have per-instance dictionaries. 
# Each kind of namedtuple is represented by its own class, 
# created by using the namedtuple() factory function. 
# The arguments are the name of the new class and a string containing the names of the elements.
Dog = namedtuple('Dog', 'size name')
corgi = Dog('小型犬', '柯基')
husky = Dog('中型犬', '哈士奇')
print('size = {}, name = {}'.format(corgi.size, corgi.name))
print('size = {}, name = {}'.format(husky.size, husky.name))

2018/04/05

[Python] How to parse JSON string?

Problem
I plan to connect to a url, http://od.moi.gov.tw/api/v1/rest/datastore/A01010000C-000628-023, to get data with JSON format. How to parse JSON string vi Python, and get specific data?


How-to
Here has sample code:
import urllib.request, json
from test.json.row import row

import os
os.environ['http_proxy'] = 'http://proxy.cht.com.tw:8080'

with urllib.request.urlopen("http://od.moi.gov.tw/api/v1/rest/datastore/A01010000C-000628-023") as url:
    # return with dict data type
    data = json.loads(url.read().decode())
    dataList = []
    count = 1
    # 取得 result / records 下的資料
    for value in data['result']['records']:
        # Skip the first record
        if(count > 1):
            no = value['No']              # 編號
            address = value['Address']    # 地點位置
            deptNm = value['DeptNm']      # 管轄警察局
            branchNm = value['BranchNm']  # 分局
            dataList.append(row(no, address, deptNm, branchNm)) 
            print('no={}, address={}, deptNm={}, branchNm={}'.format(no, address, deptNm, branchNm))
        count += count 


Reference
[1] https://data.gov.tw/dataset/6247