zipWithIndex

A common desire is to have access to the index of an element when using collection methods like foreach, filter, foldLeft/Right, etc… Fortunately there is a simple way.

List('a','b','c','d').zipWithIndex.

But wait!

Does that not trigger an extra iteration through the collection?. Indeed it does and that is where Views help.

List('a','b','c','d').view.zipWithIndex

When using a view the collection is only traversed when required so there is no performance loss.

Here are some examples of zipWithIndex:

  1. scala> val list = List('a','b','c','d')
  2. list: List[Char] = List(a, b, c, d)
  3. /*
  4. I like to use functions constructed with case statements
  5. in order to clearly label the index.  The alternative is 
  6. to use x._2 for the index and x._1 for the value
  7. */
  8. scala> list.view.zipWithIndex foreach {case (value,index) => println(value,index)}
  9. (a,0)
  10. (b,1)
  11. (c,2)
  12. (d,3)
  13. // alternative syntax without case statement
  14. scala> list.view.zipWithIndex foreach {e => println(e._1,e._2)}
  15. (a,0)
  16. (b,1)
  17. (c,2)
  18. (d,3)
  19. /*
  20. Fold left and right functions have 2 parameters (accumulator, nextValue) 
  21. using a case statement allows you to expand that but watch the brackets!
  22. */
  23. scala> (list.view.zipWithIndex foldLeft 0) {case (acc,(value,index)) => acc + value.toInt + index} 
  24. res14: Int = 400
  25. // alternative syntax without case statement
  26. scala> (list.view.zipWithIndex foldLeft 0) {(acc,e) => acc + e._1.toInt + e._2} 
  27. res23: Int = 400
  28. /*
  29. alternative foldLeft operator.  The thing I like about this
  30. syntax is that it has the initial accumulator value on the left 
  31. in the same position as the accumulator parameter in the function.
  32. The other thing I like about it is that visually you can see that it starts with
  33. "" and the folds left
  34. */
  35. scala> ("" /: list.view.zipWithIndex) {                          
  36.      | case (acc, (value, index)) if index % 2 == 0 => acc + value
  37.      | case (acc, _) => acc                                       
  38.      | }
  39. res15: java.lang.String = ac
  40. /*
  41. This example filters based on the index then uses map to remove the index
  42. force simply forces the view to be processed.  (I love these collections!)
  43. */
  44. scala> list.view.zipWithIndex.filter { _._2 % 2 == 0 }.map { _._1}.force
  45. res29: Seq[Char] = List(a, c)

Continua a leggere

Pubblicato in Senza categoria

模擬實戰標籤綁架手法(Challenge to TabNapping)

暨「點閱綁架(Clickjacking)」手法之後,又出現「標籤綁架(TabNapping)」的新手法了。
直接來親身體驗吧!這裡有實作的體驗網站 (FireFox 確定可以被利用)。畫面如下:


實戰標籤綁架,主要利用欺瞞手法,當你瀏覽網站時,切換到不同索引標籤(或書籤、分頁),或切換到不同視窗後五秒鐘,該有問題的頁面就會被偷偷轉換成另外一個誘騙的瀏覽頁面,於是就出現「猥琐」的事件。目前已知可以成功的瀏覽器:
1.Firefox 3.6.3
2.Chrome 4.1.249.1064

手法剖析:
1.目前大多主流之瀏覽器都有索引標籤(IE & Safari 使用此稱呼)、標籤頁(Safari 亦有用此稱呼),或稱「分頁」(Chrome & FireFox 使用此稱呼)功能。
2.當大量使用上述功能於同一瀏覽器中,其中一頁面可以用此程式語法加以利用。
3.將頁面內容偷偷改變成為另一頁面內容,導致誘騙上當之情事。
4.可做為網路釣魚或詐騙的手法之一。

相關挑戰之系列文章:
模擬實戰點閱綁架手法
模擬實戰釣魚網站」(目前已被歸類為 Click by Download 手法)

參考資料:
Raskin 之個人部落格 PS:他是 Mozilla Firefox 瀏覽器的介面及創意負責人。在他的 Bolg 上亦展示了此手法。
相關新聞:
ITHome
資安之眼

本文同步張貼於「阿碼外傳」。 Continua a leggere

Pubblicato in Senza categoria

Return value of a block

A common misunderstanding is that a code block (without parameters) is a function. That is not the case. A code block is a sequence of statements that are executed and result the last statement is returned. That sounds like a Function0, however, if the block is passed to a method/function only the last statement will be returned to the function/method. If that method/function expects a function as the parameter the last statement maybe returned as a function not a value, this means that the block itself is not a function.

  1. scala> var count = 0                                                                                                                         
  2. count: Int = 0
  3. // the last statement is returned as a function so count
  4. // is incremented only one during the creation of the function
  5. scala> List(1,2,3,4).map{count += 1;_ + 1}
  6. res9: List[Int] = List(2, 3, 4, 5)
  7. scala> count
  8. res10: Int = 1
  9. // now the count increment is within the function
  10. scala> List(1,2,3,4).map{i => count += 1;i + 1}
  11. res11: List[Int] = List(2, 3, 4, 5)
  12. scala> count
  13. res12: Int = 5


The previous example demonstrates a Gotcha if I ever saw one. Map expects a function so the block essentially constructs a function. The last statement being the function. The first line count += 1 executed only once because it is part of creating the function not part of the resulting function. This is equivalent to:

  1. scala> val x = {count += 1 ; i:Int => i +1}
  2. x: (Int) => Int = < function1>
  3. scala> List(1,2,3,4).map(x)
  4. res15: List[Int] = List(2, 3, 4, 5)


Beginning a block with the parameter list signals that the entire block is a function.

Rule of thumb: Functions with placeholder parameters should be a single statement. Continua a leggere

Pubblicato in Senza categoria

How to define the hardness of the aluminum oxide film formed by hard anodizing

The term “Hard Coat” or Hard Anodizing gives the impression of an anodizing process which gives a very hard anodic layer. The values below show that the anodic layer formed by this process really is harder but it is still important to remember that saying “Hard Coat” to an anodizer doesn’t give him enough information to process the metal.

HARDNESS COMPARISON between different materials
  • Untreated Aluminum Alloy 6082 - HV 100 – 120
  • Hard Anodized Alloy 6082 - HV 400 – 460
  • Stainless Steel - HV 300 – 350
  • Mild Steel - HV 200 – 220

The values are measured in (VPN) = Vickers pyramid number, also referred to as the Vickers hardness number (HV or VHN).

The Vickers hardness is the amount of force applied to the diamond divided by the area of the indentation the diamond makes in the material; in practice the diagonal of the pyramidal indentation is measured and the result is read from a table and is stated as an empirical measurement, without units.
Other hardness measurement numbers are found, such as, Brinell, Rockwell and Knoops. The Vickers hardness is up to about HV 500 about 1.04 times the Brinell hardness but most of the time hardness of the anodic oxide layer is measure by Vickers.
Knoops hardness is almost identical with Vickers hardness except for the form of the diamond. In this testing method the diamond has a rhombic-based pyramidal shape. The form of this
indentation makes it possible to measure the hardness of aluminum oxide more accurate but it is still not widely used.

The anodic oxide layer is very brittle and to obtain the best reproducibility of the measurements the Knoops diamond should be used. Using Vickers hardness measurements causes cracks in the oxide layer, so only measurements in the middle of the oxide layer are possible.

HARDENSS TESTING on anodic coatings should be carried out on the edge of the film so that the effect of the underlying, soft, aluminum is eliminated but not to close to the edge so the

softness of the resin influence the results.

The image to the right shows a cross section of a hard anodic coating with Vickers indentations and thickness measurements.
The pyramid has to be square formed to be sure of hardness value measured.
The light blue to the left is the aluminum alloy and the dark to the right in the picture is the resin.

THE MILITARY SPECIFICATION, MIL-A-8625F, for “Anodic Coatings for Aluminum and Aluminum Alloys” says nothing about any requirements of the hardness of Type III – Hard Anodic Coatings, see earlier post about this subject here.
The European Standard EN 12373 ”Aluminium and aluminium alloys – Anodizing” has none either. Both of them have on the other hand requirements of a wear resistance of the coating.
The maximum wear index for coatings on aluminum alloys having a copper content of 2 % or higher is of 3.5 mg/1000 cycles and 1.5 mg/1000 cycles for all other alloys.
Next post will discuss the wear resistance versus the hardness of hard anodic oxide coatings.

For more information on how to define your hard coat for your product please contact me [email protected]

__________________________________________________

Continua a leggere

Pubblicato in Senza categoria

Type Inference with Abstract Types

A second “gotcha” that one might get tripped up when dealing with abstract types is the signature of the concrete class contains type information about the abstract type. So if you are not explicit when assigning a variable or defining a function you can get unexpected compiler errors.

  1. scala> trait S {
  2.      |   type x
  3.      |   def get : x
  4.      | }
  5. defined trait S
  6. scala> var sample = new S{ 
  7.      |   type x = Int
  8.      |   def get = 3
  9.      | }
  10. sample: java.lang.Object with S{type x = Int} = $anon$1@397af435
  11. scala> sample = new S {
  12.      |   type x = Double
  13.      |   def get = 3.0
  14.      | }
  15. < console>:7: error: type mismatch;
  16.  found   : java.lang.Object with S
  17.  required: java.lang.Object with S{type x = Int}
  18.        sample = new S {


In this example sample uses type inference so the actual type is S with underlying type Int. The consequence is that sample can only be assigned with instances of S with type x = Int. The fix is to explicitly declare the variable type:

  1. scala> var sample2 : S = new S{ 
  2.      |   type x = Int
  3.      |   def get = 3
  4.      | }
  5. sample2: S = $anon$1@31602bbc
  6. scala> sample2 = new S {
  7.      |   type x = Double
  8.      |   def get = 3.0
  9.      | }
  10. sample2: S = $anon$1@4de5ed7b


The same thing happens when declaring functions and allows type inference for function definition

  1. scala> class Fac {
  2.      |   def newS = new S {
  3.      |     type x = Int
  4.      |     def get = 3
  5.      |   }
  6.      | }
  7. defined class Fac
  8. scala> class SubFac extends Fac{
  9.      |   override def newS = new S {
  10.      |     type x = Double
  11.      |     def get = 3.0
  12.      |   }
  13.      | }
  14. < console>:8: error: type mismatch;
  15.  found   : java.lang.Object with S
  16.  required: java.lang.Object with S{type x = Int}
  17.          override def newS = new S {


The fix for this example is to be explicit in the definition of the function in the superclass Continua a leggere

Pubblicato in Senza categoria

攻擊與防禦思維 II

有鑑於前一篇「攻擊與防禦思維」太過於消極,所以這邊平反一下,還是要正面思考…(丟筆…

一、「攻擊者積極,防守者消極」
1.防守士氣:這點是非常重要的。主官如何激勵士氣,為首要要務。如果沒有士氣,砸再多資安防護設備也是枉然。士氣有多重要,可以看看這個新聞,不過一般常見士氣不彰的結果,是會造成人員異動頻繁的。話說回來,不只是資安單位,整個公司的氛圍更重要,這不是多高薪水能禰補的,唯一不受影響的只有肥貓。且一旦士氣萎靡,要提升可不是短時間就可以達成的,務必多加留意。
2.內部該「一致」對駭客:很多狀況是,明明野生動物在門口拉的一坨屎,兩鄰居卻大打出手,終身不相往來。如何避免這種狀況,考驗主管們的 EQ 了。很多問題其是沒有對錯的。
3.資安未必是專責,資安至少要成為共同語言:這一點其實我也有點矛盾,到底是應該資安專責專才呢?還是要全民皆兵呢?我想了很久;應該要配合公司體質吧!我深深的覺得有時候「資安觀念就跟衛生觀念一樣,你的社區有個衛生習慣很差的人,往往整個社區烏煙瘴氣」。電腦技能目前已經成為職場必要技能了,我想資安觀念也該成為基本技能之一了。
4.培養 IT 人員的資安專才:這是持續長久的工作,也是計畫。甚至培養 IT 人員的資安第二專長,逐漸建立企業內部的資安專業人才。
5.建立資安人脈:有了技術,就該用技術出去交流了。企業的上下游、資安供應商…等,都該保持良好關係的。也可參考「我不是教你使詐」一文。

二、「木桶理論」
1.建議重新檢視網路架構開始:只要網路架構有問題,結果應該跟 IT 團隊士氣潰散差不多,甚至更糟,它可是所有架構的根基啊。
2.在端點安全無法求的安全前,全面切割內部使用者,接觸核心系統的可能;反之,如果無法與核心系統切割,哪,使用者就必須與外部切割。舉個簡單的例子,你有看過銀行行員處理金融業務的電腦可以上網嗎?可以收 E-Mail 嗎?現實問題大多是使用者過於寬鬆的電腦使用權限,IT 部門收不回來。
3.參考「資訊安全-管理、制度」系列一文。
4.ISMS 已經提很多了,積極管理、有效落實吧。

三、「風險的變遷」
1.了解自己的系統架構:這是基本的,如果對於自己使用了哪些系統平台或架構不清楚,哪…「風險 = 資產價值 + 安全威脅 + 安全弱點」該如何評估呢?很明顯,風險變化跟資產、威脅、弱點都有極大關係的,而這裡面的每一點都跟你擁有的系統有關聯。
2.資安盟友:有時資安圈都有一手的小道消息,這時你就知道「意義是三小,我只知道義氣」道理了。
3.自我研習:嗯嗯啊啊!這點大家的問題應該都是「有空再說」。這點需要有誘因的,獎勵措施往往都是最有效的方法,否則,只能單靠個人的熱血或熱情支撐吧,難道,資安工作也靠個人的熱血或熱情支撐?
4.資訊吸收與分析:訂閱資安技術消息、資安通告、駭客技術發佈…等 RSS 文章。情蒐是很重要的,主要問題在於要消化卻是不容易的。

四、「商業邏輯問題」
1.對於「B to C」及「C to C」的業者,建議應該有「防詐騙官」的角色,來協助解決各種防詐騙的技倆,並加以防治。
2.「為何有人會造成這問題」:主要還是「當初設計時沒有想到」的問題。換句話說,在架構或機制設計時,只有考慮功能面,沒有資安或防詐騙的觀念融入。
3.「誰會利用這問題」:透過「防詐騙官」的角色,可以找出已經被利用的問題,並設法加以解決,企業衍生的社會問題,得要拿出企業社會責任。
4.其他比較一般性的問題,「滲透測試」大多可以發現,前提是「好的」滲透測試。
5.我比較贊成類似「Yahoo!奇摩 Open Hack Day」的方式,也許可以僅限公司內部、或企業對企業、或企業上下游…等方式來舉辦,同時還可以提升 IT 團隊的工作士氣,也能促進跨企業 IT 人員之間的互動。這點也是我寫「滲透測試之全民公測」的起因之一。要相信一點,人人都有功夫,網路上人人都是 Hacker,這真的無關太多技術,即使「誤用(Misuse)」也一種 Hacking。

五、「未知弱點」
這點跟「風險的變遷」有頗大的關聯。
1.對於目前使用的系統,接收相關漏洞揭漏的資訊來源。
2.思考如何掌握「未知」變成「已知」的關鍵時刻:這點是許多人不敢想的,說穿了,要不就沒人發現,不然,只能比駭客還早發現,但,你有哪些作為來掌握此關鍵時刻呢?滲透測試?你一定得要想些不用成本的,或好幾種措施才行。
3.資安或 IT 圈子之間的互通有無。
4.是不是也該有點內部的舉報獎勵措施呢?花錢請人找漏洞,怎不給自己人一點機會…XD。舉辦類似「Hacking Day」的活動也不錯。
5.對使用的技術、系統、架構、平台…等,持續保持研究的態度。如果 IT 是你的核心業務支助的話,絕對不能只會開車,而不會修車…這樣是不夠的;況且,很多企業是請一個人來開車、另一個來修車的,因為你很難確實掌握車況,結果卻是一天到晚「顧馬路」。

六、「資安打手」
no comment…

七、「有發生啥事嗎」
唯有正面面對一途。

最後,提一點,企業對資安的設備(或技術)、人才、管理上,三方面的投資比重是多少?比例該多少才合理呢?我不知道,也沒有答案。我也希望有人提供資料給我參考哩!但我想,如果花在資安的設備(或技術)達八九成以上,是不合理的。 Continua a leggere

Pubblicato in Senza categoria

Why is Hexavalent Chromium so hazardous

The reason for the toxicity of hexavalent chromium is explained great on Wikipidia

Hexavalent chromium is transported into cells via the sulfate transport mechanisms, taking advantage of the similarity of sulfate and chromate with respect to their structure and charge.

Trivalent chromium, which is the more common variety of chromium compounds, is not transported into cells.

Inside the cell, Cr(VI) is reduced first to metastable pentavalent chromium (Cr(V)), then to trivalent chromium (Cr(III)). Trivalent chromium binds to proteins and creates haptens that trigger immune response. Once developed, chrome sensitivity can be persistent. In such cases, contact with chromate-dyed textiles or wearing of chromate-tanned leather shoes can cause or exacerbate contact dermatitis. Vitamin C and other reducing agents combine with chromate to give Cr(III) products inside the cell.

Hexavalent chromium compounds are genotoxic carcinogens. Chronic inhalation of hexavalent chromium compounds increases risk of lung cancer (lungs are especially vulnerable, followed by fine capillaries in kidneys and intestine). It appears that the mechanism of genotoxicity relies on pentavalent or trivalent chromium. According to some researchers, the damage is caused by hydroxyl radicals, produced during reoxidation of pentavalent chromium by hydrogen peroxide molecules present in the cell. Strontium chromate is the strongest carcinogen of the chromates used in industry. Soluble compounds, like chromic acid, are much weaker carcinogens.

Chromic acid is used in various surface treatments on aluminum, such as chrome plating, chromating and Chromic Acid Anodizing.

In the U.S., the OSHA PEL for airborne exposures to hexavalent chromium is 5 µg/m3 (0.005 mg/m3).

__________________________________________________

Continua a leggere

Pubblicato in Senza categoria

Instance Type (Abstract type gotcha 1)

In a previous post about abstract types I showed one of the benefits of using abstract types over parameterized types. Abstract Types vs Parameter. The next several posts will feature potential problems you may encounter when using Abstract Types.

I should point out that abstract types are not inherently difficult to understand but they are rather different from anything you will see when you come from the Java world so if you are new to them I would use them with caution at first.

In the abstract types example you will notice that the abstract type ‘I’ in Foreach is not within the trait Source rather it is outside in the Foreach trait. At first one might consider putting the type in Source rather than Foreach. The naive change can get you in trouble (but there is a couple easy fixes)

  1. trait Foreach[A] {
  2.   trait Source {
  3.     type I <: java.io.Closeable  // moved this line into Source
  4.     def in : I
  5.     def next(in : I) : Option[A]
  6.   }
  7.   def source : Source
  8.   
  9.   def foreach[U](f : A => U) : Unit = {
  10.     val s = source.in
  11.     try {
  12.       def processNext : Unit = source.next(s) match {
  13.         case None => 
  14.           ()
  15.         case Some(value) => 
  16.           f(value)
  17.           processNext
  18.       }
  19.       
  20.       processNext
  21.     } finally {
  22.       // correctly handle exceptions
  23.       s.close
  24.     }
  25.   }
  26. }


Compiling the class results in a compilation error:

jeichar: tmp$ scalac XX.scala
XX.scala:12: error: type mismatch;
found : s.type (with underlying type Foreach.this.Source#I)
required: _2.I where val _2: Foreach.this.Source
def processNext : Unit = source.next(s) match {
^
XX.scala:16: error: type mismatch;
found : value.type (with underlying type Any)
required: A
f(value)
^
two errors found

So what is the problem? The problem is simple but subtle. Notice that source is defined as a def. So calling source 2 times may return 2 different instances of Source. A simple change can fix this. Either change def source : Source to val source : Source. Or change the method foreach to assign the result from source to a val.

  1. trait Foreach {
  2.   trait Source {
  3.     type I <: java.io.Closeable  // moved this line into Source
  4.     def in : I
  5.     def next(in : I) : Option[Int]
  6.   }
  7.   def source : Source
  8.   
  9.   def foreach[U](f : Int => U) : Unit = {
  10.     // this assignment allows this example to compile
  11.     val sameSource = source
  12.     val s = sameSource.in
  13.     try {
  14.       def processNext : Unit = sameSource.next(s) match {
  15.         case None => 
  16.           ()
  17.         case Some(value) => 
  18.           f(value)
  19.           processNext
  20.       }
  21.       
  22.       processNext
  23.     } finally {
  24.       // correctly handle exceptions
  25.       s.close
  26.     }
  27.   }
  28. }

Continua a leggere

Pubblicato in Senza categoria

2000 "Fans!"

This week we reached a fun milestone: 2000 “fans” on Facebook!In celebration, we offered a rare two-day 20% off sale! A promo code was posted to our Facebook page, and we encourage you to join us in this final day. Go to our Facebook page for the pro… Continua a leggere

Pubblicato in Senza categoria