Detecting and Learning Out-of-Distribution Data in the Open world: Algorithm and Theory