WeixiangYan/CodeTransOcean huggingface dataset:
Task: Self-describing numbers


C++: #include <iostream>
 

typedef unsigned long long bigint;
 

using namespace std;
 

class sdn
{
public:
    bool check( bigint n )
    {
	int cc = digitsCount( n );
	return compare( n, cc );
    }
 
    void displayAll( bigint s )
    {
	for( bigint y = 1; y < s; y++ )
	    if( check( y ) )
		cout << y << " is a Self-Describing Number." << endl;
    }
 
private:
    bool compare( bigint n, int cc )
    {
	bigint a;
	while( cc )
	{
	    cc--; a = n % 10;
	    if( dig[cc] != a ) return false;
	    n -= a; n /= 10;
	}
	return true;
    }
 
    int digitsCount( bigint n )
    {
	int cc = 0; bigint a;
	memset( dig, 0, sizeof( dig ) );
	while( n )
	{
	    a = n % 10; dig[a]++;
	    cc++ ; n -= a; n /= 10;
	}
	return cc;
    }
 
    int dig[10];
};

int main( int argc, char* argv[] )
{
    sdn s;
    s. displayAll( 1000000000000 );
    cout << endl << endl; system( "pause" );
 
    bigint n;
    while( true )
    {
	system( "cls" );
	cout << "Enter a positive whole number ( 0 to QUIT ): "; cin >> n;
	if( !n ) return 0;
	if( s.check( n ) ) cout << n << " is";
	else cout << n << " is NOT";
	cout << " a Self-Describing Number!" << endl << endl;
	system( "pause" );
    }
 
    return 0;
}





PHP: <?php

function is_describing($number) {
    foreach (str_split((int) $number) as $place => $value) {
        if (substr_count($number, $place) != $value) { 
            return false;
        }
    }    
    return true;
}

for ($i = 0; $i <= 50000000; $i += 10) {
    if (is_describing($i)) {
        echo $i . PHP_EOL;
    }
}

?>
Task: Modular inverse


C++: #include <iostream>
 
int mul_inv(int a, int b)
{
	int b0 = b, t, q;
	int x0 = 0, x1 = 1;
	if (b == 1) return 1;
	while (a > 1) {
		q = a / b;
		t = b, b = a % b, a = t;
		t = x0, x0 = x1 - q * x0, x1 = t;
	}
	if (x1 < 0) x1 += b0;
	return x1;
}
 
int main(void) {
	std::cout << mul_inv(42, 2017) << std::endl;
	return 0;
}





PHP: <?php
function invmod($a,$n){
        if ($n < 0) $n = -$n;
        if ($a < 0) $a = $n - (-$a % $n);
	$t = 0; $nt = 1; $r = $n; $nr = $a % $n;
	while ($nr != 0) {
		$quot= intval($r/$nr);
		$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;
		$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;
	}
	if ($r > 1) return -1;
	if ($t < 0) $t += $n;
	return $t;
}
	printf("%d\n", invmod(42, 2017));
?>
Task: Literals_Floating point


C++: #include <iostream>

int main()
{
  
  auto double1 = 2.5;

  
  auto float1 = 2.5f;

  
  auto longdouble1 = 2.5l;

  
  auto double2 = 2.5e-3;
  auto float2 = 2.5e3f;

  
  auto double3 = 0x1p4;
  auto float3 = 0xbeefp-8f;

  std::cout << "\ndouble1: " << double1;
  std::cout << "\nfloat1: " << float1;
  std::cout << "\nlongdouble1: " << longdouble1;
  std::cout << "\ndouble2: " << double2;
  std::cout << "\nfloat2: " << float2;
  std::cout << "\ndouble3: " << double3;
  std::cout << "\nfloat3: " << float3;
  std::cout << "\n";
}





PHP: .12
0.1234
1.2e3
7E-10
Task: Break OO privacy


C++: #include <iostream>

class CWidget; 

class CFactory
{
  friend class CWidget;
private:
  unsigned int m_uiCount;
public:
  CFactory();
  ~CFactory();
  CWidget* GetWidget();
};

class CWidget
{
private:
  CFactory& m_parent;

private:
  CWidget(); 
  CWidget(const CWidget&); 
  CWidget& operator=(const CWidget&); 
public:
  CWidget(CFactory& parent);
  ~CWidget();
};


CFactory::CFactory() : m_uiCount(0) {}
CFactory::~CFactory() {}


CWidget* CFactory::GetWidget()
{
  
  return new CWidget(*this);
}


CWidget::CWidget(CFactory& parent) : m_parent(parent)
{
  ++m_parent.m_uiCount;

  std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

CWidget::~CWidget()
{
  --m_parent.m_uiCount;

  std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

int main()
{
  CFactory factory;

  CWidget* pWidget1 = factory.GetWidget();
  CWidget* pWidget2 = factory.GetWidget();
  delete pWidget1;

  CWidget* pWidget3 = factory.GetWidget();
  delete pWidget3;
  delete pWidget2;
}





PHP: <?php
class SimpleClass {
    private $answer = "hello\"world\nforever :)";
}
 
$class = new SimpleClass;
ob_start();



var_export($class);
$class_content = ob_get_clean();
 
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);

$new_class = eval($class_content);
echo $new_class['answer'];
Task: Object serialization


C++: #include <string>
#include <fstream>
#include <boost/serialization/string.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/base_object.hpp>
#include <iostream>

class Employee {
public :   
   Employee( ) { }

   Employee ( const std::string &dep , const std::string &namen ) 
      : department( dep ) , name( namen ) {
	 my_id = count++ ;
      }

   std::string getName( ) const {
      return name ;
   }

   std::string getDepartment( ) const {
      return department ;
   }

   int getId( ) const {
      return my_id ;
   }

   void setDepartment( const std::string &dep ) {
      department.assign( dep ) ;
   }

   virtual void print( ) {
      std::cout << "Name: " << name << '\n' ;
      std::cout << "Id: " << my_id << '\n' ;
      std::cout << "Department: " << department << '\n' ;
   }

   virtual ~Employee( ) { } 
   static int count ;
private :
   std::string name ;
   std::string department ;
   int my_id ;
   friend class boost::serialization::access ;

   template <class Archive>
      void serialize( Archive &ar, const unsigned int version ) {
	 ar & my_id ;
	 ar & name ;
	 ar & department ;
      }

} ;

class Worker : public Employee {
public :
   Worker( const std::string & dep, const std::string &namen ,
	 double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }

   Worker( ) { }

   double getSalary( ) {
      return salary ;
   }

   void setSalary( double pay ) {
      if ( pay > 0 ) 
	 salary = pay ;
   }
   
   virtual void print( ) {
      Employee::print( ) ;
      std::cout << "wage per hour: " << salary << '\n' ;
   }
private :
   double salary ;
   friend class boost::serialization::access ;
   template <class Archive>
      void serialize ( Archive & ar, const unsigned int version ) {
	 ar & boost::serialization::base_object<Employee>( *this ) ;
	 ar & salary ;
      }
} ;
  
int Employee::count = 0 ;

int main( ) {
   std::ofstream storefile( "/home/ulrich/objects.dat"  ) ; 
   const Employee emp1( "maintenance" , "Fritz Schmalstieg"  ) ;
   const Employee emp2( "maintenance" , "John Berry" ) ;
   const Employee emp3( "repair" , "Pawel Lichatschow" ) ;
   const Employee emp4( "IT" , "Marian Niculescu" ) ;
   const Worker worker1( "maintenance" , "Laurent Le Chef" , 20 ) ;
   const Worker worker2 ( "IT" , "Srinivan Taraman" , 55.35 ) ;
   boost::archive::text_oarchive oar ( storefile ) ;
   oar << emp1 ; 
   oar << emp2 ;
   oar << emp3 ;
   oar << emp4 ;
   oar << worker1 ;
   oar << worker2 ;
   storefile.close( ) ;
   std::cout << "Reading out the data again\n" ;
   Employee e1 , e2 , e3 , e4 ; 
   Worker w1, w2 ; 
   std::ifstream sourcefile( "/home/ulrich/objects.dat"  ) ;
   boost::archive::text_iarchive iar( sourcefile ) ;
   iar >> e1 >> e2 >> e3 >> e4 ; 
   iar >> w1 >> w2 ;
   sourcefile.close( ) ;
   std::cout << "And here are the data after deserialization!( abridged):\n" ;
   e1.print( ) ;
   e3.print( ) ;
   w2.print( ) ;
   return 0 ;
}





PHP: $myObj = new Object();
$serializedObj = serialize($myObj);
Task: Long year


C++: #include <stdio.h>
#include <math.h>



int p(int year) {
	return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;
}

int is_long_year(int year) {
	return p(year) == 4 || p(year - 1) == 3;
}

void print_long_years(int from, int to) {
	for (int year = from; year <= to; ++year) {
		if (is_long_year(year)) {
			printf("%d ", year);
		}
	}
}

int main() {

	printf("Long (53 week) years between 1800 and 2100\n\n");
	print_long_years(1800, 2100);
	printf("\n");
	return 0;
}





PHP: function isLongYear($year) {
  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));
}

for ($y=1995; $y<=2045; ++$y) {
  if (isLongYear($y)) {
    printf("%s\n", $y);
  }
}
Task: Associative array_Merging


C++: #include <iostream>
#include <string>
#include <map>

template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
    map_type result(update);
    result.insert(original.begin(), original.end());
    return result;
}

int main() {
    typedef std::map<std::string, std::string> map;
    map original{
        {"name", "Rocket Skates"},
        {"price", "12.75"},
        {"color", "yellow"}
    };
    map update{
        {"price", "15.25"},
        {"color", "red"},
        {"year", "1974"}
    };
    map merged(merge(original, update));
    for (auto&& i : merged)
        std::cout << "key: " << i.first << ", value: " << i.second << '\n';
    return 0;
}





PHP: <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);

$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
Task: Associative array_Iteration


C++: #include <iostream>
#include <map>
#include <string>

int main() {
  std::map<std::string, int> dict {
    {"One", 1},
    {"Two", 2},
    {"Three", 7}
  };

  dict["Three"] = 3;

  std::cout << "One: " << dict["One"] << std::endl;
  std::cout << "Key/Value pairs: " << std::endl;
  for(auto& kv: dict) {
    std::cout << "  " << kv.first << ": " << kv.second << std::endl;
  }

  return 0;
}





PHP: <?php
$pairs = array( "hello" => 1,
		"world" => 2,
		"!"     => 3 );

foreach($pairs as $k => $v) {
  echo "(k,v) = ($k, $v)\n";
}

foreach(array_keys($pairs) as $key) {
  echo "key = $key, value = $pairs[$key]\n";
}

foreach($pairs as $value) {
  echo "values = $value\n";
}
?>
Task: Here document


C++: #include <iostream> 

int main()
{
  std::cout <<
R"EOF(  A  raw  string  begins  with  R,  then a double-quote ("),  then an optional
identifier (here I've used "EOF"),  then an opening parenthesis ('(').  If you
use  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot
contain a space,  either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.

  It  ends with a closing parenthesis (')'),  the identifer (if you used one),
and a double-quote.

  All  characters are okay in a raw string,  no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}





PHP: $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
Task: Hash join


C++: #include <iostream>
#include <string>
#include <vector>
#include <unordered_map>

using tab_t = std::vector<std::vector<std::string>>;
tab_t tab1 {

  {"27", "Jonah"}
, {"18", "Alan"}
, {"28", "Glory"}
, {"18", "Popeye"}
, {"28", "Alan"}
};

tab_t tab2 {

  {"Jonah", "Whales"}
, {"Jonah", "Spiders"}
, {"Alan", "Ghosts"}
, {"Alan", "Zombies"}
, {"Glory", "Buffy"}
};

std::ostream& operator<<(std::ostream& o, const tab_t& t) {
  for(size_t i = 0; i < t.size(); ++i) {
    o << i << ":";
    for(const auto& e : t[i]) 
      o << '\t' << e;
    o << std::endl;
  }
  return o;
}

tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {
  std::unordered_multimap<std::string, size_t> hashmap;
  
  for(size_t i = 0; i < a.size(); ++i) {
    hashmap.insert(std::make_pair(a[i][columna], i));
  }
  
  tab_t result;
  for(size_t i = 0; i < b.size(); ++i) {
    auto range = hashmap.equal_range(b[i][columnb]);
    for(auto it = range.first; it != range.second; ++it) {
      tab_t::value_type row;
      row.insert(row.end() , a[it->second].begin() , a[it->second].end());
      row.insert(row.end() , b[i].begin()          , b[i].end());
      result.push_back(std::move(row));
    }
  }
  return result;
}

int main(int argc, char const *argv[])
{
  using namespace std;
  int ret = 0;
  cout << "Table A: "       << endl << tab1 << endl;
  cout << "Table B: "       << endl << tab2 << endl;
  auto tab3 = Join(tab1, 1, tab2, 0);
  cout << "Joined tables: " << endl << tab3 << endl;
  return ret;
}





PHP: <?php
function hashJoin($table1, $index1, $table2, $index2) {

    foreach ($table1 as $s)
        $h[$s[$index1]][] = $s;

    foreach ($table2 as $r)
    	foreach ($h[$r[$index2]] as $s)
	    $result[] = array($s, $r);
    return $result;
}

$table1 = array(array(27, "Jonah"),
           array(18, "Alan"),
           array(28, "Glory"),
           array(18, "Popeye"),
           array(28, "Alan"));
$table2 = array(array("Jonah", "Whales"),
           array("Jonah", "Spiders"),
           array("Alan", "Ghosts"),
           array("Alan", "Zombies"),
           array("Glory", "Buffy"),
           array("Bob", "foo"));

foreach (hashJoin($table1, 1, $table2, 0) as $row)
    print_r($row);
?>
Task: Respond to an unknown method call


C++: class animal {
public:
  virtual void bark() 
  {
    throw "implement me: do not know how to bark";
  }
};

class elephant : public animal 
{
};

int main()
{
  elephant e;
  e.bark();  
}





PHP: <?php
class Example {
  function foo() {
    echo "this is foo\n";
  }
  function bar() {
    echo "this is bar\n";
  }
  function __call($name, $args) {
    echo "tried to handle unknown method $name\n";
    if ($args)
      echo "it had arguments: ", implode(', ', $args), "\n";
  }
}

$example = new Example();

$example->foo();        // prints "this is foo"
$example->bar();        // prints "this is bar"
$example->grill();      // prints "tried to handle unknown method grill"
$example->ding("dong"); // prints "tried to handle unknown method ding"

?>
Task: Inheritance_Single


C++: class Animal
{
  
};

class Dog: public Animal
{
  
};

class Lab: public Dog
{
  
};

class Collie: public Dog
{
  
};

class Cat: public Animal
{
  
};





PHP: class Animal {

}

class Dog extends Animal {

}

class Cat extends Animal {

}

class Lab extends Dog {

}

class Collie extends Dog {

}
Task: Associative array_Creation


C++: #include <map>





PHP: $array = array();
$array = []; // Simpler form of array initialization
$array['foo'] = 'bar';
$array['bar'] = 'foo';

echo($array['foo']); // bar
echo($array['moo']); // Undefined index

$array2 = array('fruit' => 'apple',
                'price' => 12.96,
                'colour' => 'green');

$array2 = ['fruit' => 'apple',
                'price' => 12.96,
                'colour' => 'green'];

echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null
Task: Polymorphism


C++: #include <cstdio>
#include <cstdlib>

class Point {
protected:
    int x, y;

public:
    Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}
    Point(const Point &p) : x(p.x), y(p.y) {}
    virtual ~Point() {}
    const Point& operator=(const Point &p) {
        if (this != &p) {
            x = p.x;
            y = p.y;
        }
        return *this;
    }
    int getX() { return x; }
    int getY() { return y; }
    void setX(int x0) { x = x0; }
    void setY(int y0) { y = y0; }
    virtual void print() { printf("Point\n"); }
};

class Circle: public Point {
private:
    int r;

public:
    Circle(Point p, int r0 = 0) : Point(p), r(r0) {}
    Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}
    virtual ~Circle() {}
    const Circle& operator=(const Circle &c) {
        if (this != &c) {
            x = c.x;
            y = c.y;
            r = c.r;
        }
        return *this;
    }
    int getR() { return r; }
    void setR(int r0) { r = r0; }
    virtual void print() { printf("Circle\n"); }
};

int main() {
    Point *p = new Point();
    Point *c = new Circle();
    p->print();
    c->print();
    delete p;
    delete c;

    return EXIT_SUCCESS;
}





PHP: class Point
{
  protected $_x;

  protected $_y;
  
  public function __construct()
  {
    switch( func_num_args() )
    {
      case 1:
        $point = func_get_arg( 0 );
        $this->setFromPoint( $point );
        break;
      case 2:
        $x = func_get_arg( 0 );
        $y = func_get_arg( 1 );
        $this->setX( $x );
        $this->setY( $y );
        break;
      default:
        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );
    }
  }
  
  public function setFromPoint( Point $point )
  {
    $this->setX( $point->getX() );
    $this->setY( $point->getY() );
  }
  
  public function getX()
  {
    return $this->_x;
  }
  
  public function setX( $x )
  {
    if( !is_numeric( $x ) )
    {
      throw new InvalidArgumentException( 'expecting numeric value' );
    }
    
    $this->_x = (float) $x;
  }
  
  public function getY()
  {
    return $this->_y;
  }
  
  public function setY( $y )
  {
    if( !is_numeric( $y ) )
    {
      throw new InvalidArgumentException( 'expecting numeric value' );
    }
    
    $this->_y = (float) $y;
  }
  
  public function output()
  {
    echo $this->__toString();
  }
  
  public function __toString()
  {
    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';
  }
}
Task: Variables


C++: int a;





PHP: <?php





# NULL typed variable
$null = NULL;				var_dump($null);	// output: null

# defining a boolean
$boolean = true;			var_dump($boolean);	// output: boolean true
$boolean = false;			var_dump($boolean);	// output: boolean false


# bool and boolean is the same
$boolean = (bool)1;			var_dump($boolean);	// output: boolean true
$boolean = (boolean)1;			var_dump($boolean);	// output: boolean true

$boolean = (bool)0;			var_dump($boolean);	// output: boolean false
$boolean = (boolean)0;			var_dump($boolean);	// output: boolean false

# defining an integer
$int = 0;				var_dump($int);		// output: int 0

# defining a float,
$float = 0.01;				var_dump($float);	// output: float 0.01

# which is also identical to "real" and "double"
var_dump((double)$float);					// output: float 0.01
var_dump((real)$float);						// output: float 0.01

# casting back to int (auto flooring the value)
var_dump((int)$float);						// output: int 0
var_dump((int)($float+1));					// output: int 1
var_dump((int)($float+1.9));					// output: int 1

# defining a string
$string = 'string';
var_dump($string);						// output: string 'string' (length=6)

# referencing a variable (there are no pointers in PHP).
$another_string = &$string;
var_dump($another_string);


$string = "I'm the same string!";
var_dump($another_string);

# "deleting" a variable from memory
unset($another_string);

$string = 'string';

$parsed_string = "This is a $string";
var_dump($parsed_string);

$parsed_string .= " with another {$string}";
var_dump($parsed_string);


# with string parsing
$heredoc = <<<HEREDOC
This is the content of \$string: {$string}
HEREDOC;
var_dump($heredoc);


# without string parsing (notice the single quotes surrounding NOWDOC)
$nowdoc = <<<'NOWDOC'
This is the content of \$string: {$string}
NOWDOC;
var_dump($nowdoc);


# as of PHP5, defining an object typed stdClass => standard class
$stdObject = new stdClass();	var_dump($stdObject);

# defining an object typed Foo
class Foo {}
$foo = new Foo();		var_dump($foo);

# defining an empty array
$array = array();		var_dump($array);



$assoc = array(
	0 => $int,
	'integer' => $int,
	1 => $float,
	'float' => $float,
	2 => $string,
	'string' => $string,
	3 => NULL, // <=== key 3 is NULL
	3, // <=== this is a value, not a key (key is 4)
	5 => $stdObject,
	'Foo' => $foo,
);
var_dump($assoc);




















function a_function()
{
	# not reachable
	var_dump(isset($foo));				// output: boolean false

	global $foo;
	# "global" (reachable) inside a_function()'s scope
	var_dump(isset($foo));				// output: boolean true
}

a_function();
Task: Monads_Writer monad


C++: #include <cmath>
#include <iostream>
#include <string>

using namespace std;


struct LoggingMonad
{
    double Value;
    string Log;
};


auto operator>>(const LoggingMonad& monad, auto f)
{
    auto result = f(monad.Value);
    return LoggingMonad{result.Value, monad.Log + "\n" + result.Log};
}


auto Root = [](double x){ return sqrt(x); };
auto AddOne = [](double x){ return x + 1; };
auto Half = [](double x){ return x / 2.0; };


auto MakeWriter = [](auto f, string message)
{
    return [=](double x){return LoggingMonad(f(x), message);};
};


auto writerRoot = MakeWriter(Root, "Taking square root");
auto writerAddOne = MakeWriter(AddOne, "Adding 1");
auto writerHalf = MakeWriter(Half, "Dividing by 2");


int main()
{
    
    auto result = LoggingMonad{5, "Starting with 5"} >> writerRoot >> writerAddOne >> writerHalf;
    cout << result.Log << "\nResult: " << result.Value;
}





PHP: class WriterMonad {

	
	private $value;
	
	private $logs;

	private function __construct($value, array $logs = []) {
		$this->value = $value;
		$this->logs = $logs;
	}

	public static function unit($value, string $log): WriterMonad {
		return new WriterMonad($value, ["{$log}: {$value}"]);
	}

	public function bind(callable $mapper): WriterMonad  {
		$mapped = $mapper($this->value);
		assert($mapped instanceof WriterMonad);
		return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);
	}

	public function value() {
		return $this->value;
	}

	public function logs(): array {
		return $this->logs;
	}
}

$root = fn(float $i): float => sqrt($i);
$addOne = fn(float $i): float => $i + 1;
$half = fn(float $i): float => $i / 2;

$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);

$result = WriterMonad::unit(5, "Initial value")
	->bind($m($root, "square root"))
	->bind($m($addOne, "add one"))
	->bind($m($half, "half"));

print "The Golden Ratio is: {$result->value()}\n";
print join("\n", $result->logs());
Task: FTP





Java: import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPconn {

    public static void main(String[] args) throws IOException {
        String server = "ftp.hq.nasa.gov";
        int port = 21;
        String user = "anonymous";
        String pass = "ftptest@example.com";

        OutputStream output = null;

        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(server, port);

            serverReply(ftpClient);

            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("Failure. Server reply code: " + replyCode);
                return;
            }

            serverReply(ftpClient);

            if (!ftpClient.login(user, pass)) {
                System.out.println("Could not login to the server.");
                return;
            }

            String dir = "pub/issoutreach/Living in Space Stories (MP3 Files)/";
            if (!ftpClient.changeWorkingDirectory(dir)) {
                System.out.println("Change directory failed.");
                return;
            }

            ftpClient.enterLocalPassiveMode();

            for (FTPFile file : ftpClient.listFiles())
                System.out.println(file);

            String filename = "Can People go to Mars.mp3";
            output = new FileOutputStream(filename);

            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (!ftpClient.retrieveFile(filename, output)) {
                System.out.println("Retrieving file failed");
                return;
            }

            serverReply(ftpClient);

            ftpClient.logout();

        } finally {
            if (output != null)
                output.close();
        }
    }

    private static void serverReply(FTPClient ftpClient) {
        for (String reply : ftpClient.getReplyStrings()) {
            System.out.println(reply);
        }
    }
}



Python: from ftplib import FTP
ftp = FTP('kernel.org')
ftp.login()
ftp.cwd('/pub/linux/kernel')
ftp.set_pasv(True) 
print ftp.retrlines('LIST')
print ftp.retrbinary('RETR README', open('README', 'wb').write)
ftp.quit()