WeixiangYan/CodeTransOcean huggingface dataset:
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 ) ;
}
Task: Find common directory path





Java: public class CommonPath {
	public static String commonPath(String... paths){
		String commonPath = "";
		String[][] folders = new String[paths.length][];
		for(int i = 0; i < paths.length; i++){
			folders[i] = paths[i].split("/"); 
		}
		for(int j = 0; j < folders[0].length; j++){
			String thisFolder = folders[0][j]; 
			boolean allMatched = true; 
			for(int i = 1; i < folders.length && allMatched; i++){ 
				if(folders[i].length < j){ 
					allMatched = false; 
					break; 
				}
				
				allMatched &= folders[i][j].equals(thisFolder); 
			}
			if(allMatched){ 
				commonPath += thisFolder + "/"; 
			}else{
				break;
			}
		}
		return commonPath;
	}
	
	public static void main(String[] args){
		String[] paths = { "/home/user1/tmp/coverage/test",
				 "/home/user1/tmp/covert/operator",
				 "/home/user1/tmp/coven/members"};
		System.out.println(commonPath(paths));
		
		String[] paths2 = { "/hame/user1/tmp/coverage/test",
				 "/home/user1/tmp/covert/operator",
				 "/home/user1/tmp/coven/members"};
		System.out.println(commonPath(paths2));
	}
}
Task: Find common directory path







Python: >>> import os
>>> os.path.commonpath(['/home/user1/tmp/coverage/test', 
                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'
Task: Find common directory path








VB: Public Function CommonDirectoryPath(ParamArray Paths()) As String
Dim v As Variant
Dim Path() As String, s As String
Dim i As Long, j As Long, k As Long
Const PATH_SEPARATOR As String = "/"
  
  For Each v In Paths
    ReDim Preserve Path(0 To i)
    Path(i) = v
    i = i + 1
  Next v
  
  k = 1
  
  Do
    For i = 0 To UBound(Path)
      If i Then
        If InStr(k, Path(i), PATH_SEPARATOR) <> j Then
          Exit Do
        ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then
          Exit Do
        End If
      Else
        j = InStr(k, Path(i), PATH_SEPARATOR)
        If j = 0 Then
          Exit Do
        End If
      End If
    Next i
    s = Left$(Path(0), j + CLng(k <> 1))
    k = j + 1
  Loop
  CommonDirectoryPath = s
  
End Function

Sub Main()



Debug.Assert CommonDirectoryPath( _
 "/home/user1/tmp/coverage/test", _
 "/home/user1/tmp/covert/operator", _
 "/home/user1/tmp/coven/members") = _
 "/home/user1/tmp"
 
 Debug.Assert CommonDirectoryPath( _
 "/home/user1/tmp/coverage/test", _
 "/home/user1/tmp/covert/operator", _
 "/home/user1/tmp/coven/members", _
 "/home/user1/abc/coven/members") = _
 "/home/user1"

Debug.Assert CommonDirectoryPath( _
 "/home/user1/tmp/coverage/test", _
 "/hope/user1/tmp/covert/operator", _
 "/home/user1/tmp/coven/members") = _
 "/"

End Sub
Task: Find common directory path




Go: package main

import (
	"fmt"
	"os"
	"path"
)

func CommonPrefix(sep byte, paths ...string) string {
	
	switch len(paths) {
	case 0:
		return ""
	case 1:
		return path.Clean(paths[0])
	}

	
	
	
	
	
	
	
	
	c := []byte(path.Clean(paths[0]))

	
	
	
	
	
	
	c = append(c, sep)

	
	for _, v := range paths[1:] {
		
		v = path.Clean(v) + string(sep)

		
		if len(v) < len(c) {
			c = c[:len(v)]
		}
		for i := 0; i < len(c); i++ {
			if v[i] != c[i] {
				c = c[:i]
				break
			}
		}
	}

	
	for i := len(c) - 1; i >= 0; i-- {
		if c[i] == sep {
			c = c[:i]
			break
		}
	}

	return string(c)
}

func main() {
	c := CommonPrefix(os.PathSeparator,
		
		"/home/user1/tmp/coverage/test",
		"/home/user1/tmp/covert/operator",
		"/home/user1/tmp/coven/members",
		"/home
		"/home/user1/././tmp/covertly/foo",
		"/home/bob/../user1/tmp/coved/bar",
	)
	if c == "" {
		fmt.Println("No common path")
	} else {
		fmt.Println("Common path:", c)
	}
}
Task: Find common directory path






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: Find common directory path






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';
}

?>






Ada: with Ada.Text_IO;  use Ada.Text_IO;

procedure Test_Common_Path is
   function "rem" (A, B : String) return String is
      Slash : Integer := A'First; 
      At_A  : Integer := A'first;
      At_B  : Integer := B'first;
   begin
      loop
         if At_A > A'Last then
            if At_B > B'Last or else B (At_B) = '/' then
               return A;
            else
               return A (A'First..Slash - 1);
            end if;
         elsif At_B > B'Last then
            if A (At_A) = '/' then 
               return B;
            else
               return A (A'First..Slash - 1);
            end if;
         elsif A (At_A) /= B (At_B) then
            return A (A'First..Slash - 1);
         elsif A (At_A) = '/' then
            Slash := At_A;
         end if;
         At_A := At_A + 1;
         At_B := At_B + 1;
      end loop;      
   end "rem";
begin
   Put_Line
   (  "/home/user1/tmp/coverage/test" rem
      "/home/user1/tmp/covert/operator" rem
      "/home/user1/tmp/coven/members"
   );
end Test_Common_Path;
Task: Delegates



C#: using System;

interface IOperable
{
    string Operate();
}

class Inoperable
{
}

class Operable : IOperable
{
    public string Operate()
    {
        return "Delegate implementation.";
    }
}

class Delegator : IOperable
{
    object Delegate;

    public string Operate()
    {
        var operable = Delegate as IOperable;
        return operable != null ? operable.Operate() : "Default implementation.";
    }

    static void Main()
    {
        var delegator = new Delegator();
        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })
        {
            delegator.Delegate = @delegate;
            Console.WriteLine(delegator.Operate());
        }
    }
}









Ada: with Ada.Text_IO;  use Ada.Text_IO;

procedure Delegation is
   package Things is
      
      type Object is tagged null record;
      type Object_Ptr is access all Object'Class;
      
      
      type Substantial is new Object with null record;
      function Thing (X : Substantial) return String;
      
      
      type Delegator is new Object with record
         Delegate : Object_Ptr;
      end record;
      function Operation (X : Delegator) return String;
      
      No_Thing  : aliased Object;      
      Has_Thing : aliased Substantial; 
   end Things;
      
   package body Things is
      function Thing (X : Substantial) return String is
      begin
         return "delegate implementation";
      end Thing;
   
      function Operation (X : Delegator) return String is
      begin
         if X.Delegate /= null and then X.Delegate.all in Substantial'Class then
            return Thing (Substantial'Class (X.Delegate.all));
         else
            return "default implementation";
         end if;
      end Operation;
   end Things;

   use Things;

   A : Delegator; 
begin
   Put_Line (A.Operation);
   A.Delegate := No_Thing'Access; 
   Put_Line (A.Operation);
   A.Delegate := Has_Thing'Access; 
   Put_Line (A.Operation);
end Delegation;
Task: Delegates

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

typedef const char * (*Responder)( int p1);

typedef struct sDelegate {
    Responder operation;
} *Delegate;


Delegate NewDelegate( Responder rspndr )
{
    Delegate dl = malloc(sizeof(struct sDelegate));
    dl->operation = rspndr;
    return dl;
}


const char *DelegateThing(Delegate dl, int p1)
{
    return  (dl->operation)? (*dl->operation)(p1) : NULL;
}


typedef struct sDelegator {
    int     param;
    char    *phrase;
    Delegate delegate;
} *Delegator;

const char * defaultResponse( int p1)
{
    return "default implementation";
}

static struct sDelegate defaultDel = { &defaultResponse };


Delegator NewDelegator( int p, char *phrase)
{
    Delegator d  = malloc(sizeof(struct sDelegator));
    d->param = p;
    d->phrase = phrase;
    d->delegate = &defaultDel;	
    return d;
}


const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)
{
    const char *rtn;
    if (delroy) {
        rtn = DelegateThing(delroy, p1);
        if (!rtn) {			
            rtn = DelegateThing(theDelegator->delegate, p1);
        }
    }
    else 		
        rtn = DelegateThing(theDelegator->delegate, p1);

    printf("%s\n", theDelegator->phrase );
    return rtn;
}


const char *thing1( int p1)
{
    printf("We're in thing1 with value %d\n" , p1);
    return "delegate implementation";
}

int main()
{
    Delegate del1 = NewDelegate(&thing1);
    Delegate del2 = NewDelegate(NULL);
    Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby.");

    printf("Delegator returns %s\n\n", 
            Delegator_Operation( theDelegator, 3, NULL));
    printf("Delegator returns %s\n\n", 
            Delegator_Operation( theDelegator, 3, del1));
    printf("Delegator returns %s\n\n",
            Delegator_Operation( theDelegator, 3, del2));
    return 0;
}











Ada: with Ada.Text_IO;  use Ada.Text_IO;

procedure Delegation is
   package Things is
      
      type Object is tagged null record;
      type Object_Ptr is access all Object'Class;
      
      
      type Substantial is new Object with null record;
      function Thing (X : Substantial) return String;
      
      
      type Delegator is new Object with record
         Delegate : Object_Ptr;
      end record;
      function Operation (X : Delegator) return String;
      
      No_Thing  : aliased Object;      
      Has_Thing : aliased Substantial; 
   end Things;
      
   package body Things is
      function Thing (X : Substantial) return String is
      begin
         return "delegate implementation";
      end Thing;
   
      function Operation (X : Delegator) return String is
      begin
         if X.Delegate /= null and then X.Delegate.all in Substantial'Class then
            return Thing (Substantial'Class (X.Delegate.all));
         else
            return "default implementation";
         end if;
      end Operation;
   end Things;

   use Things;

   A : Delegator; 
begin
   Put_Line (A.Operation);
   A.Delegate := No_Thing'Access; 
   Put_Line (A.Operation);
   A.Delegate := Has_Thing'Access; 
   Put_Line (A.Operation);
end Delegation;
Task: Delegates


C++: #include <tr1/memory>
#include <string>
#include <iostream>
#include <tr1/functional>

using namespace std;
using namespace std::tr1;
using std::tr1::function;


class IDelegate
{
public:
    virtual ~IDelegate() {}
};


class IThing
{
public:
    virtual ~IThing() {}
    virtual std::string Thing() = 0;
};


class DelegateA : virtual public IDelegate
{
};
 

class DelegateB : public IThing, public IDelegate
{
    std::string Thing()
    {
        return "delegate implementation";
    }
};
 
class Delegator
{
public:
    std::string Operation()
    {
        if(Delegate) 
           if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))
            
            return pThing->Thing();
        
        return "default implementation";
    }
 
    shared_ptr<IDelegate> Delegate;
};
 
int main()
{
    shared_ptr<DelegateA> delegateA(new DelegateA());
    shared_ptr<DelegateB> delegateB(new DelegateB());
    Delegator delegator;
 
    
    std::cout << delegator.Operation() << std::endl;
 
    
    delegator.Delegate = delegateA;
    std::cout << delegator.Operation() << std::endl;
 
    
    delegator.Delegate = delegateB;
    std::cout << delegator.Operation() << std::endl;


}










Ada: with Ada.Text_IO;  use Ada.Text_IO;

procedure Delegation is
   package Things is
      
      type Object is tagged null record;
      type Object_Ptr is access all Object'Class;
      
      
      type Substantial is new Object with null record;
      function Thing (X : Substantial) return String;
      
      
      type Delegator is new Object with record
         Delegate : Object_Ptr;
      end record;
      function Operation (X : Delegator) return String;
      
      No_Thing  : aliased Object;      
      Has_Thing : aliased Substantial; 
   end Things;
      
   package body Things is
      function Thing (X : Substantial) return String is
      begin
         return "delegate implementation";
      end Thing;
   
      function Operation (X : Delegator) return String is
      begin
         if X.Delegate /= null and then X.Delegate.all in Substantial'Class then
            return Thing (Substantial'Class (X.Delegate.all));
         else
            return "default implementation";
         end if;
      end Operation;
   end Things;

   use Things;

   A : Delegator; 
begin
   Put_Line (A.Operation);
   A.Delegate := No_Thing'Access; 
   Put_Line (A.Operation);
   A.Delegate := Has_Thing'Access; 
   Put_Line (A.Operation);
end Delegation;
Task: Delegates




Go: package main
import "fmt"

type Delegator struct {
    delegate interface{} 
}


type Thingable interface {
    thing() string
}

func (self Delegator) operation() string {
    if v, ok := self.delegate.(Thingable); ok {
        return v.thing()
    }
    return "default implementation"
}

type Delegate int 

func (Delegate) thing() string {
    return "delegate implementation"
}

func main() {
    
    a := Delegator{}
    fmt.Println(a.operation()) 

    
    a.delegate = "A delegate may be any object"
    fmt.Println(a.operation()) 

    
    var d Delegate
    a.delegate = d
    fmt.Println(a.operation()) 
}








Ada: with Ada.Text_IO;  use Ada.Text_IO;

procedure Delegation is
   package Things is
      
      type Object is tagged null record;
      type Object_Ptr is access all Object'Class;
      
      
      type Substantial is new Object with null record;
      function Thing (X : Substantial) return String;
      
      
      type Delegator is new Object with record
         Delegate : Object_Ptr;
      end record;
      function Operation (X : Delegator) return String;
      
      No_Thing  : aliased Object;      
      Has_Thing : aliased Substantial; 
   end Things;
      
   package body Things is
      function Thing (X : Substantial) return String is
      begin
         return "delegate implementation";
      end Thing;
   
      function Operation (X : Delegator) return String is
      begin
         if X.Delegate /= null and then X.Delegate.all in Substantial'Class then
            return Thing (Substantial'Class (X.Delegate.all));
         else
            return "default implementation";
         end if;
      end Operation;
   end Things;

   use Things;

   A : Delegator; 
begin
   Put_Line (A.Operation);
   A.Delegate := No_Thing'Access; 
   Put_Line (A.Operation);
   A.Delegate := Has_Thing'Access; 
   Put_Line (A.Operation);
end Delegation;
Task: Delegates





Java: interface Thingable {
    String thing();
}

class Delegator {
    public Thingable delegate;

    public String operation() {
        if (delegate == null)
            return "default implementation";
        else
            return delegate.thing();
    }
}

class Delegate implements Thingable {
    public String thing() {
        return "delegate implementation";
    }
}



public class DelegateExample {
    public static void main(String[] args) {
        
        Delegator a = new Delegator();
        assert a.operation().equals("default implementation");

        
        Delegate d = new Delegate();
        a.delegate = d;
        assert a.operation().equals("delegate implementation");

        
        a.delegate = new Thingable() {
                public String thing() {
                    return "anonymous delegate implementation";
                }
            };
        assert a.operation().equals("anonymous delegate implementation");
    }
}







Ada: with Ada.Text_IO;  use Ada.Text_IO;

procedure Delegation is
   package Things is
      
      type Object is tagged null record;
      type Object_Ptr is access all Object'Class;
      
      
      type Substantial is new Object with null record;
      function Thing (X : Substantial) return String;
      
      
      type Delegator is new Object with record
         Delegate : Object_Ptr;
      end record;
      function Operation (X : Delegator) return String;
      
      No_Thing  : aliased Object;      
      Has_Thing : aliased Substantial; 
   end Things;
      
   package body Things is
      function Thing (X : Substantial) return String is
      begin
         return "delegate implementation";
      end Thing;
   
      function Operation (X : Delegator) return String is
      begin
         if X.Delegate /= null and then X.Delegate.all in Substantial'Class then
            return Thing (Substantial'Class (X.Delegate.all));
         else
            return "default implementation";
         end if;
      end Operation;
   end Things;

   use Things;

   A : Delegator; 
begin
   Put_Line (A.Operation);
   A.Delegate := No_Thing'Access; 
   Put_Line (A.Operation);
   A.Delegate := Has_Thing'Access; 
   Put_Line (A.Operation);
end Delegation;
Task: Delegates







Python: class Delegator:
   def __init__(self):
      self.delegate = None
   def operation(self):
       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):
          return self.delegate.thing()
       return 'default implementation'

class Delegate:
   def thing(self):
      return 'delegate implementation'

if __name__ == '__main__':

   
   a = Delegator()
   assert a.operation() == 'default implementation'

   
   a.delegate = 'A delegate may be any object'
   assert a.operation() == 'default implementation'

   
   a.delegate = Delegate()
   assert a.operation() == 'delegate implementation'





Ada: with Ada.Text_IO;  use Ada.Text_IO;

procedure Delegation is
   package Things is
      
      type Object is tagged null record;
      type Object_Ptr is access all Object'Class;
      
      
      type Substantial is new Object with null record;
      function Thing (X : Substantial) return String;
      
      
      type Delegator is new Object with record
         Delegate : Object_Ptr;
      end record;
      function Operation (X : Delegator) return String;
      
      No_Thing  : aliased Object;      
      Has_Thing : aliased Substantial; 
   end Things;
      
   package body Things is
      function Thing (X : Substantial) return String is
      begin
         return "delegate implementation";
      end Thing;
   
      function Operation (X : Delegator) return String is
      begin
         if X.Delegate /= null and then X.Delegate.all in Substantial'Class then
            return Thing (Substantial'Class (X.Delegate.all));
         else
            return "default implementation";
         end if;
      end Operation;
   end Things;

   use Things;

   A : Delegator; 
begin
   Put_Line (A.Operation);
   A.Delegate := No_Thing'Access; 
   Put_Line (A.Operation);
   A.Delegate := Has_Thing'Access; 
   Put_Line (A.Operation);
end Delegation;
Task: Delegates

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

typedef const char * (*Responder)( int p1);

typedef struct sDelegate {
    Responder operation;
} *Delegate;


Delegate NewDelegate( Responder rspndr )
{
    Delegate dl = malloc(sizeof(struct sDelegate));
    dl->operation = rspndr;
    return dl;
}


const char *DelegateThing(Delegate dl, int p1)
{
    return  (dl->operation)? (*dl->operation)(p1) : NULL;
}


typedef struct sDelegator {
    int     param;
    char    *phrase;
    Delegate delegate;
} *Delegator;

const char * defaultResponse( int p1)
{
    return "default implementation";
}

static struct sDelegate defaultDel = { &defaultResponse };


Delegator NewDelegator( int p, char *phrase)
{
    Delegator d  = malloc(sizeof(struct sDelegator));
    d->param = p;
    d->phrase = phrase;
    d->delegate = &defaultDel;	
    return d;
}


const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)
{
    const char *rtn;
    if (delroy) {
        rtn = DelegateThing(delroy, p1);
        if (!rtn) {			
            rtn = DelegateThing(theDelegator->delegate, p1);
        }
    }
    else 		
        rtn = DelegateThing(theDelegator->delegate, p1);

    printf("%s\n", theDelegator->phrase );
    return rtn;
}


const char *thing1( int p1)
{
    printf("We're in thing1 with value %d\n" , p1);
    return "delegate implementation";
}

int main()
{
    Delegate del1 = NewDelegate(&thing1);
    Delegate del2 = NewDelegate(NULL);
    Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby.");

    printf("Delegator returns %s\n\n", 
            Delegator_Operation( theDelegator, 3, NULL));
    printf("Delegator returns %s\n\n", 
            Delegator_Operation( theDelegator, 3, del1));
    printf("Delegator returns %s\n\n",
            Delegator_Operation( theDelegator, 3, del2));
    return 0;
}
Task: Delegates



C#: using System;

interface IOperable
{
    string Operate();
}

class Inoperable
{
}

class Operable : IOperable
{
    public string Operate()
    {
        return "Delegate implementation.";
    }
}

class Delegator : IOperable
{
    object Delegate;

    public string Operate()
    {
        var operable = Delegate as IOperable;
        return operable != null ? operable.Operate() : "Default implementation.";
    }

    static void Main()
    {
        var delegator = new Delegator();
        foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })
        {
            delegator.Delegate = @delegate;
            Console.WriteLine(delegator.Operate());
        }
    }
}