WeixiangYan/CodeTransOcean huggingface dataset:
Task: Loops_Wrong ranges







Python: import re
from itertools import islice 




data = 

table = [re.split(r'\s\s+', line.strip()) for line in data.strip().split('\n')]

for _start, _stop, _increment, comment in table[1:]:
    start, stop, increment = [int(x) for x in (_start, _stop, _increment)]
    print(f'{comment.upper()}:\n  range({start}, {stop}, {increment})')
    values = None
    try: 
        values = list(islice(range(start, stop, increment), 999))
    except ValueError as e:
        print('  !!ERROR!!', e)
    if values is not None:
        if len(values) < 22:
            print('    =', values)
        else:
            print('    =', str(values[:22])[:-1], '...')





Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;

procedure Main is
   procedure print_range(start : integer; stop : integer; step : integer) is
      Num : Integer := start;
   begin
      Put("Range(" & start'Image & ", " & stop'image &
            ", " & step'image & ") => ");
      if stop < start then
         Put_Line("Error: stop must be no less than start!");
      elsif step not in positive then
         Put_Line("Error: increment must be greater than 0!");
      elsif start = stop then
         Put_Line(start'image);
      else
         while num <= stop loop
            Put(num'Image);
            num := num + step;
         end loop;
         New_Line;
      end if;
   end print_range;

   type test_record is record
      start   : integer;
      stop    : integer;
      step    : integer;
      comment : unbounded_string := null_unbounded_string;
   end record;

   tests : array(1..9) of test_record :=
     ( 1 => (-2, 2, 1, To_Unbounded_String("Normal")),
       2 => (-2, 2, 0, To_Unbounded_String("Zero increment")),
       3 => (-2, 2, -1, To_Unbounded_String("Increments away from stop value")),
       4 => (-2, 2, 10, To_Unbounded_String("First increment is beyond stop value")),
       5 => (2, -1, 1, To_Unbounded_String("Start more than stop: positive increment")),
       6 => (2, 2, 1, To_Unbounded_String("Start equal stop: positive increment")),
       7 => (2, 2, -1, To_Unbounded_String("Start equal stop: negative increment")),
       8 => (2, 2, 0, To_Unbounded_String("Start equal stop: zero increment")),
       9 => (0, 0, 0, To_Unbounded_String("Start equal stop equal zero: zero increment")));


begin
   for test of tests loop
      Put(Test.Comment); Put(" : ");
      print_range(test.start, test.stop, test.step);
      New_line;
   end loop;
end Main;
Task: Loops_Wrong ranges








VB: Public Sub LoopsWrongRanges()
    Call Example(-2, 2, 1, "Normal")
    Call Example(-2, 2, 0, "Zero increment")
    Call Example(-2, 2, -1, "Increments away from stop value")
    Call Example(-2, 2, 10, "First increment is beyond stop value")
    Call Example(2, -2, 1, "Start more than stop: positive increment")
    Call Example(2, 2, 1, "Start equal stop: positive increment")
    Call Example(2, 2, -1, "Start equal stop: negative increment")
    Call Example(2, 2, 0, "Start equal stop: zero increment")
    Call Example(0, 0, 0, "Start equal stop equal zero: zero increment")
End Sub
Private Sub Example(start As Integer, stop_ As Integer, by As Integer, comment As String)
    Dim i As Integer
    Dim c As Integer
    Const limit = 10
    c = 0
    Debug.Print start; " "; stop_; " "; by; " | ";
    For i = start To stop_ Step by
        Debug.Print i & ",";
        c = c + 1
        If c > limit Then Exit For
    Next i
    Debug.Print
    Debug.Print comment & vbCrLf
End Sub




Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;

procedure Main is
   procedure print_range(start : integer; stop : integer; step : integer) is
      Num : Integer := start;
   begin
      Put("Range(" & start'Image & ", " & stop'image &
            ", " & step'image & ") => ");
      if stop < start then
         Put_Line("Error: stop must be no less than start!");
      elsif step not in positive then
         Put_Line("Error: increment must be greater than 0!");
      elsif start = stop then
         Put_Line(start'image);
      else
         while num <= stop loop
            Put(num'Image);
            num := num + step;
         end loop;
         New_Line;
      end if;
   end print_range;

   type test_record is record
      start   : integer;
      stop    : integer;
      step    : integer;
      comment : unbounded_string := null_unbounded_string;
   end record;

   tests : array(1..9) of test_record :=
     ( 1 => (-2, 2, 1, To_Unbounded_String("Normal")),
       2 => (-2, 2, 0, To_Unbounded_String("Zero increment")),
       3 => (-2, 2, -1, To_Unbounded_String("Increments away from stop value")),
       4 => (-2, 2, 10, To_Unbounded_String("First increment is beyond stop value")),
       5 => (2, -1, 1, To_Unbounded_String("Start more than stop: positive increment")),
       6 => (2, 2, 1, To_Unbounded_String("Start equal stop: positive increment")),
       7 => (2, 2, -1, To_Unbounded_String("Start equal stop: negative increment")),
       8 => (2, 2, 0, To_Unbounded_String("Start equal stop: zero increment")),
       9 => (0, 0, 0, To_Unbounded_String("Start equal stop equal zero: zero increment")));


begin
   for test of tests loop
      Put(Test.Comment); Put(" : ");
      print_range(test.start, test.stop, test.step);
      New_line;
   end loop;
end Main;
Task: Loops_Wrong ranges

C: #include <stdio.h>

#define TRUE 1
#define FALSE 0

typedef int bool;

typedef struct {
    int start, stop, incr;
    const char *comment;
} S;

S examples[9] = {
    {-2, 2, 1, "Normal"},
    {-2, 2, 0, "Zero increment"},
    {-2, 2, -1, "Increments away from stop value"},
    {-2, 2, 10, "First increment is beyond stop value"},
    {2, -2, 1, "Start more than stop: positive increment"},
    {2, 2, 1, "Start equal stop: positive increment"},
    {2, 2, -1, "Start equal stop: negative increment"},
    {2, 2, 0, "Start equal stop: zero increment"},
    {0, 0, 0, "Start equal stop equal zero: zero increment"}
};

int main() {
    int i, j, c;
    bool empty;
    S s;
    const int limit = 10;
    for (i = 0; i < 9; ++i) {
        s = examples[i];
        printf("%s\n", s.comment);
        printf("Range(%d, %d, %d) -> [", s.start, s.stop, s.incr);
        empty = TRUE;
        for (j = s.start, c = 0; j <= s.stop && c < limit; j += s.incr, ++c) {
            printf("%d ", j);
            empty = FALSE;
        }
        if (!empty) printf("\b");
        printf("]\n\n");
    }
    return 0;
}
Task: Loops_Wrong ranges



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

static class Program
{
    static void Main()
    {
        Example(-2, 2, 1, "Normal");
        Example(-2, 2, 0, "Zero increment");
        Example(-2, 2, -1, "Increments away from stop value");
        Example(-2, 2, 10, "First increment is beyond stop value");
        Example(2, -2, 1, "Start more than stop: positive increment");
        Example(2, 2, 1, "Start equal stop: positive increment");
        Example(2, 2, -1, "Start equal stop: negative increment");
        Example(2, 2, 0, "Start equal stop: zero increment");
        Example(0, 0, 0, "Start equal stop equal zero: zero increment");
    }

    static IEnumerable<int> Range(int start, int stop, int increment)
    {
        
        

        
        

        
        for (int i = start; i <= stop; i += increment)
            yield return i;
    }

    static void Example(int start, int stop, int increment, string comment)
    {
        
        Console.Write((comment + " ").PadRight(50, '-') + " ");

        const int MAX_ITER = 9;

        int iteration = 0;
        foreach (int i in Range(start, stop, increment))
        {
            Console.Write("{0,2} ", i);

            if (++iteration > MAX_ITER) break;
        }

        Console.WriteLine();
    }
}
Task: Loops_Wrong ranges





Java: import java.util.ArrayList;
import java.util.List;

public class LoopsWrongRanges {

    public static void main(String[] args) {
        runTest(new LoopTest(-2, 2, 1, "Normal"));
        runTest(new LoopTest(-2, 2, 0, "Zero increment"));
        runTest(new LoopTest(-2, 2, -1, "Increments away from stop value"));
        runTest(new LoopTest(-2, 2, 10, "First increment is beyond stop value"));
        runTest(new LoopTest(2, -2, 1, "Start more than stop: positive increment"));
        runTest(new LoopTest(2, 2, 1, "Start equal stop: positive increment"));
        runTest(new LoopTest(2, 2, -1, "Start equal stop: negative increment"));
        runTest(new LoopTest(2, 2, 0, "Start equal stop: zero increment"));
        runTest(new LoopTest(0, 0, 0, "Start equal stop equal zero: zero increment"));
    }
    
    private static void runTest(LoopTest loopTest) {
        List<Integer> values = new ArrayList<>();
        for (int i = loopTest.start ; i <= loopTest.stop ; i += loopTest.increment ) {
            values.add(i);
            if ( values.size() >= 10 ) {
                break;
            }
        }
        System.out.printf("%-45s %s%s%n", loopTest.comment, values, values.size()==10 ? " (loops forever)" : "");
    }
    
    private static class LoopTest {
        int start;
        int stop;
        int increment;
        String comment;
        public LoopTest(int start, int stop, int increment, String comment) {
            this.start = start;
            this.stop = stop;
            this.increment = increment;
            this.comment = comment;
        }
    }

}
Task: Loops_Wrong ranges







Python: import re
from itertools import islice 




data = 

table = [re.split(r'\s\s+', line.strip()) for line in data.strip().split('\n')]

for _start, _stop, _increment, comment in table[1:]:
    start, stop, increment = [int(x) for x in (_start, _stop, _increment)]
    print(f'{comment.upper()}:\n  range({start}, {stop}, {increment})')
    values = None
    try: 
        values = list(islice(range(start, stop, increment), 999))
    except ValueError as e:
        print('  !!ERROR!!', e)
    if values is not None:
        if len(values) < 22:
            print('    =', values)
        else:
            print('    =', str(values[:22])[:-1], '...')
Task: Loops_Wrong ranges








VB: Public Sub LoopsWrongRanges()
    Call Example(-2, 2, 1, "Normal")
    Call Example(-2, 2, 0, "Zero increment")
    Call Example(-2, 2, -1, "Increments away from stop value")
    Call Example(-2, 2, 10, "First increment is beyond stop value")
    Call Example(2, -2, 1, "Start more than stop: positive increment")
    Call Example(2, 2, 1, "Start equal stop: positive increment")
    Call Example(2, 2, -1, "Start equal stop: negative increment")
    Call Example(2, 2, 0, "Start equal stop: zero increment")
    Call Example(0, 0, 0, "Start equal stop equal zero: zero increment")
End Sub
Private Sub Example(start As Integer, stop_ As Integer, by As Integer, comment As String)
    Dim i As Integer
    Dim c As Integer
    Const limit = 10
    c = 0
    Debug.Print start; " "; stop_; " "; by; " | ";
    For i = start To stop_ Step by
        Debug.Print i & ",";
        c = c + 1
        If c > limit Then Exit For
    Next i
    Debug.Print
    Debug.Print comment & vbCrLf
End Sub
Task: Loops_Wrong ranges




Go: package main

import "fmt"

type S struct {
    start, stop, incr int
    comment          string
}

var examples = []S{
    {-2, 2, 1, "Normal"},
    {-2, 2, 0, "Zero increment"},
    {-2, 2, -1, "Increments away from stop value"},
    {-2, 2, 10, "First increment is beyond stop value"},
    {2, -2, 1, "Start more than stop: positive increment"},
    {2, 2, 1, "Start equal stop: positive increment"},
    {2, 2, -1, "Start equal stop: negative increment"},
    {2, 2, 0, "Start equal stop: zero increment"},
    {0, 0, 0, "Start equal stop equal zero: zero increment"},
}

func sequence(s S, limit int) []int {
    var seq []int
    for i, c := s.start, 0; i <= s.stop && c < limit; i, c = i+s.incr, c+1 {
        seq = append(seq, i)
    }
    return seq
}

func main() {
    const limit = 10
    for _, ex := range examples {
        fmt.Println(ex.comment)
        fmt.Printf("Range(%d, %d, %d) -> ", ex.start, ex.stop, ex.incr)
        fmt.Println(sequence(ex, limit))
        fmt.Println()
    }
}
Task: Loops_Wrong ranges








VB: Module Program
    Sub Main()
        Example(-2, 2, 1, "Normal")
        Example(-2, 2, 0, "Zero increment")
        Example(-2, 2, -1, "Increments away from stop value")
        Example(-2, 2, 10, "First increment is beyond stop value")
        Example(2, -2, 1, "Start more than stop: positive increment")
        Example(2, 2, 1, "Start equal stop: positive increment")
        Example(2, 2, -1, "Start equal stop: negative increment")
        Example(2, 2, 0, "Start equal stop: zero increment")
        Example(0, 0, 0, "Start equal stop equal zero: zero increment")
    End Sub

    
    Iterator Function Range(start As Integer, [stop] As Integer, increment As Integer) As IEnumerable(Of Integer)
        For i = start To [stop] Step increment
            Yield i
        Next
    End Function

    Sub Example(start As Integer, [stop] As Integer, increment As Integer, comment As String)
        
        Console.Write((comment & " ").PadRight(50, "-"c) & " ")

        Const MAX_ITER = 9

        Dim iteration = 0
        
        For Each i In Range(start, [stop], increment)
            Console.Write("{0,2} ", i)

            iteration += 1
            If iteration > MAX_ITER Then Exit For
        Next

        Console.WriteLine()
    End Sub
End Module
Task: Bacon cipher

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


char *codes[] = {
    "AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA",
    "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB",
    "ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA",
    "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB",
    "BABAA", "BABAB", "BABBA", "BABBB", "BBAAA",
    "BBAAB", "BBBAA"
};

char *get_code(const char c) {
    if (c >= 97 && c <= 122) return codes[c - 97];
    return codes[26];
}

char get_char(const char *code) {
    int i;
    if (!strcmp(codes[26], code)) return ' ';
    for (i = 0; i < 26; ++i) {
        if (strcmp(codes[i], code) == 0) return 97 + i;
    }
    printf("\nCode \"%s\" is invalid\n", code);
    exit(1);
}

void str_tolower(char s[]) {
    int i;
    for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);
}

char *bacon_encode(char plain_text[], char message[]) {
    int i, count;
    int plen = strlen(plain_text), mlen = strlen(message);
    int elen = 5 * plen;
    char c;
    char *p, *et, *mt;
    et = malloc(elen + 1);  
    str_tolower(plain_text);
    for (i = 0, p = et; i < plen; ++i, p += 5) {
        c = plain_text[i];
        strncpy(p, get_code(c), 5);
    }
    *++p = '\0';

    
    str_tolower(message);
    mt = calloc(mlen + 1, 1);
    for (i = 0, count = 0; i < mlen; ++i) {
        c = message[i];
        if (c >= 'a' && c <= 'z') {
            if (et[count] == 'A')
                mt[i] = c;
            else
                mt[i] = c - 32;  
            if (++count == elen) break;
        }
        else mt[i] = c;
    }
    free(et);     
    return mt;
}

char *bacon_decode(char cipher_text[]) {
    int i, count, clen = strlen(cipher_text);
    int plen;
    char *p, *ct, *pt;
    char c, quintet[6];
    ct = calloc(clen + 1, 1);
    for (i = 0, count = 0; i < clen; ++i) {
        c = cipher_text[i];
        if (c >= 'a' && c <= 'z')
            ct[count++] = 'A';
        else if (c >= 'A' && c <= 'Z')
            ct[count++] = 'B';
    }

    plen = strlen(ct) / 5; 
    pt = malloc(plen + 1);
    for (i = 0, p = ct; i < plen; ++i, p += 5) {
        strncpy(quintet, p, 5);
        quintet[5] = '\0';
        pt[i] = get_char(quintet);
    }
    pt[plen] = '\0';
    free(ct);
    return pt;
} 

int main() {
    char plain_text[] = "the quick brown fox jumps over the lazy dog";
    char message[] = "bacon's cipher is a method of steganography created by francis bacon."
        "this task is to implement a program for encryption and decryption of "
        "plaintext using the simple alphabet of the baconian cipher or some "
        "other kind of representation of this alphabet (make anything signify anything). "
        "the baconian alphabet may optionally be extended to encode all lower "
        "case characters individually and/or adding a few punctuation characters "
        "such as the space.";
    char *cipher_text, *hidden_text;
    cipher_text = bacon_encode(plain_text, message);
    printf("Cipher text ->\n\n%s\n", cipher_text);
    hidden_text = bacon_decode(cipher_text);
    printf("\nHidden text ->\n\n%s\n", hidden_text);
    free(cipher_text);
    free(hidden_text);
    return 0;
}
Task: Bacon cipher


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

class bacon {
public:
    bacon() {
        int x = 0;
        for( ; x < 9; x++ )
            bAlphabet.push_back( std::bitset<5>( x ).to_string() );
        bAlphabet.push_back( bAlphabet.back() );
        
        for( ; x < 20; x++ )
            bAlphabet.push_back( std::bitset<5>( x ).to_string() );
        bAlphabet.push_back( bAlphabet.back() );
        
        for( ; x < 24; x++ )
            bAlphabet.push_back( std::bitset<5>( x ).to_string() );
    }

    std::string encode( std::string txt ) {
        std::string r;
        size_t z;
        for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {
            z = toupper( *i );
            if( z < 'A' || z > 'Z' ) continue;
            r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );
        }
        return r;
    }

    std::string decode( std::string txt ) {
        size_t len = txt.length();
        while( len % 5 != 0 ) len--;
        if( len != txt.length() ) txt = txt.substr( 0, len );
        std::string r;
        for( size_t i = 0; i < len; i += 5 ) {
            r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );
        }
        return r;
    }

private:
    std::vector<std::string> bAlphabet;
};
Task: Bacon cipher







Python: import string

sometext = .lower()

lc2bin = {ch: '{:05b}'.format(i) 
          for i, ch in enumerate(string.ascii_lowercase + ' .')}
bin2lc = {val: key for key, val in lc2bin.items()}

phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()

def to_5binary(msg):
    return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))

def encrypt(message, text):
    bin5 = to_5binary(message)
    textlist = list(text.lower())
    out = []
    for capitalise in bin5:
        while textlist:
            ch = textlist.pop(0)
            if ch.isalpha():
                if capitalise:
                    ch = ch.upper()
                out.append(ch)
                break
            else:
                out.append(ch)
        else:
            raise Exception('ERROR: Ran out of characters in sometext')
    return ''.join(out) + '...'


def  decrypt(bacontext):
    binary = []
    bin5 = []
    out = []
    for ch in bacontext:
        if ch.isalpha():
            binary.append('1' if ch.isupper() else '0')
            if len(binary) == 5:
                bin5 = ''.join(binary)
                out.append(bin2lc[bin5])
                binary = []
    return ''.join(out)
                

print('PLAINTEXT = \n%s\n' % phrase)
encrypted = encrypt(phrase, sometext)
print('ENCRYPTED = \n%s\n' % encrypted)
decrypted = decrypt(encrypted)
print('DECRYPTED = \n%s\n' % decrypted)
assert phrase == decrypted, 'Round-tripping error'
Task: Bacon cipher








VB: Imports System.Text

Module Module1

    ReadOnly CODES As New Dictionary(Of Char, String) From {
        {"a", "AAAAA"}, {"b", "AAAAB"}, {"c", "AAABA"}, {"d", "AAABB"}, {"e", "AABAA"},
        {"f", "AABAB"}, {"g", "AABBA"}, {"h", "AABBB"}, {"i", "ABAAA"}, {"j", "ABAAB"},
        {"k", "ABABA"}, {"l", "ABABB"}, {"m", "ABBAA"}, {"n", "ABBAB"}, {"o", "ABBBA"},
        {"p", "ABBBB"}, {"q", "BAAAA"}, {"r", "BAAAB"}, {"s", "BAABA"}, {"t", "BAABB"},
        {"u", "BABAA"}, {"v", "BABAB"}, {"w", "BABBA"}, {"x", "BABBB"}, {"y", "BBAAA"},
        {"z", "BBAAB"}, {" ", "BBBAA"} 
    }

    Function Encode(plainText As String, message As String) As String
        Dim pt = plainText.ToLower()
        Dim sb As New StringBuilder()
        For Each c In pt
            If "a" <= c AndAlso c <= "z" Then
                sb.Append(CODES(c))
            Else
                sb.Append(CODES(" "))
            End If
        Next

        Dim et = sb.ToString()
        Dim mg = message.ToLower() 

        sb.Length = 0
        Dim count = 0
        For Each c In mg
            If "a" <= c AndAlso c <= "z" Then
                If et(count) = "A" Then
                    sb.Append(c)
                Else
                    sb.Append(Chr(Asc(c) - 32)) 
                End If
                count += 1
                If count = et.Length Then
                    Exit For
                End If
            Else
                sb.Append(c)
            End If
        Next

        Return sb.ToString()
    End Function

    Function Decode(message As String) As String
        Dim sb As New StringBuilder

        For Each c In message
            If "a" <= c AndAlso c <= "z" Then
                sb.Append("A")
            ElseIf "A" <= c AndAlso c <= "Z" Then
                sb.Append("B")
            End If
        Next

        Dim et = sb.ToString()
        sb.Length = 0
        For index = 0 To et.Length - 1 Step 5
            Dim quintet = et.Substring(index, 5)
            Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key
            sb.Append(key)
        Next

        Return sb.ToString()
    End Function

    Sub Main()
        Dim plainText = "the quick brown fox jumps over the lazy dog"
        Dim message =
            "bacon
            "this task is to implement a program for encryption and decryption of " +
            "plaintext using the simple alphabet of the baconian cipher or some " +
            "other kind of representation of this alphabet (make anything signify anything). " +
            "the baconian alphabet may optionally be extended to encode all lower " +
            "case characters individually and/or adding a few punctuation characters " +
            "such as the space."

        Dim cipherText = Encode(plainText, message)
        Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText)

        Dim decodedText = Decode(cipherText)
        Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText)
    End Sub

End Module