WeixiangYan/CodeTransOcean huggingface dataset:
Task: JSON



C#: using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

class Program
{
    static void Main()
    {
        var people = new Dictionary<string, object> {{"1", "John"}, {"2", "Susan"}};
        var serializer = new JavaScriptSerializer();
        
        var json = serializer.Serialize(people);
        Console.WriteLine(json);

        var deserialized = serializer.Deserialize<Dictionary<string, object>>(json);
        Console.WriteLine(deserialized["2"]);

        var jsonObject = serializer.DeserializeObject(@"{ ""foo"": 1, ""bar"": [10, ""apples""] }");
        var data = jsonObject as Dictionary<string, object>;
        var array = data["bar"] as object[];
        Console.WriteLine(array[1]);
    }
}




PHP: <?php
$data = json_decode('{ "foo": 1, "bar": [10, "apples"] }'); // dictionaries will be returned as objects
$data2 = json_decode('{ "foo": 1, "bar": [10, "apples"] }', true); // dictionaries will be returned as arrays

$sample = array( "blue" => array(1,2), "ocean" => "water" );
$json_string = json_encode($sample);
?>
Task: JSON


C++: #include "Core/Core.h"

using namespace Upp;

CONSOLE_APP_MAIN
{
	JsonArray a;
	a << Json("name", "John")("phone", "1234567") << Json("name", "Susan")("phone", "654321");
	String txt = ~a;
	Cout() << txt << '\n';
	Value v = ParseJSON(txt);
	for(int i = 0; i < v.GetCount(); i++)
		Cout() << v[i]["name"] << ' ' << v[i]["phone"] << '\n';
}





PHP: <?php
$data = json_decode('{ "foo": 1, "bar": [10, "apples"] }'); // dictionaries will be returned as objects
$data2 = json_decode('{ "foo": 1, "bar": [10, "apples"] }', true); // dictionaries will be returned as arrays

$sample = array( "blue" => array(1,2), "ocean" => "water" );
$json_string = json_encode($sample);
?>
Task: JSON




Go: package main

import "encoding/json"
import "fmt"

func main() {
    var data interface{}
    err := json.Unmarshal([]byte(`{"foo":1, "bar":[10, "apples"]}`), &data)
    if err == nil {
        fmt.Println(data)
    } else {
        fmt.Println(err)
    }

    sample := map[string]interface{}{
        "blue":  []interface{}{1, 2},
        "ocean": "water",
    }
    json_string, err := json.Marshal(sample)
    if err == nil {
        fmt.Println(string(json_string))
    } else {
        fmt.Println(err)
    }
}



PHP: <?php
$data = json_decode('{ "foo": 1, "bar": [10, "apples"] }'); // dictionaries will be returned as objects
$data2 = json_decode('{ "foo": 1, "bar": [10, "apples"] }', true); // dictionaries will be returned as arrays

$sample = array( "blue" => array(1,2), "ocean" => "water" );
$json_string = json_encode($sample);
?>
Task: JSON





Java: 



grammar JSON ;
@members {
String Indent = "";
}
Number	:	(('0')|('-'? ('1'..'9') ('0'..'9')*)) ('.' ('0'..'9')+)? (('e'|'E') ('+'|'-')? ('0'..'9')+)?;
WS	:	(' ' | '\t' | '\r' |'\n') {skip();};
Tz	:	' ' .. '!' | '#' .. '[' | ']' .. '~';
Control	:	'\\' ('"'|'\\'|'/'|'b'|'f'|'n'|'r'|'t'|UCode);
UCode	:	'u' ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F');
Keyword	:	'true' | 'false' | 'null';
String	:	'"' (Control? Tz)* '"';
object	:       '{' {System.out.println(Indent + "{Object}"); Indent += "    ";} (pair (',' pair*)*)? '}' {Indent = Indent.substring(4);};
pair	:	e = String {System.out.println(Indent + "{Property}\t" + $e.text);} ':' value;
value	:	Number             {System.out.println(Indent + "{Number}  \t" + $Number.text);}
	|	object
	|	String             {System.out.println(Indent + "{String}  \t" + $String.text);}
	|	Keyword            {System.out.println(Indent + "{Keyword} \t" + $Keyword.text);}
	|	array;
array	:	'[' {System.out.println(Indent + "Array"); Indent += "    ";} (value (',' value)*)? ']' {Indent = Indent.substring(4);};


PHP: <?php
$data = json_decode('{ "foo": 1, "bar": [10, "apples"] }'); // dictionaries will be returned as objects
$data2 = json_decode('{ "foo": 1, "bar": [10, "apples"] }', true); // dictionaries will be returned as arrays

$sample = array( "blue" => array(1,2), "ocean" => "water" );
$json_string = json_encode($sample);
?>
Task: JSON






PHP: <?php
$data = json_decode('{ "foo": 1, "bar": [10, "apples"] }'); // dictionaries will be returned as objects
$data2 = json_decode('{ "foo": 1, "bar": [10, "apples"] }', true); // dictionaries will be returned as arrays

$sample = array( "blue" => array(1,2), "ocean" => "water" );
$json_string = json_encode($sample);
?>


Python: >>> import json
>>> data = json.loads('{ "foo": 1, "bar": [10, "apples"] }')
>>> sample = { "blue": [1,2], "ocean": "water" }
>>> json_string = json.dumps(sample)
>>> json_string
'{"blue": [1, 2], "ocean": "water"}'
>>> sample
{'blue': [1, 2], 'ocean': 'water'}
>>> data
{'foo': 1, 'bar': [10, 'apples']}
Task: JSON






PHP: <?php
$data = json_decode('{ "foo": 1, "bar": [10, "apples"] }'); // dictionaries will be returned as objects
$data2 = json_decode('{ "foo": 1, "bar": [10, "apples"] }', true); // dictionaries will be returned as arrays

$sample = array( "blue" => array(1,2), "ocean" => "water" );
$json_string = json_encode($sample);
?>



VB: #include "inc/fbJSON.bas"

Sub printNodeChildren(Byval n As fbJSON Ptr, Byval level As Integer)
End Sub

Dim test As fbJSON Ptr = fbJSON_ImportFile("test1.json")

If test = NULL Then
	Print "Unable to load json file/string!"
	End 1
End If

Print fbJSON_ExportString(test, 1)

fbJSON_Delete(test)

Sleep
Task: Determine if a string is squeezable


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

template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
    auto i = std::unique(str.begin(), str.end(),
        [ch](char_type a, char_type b) { return a == ch && b == ch; });
    str.erase(i, str.end());
    return str;
}

void test(const std::string& str, char ch) {
    std::cout << "character: '" << ch << "'\n";
    std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
    std::string squeezed(squeeze(str, ch));
    std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
    std::cout << '\n';
}

int main(int argc, char** argv) {
    test("", ' ');
    test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
    test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
    test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
    std::string truman("                                                    --- Harry S Truman  ");
    test(truman, ' ');
    test(truman, '-');
    test(truman, 'r');
    return 0;
}


C#: using System;
using static System.Linq.Enumerable;

public class Program
{
    static void Main()
    {
        SqueezeAndPrint("", ' ');
        SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
        SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
        SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
        string s = "                                                    --- Harry S Truman  ";
        SqueezeAndPrint(s, ' ');
        SqueezeAndPrint(s, '-');
        SqueezeAndPrint(s, 'r');
    }

    static void SqueezeAndPrint(string s, char c) {
        Console.WriteLine($"squeeze: '{c}'");
        Console.WriteLine($"old: {s.Length} «««{s}»»»");
        s = Squeeze(s, c);
        Console.WriteLine($"new: {s.Length} «««{s}»»»");
    }

    static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" :
        s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray());
}
Task: Determine if a string is squeezable


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

template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
    auto i = std::unique(str.begin(), str.end(),
        [ch](char_type a, char_type b) { return a == ch && b == ch; });
    str.erase(i, str.end());
    return str;
}

void test(const std::string& str, char ch) {
    std::cout << "character: '" << ch << "'\n";
    std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
    std::string squeezed(squeeze(str, ch));
    std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
    std::cout << '\n';
}

int main(int argc, char** argv) {
    test("", ' ');
    test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
    test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
    test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
    std::string truman("                                                    --- Harry S Truman  ");
    test(truman, ' ');
    test(truman, '-');
    test(truman, 'r');
    return 0;
}



Go: package main

import "fmt"



func squeeze(s string, c rune) (string, int, int) {
    r := []rune(s)
    le, del := len(r), 0
    for i := le - 2; i >= 0; i-- {
        if r[i] == c && r[i] == r[i+1] {
            copy(r[i:], r[i+1:])
            del++
        }
    }
    if del == 0 {
        return s, le, le
    }
    r = r[:le-del]
    return string(r), le, len(r)
}

func main() {
    strings := []string{
        "",
        `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                   ---  Harry S Truman  ",
        "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
        "headmistressship",
        "aardvark",
        "😍😀🙌💃😍😍😍🙌",
    }
    chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}

    for i, s := range strings {
        for _, c := range chars[i] {
            ss, olen, slen := squeeze(s, c)
            fmt.Printf("specified character = %q\n", c)
            fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
            fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
        }
    }
}
Task: Determine if a string is squeezable


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

template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
    auto i = std::unique(str.begin(), str.end(),
        [ch](char_type a, char_type b) { return a == ch && b == ch; });
    str.erase(i, str.end());
    return str;
}

void test(const std::string& str, char ch) {
    std::cout << "character: '" << ch << "'\n";
    std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
    std::string squeezed(squeeze(str, ch));
    std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
    std::cout << '\n';
}

int main(int argc, char** argv) {
    test("", ' ');
    test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
    test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
    test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
    std::string truman("                                                    --- Harry S Truman  ");
    test(truman, ' ');
    test(truman, '-');
    test(truman, 'r');
    return 0;
}




Java: 

public class StringSqueezable {

    public static void main(String[] args) {
        String[] testStrings = new String[] {
                "", 
                "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", 
                "..1111111111111111111111111111111111111111111111111111111111111117777888", 
                "I never give 'em hell, I just tell the truth, and they think it's hell. ", 
                "                                                    --- Harry S Truman  ",
                "122333444455555666666777777788888888999999999",
                "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
                "headmistressship"};

        String[] testChar = new String[] {
                " ", 
                "-", 
                "7", 
                ".", 
                " -r",
                "5",
                "e",
                "s"};
        for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) {
            String s = testStrings[testNum];
            for ( char c : testChar[testNum].toCharArray() ) {
                String result = squeeze(s, c);
                System.out.printf("use: '%c'%nold:  %2d <<<%s>>>%nnew:  %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result);
            }
        }
    }
    
    private static String squeeze(String in, char include) {
        StringBuilder sb = new StringBuilder();
        for ( int i = 0 ; i < in.length() ; i++ ) {
            if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) {
                sb.append(in.charAt(i));
            }
        }
        return sb.toString();
    }

}
Task: Determine if a string is squeezable


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

template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
    auto i = std::unique(str.begin(), str.end(),
        [ch](char_type a, char_type b) { return a == ch && b == ch; });
    str.erase(i, str.end());
    return str;
}

void test(const std::string& str, char ch) {
    std::cout << "character: '" << ch << "'\n";
    std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
    std::string squeezed(squeeze(str, ch));
    std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
    std::cout << '\n';
}

int main(int argc, char** argv) {
    test("", ' ');
    test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
    test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
    test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
    std::string truman("                                                    --- Harry S Truman  ");
    test(truman, ' ');
    test(truman, '-');
    test(truman, 'r');
    return 0;
}






Python: from itertools import groupby

def squeezer(s, txt):
    return ''.join(item if item == s else ''.join(grp)
                   for item, grp in groupby(txt))

if __name__ == '__main__':
    strings = [
            "",
            '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
            "..1111111111111111111111111111111111111111111111111111111111111117777888",
            "I never give 'em hell, I just tell the truth, and they think it's hell. ",
            "                                                   ---  Harry S Truman  ",
            "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
            "headmistressship",
            "aardvark",
            "😍😀🙌💃😍😍😍🙌",
            ]
    squeezers = ' ,-,7,., -r,e,s,a,😍'.split(',')
    for txt, chars in zip(strings, squeezers):
        this = "Original"
        print(f"\n{this:14} Size: {len(txt)} «««{txt}»»»" )
        for ch in chars:
            this = f"Squeezer '{ch}'"
            sqz = squeezer(ch, txt)
            print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )
Task: Determine if a string is squeezable


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

template<typename char_type>
std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) {
    auto i = std::unique(str.begin(), str.end(),
        [ch](char_type a, char_type b) { return a == ch && b == ch; });
    str.erase(i, str.end());
    return str;
}

void test(const std::string& str, char ch) {
    std::cout << "character: '" << ch << "'\n";
    std::cout << "original: <<<" << str << ">>>, length: " << str.length() << '\n';
    std::string squeezed(squeeze(str, ch));
    std::cout << "result: <<<" << squeezed << ">>>, length: " << squeezed.length() << '\n';
    std::cout << '\n';
}

int main(int argc, char** argv) {
    test("", ' ');
    test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
    test("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
    test("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
    std::string truman("                                                    --- Harry S Truman  ");
    test(truman, ' ');
    test(truman, '-');
    test(truman, 'r');
    return 0;
}







VB: Imports System.Linq.Enumerable

Module Module1

    Function Squeeze(s As String, c As Char) As String
        If String.IsNullOrEmpty(s) Then
            Return ""
        End If
        Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray())
    End Function

    Sub SqueezeAndPrint(s As String, c As Char)
        Console.WriteLine("squeeze: 
        Console.WriteLine("old: {0} «««{1}»»»", s.Length, s)
        s = Squeeze(s, c)
        Console.WriteLine("new: {0} «««{1}»»»", s.Length, s)
    End Sub

    Sub Main()
        Const QUOTE = """"

        SqueezeAndPrint("", " ")
        SqueezeAndPrint(QUOTE & "If I were two-faced, would I be wearing this one?" & QUOTE & " --- Abraham Lincoln ", "-")
        SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", "7")
        SqueezeAndPrint("I never give 

        Dim s = "                                                    --- Harry S Truman  "
        SqueezeAndPrint(s, " ")
        SqueezeAndPrint(s, "-")
        SqueezeAndPrint(s, "r")
    End Sub

End Module
Task: Determine if a string is squeezable



C#: using System;
using static System.Linq.Enumerable;

public class Program
{
    static void Main()
    {
        SqueezeAndPrint("", ' ');
        SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
        SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
        SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
        string s = "                                                    --- Harry S Truman  ";
        SqueezeAndPrint(s, ' ');
        SqueezeAndPrint(s, '-');
        SqueezeAndPrint(s, 'r');
    }

    static void SqueezeAndPrint(string s, char c) {
        Console.WriteLine($"squeeze: '{c}'");
        Console.WriteLine($"old: {s.Length} «««{s}»»»");
        s = Squeeze(s, c);
        Console.WriteLine($"new: {s.Length} «««{s}»»»");
    }

    static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" :
        s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray());
}


Go: package main

import "fmt"



func squeeze(s string, c rune) (string, int, int) {
    r := []rune(s)
    le, del := len(r), 0
    for i := le - 2; i >= 0; i-- {
        if r[i] == c && r[i] == r[i+1] {
            copy(r[i:], r[i+1:])
            del++
        }
    }
    if del == 0 {
        return s, le, le
    }
    r = r[:le-del]
    return string(r), le, len(r)
}

func main() {
    strings := []string{
        "",
        `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                   ---  Harry S Truman  ",
        "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
        "headmistressship",
        "aardvark",
        "😍😀🙌💃😍😍😍🙌",
    }
    chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}

    for i, s := range strings {
        for _, c := range chars[i] {
            ss, olen, slen := squeeze(s, c)
            fmt.Printf("specified character = %q\n", c)
            fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
            fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
        }
    }
}
Task: Determine if a string is squeezable



C#: using System;
using static System.Linq.Enumerable;

public class Program
{
    static void Main()
    {
        SqueezeAndPrint("", ' ');
        SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-');
        SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
        SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
        string s = "                                                    --- Harry S Truman  ";
        SqueezeAndPrint(s, ' ');
        SqueezeAndPrint(s, '-');
        SqueezeAndPrint(s, 'r');
    }

    static void SqueezeAndPrint(string s, char c) {
        Console.WriteLine($"squeeze: '{c}'");
        Console.WriteLine($"old: {s.Length} «««{s}»»»");
        s = Squeeze(s, c);
        Console.WriteLine($"new: {s.Length} «««{s}»»»");
    }

    static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" :
        s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray());
}



Java: 

public class StringSqueezable {

    public static void main(String[] args) {
        String[] testStrings = new String[] {
                "", 
                "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", 
                "..1111111111111111111111111111111111111111111111111111111111111117777888", 
                "I never give 'em hell, I just tell the truth, and they think it's hell. ", 
                "                                                    --- Harry S Truman  ",
                "122333444455555666666777777788888888999999999",
                "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
                "headmistressship"};

        String[] testChar = new String[] {
                " ", 
                "-", 
                "7", 
                ".", 
                " -r",
                "5",
                "e",
                "s"};
        for ( int testNum = 0 ; testNum < testStrings.length ; testNum++ ) {
            String s = testStrings[testNum];
            for ( char c : testChar[testNum].toCharArray() ) {
                String result = squeeze(s, c);
                System.out.printf("use: '%c'%nold:  %2d <<<%s>>>%nnew:  %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result);
            }
        }
    }
    
    private static String squeeze(String in, char include) {
        StringBuilder sb = new StringBuilder();
        for ( int i = 0 ; i < in.length() ; i++ ) {
            if ( i == 0 || in.charAt(i-1) != in.charAt(i) || (in.charAt(i-1) == in.charAt(i) && in.charAt(i) != include)) {
                sb.append(in.charAt(i));
            }
        }
        return sb.toString();
    }

}