WeixiangYan/CodeTransOcean huggingface dataset:
Task: Bitmap_Bézier curves_Cubic

C: void cubic_bezier(
       	image img,
        unsigned int x1, unsigned int y1,
        unsigned int x2, unsigned int y2,
        unsigned int x3, unsigned int y3,
        unsigned int x4, unsigned int y4,
        color_component r,
        color_component g,
        color_component b );






PHP: <?

$image = imagecreate(200, 200);

imagecolorallocate($image, 255, 255, 255);
$color = imagecolorallocate($image, 255, 0, 0);
cubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);
imagepng($image);

function cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {
	$pts = array();

	for($i = 0; $i <= $n; $i++) {
		$t = $i / $n;
		$t1 = 1 - $t;
		$a = pow($t1, 3);
		$b = 3 * $t * pow($t1, 2);
		$c = 3 * pow($t, 2) * $t1;
		$d = pow($t, 3);

		$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);
		$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);
		$pts[$i] = array($x, $y);
	}

	for($i = 0; $i < $n; $i++) {
		imageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);
	}
}
Task: Active Directory_Connect

C: #include <ldap.h>
...
char *name, *password;
...
LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);
... after done with it...
ldap_unbind(ld);






PHP: <?php
$ldap = ldap_connect($hostname, $port);
$success = ldap_bind($ldap, $username, $password);
Task: Update a configuration file

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define strcomp(X, Y) strcasecmp(X, Y)

struct option
{ const char *name, *value; 
  int flag; };


struct option updlist[] =
{ { "NEEDSPEELING", NULL },
  { "SEEDSREMOVED", "" },
  { "NUMBEROFBANANAS", "1024" },
  { "NUMBEROFSTRAWBERRIES", "62000" },
  { NULL, NULL } };

int output_opt(FILE *to, struct option *opt)
{ if (opt->value == NULL)
    return fprintf(to, "; %s\n", opt->name);
  else if (opt->value[0] == 0)
    return fprintf(to, "%s\n", opt->name);
  else 
    return fprintf(to, "%s %s\n", opt->name, opt->value); }

int update(FILE *from, FILE *to, struct option *updlist) 
{ char line_buf[256], opt_name[128];
  int i;
  for (;;)
  { size_t len, space_span, span_to_hash;
    if (fgets(line_buf, sizeof line_buf, from) == NULL)
      break;
    len = strlen(line_buf);
    space_span = strspn(line_buf, "\t ");
    span_to_hash = strcspn(line_buf, "#");
    if (space_span == span_to_hash)
      goto line_out;
    if (space_span == len)
      goto line_out;
    if ((sscanf(line_buf, "; %127s", opt_name) == 1) ||
        (sscanf(line_buf, "%127s", opt_name) == 1))
    { int flag = 0;
      for (i = 0; updlist[i].name; i++)
      { if (strcomp(updlist[i].name, opt_name) == 0)
        { if (output_opt(to, &updlist[i]) < 0)
            return -1;
          updlist[i].flag = 1;
          flag = 1; } }
      if (flag == 0)
        goto line_out; }
    else
  line_out: 
      if (fprintf(to, "%s", line_buf) < 0)
        return -1;
    continue; }
  { for (i = 0; updlist[i].name; i++)
    { if (!updlist[i].flag)
        if (output_opt(to, &updlist[i]) < 0)
          return -1; } }
  return feof(from) ? 0 : -1; }

int main(void)
{ if (update(stdin, stdout, updlist) < 0)
  { fprintf(stderr, "failed\n");
    return (EXIT_FAILURE); }
  return 0; }






PHP: <?php

$conf = file_get_contents('update-conf-file.txt');

$conf = preg_replace('/^(needspeeling)(|\s*\S*)$/mi', '; $1', $conf);

$conf = preg_replace('/^;?\s*(seedsremoved)/mi', '$1', $conf);

$conf = preg_replace('/^(numberofbananas)(|\s*\S*)$/mi', '$1 1024', $conf);

if (preg_match('/^;?\s*(numberofstrawberries)/mi', $conf, $matches)) {
    $conf = preg_replace('/^(numberofstrawberries)(|\s*\S*)$/mi', '$1 62000', $conf);
} else {
    $conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;
}

echo $conf;
Task: Variables

C: int j;






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: Primality by trial division


C++: #include <cmath>

bool is_prime(unsigned int n)
{
    if (n <= 1)
        return false;
    if (n == 2)
        return true;
    for (unsigned int i = 2; i <= sqrt(n); ++i)
        if (n % i == 0)
            return false;
    return true;
}





PHP: <?php
function prime($a) {
  if (($a % 2 == 0 && $a != 2) || $a < 2)
    return false;
  $limit = sqrt($a);
  for ($i = 2; $i <= $limit; $i++)
    if ($a % $i == 0)
      return false;
  return true;
}

foreach (range(1, 100) as $x)
  if (prime($x)) echo "$x\n";

?>
Task: Evaluate binomial coefficients


C++: double Factorial(double nValue)
   {
       double result = nValue;
       double result_next;
       double pc = nValue;
       do
       {
           result_next = result*(pc-1);
           result = result_next;
           pc--;
       }while(pc>2);
       nValue = result;
       return nValue;
   }

double binomialCoefficient(double n, double k)
   {
       if (abs(n - k) < 1e-7 || k  < 1e-7) return 1.0;
       if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;
       return Factorial(n) /(Factorial(k)*Factorial((n - k)));
   }





PHP: <?php
$n=5;
$k=3;
function factorial($val){
    for($f=2;$val-1>1;$f*=$val--);
    return $f;
}
$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));
echo $binomial_coefficient;
?>
Task: Collections


C++: int a[5]; 
a[0] = 1; 

int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; 

#include <string>
std::string strings[4]; 
                        





PHP: <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
Task: Bitmap_Write a PPM file


C++: #include <fstream>

int main() {
    constexpr auto dimx = 800u, dimy = 800u;

    std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary);
    ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n";

    for (auto j = 0u; j < dimy; ++j)
        for (auto i = 0u; i < dimx; ++i)
            ofs << static_cast<char>(i % 256) 
                << static_cast<char>(j % 256)
                << static_cast<char>((i * j) % 256);
}





PHP: class Bitmap {
  public $data;
  public $w;
  public $h;
  public function __construct($w = 16, $h = 16){
    $white = array_fill(0, $w, array(255,255,255));
    $this->data = array_fill(0, $h, $white);
    $this->w = $w;
    $this->h = $h;
  }

  public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
    if (is_null($w)) $w = $this->w;
    if (is_null($h)) $h = $this->h;
    $w += $x;
    $h += $y;
    for ($i = $y; $i < $h; $i++){
      for ($j = $x; $j < $w; $j++){
        $this->setPixel($j, $i, $color);
      }
    }
  }
  public function setPixel($x, $y, $color = array(0,0,0)){
    if ($x >= $this->w) return false;
    if ($x < 0) return false;
    if ($y >= $this->h) return false;
    if ($y < 0) return false;
    $this->data[$y][$x] = $color;
  }
  public function getPixel($x, $y){
    return $this->data[$y][$x];
  }
  public function writeP6($filename){
    $fh = fopen($filename, 'w');
    if (!$fh) return false;
    fputs($fh, "P6 {$this->w} {$this->h} 255\n");
    foreach ($this->data as $row){
      foreach($row as $pixel){
        fputs($fh, pack('C', $pixel[0]));
        fputs($fh, pack('C', $pixel[1]));
        fputs($fh, pack('C', $pixel[2]));
      }
    }
    fclose($fh);
  }
}

$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
Task: Delete a file


C++: #include <cstdio>
#include <direct.h>

int main() {
	remove( "input.txt" );
	remove( "/input.txt" );
	_rmdir( "docs" );
	_rmdir( "/docs" );

	return 0;
}





PHP: <?php
unlink('input.txt');
unlink('/input.txt');
rmdir('docs');
rmdir('/docs');
?>
Task: String interpolation (included)


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

int main( ) {
   std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) ,
      replacement ( "little" ) ;
   std::string newString = original.replace( original.find( "X" ) ,
	 toBeReplaced.length( ) , replacement ) ;
   std::cout << "String after replacement: " << newString << " \n" ;
   return 0 ;
}





PHP: <?php
$extra = 'little';
echo "Mary had a $extra lamb.\n";
printf("Mary had a %s lamb.\n", $extra);
?>
Task: Sorting algorithms_Patience sort


C++: #include <iostream>
#include <vector>
#include <stack>
#include <iterator>
#include <algorithm>
#include <cassert>

template <class E>
struct pile_less {
  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {
    return pile1.top() < pile2.top();
  }
};

template <class E>
struct pile_greater {
  bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {
    return pile1.top() > pile2.top();
  }
};


template <class Iterator>
void patience_sort(Iterator first, Iterator last) {
  typedef typename std::iterator_traits<Iterator>::value_type E;
  typedef std::stack<E> Pile;

  std::vector<Pile> piles;
  
  for (Iterator it = first; it != last; it++) {
    E& x = *it;
    Pile newPile;
    newPile.push(x);
    typename std::vector<Pile>::iterator i =
      std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>());
    if (i != piles.end())
      i->push(x);
    else
      piles.push_back(newPile);
  }

  
  
  std::make_heap(piles.begin(), piles.end(), pile_greater<E>());
  for (Iterator it = first; it != last; it++) {
    std::pop_heap(piles.begin(), piles.end(), pile_greater<E>());
    Pile &smallPile = piles.back();
    *it = smallPile.top();
    smallPile.pop();
    if (smallPile.empty())
      piles.pop_back();
    else
      std::push_heap(piles.begin(), piles.end(), pile_greater<E>());
  }
  assert(piles.empty());
}

int main() {
  int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1};
  patience_sort(a, a+sizeof(a)/sizeof(*a));
  std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, ", "));
  std::cout << std::endl;
  return 0;
}





PHP: <?php
class PilesHeap extends SplMinHeap {
    public function compare($pile1, $pile2) {
        return parent::compare($pile1->top(), $pile2->top());
    }
}

function patience_sort(&$n) {
    $piles = array();

    foreach ($n as $x) {

        $low = 0; $high = count($piles)-1;
        while ($low <= $high) {
            $mid = (int)(($low + $high) / 2);
            if ($piles[$mid]->top() >= $x)
                $high = $mid - 1;
            else
                $low = $mid + 1;
        }
        $i = $low;
        if ($i == count($piles))
            $piles[] = new SplStack();
        $piles[$i]->push($x);
    }

    $heap = new PilesHeap();
    foreach ($piles as $pile)
        $heap->insert($pile);
    for ($c = 0; $c < count($n); $c++) {
        $smallPile = $heap->extract();
        $n[$c] = $smallPile->pop();
        if (!$smallPile->isEmpty())
        $heap->insert($smallPile);
    }
    assert($heap->isEmpty());
}

$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);
patience_sort($a);
print_r($a);
?>
Task: Count occurrences of a substring


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


int countSubstring(const std::string& str, const std::string& sub)
{
    if (sub.length() == 0) return 0;
    int count = 0;
    for (size_t offset = str.find(sub); offset != std::string::npos;
	 offset = str.find(sub, offset + sub.length()))
    {
        ++count;
    }
    return count;
}

int main()
{
    std::cout << countSubstring("the three truths", "th")    << '\n';
    std::cout << countSubstring("ababababab", "abab")        << '\n';
    std::cout << countSubstring("abaabba*bbaba*bbab", "a*b") << '\n';

    return 0;
}





PHP: <?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
Task: Take notes on the command line


C++: #include <fstream>
#include <iostream>
#include <ctime>
using namespace std;

#define note_file "NOTES.TXT"

int main(int argc, char **argv)
{
	if(argc>1)
	{
		ofstream Notes(note_file, ios::app);
		time_t timer = time(NULL);
		if(Notes.is_open())
		{
			Notes << asctime(localtime(&timer)) << '\t';
			for(int i=1;i<argc;i++)
				Notes << argv[i] << ' ';
			Notes << endl;
			Notes.close();
		}
	}
	else
	{
		ifstream Notes(note_file, ios::in);
		string line;
		if(Notes.is_open())
		{
			while(!Notes.eof())
			{
				getline(Notes, line);
				cout << line << endl;
			}
			Notes.close();
		}
	}
}





PHP: #!/usr/bin/php
<?php
if ($argc > 1)
    file_put_contents(
        'notes.txt', 
        date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
        FILE_APPEND
    );
else
    @readfile('notes.txt');
Task: Find common directory path


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

std::string longestPath( const std::vector<std::string> & , char ) ;

int main( ) {
   std::string dirs[ ] = {
      "/home/user1/tmp/coverage/test" ,
      "/home/user1/tmp/covert/operator" ,
      "/home/user1/tmp/coven/members" } ;
   std::vector<std::string> myDirs ( dirs , dirs + 3 ) ;
   std::cout << "The longest common path of the given directories is "
             << longestPath( myDirs , '/' ) << "!\n" ;
   return 0 ;
}

std::string longestPath( const std::vector<std::string> & dirs , char separator ) {
   std::vector<std::string>::const_iterator vsi = dirs.begin( ) ;
   int maxCharactersCommon = vsi->length( ) ;
   std::string compareString = *vsi ;
   for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) {
      std::pair<std::string::const_iterator , std::string::const_iterator> p = 
	 std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ;
      if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) 
	 maxCharactersCommon = p.first - compareString.begin( ) ;
   }
   std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ;
   return compareString.substr( 0 , found ) ;
}





PHP: <?php



function _commonPath($dirList)
{
	$arr = array();
	foreach($dirList as $i => $path)
	{
		$dirList[$i]	= explode('/', $path);
		unset($dirList[$i][0]);
		
		$arr[$i] = count($dirList[$i]);
	}
	
	$min = min($arr);
	
	for($i = 0; $i < count($dirList); $i++)
	{
		while(count($dirList[$i]) > $min)
		{
			array_pop($dirList[$i]);
		}
		
		$dirList[$i] = '/' . implode('/' , $dirList[$i]);
	}
	
	$dirList = array_unique($dirList);
	while(count($dirList) !== 1)
	{
		$dirList = array_map('dirname', $dirList);
		$dirList = array_unique($dirList);
	}
	reset($dirList);
	
	return current($dirList);
}

 

$dirs = array(
 '/home/user1/tmp/coverage/test',
 '/home/user1/tmp/covert/operator',
 '/home/user1/tmp/coven/members',
);


if('/home/user1/tmp' !== common_path($dirs))
{
  echo 'test fail';
} else {
  echo 'test success';
}

?>
Task: Recaman's sequence


C++: #include <iostream>
#include <ostream>
#include <set>
#include <vector>

template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
    auto i = v.cbegin();
    auto e = v.cend();
    os << '[';
    if (i != e) {
        os << *i;
        i = std::next(i);
    }
    while (i != e) {
        os << ", " << *i;
        i = std::next(i);
    }
    return os << ']';
}

int main() {
    using namespace std;

    vector<int> a{ 0 };
    set<int> used{ 0 };
    set<int> used1000{ 0 };
    bool foundDup = false;
    int n = 1;
    while (n <= 15 || !foundDup || used1000.size() < 1001) {
        int next = a[n - 1] - n;
        if (next < 1 || used.find(next) != used.end()) {
            next += 2 * n;
        }
        bool alreadyUsed = used.find(next) != used.end();
        a.push_back(next);
        if (!alreadyUsed) {
            used.insert(next);
            if (0 <= next && next <= 1000) {
                used1000.insert(next);
            }
        }
        if (n == 14) {
            cout << "The first 15 terms of the Recaman sequence are: " << a << '\n';
        }
        if (!foundDup && alreadyUsed) {
            cout << "The first duplicated term is a[" << n << "] = " << next << '\n';
            foundDup = true;
        }
        if (used1000.size() == 1001) {
            cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n";
        }
        n++;
    }

    return 0;
}





PHP: <?php
$a = array();
array_push($a, 0);

$used = array();
array_push($used, 0);

$used1000 = array();
array_push($used1000, 0);

$foundDup = false;
$n = 1;

while($n <= 15 || !$foundDup || count($used1000) < 1001) {
	$next = $a[$n - 1] - $n;
	if ($next < 1 || in_array($next, $used)) {
		$next += 2 * $n;
	}
	$alreadyUsed = in_array($next, $used);
	array_push($a, $next);
	if (!$alreadyUsed) {
		array_push($used, $next);
		if (0 <= $next && $next <= 1000) {
			array_push($used1000, $next);
		}
	}
	if ($n == 14) {
		echo "The first 15 terms of the Recaman sequence are : [";
		foreach($a as $i => $v) {
			if ( $i == count($a) - 1)
				echo "$v";
			else
				echo "$v, ";
		}
		echo "]\n";
	}
	if (!$foundDup && $alreadyUsed) {
		printf("The first duplicate term is a[%d] = %d\n", $n, $next);
		$foundDup = true;
	}
	if (count($used1000) == 1001) {
		printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
	}
	$n++;
}
Task: Entropy_Narcissist


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

using namespace std;

string readFile (string path) {
    string contents;
    string line;
    ifstream inFile(path);
    while (getline (inFile, line)) {
        contents.append(line);
        contents.append("\n");
    }
    inFile.close();
    return contents;
}

double entropy (string X) {
    const int MAXCHAR = 127;
    int N = X.length();
    int count[MAXCHAR];
    double count_i;
    char ch;
    double sum = 0.0;
    for (int i = 0; i < MAXCHAR; i++) count[i] = 0;
    for (int pos = 0; pos < N; pos++) {
        ch = X[pos];
        count[(int)ch]++;
    }
    for (int n_i = 0; n_i < MAXCHAR; n_i++) {
        count_i = count[n_i];
        if (count_i > 0) sum -= count_i / N * log2(count_i / N);
    }
    return sum;
}

int main () {
    cout<<entropy(readFile("entropy.cpp"));
    return 0;
}





PHP: <?php
$h  =                             0;
$s  =   file_get_contents(__FILE__);
$l  =                    strlen($s);
foreach ( count_chars($s, 1) as $c )
                               $h -=
                       ( $c / $l ) *
                  log( $c / $l, 2 );
echo                             $h;
Task: DNS query


C++: #include <Rcpp.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace Rcpp ;


CharacterVector getNameInfo(std::string fqdn) {

  struct addrinfo hints, *res, *res0;
	int error;
	char host[NI_MAXHOST];

  memset(&hints, 0, sizeof hints);
	hints.ai_family = PF_UNSPEC;
	hints.ai_socktype = SOCK_DGRAM;

	error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);
	if (error) { return(NA_STRING);	}

  int i = 0 ;
	for (res = res0; res; res = res->ai_next) {
  	error = getnameinfo(res->ai_addr, res->ai_addrlen,
		    host, sizeof host, NULL, 0, NI_NUMERICHOST);
		if (!error) { i++ ; }
	}

  CharacterVector results(i) ;

  i = 0;

  for (res = res0; res; res = res->ai_next) {
		error = getnameinfo(res->ai_addr, res->ai_addrlen,
		    host, sizeof host, NULL, 0, NI_NUMERICHOST);
		if (!error) { results[i++] = host ; }
	}

  freeaddrinfo(res0);

  return(results) ;

}





PHP: <?php
  $ipv4_record = dns_get_record("www.kame.net",DNS_A);
  $ipv6_record = dns_get_record("www.kame.net",DNS_AAAA);
  print "ipv4: " . $ipv4_record[0]["ip"] . "\n";
  print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n";
?>
Task: Y combinator


C++: #include <iostream>
#include <functional>

template <typename F>
struct RecursiveFunc {
	std::function<F(RecursiveFunc)> o;
};

template <typename A, typename B>
std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {
	RecursiveFunc<std::function<B(A)>> r = {
		std::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {
			return f(std::function<B(A)>([w](A x) {
				return w.o(w)(x);
			}));
		})
	};
	return r.o(r);
}

typedef std::function<int(int)> Func;
typedef std::function<Func(Func)> FuncFunc;
FuncFunc almost_fac = [](Func f) {
	return Func([f](int n) {
		if (n <= 1) return 1;
		return n * f(n - 1);
	});
};

FuncFunc almost_fib = [](Func f) {
	return Func([f](int n) {
	 	if (n <= 2) return 1;
		return  f(n - 1) + f(n - 2);
	});
};

int main() {
	auto fib = Y(almost_fib);
	auto fac = Y(almost_fac);
	std::cout << "fib(10) = " << fib(10) << std::endl;
	std::cout << "fac(10) = " << fac(10) << std::endl;
	return 0;
}





PHP: <?php
function Y($f) {
  $g = function($w) use($f) {
    return $f(function() use($w) {
      return call_user_func_array($w($w), func_get_args());
    });
  };
  return $g($g);
}

$fibonacci = Y(function($f) {
  return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };
});

echo $fibonacci(10), "\n";

$factorial = Y(function($f) {
  return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };
});

echo $factorial(10), "\n";
?>
Task: Return multiple values


C++: #include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include <tuple>

std::tuple<int, int> minmax(const int * numbers, const std::size_t num) {
   const auto maximum = std::max_element(numbers, numbers + num);
   const auto minimum = std::min_element(numbers, numbers + num);
   return std::make_tuple(*minimum, *maximum) ;
}

int main( ) {
   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};
   int min{};
   int max{};
   std::tie(min, max) = minmax(numbers.data(), numbers.size());
   std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ;
}





PHP: function addsub($x, $y) {
  return array($x + $y, $x - $y);
}