Failure is not an option, it is a requirement

July 4th, 2012 No comments

Of course that statement on it’s own can obviously be shown to be fallacy. When you consider the context of continuous improvement, learning or generally advancing our own capabilities and understanding, though, this statement can be quit liberating. Why? Because without failure, you are not learning anything.

Let’s say you are faced with a problem, a challenge, or a need that you are trying to fulfill. If your first attempt and creating a solution is successful you have learned nothing. You already knew how to provide the solution. it only took some thinking to analyze the situation and apply your existing knowledge. If, however, you stretch yourself as far as you can, put every last effort that you currently have into the solution and employ all of your existing knowledge, capabilities and resources but you still fail the first time, fail again and fail some more before finding a solution, then you are learning. You are stepping outside of your own knowledge and capabilities, learning new things and gaining new insight and experience that leads to new solutions for situations that you did not know how to previously solve.

Consider any endeavor to learn, from this light. Whether it’s adopting a new process or methodology such as an agile process or lean toolkit, using a new tool or technology, contributing to an open source project, or learning how to ride a bicycle – having the correct mentality, that failure is required, will undoubtedly help you succeed.

Mike Rother said it quite well in his book, Toyota Kata (p.138-139), when faced with people who are merely capitulating because they were told to do so, or because they want to prove that some change or new way of doing things won’t work:

Eventually it dawned on me how to deal with this question. Now, when arms fold up and people say, “Let’s see if this will work,” I say, “I can save you the time. We already know it probably won’t work. Despite our best efforts to plan this, we know that within a short time there will be ‘charred and glowing pieces’ lying around. We just don’t know in advance when, where, or why it will fail.”

Think about the last time you delivered any fragment of functionality to a customer or customer representative for feedback. Did you expect that they would be 100% satisfied and would accept it as is? Not if you were asking for feedback. When the customer responds with changes or updates that they would like, you have effectively failed. Hopefully you have failed within a very short cycle, though, and are able to incorporate the feedback of the customer into the next delivery or demonstration.

They key is not learning from mistakes and failures. The key is failing fast, failing cheap, and responding to those failures in a timely manner so that you can learn quickly and still reach your objectives. Failure is critical to success and learning, and short feedback cycles are critical to the effective use of failure as a learning tool.

Derick Bailey

(Source: http://lostechies.com/derickbailey/2010/02/28/failure-is-not-an-option-it-is-a-requirement/)

Tiến sĩ Alan Phan: “Cơ hội dành cho các bạn trẻ luôn hiện diện ở khắp mọi nơi”

April 13th, 2012 No comments

“Đừng sợ thất bại” là lời khuyên mà Tiến sĩ, doanh nhân lớn Việt kiều Mỹ Alan Phan gửi đến thế hệ trẻ trên con đường tìm kiếm sự thành công. Hiện ông đang được giới trẻ chú ý qua những bài viết và phân tích sâu sắc của mình về kinh tế – xã hội cũng như con người.”

Điều đó được thể hiện qua những thảo luận sôi nổi tại trang blog www.gocnhinalan.com của ông.

Bay Vút đã có dịp phỏng vấn Tiến sĩ Alan Phan về một số vấn đề liên quan đến người trẻ nhân dịp ông trở về Việt Nam.

“Tôi trở về Việt Nam đầu tư không mang nặng tính tiền bạc mà phần nhiều vì tình cảm. Tôi muốn chia sẻ đến các bạn trẻ kiến thức, kinh nghiệm cũng như các góc nhìn của tôi để họ có thêm những tư duy và góc nhìn mới cho cuộc đời của mình”, Tiến sĩ Alan Phan chia sẻ.

Bay Vút: Mặc dù thời tuổi trẻ của ông với thế hệ trẻ ngày nay có những khác biệt rất lớn nhưng xin ông cho biết một số điểm chung nhất định giữa hai thế hệ?

TS. Alan Phan: “Mẫu số chung giữa thời tuổi trẻ của tôi và các bạn trẻ bây giờ đó là có năng lực tràn trề, những suy nghĩ khá ngây ngô và nhiều lý tưởng rất ‘hoang tưởng’. Tuy nhiên, điểm chung lớn nhất mà ở mọi thời thế đều có là cơ hội dành cho các bạn trẻ luôn hiện diện ở khắp mọi nơi, vấn đề là họ có nhìn thấy và nắm bắt được nó hay không”.

“Còn cái khác biệt là thời bây giờ, con người ít phải âu lo về những chuyện no, đói hay chiến tranh. Thêm vào đó, cuộc cách mạng Internet đã giúp người trẻ có được những kho tàng kiến thức 24/7 với tốc độ của ánh sáng”.

Bay Vút: Suy nghĩ cũng như góc nhìn của ông đều rất trẻ và tràn đầy năng lượng. Ông có thể chia sẻ về bí quyết này?

TS. Alan Phan: “Đó là bản chất của mỗi con người. Như trong một bài viết, tôi có nhắc tới những người mới ngoài 20 tuổi nhưng đã già như cụ ông, sẵn sàng về hưu, suốt ngày chỉ muốn đi nhậu hay đi café ‘chém gió’. Đi làm thì chỉ muốn yên thân, kiếm vài ba đồng đưa vợ con cho qua chuyện. Dĩ nhiên, chưa chắc họ đã sai hoặc tôi đã đúng. Với họ, có thể đó là một đời sống hạnh phúc rồi”.

“Còn triết lý sống của tôi là cuộc đời như một cuộc phiêu lưu, một hành trình mà trên con đường đi mình sẽ gặp những niềm vui, những khó khăn, tất cả đều mang cho mình những cảm xúc mới mẻ. Tôi phải luôn hành động chứ tìm một góc nhỏ nào đó để an bình nghỉ hưu thì đấy không phải là bản chất của tôi”.

“Tuy nhiên, không phải lúc nào tôi cũng tươi trẻ như thế. Tôi cũng chịu đựng những mệt mỏi và đôi khi tự hỏi sao mình phải khổ vậy? Nhưng cuối cùng, bản chất năng động trong con người lại thắng thế. Đành biện hộ là vài ba chục năm nữa, tôi sẽ nằm sâu dưới sáu tấc đất rồi, lúc ấy tha hồ được yên thân nghỉ ngơi”.

Bay Vút: Có một câu nói được ông ưa thích, đó là: “Tất cả bắt đầu từ suy nghĩ”. Tuy nhiên, để có được suy nghĩ tốt thì phải có sự giáo dục tốt và nền giáo dục dành cho người trẻ hiện nay vẫn chưa được tốt lắm. Vậy theo ông, để suy nghĩ tốt thì họ nên bắt đầu từ đâu?

TS. Alan Phan: “Mình có thể đổ lỗi cho ngày hôm qua nhưng không thể đổ lỗi cho ngày hôm nay và tương lai. Có thể người trẻ chưa được hưởng một nền giáo dục không tốt, họ sinh ra trong một môi trường mà sự vô cảm càng ngày càng gia tăng và đôi khi thiếu cả sự dạy dỗ đúng đắn của gia đình nhưng đó là những chuyện đã qua”.

“Ngày hôm nay là một ngày mới. Những việc mình làm hôm nay và trong tương lai hoàn toàn nằm trong tay mình, cái tư duy mới của mình phải bắt đầu từ ngay bây giờ. Và bắt đầu như thế nào thì thực tình nền giáo dục qua Internet ngày nay phong phú vô cùng. Vấn đề là lựa chọn những gì mình thích và ứng dụng triệt để trên con đường mình đã chọn”.

“Nhiều người cũng hỏi làm sao để bắt đầu? Đơn giản nhất là vào Google và tìm hiểu hàng triệu kiến thức trong đó. Cốt lõi của vấn đề là khả năng chọn lựa và chấp nhận của các bạn. Đừng đổ thừa cho giáo dục hay cho quá khứ”.

Bay Vút: Rất nhiều người trẻ đọc những điều ông viết ra trên blog. Giả sử họ làm theo lời khuyên của ông và gặp thất bại thì ông sẽ nói gì với họ?

TS. Alan Phan: “Đừng sợ thất bại, đó là kinh nghiệm của đời tôi. Càng nhiều thất bại thì càng đến gần thành công lớn hơn. Sau mỗi lần thất bại, tôi thường bùng lên khá hơn lúc trước vì được tôi luyện mạnh hơn. Hãy coi thất bại như một người bạn, một người thầy để dạy mình”.

“Khi người ta coi thất bại là kẻ thù thì thất bại sẽ theo đuổi bạn hoài. Thực ra, những gì tôi viết chẳng phải là lời khuyên, đó chỉ là những suy nghĩ, trải nghiệm cá nhân. Tôi không bao giờ khuyên hay bảo người khác phải làm gì cho đời mình. Mỗi người tự do lựa chọn một lối sống”.

Bay Vút: Sự thay đổi luôn cần một đích đến và một hệ quy chiếu để so sánh. Nếu như giới trẻ Việt Nam hiện nay cần sự thay đổi lớn về mặt tư duy thì cái đích đến và hệ quy chiếu so sánh ấy là gì, thưa ông?

TS. Alan Phan: “Cái đích đến của mỗi cá nhân đều từ bản chất riêng. Bạn muốn đi đến đâu, làm cái gì thì bạn phải tự suy xét, định đoạt và chấp nhận hậu quả. Sự thay đổi theo chiều hướng nào, việc muốn loại thải hay thu nạp cái gì thì mỗi người phải tự biết. Không ai có thể nói hay làm thay bạn được”.

Bay Vút: Ông cảm thấy thế nào khi hiện nay sách cũng như blog của ông thu hút được nhiều bạn đọc?

TS. Alan Phan: “Đối với người viết thì càng có nhiều người đọc, họ càng có hứng thú và khích lệ cho sự cố gắng của mình. Tuy nhiên mình cũng đừng nên nghĩ đó là một cái gì quan trọng hay ghê gớm. Có một bài tôi viết trên Vietnamnet được hơn 22.000 người đọc. Tôi mới hỏi lại Vietnamnet là bài nào có nhiều người đọc hơn? Họ cho biết là bất cứ cái bài nào liên quan tới Cường Đôla với Hồ Ngọc Hà thì trung bình có tới sáu trăm nghìn người đọc”.

“Thành ra mình phải hiểu rõ vị trí nhỏ nhoi của mình trong xã hội. Chỉ có một số ít lượng người quan tâm đọc những gì mình viết đã là niềm vui rồi”.

Bay Vút: Ông từng là giáo sư thỉnh giảng tại các trường đại học Mỹ và Trung Quốc. Trong tương lai, ông có nghĩ tới việc sẽ làm công việc này tại các trường ĐH Việt Nam không?

TS. Alan Phan: “Tôi đã bỏ dạy từ lâu rồi. Cách đây khoảng 10 năm tôi dạy ở hai đại học ở Thượng Hải. Theo tôi, các sinh viên Châu Á rất thụ động. Có lẽ vì nhiều giáo sư Châu Á lên giảng đường ‘thao thao bất tuyệt’ trong khi sinh viên ở dưới cứ cắm cúi ghi chép”.

“Cách dạy của tôi khác hơn. Tôi cho sinh viên đọc trước các bài ở nhà, hy vọng họ nắm được vấn đề. Khi vào lớp tôi dành khoảng 15 phút để điểm lại một vài vấn đề quan trọng hay những gì họ chưa hiểu. Thời gian còn lại tôi muốn họ đứng lên bàn cãi, thảo luận những gì họ đã đọc”.

“Tôi muốn họ phản biện lại những gì đã đọc vì chưa chắc các tác giả hay tôi đã đúng nhưng đáng tiếc là các cuộc thảo luận hầu như chưa bao giờ xảy ra vì sinh viên lười biếng đọc trước và chỉ thích ngồi im. Thành ra tôi cảm thấy hụt hẫng, cứ phải độc thoại. Sau một thời gian, tôi chán không muốn dạy. Ngoài ra, đến kỳ thi thì chấm bài toàn thấy ‘copy’ với ‘paste’ từ Google nên tôi nghĩ sự đóng góp của tôi cho giáo dục có lẽ không hiệu quả”.

Bay Vút: Một câu hỏi cuối liên quan đến cá nhân ông. Theo ông chia sẻ thì hạnh phúc đối với mình là sự tự do. Vậy sống ở Việt Nam ông có cảm thấy hạnh phúc không?

TS. Alan Phan: “Cái tự do tôi muốn nói là tự do về suy nghĩ, về phát ngôn, về quyền yêu và ghét… Một thứ cũng rất quan trọng là tự do về những lo lắng tiền bạc, muốn làm gì thì làm, kể cả những điều ngu xuẩn”.

“Ở đây, môi trường hơi khép kín nên mỗi lần tôi muốn tìm tự do hoàn toàn thì phải bay sang Thái Lan hay Singapore. Tuy nhiên, thực tình, Việt Nam cũng là một nơi ‘okie’ để sống. Có thể nói cả thế giới là một ‘nhà tù’ nhưng nếu được sống trong một ‘nhà tù’ rộng rãi như thế giới thì cũng thoải mái rồi”.

Nhuệ Giang thực hiện

Bài đăng trên bayvut.com.au ngày 22/11/2011

Different points of Java and C#

October 3rd, 2011 No comments

Recently I’ve started discovering C# in .NET world. As my background is Java and its world, I encounter various difficulties in learning C#. It’s not a bad idea for me to take note different points of Java and C#, that would not only let me validate my understanding well, but also help those who are in a situation like me can quickly stick to the core of both worlds.

I make comparison based on:

  • Java 6
  • C# 4.0

Points of difference are written:

  • in pairs
  • one by one
  • in no order

Mostly I will collect materials from Internet for explanation and demonstration. Feel free to comment or drop me an email if I wrote something wrong. Thank you!

1. Class variables

Java

Member variables in a class are called fields.

public class Bicycle {

    // the Bicycle class has three fields
    public int cadence;
    public int gear;
    public int speed;
}

C#

A class can have fields and properties. They look similar from outside but from inside, a field has no logic while a property may have logic.

public class Stock

{

decimal currentPrice;  // The private “backing” field

public decimal CurrentPrice    // The public property

{

get { return currentPrice; }

set { currentPrice = value; }

}

}

2. Access modifiers

Java

Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier

(package-private)

Y Y N N
private Y N N N

The first data column indicates whether the class itself has access to the member defined by the access level. As you can see, a class always has access to its own members. The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member. The third column indicates whether subclasses of the class “declared outside this package” have access to the member. The fourth column indicates whether all classes have access to the member.

C#

public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private
The type or member can be accessed only by code in the same class or struct.

protected
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

3. Constant variables

Java

A final variable can only be initialized once, either via an initializer or an assignment statement. It need not be initialized at the point of declaration: this is called a ‘blank final’ variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared: otherwise, a compile-time error occurs in both cases.

public class Sphere {
    public static final double PI = 3.141592653589793;  // a constant
    public final double radius;  // a blank final constant
    public Sphere() {
    radius = 1.0;
    }
}

C#

Constants are declared with the const modifier. Only the C# built-in types (excluding System.Object) may be declared as const. For a list of the built-in types, see Built-In Types Table (C# Reference). User-defined types, including classes, structs, and arrays, cannot be const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed.

Constants must be initialized as they are declared.

class Calendar1
{
    public const int months = 12;
}

When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

class Age
    {
        readonly int _year;
        Age(int year)
        {
            _year = year;
        }
        void ChangeYear()
        {
            //_year = 1967; // Compile error if uncommented.
        }
    }

3. Static Constructors

Java

Static constructor is not really supported by Java, but you can use static initialization block instead. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static {

    // whatever code is needed for initialization goes here
}

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

C#

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:

  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Example.

class Apple
 {
 static Apple()
 {
 Console.WriteLine("Apple type is initialized.");
 }

 public Apple()
 {
 Console.WriteLine("one");
 }
 }

When you instantiate above class, output will be:

Apple type is initialized.

one

4. Packages and Namespaces

Java

Classes and interfaces are organized into packages, which in fact are directories on operating system. Package declaration must be first and before any other statement (except comment) in a Java source file.

To declare a package, use keyword package.

//in the Rectangle.java file
package graphics;
public class Rectangle {
   . . .
}

Then, put the source file in a directory whose name reflects the name of the package to which the type belongs:

.....\graphics\Rectangle.java

C#

Classes are organized virtually into namespaces, no directory is required like that of Java. A class can have many namespace declarations.

To declare a namespace, use keyword namespace.

namespace N1     // N1
{
    class C1      // N1.C1
    {
        class C2   // N1.C1.C2
        {
        }
    }
    namespace N2  // N1.N2
    {
        class C2   // N1.N2.C2
        {
        }
    }
}

The following code:

namespace N1.N2
{
   class A {}
   class B {}
}

is semantically equivalent to

namespace N1
{
   namespace N2
   {
      class A {}
      class B {}
   }
}

5. Order of declaration

Java

// declare package first

package A

// then import something

import B

C#

A traditional order is (more):

// use something

using B

// then declare namespace

namespace A

Howeve the correct order is (more):

// declare namespace

namespace A

// then use something

using B


CEO vs COO

September 19th, 2011 No comments

You can probably rate the effectiveness of a CEO by the stack of papers on his desk. The larger the stack, the less he or she is probably operating as a CEO. The larger the stack, the more he or she is probably operating as a COO.

As I transitioned, over the years, from an entrepreneur who is operating a one or two-person company into someone who is operating a company employing several hundred people, it occurred to me that the size of the stack has progressively diminished.

I have always been somewhat retentive with respect to the configuration of my desk. Whether I was in college, law school, or even in my law or business office, I always maintained a stack of papers, which was my “In” basket, on the left-hand side of my desk.

If an action had not been generated, it simply sat there in the stack. If I took an action on it, I made the notes or dictated and passed it along. I might get that think back at some future time but so be it.

In the meantime, it was somebody else’s problem to act on.

Over the years, I watched the nature and status of that stack shift, not only based on my effectiveness but also based on how I was operating as a manager.

Regardless of whether I was a start-up entrepreneur, someone operating at a COO capacity, or someone operating at a CEO capacity I could always tell how effective I was based upon the size of the stack. The larger the stack, the less effective I was at running an actual organization. The smaller the stack, the more the reverse was true.

An entrepreneur’s responsibility is to do absolutely everything that needs to be done to get the job accomplished correctly. Therefore, the stack is immense. You are individually taking personal responsibility for everything to be done, right down to the last farthing of money in your bank account. It’s understandable that the stack is high, and it rightfully should be, because you simply do not have the resources to be able to hire people to delegate to, not only to monitor objectives but also to accomplish those objectives.

A COO operates in fundamentally the same way with one exception.

Whereas an entrepreneur is actually doing it himself or herself, a COO is still personally doing it through other people. The bottom line, however, is that the COO is responsible. Therefore, whether the job is ultimately acquitted correctly or not is, in the final analysis, the responsibility of the COO. The COO may do something himself or herself. The COO may choose to delegate it. But either way, the COO is responsible. Therefore, the stacks shrink, but it’s still there.

The CEO moves along that continuum. The CEO’s responsibilities are to operate through executive and management teams, not through operational teams. Therefore, what should be in front of the CEO are issues associated with performance commitments from his or her executive or management teams and external communications, which need to be either handled or farmed out. Otherwise, the entire output of the CEO’s desk is the intellectual property of the CEO: those things a CEO is thinking that he or she intends on transferring to the executive or management team.

The larger the stack on the CEO’s desk, the less effective the CEO’s relationship to the executive and management teams. The smaller the stack, the more effective.

Over the past years, I remember reading about executives in major cities such as New York, San Francisco, Los Angeles, and so forth, who literally have one or two pieces of paper on their desks. Nothing else! They are not working on any component of operations. They are working on the company’s present, through executives and managers, and on its future, represented by nothing other than a one or two-page synopsis sitting on their desks. Otherwise, their desks were clear. Cleaned. Pledged. Polished.

I wondered how that could be, but I understand it better now.

The more I have to operate as an entrepreneur or as a COO, the less I have the opportunity to operate as a CEO. And, if I am truly operating as a CEO, I continue to monitor operations on an exception basis through the management team, but I remove myself from operational components of the company. What I am spending my time on is sculpting how I want it to look based on what it looks like today. That might take 100 employees or 1,000 employees. But it probably takes no more than three or four items on my desk at any one time.

The transition from entrepreneur through COO to CEO has been simultaneously interesting, challenging, and agonizing…but, I wouldn’t trade the experience in a million years.

Original writing date: November 2002

(Source: http://www.ourlifeinbusiness.com/2008/02/ceo-vs-coo/)

String literal vs String object in Java

September 7th, 2011 No comments

If you’re a Java developer, you might have ever been in trouble distinguishing String literal and String object. I myself have had the trouble too. So I make a search on the internet for this topic and collect good articles for everyone to memorize.

Full topic: http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal

Question

what is difference between String str = new String(“abc”); and String str = “abc”;

Good answer

When you do this:

String str = "abc";

You are calling the intern() method on String. This method references an internal pool of ‘String’ objects. If the String you called intern() on already resides in the pool, then a reference to that String is assigned to str. If not, then the new String is placed in the pool, and a reference to it is then assigned to str.

Given the following code:

String str = "abc";
String str2 = "abc";
boolean identity = str == str2;

When you check for object identity by doing == (you are literally asking – do these two references point to the same object?), you get true.

However, you don’t need to intern() Strings. You can force the creation on a new Object on the Heap by doing this:

String str = new String("abc");
String str2 = new String("abc");
boolean identity = str == str2;

In this instance, str and str2 are references to different Objects, neither of which have been interned so that when you test for Object identity using ==, you will get false.

In terms of good coding practice – do not use == to check for String equality, use .equals() instead.

Method description of java.lang.String

intern

public String intern()
Returns a canonical representation for the string object.A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned. String literals are defined in §3.10.5 of the Java Language Specification

Returns:
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

Anh Linh wedding album service

August 24th, 2011 No comments

CSF firewall for your CPanel VPS and FTP issue

August 22nd, 2011 No comments

When you have a CPanel VPS, you may also want to have a way to manage firewall easily and effectively. I found that CSF is a good option here. It is free and has UI integration with Web Host Manager. Its features and performance are not so bad. It is recommended in many VPS forums.

http://configserver.com/cp/csf.html

Installation is straightforward: download the package, execute install command.

However after you secure your VPS with CSF, you may encounter following issue when you ftp to the server:

Command:    PASV
Response:    227 Entering Passive Mode (69,73,143,39,137,1)
Command:    MLSD
Error:    Connection timed out
Error:    Failed to retrieve directory listing

That means, your FTP client opens data connection in passive mode and tries to MLSD (list content of a given directory) on server, but it fails. The issue lies between CSF configuration and FTP server configuration: passive ports configured in FTP server are not opened in CSF firewall. So one way to fix is:

1. identify passive ports configured in FTP server

- check your /etc/pure-ftpd.conf (if you use Pure-FTP)

- find this line:

# Port range for passive connections replies. – for firewalling.
PassivePortRange 35000 36000

2. add these ports in CSF at TCP_IN entry

- restart CSF and test FTP again.

This solution can be derived from the point 13 in CSF readme content:

13. A note about FTP Connection Issues
######################################

It is important when using an SPI firewall to ensure FTP client applications
are configured to use Passive (PASV) mode connections to the server.

On servers running Monolithic kernels (e.g. VPS Virtuozzo/OpenVZ and custom
built kernels) ip_conntrack and ip_conntrack_ftp iptables kernel modules may
not be available or fully functional. If this happens, FTP passive mode (PASV)
won’t work. In such circumstances you will have to open a hole in your firewall
and configure the FTP server to use that same hole.

For example, with pure-ftpd you could add the port range 30000:35000 to TCP_IN
and add the following line to /etc/pure-ftpd.conf and then restart pure-ftpd:
PassivePortRange 30000 35000

For example, with proftpd you could add the port range 30000:35000 to TCP_IN
and add the following line to /etc/proftpd.conf and then restart proftpd:
PassivePorts 30000 35000

FTP over SSL/TLS will usually fail when using an SPI firewall. This is because
of the way the FTP protocol established a connection between client and server.
iptables fails to establish a related connection when using FTP over SSL
because the FTP control connection is encrypted and so cannot track the
relationship between the connection and the allocation of an ephemeral port.

If you need to use FTP over SSL, you will have to open up a passive port block
in both csf and your FTP server configuration (see above).

Perversely, this makes your firewall less secure, while trying to make FTP
connections more secure.

Hope this solution works for you.

Please share with me your feedback or another solution. Many thanks!

Some quick steps to secure your VPS

August 10th, 2011 1 comment

This article describes standard Security Best Practices for Linux servers and provides basic instructions for securing a virtual private server against most common attacks.

User Accounts

  • Observe the Password Security recommendations for your root account
  • Create a user account for any trusted users who should have access to the VPS – do not share your root login
  • Eliminate unnecessary user accounts and disable shell access for daemons
    1. Run cat /etc/passwd and identify unnecessary user accounts
    2. Remove unnecessary users with userdel <username>
    3. Disable interactive logins for daemon accounts by specifying /bin/false for the user’s shell

SSH Configuration

  • Change the SSH port
    1. Open your sshd_config file for editing
    2. Locate the Port directive
    3. Change the default SSH port – any port above the 1-1024 range is preferable (check theInternet Assigned Numbers Authority site for unassigned port numbers if you want to ensure no conflicts are encountered)
    4. Restart SSH and connect to your VPS using the new port
  • Restrict SSH users and hosts in sshd_config
    • Use the PermitRootLogin no directive to disable root logins over SSH (if you have created a user account for yourself and plan to use su to administer your VPS)
    • Use the AllowUsers directive to specify which user accounts may be used to log in
  • Additional Recommendations
    • Limit SSH access to trusted IPs only (iptables example):
      1. -A INPUT -p tcp -m tcp --dport XXXX --source x.x.x.x -j ACCEPT (where XXXX is the port SSH is listening on and x.x.x.x is the trusted source IP)
      2. Prior to closing the established SSH session, test the SSH access rule: Create an additional SSH session from the trusted source IP. Test a non-trusted IP as well. If the non-trusted IP is unable to connect and the trusted IP is allowed, the rule is working as intended.
    • Use the DenyHosts script to block malicious users (if restricting access to a single trusted IP is not practical)
    • Configure your VPS to use public key authentication instead of password authentication

Additional Linux Security Resources

See the Security category for security guides on the VPSLink Wiki.

Linux Distribution Security

If you have an active interest in securing your VPS, you should follow up with recommendations specific to your distribution and recommendations for any daemons or applications which you use.

Security Applications

Applications geared toward security are an invaluable asset – consider installing an auditing tool and an intrusion detection system to automate monitoring and test your system’s configuration.

  • Bastille – Security auditing and configuration tool
  • Samhain – File integrity checker and intrusion detection system
  • SentryTools – A host-level security suite used to protect against port scans, automate log file auditing, and detect suspicious login activity

(Source: http://wiki.vpslink.com/Security_Best_Practices)

Categories: Máy tính Tags: , , , ,

Instant web proxy on a Linux VPS server

August 10th, 2011 2 comments

If you are unable to access a website because your computer is behind a firewall, with a VPS server you can make an instant SOCKS proxy for you to bypass the firewall in few minutes. Such a useful guide that I’ve found out from the net. Enjoy!

Introduction

There are many situations which call for a higher level of security and privacy than the immediate network provides: having a SOCKS proxy at your disposal is often the quickest and most convenient solution.

If you have ever checked POP3 e-mail, accessed an account on an FTP server, or encountered a website which was blocked by the local network administrator, this guide will explain how to protect your passwords over the local network and maintain access to the sites you frequent, regardless of local restrictions.

This guide will explain how to configure your VPS to act as a proxy server and configure your Linux or Windows client software to use the SOCKS proxy.

Note: The VPSLink Acceptable Use Policy expressly prohibits the operation of a public proxy. Please limit user accounts to trusted users to ensure the security of your VPS.

VPS Configuration

No special configuration is required – your VPS will be running an SSH daemon by default.

Note: We strongly recommend that you review our Linux security best practices to change the port which SSH is listening on as a security precaution.

Client Configuration

Considerations:

  • Ensure that the port which will act as your local proxy port is not presently active or listening for connections
  • Despite common port restrictions, most networks will allow traffic over port 80 (HTTP) and port 443 (SSL) – because encrypted traffic is expected over port 443, this port makes an ideal local proxy port
  • Client software (web browsers, e-mail clients, chat clients) must be configured to use the SOCKS proxy and perform DNS lookups over the SOCKS proxy (if you wish to keep the domains which you browse private)

Linux

  1. Open a local console
  2. Enter the following command:

    ssh -p VPS_SSH_PORT -D LOCAL_PROXY_PORT USERNAME@VPS_IP_ADDRESS

    where:

    • VPS_SSH_PORT – The port on your VPS which is listening for SSH connections
    • LOCAL_PROXY_PORT – The port on your local machine which will accept SOCKS connections
    • USERNAME – The username for an account with SSH login capabilities on your VPS
    • VPS_IP_ADDRESS – The IP address of your VPS
  3. Log in with your user account password
  4. Open your client applications and enable proxy use on your local SOCKS proxy port

Windows

  1. Open the PuTTY SSH client
  2. Complete the following fields under the Session category:
    • Host Name (or IP Address) – Enter the IP address for your VPS
    • Port – Enter the port which the SSH daemon is listening on
  3. Navigate to the ConnectionSSHTunnels category
  4. Complete the following fields under the Tunnels category:
    • Source port – Enter the port on your local machine which will accept SOCKS connections
    • Destination – Enter the IP address for your VPS
    • Select the Dynamic radio button
  5. Click the Add button to add the source port association
  6. If you would like to save your SOCKS proxy settings:
    1. Navigate back to the Session category
    2. Enter a label for your settings in the Saved Sessions field
    3. Click the Save button
  7. Click the Open button to initiate a connection with your VPS
  8. Log in with your username and password
  9. Open your client applications and enable proxy use on your local SOCKS proxy port

Application Configuration

Keep in mind that you will need to have an open an SSH connection to your VPS in order to use application SOCKS proxy settings. If your local machine is no longer listening for connections or your connection to your VPS is interrupted, SOCKS-enabled applications will report that no connection exists.

FireFox

The FireFox browser can easily be configured to make use of a SOCKS proxy – additionally, the FoxyProxy FireFox extension allows for domain-specific proxying rules.

Use the following steps to modify your FireFox settings to route all browsing over your proxy:

  1. Open FireFox and select the Tools option from the menu bar
  2. Switch to the Advanced section and select the Network tab, then click the Settings button
  3. Select the Manual proxy configuration option
  4. Enter localhost in the SOCKS Host field and your LOCAL_PROXY_PORT in the correspondingPort field
  5. Browse to WhatIsMyIP.com to confirm that the IP address for your VPS appears

(Source: http://wiki.vpslink.com/Instant_SOCKS_Proxy_over_SSH)

Javascript Data Type Conversion

June 14th, 2011 No comments

Today I discover a pretty good page discussing data type conversion in javascript. I would like to include the content of the page here for my own reference. Thanks to author of the content, Jim Ley.
(Source: http://www.jibbering.com/faq/notes/type-conversion/)

Introduction

Javascript (ECMAScript) is a loosely typed language. That does not mean that it has no data types just that the value of a variable or a Javascript object property does not need to have a particular type of value assigned to it, or that it should always hold the same type of value. Javascript also freely type-converts values into a type suitable for (or required by) the context of their use.

Javascript being loosely typed and willing to type-convert still does not save the programmer from needing to think about the actual type of values that they are dealing with. A very common error in browser scripting, for example, is to read the value property of a form control into which the user is expected to type a number and then add that value to another number. Because the value properties of form controls are strings (even if the character sequence they contain represents a number) the attempt to add that string to a value, even if that value happens to be a number, results in the second value being type-converted into a string and concatenated to the end of the first string value from the from control.

That problem arises from the dual nature of the + operator used for both numeric addition and string concatenation. With which the nature of the operation performed is determined by the context, where only if both operands are numbers to start with will the + operator perform addition. Otherwise it converts all of its operands to strings and does concatenation.

The following discussion is illustrated with Javascript generated tables of values resulting from the conversion operations. The headers of those tables display the values as represented in the Javascript source code used rather than their internal representation. So, for example 123e-2 as a number was the character sequence typed into the source code, the interpreter reads that and generates the number value 1.23 from it for internal use. The various values used for the tests have been chosen to illustrate aspects of type converting, those aspects may not apply to all of the tables presented. However, all of the test values are included in all of the tables (except where no type converting occurs) for full comparison. The bodies of the tables list the results of the various type conversion operations.

If you are accepting/using this page’s CSS style suggestions the type of the values at various stages is illustrated by the colour of the text used. The following key shows those type/colour relationships, they are derived from the string values returned by the typeof operator (which returns "object" for the null type when in reality null is distinct from objects).

Key
string
number
boolean
object
function
null
undefined

The boolean values of results also have a coloured background to highlight true or false.

Converting to Boolean

When evaluating the expression of an if statement the Javascript interpreter will type-convert the result of that expression to boolean in order to make its decision. Also various operators internally type-convert their operands to boolean in order to determine what action to take. These include the logical operators like AND (&&), OR (||) and NOT (!). The NOT operator type-converts its operand to boolean and if that value is boolean true it returns false and if false it returns true. As the result of a NOT operation is a boolean value that is the inverse of the type-converted true-ness of its operand, two NOT operations together will return a boolean value that is equivalent to the result of type-converting the operand to boolean:-

var boolValue = !!x;

That technique has been used to generate the following tables.

An alternative method of generating a boolean value that represents the type-converted true-ness of a value is to pass that value to the Boolean constructor called as a function:-

var boolValue = Boolean(x);
Double NOT (!!col) : Numeric Values.
-1.6 -0 +0 1 1.6 8 16 16.8 123e-2 -Infinity +Infinity NaN
!!col true false false true true true true true true true true false

When numbers are converted to boolean, zero becomes false and all other numbers are true. With the excepting of the special numeric value NaN (Not a Number) which is used when another type is converted to a number but that conversion does not result in a meaningful number. NaN is always false. The values of positive and negative infinity, while not finite numbers, are non-zero numeric values and always type-convert to boolean true.

Double NOT (!!col) : String Values.
“”
(empty
string)
“-1.6″ “0″ “1″ “1.6″ “8″ “16″ “16.8″ “123e-2″ “010″
(Octal)
“0×10″
(Hex)
“0xFF”
(Hex)
“-010″ “-0×10″ “xx”
!!col false true true true true true true true true true true true true true true

Type conversion rules are even simpler for string to boolean conversion as all non-empty strings always become true and empty strings become false.

Double NOT (!!col) : Other Values
undefined null true false new Object() function(){
return;
}
!!col false false true false true true

For the other types, undefined and null are converted to false, boolean values are not converted and objects and functions are always true.

This is the most valuable aspect of type-converting to boolean as it allows a script to distinguish between properties in an environment that may be undefined or may refer to an object. Treating an undefined (or null) value as if it was an object will produce errors. So when there is a doubt (as there usually is where web browsers are concerned) then code can avoid generating errors by wrapping the code that wants to access an object in an if test. Supplying the suspect reference to the object as the expression. The expression will be type converted to boolean and result in false if the object does not exist and true if it does.

if(document.documentElement){
    scrollX = document.documentElement.scrollLeft;
}

The double NOT operation also allows the setting of boolean flags that can be used to indicate the presence of various objects:-

var hasDocEl = !!document.documentElement;
...
if(hasDocEl){
    scrollX = document.documentElement.scrollLeft;
}

Converting to String

As mentioned above, type conversion to a string most often results from the action of the + operator whenever one of its operators in not a number. The easiest way of getting the string that results from type-conversion is to concatenate a value to an empty string. That technique has been used to generate the following tables.

An alternative method of converting a value into a string is to pass it as an argument to the String constructor called as a function:-

var stringValue = String(x);
type-convert to string (“” + col) : Numeric Values.
-1.6 -0 +0 1 1.6 8 16 16.8 123e-2 -Infinity +Infinity NaN
“” + col -1.6 0 0 1 1.6 8 16 16.8 1.23 -Infinity Infinity NaN

Notice that the number generated from the source code 123e-2 has resulted in the string "1.23" because that is the string representation of the internal number created from the source code. However, Javascript’s internal number representations take the form of IEEE double precision floating point numbers and that means that they cannot represent all numbers with precision. The results of mathematical operations may only produce close approximations and when they are converted to strings the string represents the approximation and may be unexpected and undesirable. It is often necessary to use custom functions to generate string representations of numbers in an acceptable format, the type-conversion mechanism is rarely suited to generating numeric output intended for presentation.

type-convert to string (“” + col) : Other Values.
undefined null true false new Object() function(){
return;
}
“” + col undefined null true false [object Object]
function(){
  return;
}

When objects or functions are type-converted to strings their toString method is called. These default to Object.prototype.toString and Function.prototype.toString but may be overloaded with a function assigned to a “toString” property of the object/function. Type-converting a function to a string does not necessarily result in the function’s source code. The behaviour of Function.prototype.toString is implementation depended and varies quite a lot, as do the results from “host objects” and methods (the objects and methods provided by the environment, such as DOM elements).

Converting to Number

Converting values to numbers, especially strings to numbers, is an extremely common requirement and many methods can be used. Any mathematical operator except the concatenation/addition operator will force type-conversion. So conversion of a string to a number might entail performing a mathematical operation on the string representation of the number that would not affect the resulting number, such as subtracting zero or multiplying by one.

var numValue = stringValue - 0;
/* or */
var numValue = stringValue * 1;
/* or */
var numValue = stringValue / 1;

However, the unary + operator also type-converts its operand to a number and because it does not do any additional mathematical operations it is the fastest method for type-converting a string into a number.

Incidentally, the unary - (minus) operator also type-converts its operand (if necessary) in addition to subsequently negating its value.

var numValue = (+stringValue);

/* The preceding unary + expression has been parenthesised. That is
   unnecessary but is often felt to make the code easier to comprehend
   and make it clear which operations are being applied. Especially
   avoiding confusion with pre and post increment and addition
   operations. Compare:-

var n = anyNumVar++ + +stringVar + ++anotherNumVar;

  - with - 

var n = (anyNumVar++) + (+stringVar) + (++anotherNumVar);
                  ^^     ^              ^^
     (post increment) + (unary plus) + (pre increment)
*/

While unary + is the fastest method for converting a string to a number a final method is available that uses the Javascript type-conversion algorithms. The Number constructor can be called with the string value as its argument and its return value is a number representing the result of the type-conversion.

var numValue = Number(stringValue);

The Number constructor is the slowest of the type-converting methods but when speed is not an overriding consideration its use does produce the clearest source code.

The following tables show the results of type-conversion to a number using the unary + operator. Though all of the preceding alternative method produce the same results as they all use exactly the same algorithm to do the conversion.

type-convert to number (+col) : String Values.
“”
(empty
string)
“-1.6″ “0″ “1″ “1.6″ “8″ “16″ “16.8″ “123e-2″ “010″
(Octal)
“0×10″
(Hex)
“0xFF”
(Hex)
“-010″ “-0×10″ “xx”
+col 0 -1.6 0 1 1.6 8 16 16.8 1.23 10 16 255 -10 NaN NaN

The important considerations when converting strings to numbers with the type-converting methods is the results from strings that do not represent numbers. The empty string is converted into the number zero, depending on the application this can be harmless or disastrous, but it is important to be aware that it is going to happen. In other contexts strings that follow the Javascript format for octal number (leading zero) can be problematic but type conversion treats them as base 10 anyway. However, strings that follow the format for hexadecimal numbers (leading 0x or 0X) are read as hexadecimal. Strings that cannot be read as a number type-convert to NaN, which can be tested for with the isNaN function. Strings representing numbers in an exponential format ("123e-2") are understood along with leading minus signs.

type-convert to number (+col) : Other Values.
undefined null true false new Object() function(){
return;
}
+col NaN 0 1 0 NaN NaN

Objects and functions always type-convert to NaN numbers, as do undefined values but it is worth noting that null type-converts to zero. Probably because it is being type-converted to boolean first and then to number and, as is clear from the boolean results above, null would become boolean false which would then become numeric zero. There is almost no need to type convert these types of values into numbers. How they convert is only really relevant to a consideration of the accidental result of converting a value that is expected to be a string but actually turns out to be one of these (and/or performing an mathematical operation with one of these as an operand).

Parsing to Number

An alternative method of converting a string into a number is to use one of the global functions designed to parse a string and return a number. The parseFloat function accepts a string argument and returns a floating point number resulting from parsing that string. Non-string arguments are first type-converted to a string as described above.

The string parsing functions read the string character by character until they encounter a character that cannot be part of the number, at which point they stop and return a number based on the characters that they have seen that can be part of the number. This feature of their action can be usefully exploited, for example, given a string representing a CSS length value such as "34.5em" parseFloat would be able to ignore the "em" because those characters cannot be combined with the preceding set to produce a valid number. The returned number would be 34.5, the numeric part of the CSS string stripped of its units.

parseFloat

parseFloat(col) : String Values.
“”
(empty
string)
“-1.6″ “0″ “1″ “1.6″ “8″ “16″ “16.8″ “123e-2″ “010″
(Octal)
“0×10″
(Hex)
“0xFF”
(Hex)
“-010″ “-0×10″ “xx”
parseFloat(col) NaN -1.6 0 1 1.6 8 16 16.8 1.23 10 0 0 -10 0 NaN

With parseFloat empty strings return NaN along with strings that cannot be subject to numeric interpretation. The exponential format is understood and the leading zero in the octal format does not hinder the string’s interpretation as a decimal number. Hexadecimal strings are interpreted as the number zero because the following "x" cannot be interpreted as part of a number so parsing stops after the leading zero.

parseFloat(col) : Other Values.
undefined null true false new Object() function(){
return;
}
parseFloat(col) NaN NaN NaN NaN NaN NaN

Non-string values are first converted into a string that is employed by parseFloat. As that type-conversion to a string would not normally result in a string that could be interpreted as a number the result is NaN. Objects and functions may have custom toString methods that may return strings that could be interpreted as numbers but that would be an unusual requirement.

parseInt

The parseInt function works in a similar way to parseFloat except that it is trying to interpret its string argument into an integer and as a result recognises fewer character as possible candidates to be part of that number.

parseInt is occasionally used as a means of turning a floating point number into an integer. It is very ill suited to that task because if its argument is of numeric type it will first be converted into a string and then parsed as a number, very inefficient. This can produce very wrong results with numbers such as 2e-200, for which the next smaller integer is zero, but with which parseInt returns 2. Also, because of the number format used by javascript, numbers are often represented by near approximations. So, for example, 1/2 + 1/3 + 1/6 = 0.9999999999999999, which isn’t quite one and parseInt would return zero if asked to act on the result of the operation.

For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable, and for a desired result that can be expressed as a 32 bit signed integer the bitwise operation described below might also suit.

parseInt(col) : Numeric Values.
-1.6 -0 +0 1 1.6 8 16 16.8 123e-2 -Infinity +Infinity NaN
parseInt(col) -1 0 0 1 1 8 16 16 1 NaN NaN NaN

When it is acting on number the effect of the initial type-conversion of the argument to a string is evident in the results. Note that the value 123e-2 is internally the number 1.23 and that type converts into the string "1.23", so that entry in the table above might look odd but it is correct.

parseInt(col) : String Values.
“”
(empty
string)
“-1.6″ “0″ “1″ “1.6″ “8″ “16″ “16.8″ “123e-2″ “010″
(Octal)
“0×10″
(Hex)
“0xFF”
(Hex)
“-010″ “-0×10″ “xx”
parseInt(col) NaN -1 0 1 1 8 16 16 123 8 16 255 -8 -16 NaN

Strings in octal and hexadecimal number formats do represent integers and parseInt is capable of interpreting them in accordance with the rules for Javascript source code, even when they have leading minus signs.

parseInt(col) : Other Values.
undefined null true false new Object() function(){
return;
}
parseInt(col) NaN NaN NaN NaN NaN NaN

As parseInt type-converts its non-string arguments to strings it always produces the same results for boolean, null, undefined, object and function arguments as parseFloat (assuming objects and functions do not have custom toString methods).

parseInt with a radix argument

It is rarely desirable to allow parseInt to deduce the base in which the number is represented from the string as leading zeros are rarely intended to indicate data in octal format (particularly with user input). To deal with this problem parseInt recognises a second, radix, argument that can be used to specify the base in which the string is to be interpreted. Specifying a second argument of 10 causes parseInt to interpret the strings as only base 10.

parseInt(col, 10) : String Values.
“”
(empty
string)
“-1.6″ “0″ “1″ “1.6″ “8″ “16″ “16.8″ “123e-2″ “010″
(Octal)
“0×10″
(Hex)
“0xFF”
(Hex)
“-010″ “-0×10″ “xx”
parseInt(col, 10) NaN -1 0 1 1 8 16 16 123 10 0 0 -10 0 NaN

The string in octal format is now interpreted as base 10 and the hexadecimal strings can now only be zero as parsing has to stop when the "x" is encountered.

Number bases 2 to 36 can be used with parseInt. The following is base 16.

parseInt(col, 16) : String Values.
“”
(empty
string)
“-1.6″ “0″ “1″ “1.6″ “8″ “16″ “16.8″ “123e-2″ “010″
(Octal)
“0×10″
(Hex)
“0xFF”
(Hex)
“-010″ “-0×10″ “xx”
parseInt(col, 16) NaN -1 0 1 1 8 22 22 4670 16 16 255 -16 -16 NaN

The hexadecimal 0x format is recognised again with the base 16 interpretation.

Finally base 3:-

parseInt(col, 3) : Numeric Values.
-1.6 -0 +0 1 1.6 8 16 16.8 123e-2 -Infinity +Infinity NaN
parseInt(col, 3) -1 0 0 1 1 NaN 1 1 1 NaN NaN NaN

The consequences of the type-converting of numeric arguments to strings is evident again. The number 8 is coming out as NaN because the "8" character cannot be interpreted as base 3, leaving an empty sequence of acceptable characters and producing the same result as an empty string.

parseInt(col, 3) : String Values.
“”
(empty
string)
“-1.6″ “0″ “1″ “1.6″ “8″ “16″ “16.8″ “123e-2″ “010″
(Octal)
“0×10″
(Hex)
“0xFF”
(Hex)
“-010″ “-0×10″ “xx”
parseInt(col, 3) NaN -1 0 1 1 NaN 1 1 5 3 0 0 -3 0 NaN

ToInt32

ToInt32 is an internal function only available to the Javascript implementation and cannot be called directly from scripts in the way that parseInt can. It is a bit unusual to mention it in connection with converting Javascript values to numbers but it can be used in a limited set of circumstances. The bitwise operators such as bitwise OR (|) and bitwise AND (&) operate on numbers so they type-convert their operands to numbers. However, they also only operate on 32 bit signed integers so given the (possibly type-converted) numeric value they call the internal ToInt32 function with that number as its argument and use the returned value as their operand. That returned value is always a 32 bit signed integer.

The effect can be like parseInt combined with type-converting to numbers. While the result is limited in range to 32 bits, it is always numeric and never NaN, or ± Infinity.

As with using mathematical operators in operations that have no effect on the value of any resulting number it is possible to perform a bitwise operation that will not affect the value returned from the call to ToInt32. The tables below were generated using a bitwise OR zero operation.

ToInt32 (col|0) : Numeric Values.
-1.6 -0 +0 1 1.6 8 16 16.8 123e-2 -Infinity +Infinity NaN
col|0 -1 0 0 1 1 8 16 16 1 0 0 0

NaN and ±Infinity become zero and floating point values are truncated to integers.

ToInt32 (col|0) : String Values.
“”
(empty
string)
“-1.6″ “0″ “1″ “1.6″ “8″ “16″ “16.8″ “123e-2″ “010″
(Octal)
“0×10″
(Hex)
“0xFF”
(Hex)
“-010″ “-0×10″ “xx”
col|0 0 -1 0 1 1 8 16 16 1 10 16 255 -10 0 0

String values that would type-convert to NaN are returned as zero from ToInt32.

ToInt32 (col|0) : Other Values.
undefined null true false new Object() function(){
return;
}
col|0 0 0 1 0 0 0

Even undefined, objects and functions are converted to zero value numbers by this operation. Note though that boolean true is converted to the number 1.

Converting User Input

Most of the mechanisms for getting input from the user, <input type="text"> and prompt for example, provide their results in the form of strings. If the user is expected to input a number they still might enter anything (at the least they may just make a typo). If the string needs to be converted into a number for later operations one of the methods mentioned above can be chosen based on what best suits the nature of the input expected but some of the results generated with erroneous input may be difficult to detect and handle.

Prior to converting a string to a number it may be advantageous to use a Regular Expression to test the contents of the string to ensure that they conform to an acceptable format. That would serve to eliminate some of the string values that may otherwise suffer from the quirks of the string to number converting processes when applied to unexpected string values.

Regular expression examples

/^\d+$/                 //All-digit
/^\s*[-+]?\d+\s*$/      //Unbroken Signed integer & spaces
/^\d{1,5}$/             //1 to 5 digits
/^\d+\.\d\d$/           //Money
/^\d+(\.\d{2})$/        //Money
/^\d{1,3}(,\d\d\d)*\.\d\d$/  //comma-separated money - 12,432.57

       // optional comma-separated money - 12,432.57 or 12432.57
/^\d{1,3}(,\d\d\d)*\.\d\d$|^\d+\.\d\d$/