WeixiangYan/CodeTransOcean huggingface dataset:
Task: Character codes





Java: module CharacterCodes
    {
    @Inject Console console;
    void run()
        {
        for (Char char : ['\0', '\d', 'A', '$', '¢', '~', '˜'])
            {
            
            UInt32 codepoint = char.codepoint;

            
            Char fromCodePoint = codepoint.toChar();   

            console.print($|Character {char.quoted()}:\
                           | Unicode codepoint={char.codepoint},\
                           | ASCII={char.ascii},\
                           | UTF8 bytes={char.utf8()},\
                           | char from codepoint={fromCodePoint.quoted()}
                         );
            }
        }
    }
Task: Character codes








VB: TextWindow.WriteLine("The ascii code for 
TextWindow.WriteLine("The character for
Task: Character codes




Go: fmt.Println('a') 
fmt.Println('π')
Task: Character codes







Python: print ord('a') 
print chr(97)
Task: Character codes



C#: using System;

namespace RosettaCode.CharacterCode
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine((int) 'a');   
            Console.WriteLine((char) 97);   
        }
    }
}








Fortran: WRITE(*,*) ACHAR(97), IACHAR("a")   
WRITE(*,*) CHAR(97), ICHAR("a")
Task: Character codes


C++: #include <iostream>

int main() {
  std::cout << (int)'a' << std::endl; 
  std::cout << (char)97 << std::endl; 
  return 0;
}









Fortran: WRITE(*,*) ACHAR(97), IACHAR("a")   
WRITE(*,*) CHAR(97), ICHAR("a")
Task: Character codes

C: #include <stdio.h>

int main() {
  printf("%d\n", 'a'); 
  printf("%c\n", 97); 
  return 0;
}










Fortran: WRITE(*,*) ACHAR(97), IACHAR("a")   
WRITE(*,*) CHAR(97), ICHAR("a")
Task: Character codes




Go: fmt.Println('a') 
fmt.Println('π') 







Fortran: WRITE(*,*) ACHAR(97), IACHAR("a")   
WRITE(*,*) CHAR(97), ICHAR("a")
Task: Character codes





Java: module CharacterCodes
    {
    @Inject Console console;
    void run()
        {
        for (Char char : ['\0', '\d', 'A', '$', '¢', '~', '˜'])
            {
            
            UInt32 codepoint = char.codepoint;

            
            Char fromCodePoint = codepoint.toChar();   

            console.print($|Character {char.quoted()}:\
                           | Unicode codepoint={char.codepoint},\
                           | ASCII={char.ascii},\
                           | UTF8 bytes={char.utf8()},\
                           | char from codepoint={fromCodePoint.quoted()}
                         );
            }
        }
    }






Fortran: WRITE(*,*) ACHAR(97), IACHAR("a")   
WRITE(*,*) CHAR(97), ICHAR("a")
Task: Character codes







Python: print ord('a') 
print chr(97)  




Fortran: WRITE(*,*) ACHAR(97), IACHAR("a")   
WRITE(*,*) CHAR(97), ICHAR("a")
Task: Character codes






PHP: echo ord('a'), "\n"; // prints "97"
echo chr(97), "\n"; // prints "a"





Fortran: WRITE(*,*) ACHAR(97), IACHAR("a")   
WRITE(*,*) CHAR(97), ICHAR("a")
Task: Character codes

C: #include <stdio.h>

int main() {
  printf("%d\n", 'a'); 
  printf("%c\n", 97); 
  return 0;
}









COBOL:        identification division.
       program-id. character-codes.
       remarks. COBOL is an ordinal language, first is 1.
       remarks. 42nd ASCII code is ")" not, "*".
       procedure division.
       display function char(42)
       display function ord('*')
       goback.
       end program character-codes.
Task: Character codes



C#: using System;

namespace RosettaCode.CharacterCode
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine((int) 'a');   
            Console.WriteLine((char) 97);   
        }
    }
}







COBOL:        identification division.
       program-id. character-codes.
       remarks. COBOL is an ordinal language, first is 1.
       remarks. 42nd ASCII code is ")" not, "*".
       procedure division.
       display function char(42)
       display function ord('*')
       goback.
       end program character-codes.
Task: Character codes


C++: #include <iostream>

int main() {
  std::cout << (int)'a' << std::endl; 
  std::cout << (char)97 << std::endl; 
  return 0;
}








COBOL:        identification division.
       program-id. character-codes.
       remarks. COBOL is an ordinal language, first is 1.
       remarks. 42nd ASCII code is ")" not, "*".
       procedure division.
       display function char(42)
       display function ord('*')
       goback.
       end program character-codes.
Task: Character codes





Java: module CharacterCodes
    {
    @Inject Console console;
    void run()
        {
        for (Char char : ['\0', '\d', 'A', '$', '¢', '~', '˜'])
            {
            
            UInt32 codepoint = char.codepoint;

            
            Char fromCodePoint = codepoint.toChar();   

            console.print($|Character {char.quoted()}:\
                           | Unicode codepoint={char.codepoint},\
                           | ASCII={char.ascii},\
                           | UTF8 bytes={char.utf8()},\
                           | char from codepoint={fromCodePoint.quoted()}
                         );
            }
        }
    }





COBOL:        identification division.
       program-id. character-codes.
       remarks. COBOL is an ordinal language, first is 1.
       remarks. 42nd ASCII code is ")" not, "*".
       procedure division.
       display function char(42)
       display function ord('*')
       goback.
       end program character-codes.
Task: Character codes







Python: print ord('a') 
print chr(97)  



COBOL:        identification division.
       program-id. character-codes.
       remarks. COBOL is an ordinal language, first is 1.
       remarks. 42nd ASCII code is ")" not, "*".
       procedure division.
       display function char(42)
       display function ord('*')
       goback.
       end program character-codes.
Task: Character codes








VB: TextWindow.WriteLine("The ascii code for 
TextWindow.WriteLine("The character for 


COBOL:        identification division.
       program-id. character-codes.
       remarks. COBOL is an ordinal language, first is 1.
       remarks. 42nd ASCII code is ")" not, "*".
       procedure division.
       display function char(42)
       display function ord('*')
       goback.
       end program character-codes.
Task: Character codes




Go: fmt.Println('a') 
fmt.Println('π') 






COBOL:        identification division.
       program-id. character-codes.
       remarks. COBOL is an ordinal language, first is 1.
       remarks. 42nd ASCII code is ")" not, "*".
       procedure division.
       display function char(42)
       display function ord('*')
       goback.
       end program character-codes.
Task: Character codes






PHP: echo ord('a'), "\n"; // prints "97"
echo chr(97), "\n"; // prints "a"
Task: Character codes






PHP: echo ord('a'), "\n"; // prints "97"
echo chr(97), "\n"; // prints "a"






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

procedure Char_Code is
begin
   Put_Line (Character'Val (97) & " =" & Integer'Image (Character'Pos ('a')));
end Char_Code;
Task: Character codes






PHP: echo ord('a'), "\n"; // prints "97"
echo chr(97), "\n"; // prints "a"




COBOL:        identification division.
       program-id. character-codes.
       remarks. COBOL is an ordinal language, first is 1.
       remarks. 42nd ASCII code is ")" not, "*".
       procedure division.
       display function char(42)
       display function ord('*')
       goback.
       end program character-codes.
Task: GUI component interaction

C: #include <windows.h>
#include "resource.h"

BOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {
    switch( msg ) {

        case WM_INITDIALOG:
            srand( GetTickCount() );
            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );
            break;

        case WM_COMMAND:
            switch( LOWORD(wPar) ) {
                case IDC_INCREMENT: {
                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );
                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );
                    } break;
                case IDC_RANDOM: {
                    int reply = MessageBox( hwnd,
                        "Do you really want to\nget a random number?",
                        "Random input confirmation", MB_ICONQUESTION|MB_YESNO );
                    if( reply == IDYES )
                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );
                    } break;
                case IDC_QUIT:
                    SendMessage( hwnd, WM_CLOSE, 0, 0 );
                    break;
                default: ;
            }
            break;

        case WM_CLOSE: {
            int reply = MessageBox( hwnd,
                "Do you really want to quit?",
                "Quit confirmation", MB_ICONQUESTION|MB_YESNO );
            if( reply == IDYES )
                EndDialog( hwnd, 0 );
            } break;

        default: ;
    }

    return 0;
}

int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {
    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );
}
Task: GUI component interaction



C#: using System; 
using System.ComponentModel; 
using System.Windows.Forms; 

class RosettaInteractionForm : Form
{    
    
    
    class NumberModel: INotifyPropertyChanged
    {

        Random rnd = new Random();

        
        public event PropertyChangedEventHandler PropertyChanged = delegate {};

        int _value;
        public int Value
        {
            get { return _value; }
            set 
            { 
                _value = value;
                
                PropertyChanged(this, new PropertyChangedEventArgs("Value"));
            }
        }

        public void ResetToRandom(){
            Value = rnd.Next(5000);
        }
    }

    NumberModel model = new NumberModel{ Value = 0};
    
    RosettaInteractionForm()    
    {
        
        var tbNumber = new MaskedTextBox
                        { 
                            Mask="0000",            
                            ResetOnSpace = false,   
                            Dock = DockStyle.Top    
                        };
        
        tbNumber.DataBindings.Add("Text", model, "Value");

        var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom};
        btIncrement.Click += delegate
                        {
                            model.Value++;
                        };
        var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom};
        btDecrement.Click += delegate
                        {
                            model.Value--;
                        };
        var btRandom = new Button{ Text="Reset to Random", Dock = DockStyle.Bottom };
        btRandom.Click += delegate
                        {
                            if (MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                model.ResetToRandom();
                        };
        Controls.Add(tbNumber);
        Controls.Add(btIncrement);
        Controls.Add(btDecrement);
        Controls.Add(btRandom);
    }
    static void Main()
    {
        Application.Run(new RosettaInteractionForm());
    }
}
Task: GUI component interaction


C++: #ifndef INTERACTION_H
#define INTERACTION_H
#include <QWidget>

class QPushButton ;
class QLineEdit ;
class QVBoxLayout ;
class MyWidget : public QWidget {
   Q_OBJECT 

public :
   MyWidget( QWidget *parent = 0 ) ;
private :
   QLineEdit *entryField ;
   QPushButton *increaseButton ;
   QPushButton *randomButton ;
   QVBoxLayout *myLayout ;
private slots :
   void doIncrement( ) ;
   void findRandomNumber( ) ;
} ;
#endif
Task: GUI component interaction





Java: import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Interact extends JFrame{
	final JTextField numberField;
	final JButton incButton, randButton;
	
	public Interact(){
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
		
		numberField = new JTextField();
		incButton = new JButton("Increment");
		randButton = new JButton("Random");
		
		numberField.setText("0");
		
		
		numberField.addKeyListener(new KeyListener(){
			@Override
			public void keyTyped(KeyEvent e) {
				
				if(!Character.isDigit(e.getKeyChar())){
					
					e.consume();
				}
			}
			@Override
			public void keyReleased(KeyEvent e){}
			@Override
			public void keyPressed(KeyEvent e){}
		});
		
		
		incButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				String text = numberField.getText();
				if(text.isEmpty()){
					numberField.setText("1");
				}else{
					numberField.setText((Long.valueOf(text) + 1) + "");
				}
			}
		});
		
		
		randButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if(JOptionPane.showConfirmDialog(null, "Are you sure?") ==
					JOptionPane.YES_OPTION){
					
					numberField.setText(Long.toString((long)(Math.random() 
							* Long.MAX_VALUE)));
				}
			}
		});
		
		
		setLayout(new GridLayout(2, 1));
		
		
		JPanel buttonPanel = new JPanel();
		
		
		buttonPanel.setLayout(new GridLayout(1, 2));
		
		buttonPanel.add(incButton);
		buttonPanel.add(randButton);
		
		
		add(numberField);
		add(buttonPanel);
		
		pack();
		
	}

	public static void main(String[] args){
		new Interact().setVisible(true);
	}
}
Task: GUI component interaction







Python: import random, tkMessageBox
from Tkinter import *
window = Tk()
window.geometry("300x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
def increase():
    s.set(int(s.get())+1)
def rand():
    if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
        s.set(random.randrange(0,5000))
def update(e):
    if not e.char.isdigit():
        tkMessageBox.showerror('Error', 'Invalid input !') 
        return "break"
e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind('<Key>', update)
b1 = Button(text="Increase", command=increase, **options )
b1.grid(column=1, row=0, **options)
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()
Task: GUI component interaction








VB: VERSION 5.00
Begin VB.Form Form1 
   Caption         =   "Form1"
   ClientHeight    =   2265
   ClientLeft      =   60
   ClientTop       =   600
   ClientWidth     =   2175
   LinkTopic       =   "Form1"
   ScaleHeight     =   2265
   ScaleWidth      =   2175
   StartUpPosition =   3  
   Begin VB.CommandButton cmdRnd 
      Caption         =   "Random"
      Height          =   495
      Left            =   120
      TabIndex        =   2
      Top             =   1680
      Width           =   1215
   End
   Begin VB.CommandButton cmdInc 
      Caption         =   "Increment"
      Height          =   495
      Left            =   120
      TabIndex        =   1
      Top             =   1080
      Width           =   1215
   End
   Begin VB.TextBox txtValue 
      Height          =   495
      Left            =   120
      TabIndex        =   0
      Text            =   "0"
      Top             =   240
      Width           =   1215
   End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False

Private Sub Form_Load()
    Randomize Timer
End Sub

Private Sub cmdRnd_Click()
    If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11)
End Sub

Private Sub cmdInc_Click()
    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1
End Sub

Private Sub txtValue_KeyPress(KeyAscii As Integer)
    Select Case KeyAscii
        Case 8, 43, 45, 48 To 57
            
        Case Else
            KeyAscii = 0
    End Select
End Sub
Task: GUI component interaction




Go: package main

import (
    "github.com/gotk3/gotk3/gtk"
    "log"
    "math/rand"
    "strconv"
    "time"
)

func validateInput(window *gtk.Window, str string) (int64, bool) {
    i, err := strconv.ParseInt(str, 10, 64)
    if err != nil {
        dialog := gtk.MessageDialogNew(
            window,
            gtk.DIALOG_MODAL,
            gtk.MESSAGE_ERROR,
            gtk.BUTTONS_OK,
            "Invalid value",
        )
        dialog.Run()
        dialog.Destroy()
        return 0, false
    }
    return i, true
}

func check(err error, msg string) {
    if err != nil {
        log.Fatal(msg, err)
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    gtk.Init(nil)

    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
    check(err, "Unable to create window:")
    window.SetTitle("Rosetta Code")
    window.SetPosition(gtk.WIN_POS_CENTER)
    window.Connect("destroy", func() {
        gtk.MainQuit()
    })

    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
    check(err, "Unable to create box:")
    box.SetBorderWidth(1)

    label, err := gtk.LabelNew("Value:")
    check(err, "Unable to create label:")

    entry, err := gtk.EntryNew()
    check(err, "Unable to create entry:")
    entry.SetText("0") 
    entry.Connect("activate", func() {
        
        str, _ := entry.GetText()
        validateInput(window, str)
    })

    
    ib, err := gtk.ButtonNewWithLabel("Increment")
    check(err, "Unable to create increment button:")
    ib.Connect("clicked", func() {
        
        str, _ := entry.GetText()
        if i, ok := validateInput(window, str); ok {
            entry.SetText(strconv.FormatInt(i+1, 10))
        }
    })

    
    rb, err := gtk.ButtonNewWithLabel("Random")
    check(err, "Unable to create random button:")
    rb.Connect("clicked", func() {
        dialog := gtk.MessageDialogNew(
            window,
            gtk.DIALOG_MODAL,
            gtk.MESSAGE_QUESTION,
            gtk.BUTTONS_YES_NO,
            "Set random value",
        )
        answer := dialog.Run()
        dialog.Destroy()
        if answer == gtk.RESPONSE_YES {
            entry.SetText(strconv.Itoa(rand.Intn(10000)))
        }
    })

    box.PackStart(label, false, false, 2)
    box.PackStart(entry, false, false, 2)
    box.PackStart(ib, false, false, 2)
    box.PackStart(rb, false, false, 2)
    window.Add(box)

    window.ShowAll()
    gtk.Main()
}
Task: Fibonacci n-step number sequences



C#: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Fibonacci
{
    class Program
    {
        static void Main(string[] args)
        {
            PrintNumberSequence("Fibonacci", GetNnacciNumbers(2, 10));
            PrintNumberSequence("Lucas", GetLucasNumbers(10));
            PrintNumberSequence("Tribonacci", GetNnacciNumbers(3, 10));
            PrintNumberSequence("Tetranacci", GetNnacciNumbers(4, 10));
            Console.ReadKey();
        }

        private static IList<ulong> GetLucasNumbers(int length)
        {
            IList<ulong> seedSequence = new List<ulong>() { 2, 1 };
            return GetFibLikeSequence(seedSequence, length);
        }

        private static IList<ulong> GetNnacciNumbers(int seedLength, int length)
        {
            return GetFibLikeSequence(GetNacciSeed(seedLength), length);
        }

        private static IList<ulong> GetNacciSeed(int seedLength)
        {
            IList<ulong> seedSquence = new List<ulong>() { 1 };

            for (uint i = 0; i < seedLength - 1; i++)
            {
                seedSquence.Add((ulong)Math.Pow(2, i));
            }

            return seedSquence;
        }

        private static IList<ulong> GetFibLikeSequence(IList<ulong> seedSequence, int length)
        {
            IList<ulong> sequence = new List<ulong>();

            int count = seedSequence.Count();

            if (length <= count)
            {
                sequence = seedSequence.Take((int)length).ToList();
            }
            else
            {
                sequence = seedSequence;

                for (int i = count; i < length; i++)
                {
                    ulong num = 0;

                    for (int j = 0; j < count; j++)
                    {
                        num += sequence[sequence.Count - 1 - j];
                    }

                    sequence.Add(num);
                }
            }

            return sequence;
        }

        private static void PrintNumberSequence(string Title, IList<ulong> numbersequence)
        {
            StringBuilder output = new StringBuilder(Title).Append("   ");

            foreach (long item in numbersequence)
            {
                output.AppendFormat("{0}, ", item);
            }

            Console.WriteLine(output.ToString());
        }
    }
}









Ada: package Bonacci is

   type Sequence is array(Positive range <>) of Positive;

   function Generate(Start: Sequence; Length: Positive := 10) return Sequence;

   Start_Fibonacci:  constant Sequence := (1, 1);
   Start_Tribonacci: constant Sequence := (1, 1, 2);
   Start_Tetranacci: constant Sequence := (1, 1, 2, 4);
   Start_Lucas:      constant Sequence := (2, 1);
end Bonacci;
Task: Fibonacci n-step number sequences

C: 

#include<stdlib.h>
#include<stdio.h>

int *
anynacci (int *seedArray, int howMany)
{
  int *result = malloc (howMany * sizeof (int));
  int i, j, initialCardinality;

  for (i = 0; seedArray[i] != 0; i++);
  initialCardinality = i;

  for (i = 0; i < initialCardinality; i++)
    result[i] = seedArray[i];

  for (i = initialCardinality; i < howMany; i++)
    {
      result[i] = 0;
      for (j = i - initialCardinality; j < i; j++)
        result[i] += result[j];
    }
  return result;
}

int
main ()
{
  int fibo[] = { 1, 1, 0 }, tribo[] = { 1, 1, 2, 0 }, tetra[] = { 1, 1, 2, 4, 0 }, luca[] = { 2, 1, 0 };
  int *fibonacci = anynacci (fibo, 10), *tribonacci = anynacci (tribo, 10), *tetranacci = anynacci (tetra, 10), 
      *lucas = anynacci(luca, 10);
  int i;

  printf ("\nFibonacci\tTribonacci\tTetranacci\tLucas\n");

  for (i = 0; i < 10; i++)
    printf ("\n%d\t\t%d\t\t%d\t\t%d", fibonacci[i], tribonacci[i],
            tetranacci[i], lucas[i]);

  return 0;
}











Ada: package Bonacci is

   type Sequence is array(Positive range <>) of Positive;

   function Generate(Start: Sequence; Length: Positive := 10) return Sequence;

   Start_Fibonacci:  constant Sequence := (1, 1);
   Start_Tribonacci: constant Sequence := (1, 1, 2);
   Start_Tetranacci: constant Sequence := (1, 1, 2, 4);
   Start_Lucas:      constant Sequence := (2, 1);
end Bonacci;