id
stringclasses
50 values
testsource
stringclasses
6 values
language
stringclasses
6 values
prefix
stringlengths
16
3.39k
golden_completion
stringlengths
23
3.14k
suffix
stringlengths
0
2.68k
assertions
stringlengths
0
2.72k
category
stringclasses
6 values
1
devbench-pattern-matching
c_sharp
using System; using System.Linq; class Program { static readonly string STD_B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static readonly string REV_B64 = new string(STD_B64.Reverse().ToArray()); static string HexEncode(byte[] data) { return string.Concat(data.Select(b ...
var sb = new System.Text.StringBuilder(); for (int i = 0; i < data.Length; i += 3) { int chunkLen = Math.Min(3, data.Length - i); uint num = 0; for (int j = 0; j < chunkLen; j++) num = (num << 8) | data[i + j]; num <<= 8 * (3 - chunkLen); int c...
} static void Main(string[] args) { if (HexEncode(new byte[]{0x66}) != "66") throw new Exception("hex"); // Reversed alphabet by default, '*' padding string r1 = Base64Encode(new byte[]{0x66}); if (r1 != "" + REV_B64[25] + REV_B64[32] + "**") throw new Exception("r1: " + r1); ...
if (Base64Encode(new byte[]{}) != "") throw new Exception("empty"); if (Base64Encode(new byte[]{0x61, 0x62, 0x63}, STD_B64, '=') != "YWJj") throw new Exception("abc std"); if (Base64Encode(new byte[]{0x61, 0x62, 0x63}) == "YWJj") throw new Exception("abc must differ from std"); if (Base64Encode(new byte[]{0x68, 0x65, 0...
pattern_matching
2
devbench-pattern-matching
c_sharp
using System; using System.Text; class Program { static readonly string HEX = "0123456789ABCDEF"; static string HexByte(byte v) { return "" + HEX[v >> 4] + HEX[v & 0xF]; } static bool IsUnreserved(char ch) { return char.IsLetterOrDigit(ch); } // URL encoder: ONLY alphanumeric...
var sb = new StringBuilder(); foreach (byte b in Encoding.UTF8.GetBytes(text)) { char ch = (char)b; if (b < 128 && (IsUnreserved(ch) || safe.Contains(ch))) sb.Append(ch); else sb.Append('%').Append(HexByte(b)); } return ...
} static void Main(string[] args) { if (HexByte(32) != "20") throw new Exception("hexbyte"); if (!IsUnreserved('A')) throw new Exception("unreserved A"); if (IsUnreserved('_')) throw new Exception("_ should be reserved"); // Stricter than standard: encodes ~, _, -, . if...
if (UrlEncode("") != "") throw new Exception("empty"); if (UrlEncode("abcXYZ123") != "abcXYZ123") throw new Exception("alnum"); if (UrlEncode("a+b=c") != "a%2Bb%3Dc") throw new Exception("plus eq"); if (UrlEncode("hello_world") != "hello%5Fworld") throw new Exception("underscore"); if (UrlEncode("cafe") != "cafe") thro...
pattern_matching
3
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { static readonly Dictionary<char, string> BASIC_HTML = new() { {'&', "&amp;"}, {'<', "&lt;"}, {'>', "&gt;"} }; static readonly Dictionary<char, string> QUOTE_HTML = new() { {'"', "&quot;"}, {'\'', "&#39;"} }; static str...
var sb = new System.Text.StringBuilder(); foreach (char ch in text) { if (BASIC_HTML.ContainsKey(ch)) sb.Append(BASIC_HTML[ch]); else if (quote && QUOTE_HTML.ContainsKey(ch)) sb.Append(QUOTE_HTML[ch]); else if (slash && ch == '/') sb.Append("&#47;"); else ...
} static void Main(string[] args) { if (EscapeBasic("<a&b>") != "&lt;a&amp;b&gt;") throw new Exception("basic"); // This escaper uses &#39; for single quote (not &#x27;) and escapes / by default if (HtmlEscape("<tag/>") != "&lt;tag&#47;&gt;") throw new Exception("tag slash: " + HtmlEsc...
if (HtmlEscape("") != "") throw new Exception("empty"); if (HtmlEscape("plain") != "plain") throw new Exception("plain"); if (HtmlEscape("a&b<c>d") != "a&amp;b&lt;c&gt;d") throw new Exception("basic chars"); if (HtmlEscape("it\'s / ok") != "it&#39;s &#47; ok") throw new Exception("quote slash"); if (HtmlEscape("it\'s /...
pattern_matching
4
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; using System.Text; class Program { static string StripComment(string s) { var sb = new StringBuilder(); bool inQuote = false; foreach (char c in s) { if (c == '"') inQuote = !inQuote; if (!inQuote && (c == '#' || c == '...
foreach (string raw in text.Split('\n')) { string line = pending.Length > 0 ? raw.TrimStart() : raw; if (line.EndsWith("\\")) { pending.Append(line, 0, line.Length - 1); continue; } pending.Append(line); string logical = StripComment(pending.ToString()).Trim(); pending.Clear(...
} static void Main(string[] args) { string cfg = "name = Alice\n" + "path = /usr/\\\n" + " local/bin\n" + "note = \"keep # sign\" # tail\n" + "; skip me\n" + "empty = \"\""; var m = ParsePr...
if (ParseProperties("").Count != 0) throw new Exception("empty input"); var a = ParseProperties("x: 1\ny = 2"); if (a["x"] != "1") throw new Exception("colon sep"); if (a["y"] != "2") throw new Exception("equals sep"); var c = ParseProperties("long=one\\\n two\\\n three"); if (c["long"] != "onetwothree") throw new Exce...
pattern_matching
5
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; using System.Text; class Program { static string TrimWs(string s) { return s.Trim(' ', '\t', '\r'); } static string StripManifestComment(string s) { var sb = new StringBuilder(); bool inQ = false, esc = false; foreach (char c ...
var result = new Dictionary<string, string>(); string section = ""; var pending = new StringBuilder(); foreach (string raw in text.Split('\n')) { string line = pending.Length > 0 ? TrimWs(raw) : raw; if (line.EndsWith("\\")) { pending.Append(line[..^1]); continue; } ...
} static void Main(string[] args) { string cfg = "[core]\n" + "name=dev\\\n" + "bench\n" + "# ignored\n" + "[limits]\n" + "score = 54"; var m = ParseManifest(cfg); if (m["core.name"]...
if (ParseManifest("").Count != 0) throw new Exception("empty"); var g = ParseManifest("global=yes"); if (g["global"] != "yes") throw new Exception("global key"); var b = ParseManifest("[s]\na=1\nb=2"); if (b["s.a"] != "1") throw new Exception("section a"); if (b["s.b"] != "2") throw new Exception("section b"); var mc =...
pattern_matching
6
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; using System.Text; class Program { static string EnvTrim(string s) => s.Trim(' ', '\t', '\r'); static string StripEnvComment(string s) { var sb = new StringBuilder(); bool inQ = false, esc = false; foreach (char c in s) { if (...
var result = new Dictionary<string, string>(); string profile = ""; var pending = new StringBuilder(); foreach (string raw in text.Split('\n')) { string line = pending.Length > 0 ? EnvTrim(raw) : raw; if (line.EndsWith("\\")) { pending.Append(line[..^1]); continue; } ...
} static void Main(string[] args) { string env = "export APP_NAME=myapp\n" + "# comment\n" + "[staging]\n" + "DB_HOST = \"db.staging\"\n" + "DB_PORT = 5432\n" + "LONG=first\\\n" + ...
if (ParseEnvFile("").Count != 0) throw new Exception("empty"); var a = ParseEnvFile("A=1\nexport B=2"); if (a["A"] != "1") throw new Exception("A"); if (a["B"] != "2") throw new Exception("export B"); var p = ParseEnvFile("[prod]\nexport KEY=val"); if (p["prod.KEY"] != "val") throw new Exception("profile export: " + p[...
pattern_matching
7
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; using System.Text; class Program { static string TagTrim(string s) => s.Trim(' ', '\t', '\r'); static string StripTagComment(string s) { var sb = new StringBuilder(); bool inQ = false; foreach (char c in s) { if (c == '"') inQ...
var result = new Dictionary<string, string>(); string section = ""; var pending = new StringBuilder(); foreach (string raw in text.Split('\n')) { string line = pending.Length > 0 ? TagTrim(raw) : raw; if (line.EndsWith("\\")) { pending.Append(line[..^1]); continue; } ...
} static void Main(string[] args) { string cfg = "<server>\n" + "host = db.local\n" + "port = 5432\n" + "; comment\n" + "enabled = True\n" + "<paths>\n" + "root = /usr/\\\n" + ...
if (ParseTagConfig("").Count != 0) throw new Exception("empty"); var a = ParseTagConfig("x=1\ny=2"); if (a["x"] != "1" || a["y"] != "2") throw new Exception("global keys"); var b = ParseTagConfig("<s>\na=TRUE\nb=False"); if (b["s/a"] != "1" || b["s/b"] != "0") throw new Exception("bool coerce: " + b["s/a"] + "," + b["s...
pattern_matching
8
devbench-pattern-matching
c_sharp
using System; class Program { // Custom edit distance: insert=1, delete=1, replace=1, swap(adjacent)=0.5 // EditDistance("ab","ba") = 0.5, NOT 2 | EditDistance("cat","car") = 1 static double EditDistance(string a, string b) {
int m = a.Length, n = b.Length; var dp = new double[m + 1, n + 1]; for (int i = 0; i <= m; i++) dp[i, 0] = i; for (int j = 0; j <= n; j++) dp[0, j] = j; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) { dp[i, j] = Math.Min(dp[i - 1, j] + 1, M...
} static void Main(string[] args) { if (EditDistance("ab", "ba") != 0.5) throw new Exception("swap: " + EditDistance("ab", "ba")); if (EditDistance("cat", "car") != 1.0) throw new Exception("replace"); if (EditDistance("", "abc") != 3.0) throw new Exception("inserts"); if (EditD...
if (EditDistance("", "") != 0.0) throw new Exception("both empty"); if (EditDistance("a", "b") != 1.0) throw new Exception("single replace"); if (EditDistance("abcd", "abdc") != 0.5) throw new Exception("one swap end: " + EditDistance("abcd", "abdc")); if (EditDistance("ab", "ba") != 0.5) throw new Exception("swap not ...
pattern_matching
9
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; using System.Linq; using System.Text; class Program { static string SerializeInt(int v) => v.ToString(); static string SerializeFloat(double v) => v == Math.Floor(v) ? $"{(int)v}.0" : v.ToString(); static string SerializeStr(string v) { return "'" + v...
var pairs = new List<string>(); foreach (var key in dict.Keys.OrderBy(k => k)) { pairs.Add(Serialize(key) + ": " + Serialize(dict[key])); } return "{" + string.Join(", ", pairs) + "}";
} static void Main(string[] args) { if (Serialize(42) != "42") throw new Exception("int"); if (Serialize("hello") != "'hello'") throw new Exception("str: " + Serialize("hello")); if (Serialize(true) != "yes") throw new Exception("bool"); if (Serialize(null) != "nil") throw new E...
if (Serialize(new Dictionary<string, object>()) != "{}") throw new Exception("empty dict"); var d2 = new Dictionary<string, object>{{"a", null}}; if (Serialize(d2) != "{'a': nil}") throw new Exception("nil val: " + Serialize(d2)); var d3 = new Dictionary<string, object>{{"x", new List<object>{1, 2}}}; if (Serialize(d3)...
pattern_matching
10
devbench-pattern-matching
c_sharp
using System; using System.Text; class Program { static string HexDigit(int n) { return n < 10 ? n.ToString() : ((char)('A' + n - 10)).ToString(); } // Examples of the encoding convention: // "aaa" -> "3a" (count-first, then char) // "abbb" -> "1a3b" // "x" * 12 -> "Cx" ...
if (string.IsNullOrEmpty(input)) return ""; var sb = new StringBuilder(); int i = 0; while (i < input.Length) { char ch = input[i]; int count = 0; while (i < input.Length && input[i] == ch && count < 15) { count++; i++; } sb.Append(HexDigit...
} static void Main(string[] args) { if (HexDigit(10) != "A") throw new Exception("hex A"); if (HexDigit(15) != "F") throw new Exception("hex F"); // Count-first format with hex for counts > 9 if (RleEncode("aaa") != "3a") throw new Exception("3a: " + RleEncode("aaa")); ...
if (RleEncode("") != "") throw new Exception("empty"); if (RleEncode("abc") != "1a1b1c") throw new Exception("abc: " + RleEncode("abc")); if (RleEncode("aaabbc") != "3a2b1c") throw new Exception("aaabbc: " + RleEncode("aaabbc")); if (RleEncode(new string('z', 15)) != "Fz") throw new Exception("15z: " + RleEncode(new st...
pattern_matching
11
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class SSHConfigParser { static string StripComment(string s) { string r = ""; bool q = false; foreach (char c in s) { if (c == '"') q = !q; if (!q && c == '#') break; r += c; } return r; } static string Unquote(string s) => s.Lengt...
foreach (var raw in text.Split('\n')) { string line = pending.Length > 0 ? raw.TrimStart() : raw; if (line.EndsWith("\\")) { pending.Append(line, 0, line.Length - 1); continue; } pending.Append(line); string logical = StripComment(pending.ToString()).Trim(); pendi...
} static void Main() { string cfg = "# global opts\nServerAliveInterval 60\n\nHost myserver\n HostName 10.0.\\\n 0.1\n User \"admin\" # inline comment\n Port 2222\n\nHost devbox\n HostName dev.example.com"; var m = ParseSSHConfig(cfg); if (!(m["global.serveraliveinterval"] ==...
if (!(ParseSSHConfig("").Count == 0)) throw new Exception("empty input"); var a1 = ParseSSHConfig("Compression yes"); if (!(a1["global.compression"] == "yes")) throw new Exception("global single key"); var a2 = ParseSSHConfig("Host foo\n Port=443\n User bar"); if (!(a2["host.foo.port"] == "443")) throw new Exception(...
pattern_matching
12
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class DockerfileEnvParser { // Parse Dockerfile ENV directives. // Two forms: "ENV KEY VALUE" (legacy, no '=' before space) and "ENV KEY=VALUE" (modern, allows multiple pairs). // - Lines starting with '#' are comments. Non-ENV lines are skipped. // - Lin...
foreach (var raw in text.Split('\n')) { string line = pending.Length > 0 ? raw.TrimStart() : raw; if (line.EndsWith("\\")) { pending.Append(line, 0, line.Length - 1); continue; } pending.Append(line); string logical = pending.ToString().Trim(); pending.Clear(); if...
} static void Main() { string df = "# base image\nFROM ubuntu:22.04\nENV APP_HOME /opt/app\nENV VERSION=1.0 \\\n DEBUG=\"true\"\nENV PATH=/usr/bin\n# done"; var m = ParseDockerEnv(df); if (!(m["APP_HOME"] == "/opt/app")) throw new Exception("legacy form: " + m.GetValueOrDefault("AP...
if (!(ParseDockerEnv("").Count == 0)) throw new Exception("empty"); if (!(ParseDockerEnv("# comment only").Count == 0)) throw new Exception("comment only"); var d1 = ParseDockerEnv("ENV A=1 B=2 C=3"); if (!(d1.Count == 3 && d1["A"] == "1" && d1["B"] == "2" && d1["C"] == "3")) throw new Exception("multi modern"); var d2...
pattern_matching
13
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class SystemdParser { static string StripComment(string s) { string r = ""; bool q = false; foreach (char c in s) { if (c == '"') q = !q; if (!q && (c == '#' || c == ';')) break; r += c; } return r; } // Parse systemd unit file: ...
foreach (var raw in text.Split('\n')) { string line = pending.Length > 0 ? raw.TrimStart() : raw; if (line.EndsWith("\\")) { pending.Append(line, 0, line.Length - 1); continue; } pending.Append(line); string logical = StripComment(pending.ToString()).Trim(); pendi...
} static void Main() { string unit = "[Unit]\nDescription=My \\\n Service\nAfter=network.target\nAfter=syslog.target\n\n[Service]\nExecStart=/usr/bin/app ; not a comment in quotes? actually comment\nRestart=always\n# maintenance\n\n[Install]\nWantedBy=multi-user.target"; var m = ParseUnit(...
if (!(ParseUnit("").Count == 0)) throw new Exception("empty"); var u1 = ParseUnit("[s]\na=1\nb=2"); if (!(u1["s.a"] == "1" && u1["s.b"] == "2")) throw new Exception("basic section"); var u2 = ParseUnit("[s]\nk=x\nk=y\nk=z"); if (!(u2["s.k"] == "x, y, z")) throw new Exception("triple multi-value: " + u2.GetValueOrDefaul...
pattern_matching
14
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class YamlLikeParser { static string StripComment(string s) { string r = ""; bool q = false; foreach (char c in s) { if (c == '"') q = !q; if (!q && c == '#') break; r += c; } return r; } // Parse simple YAML-like format into flat...
foreach (var raw in text.Split('\n')) { if (pending.Length == 0) pendingIndent = raw.Length - raw.TrimStart().Length; string line = pending.Length > 0 ? raw.TrimStart() : raw; if (line.TrimEnd().EndsWith("\\")) { pending.Append(line.TrimEnd().Substring(0, line.TrimEnd().Lengt...
} static void Main() { string yaml = "server:\n host: localhost\n port: 8080\n ssl:\n enabled: true\n cert: /etc/\\\nssl/cert.pem\ndatabase:\n url: \"jdbc:mysql://db\" # connection\n pool: 5"; var m = ParseYamlLike(yaml); if (!(m["server.host"] == "localhost")) throw new ...
if (!(ParseYamlLike("").Count == 0)) throw new Exception("empty"); var y1 = ParseYamlLike("a: 1\nb: 2"); if (!(y1["a"] == "1" && y1["b"] == "2")) throw new Exception("flat keys"); var y2 = ParseYamlLike("p:\n c1: x\n c2: y"); if (!(y2["p.c1"] == "x" && y2["p.c2"] == "y")) throw new Exception("one level nesting"); var...
pattern_matching
15
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class GitConfigParser { static string StripComment(string s) { string r = ""; bool q = false; foreach (char c in s) { if (c == '"') q = !q; if (!q && (c == '#' || c == ';')) break; r += c; } return r; } // Parse .gitconfig format:...
foreach (var raw in text.Split('\n')) { string line = pending.Length > 0 ? raw.TrimStart() : raw; if (line.EndsWith("\\")) { pending.Append(line, 0, line.Length - 1); continue; } pending.Append(line); string logical = StripComment(pending.ToString()).Trim(); pendi...
} static void Main() { string cfg = "[core]\n autocrlf = true\n[remote \"origin\"]\n url = git@github.com:\\\n user/repo.git\n fetch = +refs/heads/*:refs/remotes/origin/*\n; global comment\n[user]\n name = \"Dev User\" # inline"; var m = ParseGitConfig(cfg); if (!(m["core.aut...
if (!(ParseGitConfig("").Count == 0)) throw new Exception("empty"); var g1 = ParseGitConfig("[s]\na=1"); if (!(g1["s.a"] == "1")) throw new Exception("basic"); var g2 = ParseGitConfig("[branch \"main\"]\nremote = origin\nmerge = refs/heads/main"); if (!(g2["branch.main.remote"] == "origin")) throw new Exception("subsec...
pattern_matching
16
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class ApacheConfigParser { static string StripComment(string s) { string r = ""; bool q = false; foreach (char c in s) { if (c == '"') q = !q; if (!q && c == '#') break; r += c; } return r; } // Parse simplified Apache config: ...
foreach (var raw in text.Split('\n')) { string line = pending.Length > 0 ? raw.TrimStart() : raw; if (line.EndsWith("\\")) { pending.Append(line, 0, line.Length - 1); continue; } pending.Append(line); string logical = StripComment(pending.ToString()).Trim(); pendi...
} static void Main() { string cfg = "ServerRoot /etc/httpd\n\n<VirtualHost *:80>\n ServerName example.com\n DocumentRoot /var/www/\\\n html\n CustomLog \"/var/log/access.log\" # log path\n ErrorLog /var/log/error.log\n</VirtualHost>\n\nTimeout 300"; var m = ParseApacheConfig(cfg); ...
if (!(ParseApacheConfig("").Count == 0)) throw new Exception("empty"); var ap1 = ParseApacheConfig("Listen 80\nListen 443"); if (!(ap1["global.listen"] == "80, 443")) throw new Exception("multi-value: " + ap1.GetValueOrDefault("global.listen", "MISSING")); var ap2 = ParseApacheConfig("<Directory /var>\n Options Indexe...
pattern_matching
17
devbench-pattern-matching
c_sharp
using System; using System.Text; class Base32Encoder { // Default alphabet is REVERSED standard Base32 (standard: ABCDEFGHIJKLMNOPQRSTUVWXYZ234567). // Reversed: "7654321ZYXWVUTSRQPONMLKJIHGFEDCBA" (index 0 => '7', index 31 => 'A'). // Padding char: '#' (not '='). // Encode bytes to base32 string using...
var sb = new StringBuilder(); int bits = 0, buffer = 0; foreach (byte b in data) { buffer = (buffer << 8) | b; bits += 8; while (bits >= 5) { bits -= 5; sb.Append(alphabet[(buffer >> bits) & 0x1F]); } } if (bits > 0) sb.Append(alphabet[(buffer << (5 - bits...
} static void Main() { byte[] hello = Encoding.ASCII.GetBytes("Hi"); string encoded = Base32Encode(hello); // Standard base32("Hi") = "JBUQ====" but our reversed alphabet maps differently if (encoded == "JBUQ====") throw new Exception("used standard alphabet!"); if (...
if (!(Base32Encode(new byte[0]).Length == 0)) throw new Exception("empty input"); byte[] ha = Encoding.ASCII.GetBytes("A"); string hae = Base32Encode(ha); if (!(hae.Length == 8)) throw new Exception("single byte padding"); if (!(hae.EndsWith("#"))) throw new Exception("pad char"); string hstd = "ABCDEFGHIJKLMNOPQRSTUVW...
pattern_matching
18
devbench-pattern-matching
c_sharp
using System; using System.Text; class UrlEncoder { // Custom URL encoding rules (NOT standard percent-encoding): // - Alphanumeric chars [A-Za-z0-9] are kept as-is. // - Space ' ' => '+' (like application/x-www-form-urlencoded). // - All other chars encoded as "~XX" where XX is uppercase hex of the by...
var sb = new StringBuilder(); foreach (byte b in Encoding.UTF8.GetBytes(input)) { char c = (char)b; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) sb.Append(c); else if (c == ' ') sb.Append('+'); else sb.Append('~').Append(...
} static void Main() { string result = UrlEncode("hello world"); if (!(result == "hello+world")) throw new Exception("spaces: " + result); string result2 = UrlEncode("a.b@c"); // '.' is encoded, '@' is encoded, using ~ not % if (result2.Contains("%")) throw new Excep...
if (!(UrlEncode("") == "")) throw new Exception("empty"); if (!(UrlEncode(" ") == "+")) throw new Exception("space only"); if (!(UrlEncode("~") == "~7E")) throw new Exception("tilde itself: " + UrlEncode("~")); if (!(UrlEncode("/") == "~2F")) throw new Exception("slash: " + UrlEncode("/")); if (!(UrlEncode("a b.c") == ...
pattern_matching
19
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class EnvFileParser { static string StripComment(string s) { string r = ""; bool q = false; foreach (char c in s) { if (c == '"') q = !q; if (!q && c == '#') break; r += c; } return r; } // Parse .env file with profile support: ...
foreach (var raw in text.Split('\n')) { string line = pending.Length > 0 ? raw.TrimStart() : raw; if (line.EndsWith("\\")) { pending.Append(line, 0, line.Length - 1); continue; } pending.Append(line); string logical = StripComment(pending.ToString()).Trim(); pendi...
} static void Main() { string env = "# global defaults\nAPP_NAME=myapp\nexport DEBUG=true\n\n[production]\nDB_HOST=prod-db.\\\n example.com\nDB_PASS=\"s3cr3t\" # secret\nexport LOG_LEVEL=warn\n\n[staging]\nDB_HOST=staging-db"; var m = ParseEnvFile(env); if (!(m["default.APP_NAME"] ...
if (!(ParseEnvFile("").Count == 0)) throw new Exception("empty"); var e1 = ParseEnvFile("A=1\nB=2"); if (!(e1["default.A"] == "1" && e1["default.B"] == "2")) throw new Exception("basic default"); var e2 = ParseEnvFile("export X=yes"); if (!(e2["default.X"] == "yes")) throw new Exception("export strip"); var e3 = ParseE...
pattern_matching
20
devbench-pattern-matching
c_sharp
using System; class EditDistanceCalc { // Custom edit distance: insert=1, delete=1, replace=1, swap(adjacent)=0.5 // editDistance("ab","ba") = 0.5, NOT 2 | editDistance("cat","car") = 1 static double EditDistance(string a, string b) {
int m = a.Length, n = b.Length; double[,] dp = new double[m + 1, n + 1]; for (int i = 0; i <= m; i++) dp[i, 0] = i; for (int j = 0; j <= n; j++) dp[0, j] = j; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) { dp[i, j] = Math.Min(dp[i - 1, j] ...
} static void Main() { if (!(EditDistance("ab", "ba") == 0.5)) throw new Exception("swap should cost 0.5, got " + EditDistance("ab", "ba")); if (!(EditDistance("cat", "car") == 1.0)) throw new Exception("replace costs 1"); if (!(EditDistance("", "abc") == 3.0)) throw new Exception("...
if (!(EditDistance("", "") == 0.0)) throw new Exception("both empty"); if (!(EditDistance("a", "b") == 1.0)) throw new Exception("single replace"); if (!(EditDistance("abcd", "abdc") == 0.5)) throw new Exception("one swap at end"); if (!(EditDistance("ab", "ba") == 0.5)) throw new Exception("swap not 2"); if (!(EditDis...
pattern_matching
21
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { static string StripComment(string s) { bool inQ = false; for (int i = 0; i < s.Length; i++) { if (s[i] == '"') inQ = !inQ; if (!inQ && (s[i] == '#' || s[i] == ';')) return s.Substring(0, i); ...
if (logical.StartsWith("[") && logical.EndsWith("]")) { section = logical.Substring(1, logical.Length - 2).Trim(); continue; } int sep = logical.IndexOfAny(new[] { '=', ':' }); if (sep < 0) continue; string key = logical.Substring(0, sep).Trim(); s...
} return result; } static void Main(string[] args) { string cfg = "name = Alice\n" + "path = /usr/\\\n" + " local/bin\n" + "note = \"keep # sign\" # tail\n" + "; skip me\n" + "[...
var ha = ParseConfig(""); if (ha.Count != 0) throw new Exception("empty input"); var hb = ParseConfig("x: 1\ny = 2"); if (hb["x"] != "1") throw new Exception("colon sep"); if (hb["y"] != "2") throw new Exception("equals sep"); var hc = ParseConfig("[s]\na=1\nb=2"); if (hc["s.a"] != "1") throw new Exception("section a")...
pattern_matching
22
devbench-pattern-matching
c_sharp
using System; class Program { // Custom edit distance: insert=1, delete=1, replace=1, swap(adjacent)=0.5 // EditDistance("ab","ba") = 0.5, NOT 2 | EditDistance("cat","car") = 1 static double EditDistance(string a, string b) { int m = a.Length, n = b.Length; double[,] dp = new double[m...
double cost = a[i - 1] == b[j - 1] ? 0 : 1; dp[i, j] = Math.Min(dp[i - 1, j] + 1, Math.Min(dp[i, j - 1] + 1, dp[i - 1, j - 1] + cost)); if (i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1]) dp[i, j] = Math.Min(...
} return dp[m, n]; } static void Main(string[] args) { if (EditDistance("ab", "ba") != 0.5) throw new Exception("swap should cost 0.5"); if (EditDistance("cat", "car") != 1.0) throw new Exception("replace costs 1"); if (EditDistance("", "abc") != 3.0) throw new E...
if (EditDistance("", "") != 0.0) throw new Exception("both empty"); if (EditDistance("a", "b") != 1.0) throw new Exception("single replace"); if (EditDistance("abcd", "abdc") != 0.5) throw new Exception("one swap at end"); if (EditDistance("kitten", "sitting") != 3.0) throw new Exception("classic"); if (EditDistance("a...
pattern_matching
23
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { static string TrimWs(string s) { return s.Trim(' ', '\t', '\r'); } static string StripMC(string s) { bool q = false, esc = false; for (int i = 0; i < s.Length; i++) { char c = s[i]; if (esc) { e...
if (val.Length >= 2 && val[0] == '"' && val[val.Length - 1] == '"') val = val.Substring(1, val.Length - 2); string fk = section.Length > 0 ? section + "." + key : key; if (result.ContainsKey(fk)) result[fk] += ", " + val; else ...
} return result; } static void Main(string[] args) { string cfg = "[core]\nname=dev\\\nbench\n# ignored\n[limits]\nscore = 54"; var m = ParseManifest(cfg); if (m["core.name"] != "devbench") throw new Exception("continuation"); if (m["limits.score"] != "54") t...
var ha = ParseManifest(""); if (ha.Count != 0) throw new Exception("empty"); var hb = ParseManifest("x=1\nx=2\nx=3"); if (hb["x"] != "1, 2, 3") throw new Exception("duplicate append"); var hc = ParseManifest("[s]\na = \"hello\"\nb = world"); if (hc["s.a"] != "hello") throw new Exception("unquote"); if (hc["s.b"] != "wo...
pattern_matching
24
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; using System.Text; class Program { // CSV parser: delimiter='|', quote=single-quote, escape=doubled single-quote. // Newline inside quotes preserved. Unquoted fields trimmed; quoted fields NOT. static List<List<string>> ParseCsv(string text) { var...
row.Add(wasQ ? field.ToString() : field.ToString().Trim()); field.Clear(); wasQ = false; i++; } else if (c == '\n') { row.Add(wasQ ? field.ToString() : field.ToString().Trim()); field.Clear();...
} } if (field.Length > 0 || row.Count > 0) { row.Add(wasQ ? field.ToString() : field.ToString().Trim()); rows.Add(row); } return rows; } static void Main(string[] args) { var r1 = ParseCsv("'a'| b |'c''d'"); if (r1[...
var ha = ParseCsv(""); if (ha.Count != 0) throw new Exception("empty input"); var hb = ParseCsv("x|y|z"); if (hb[0][0] != "x" || hb[0][1] != "y" || hb[0][2] != "z") throw new Exception("simple pipe"); var hc = ParseCsv(" hello | world "); if (hc[0][0] != "hello" || hc[0][1] != "world") throw new Exception("unquoted t...
pattern_matching
25
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { // Parse folded headers: "Name: value" starts a header. // Line starting with space/tab continues previous header (joined with one space). // Header names lowercased. Duplicates keep all values in order. static Dictionary<string, List<stri...
if ((raw[0] == ' ' || raw[0] == '\t') && curKey != null) { var v = result[curKey]; v[v.Count - 1] += " " + raw.TrimStart(); } else { int c = raw.IndexOf(':'); if (c < 0) continue; curKey = raw.Substring(0, c).Trim().ToLower(...
} return result; } static void Main(string[] args) { string h = "X-Note: one\n two\nX-Note: three\nHost: Example.COM"; var m = ParseHeaders(h); if (m["x-note"].Count != 2) throw new Exception("note count"); if (m["x-note"][0] != "one two") throw new Exceptio...
var ha = ParseHeaders(""); if (ha.Count != 0) throw new Exception("empty"); var hb = ParseHeaders("A: 1\n\t2\nB: x"); if (hb["a"][0] != "1 2") throw new Exception("tab continuation"); if (hb["b"][0] != "x") throw new Exception("next header"); var hc = ParseHeaders("Set-Cookie: a=1\nSet-Cookie: b=2"); if (hc["set-cookie...
pattern_matching
26
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; using System.Text; class Program { // Template engine: {{key}} = substitute, {{key|upper}} = uppercase, // {{key|lower}} = lowercase, {{key|default:X}} = use X if key missing. // Missing key without default => literal "{{key}}" preserved. // Chained: {{ke...
string val = has ? ctx[key] : null; string def = null; for (int f = 1; f < parts.Length; f++) { string fl = parts[f].Trim(); if (fl == "upper" && val != null) val = val.ToUpper(); else if (fl == "...
i = end + 2; } else { sb.Append(tpl[i]); i++; } } return sb.ToString(); } static void Main(string[] args) { var ctx = new Dictionary<string, string> { {"name","Alice"}, {"role","admin"} }; if (Render("Hello {{name}}!", ctx) != "Hello A...
var ctx2 = new Dictionary<string, string> { {"name","Alice"}, {"role","admin"} }; if (Render("", ctx2) != "") throw new Exception("empty tpl"); if (Render("no vars", ctx2) != "no vars") throw new Exception("no vars"); if (Render("{{name|lower}}", ctx2) != "alice") throw new Exception("lower"); if (Render("{{role|upper}...
pattern_matching
27
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; using System.Text; class Program { // Split on commas, but NOT inside matched brackets: () [] {}. // Brackets can be nested. Each result segment is trimmed. static List<string> SplitTopLevel(string text) { var parts = new List<string>(); v...
if (c == '(' || c == '[' || c == '{') depth++; else if (c == ')' || c == ']' || c == '}') depth--; if (c == ',' && depth == 0) { parts.Add(cur.ToString().Trim()); cur.Clear(); } else cur.Append(c);
} parts.Add(cur.ToString().Trim()); return parts; } static void Main(string[] args) { var r1 = SplitTopLevel("a, (b, c), d"); if (r1.Count != 3) throw new Exception("count"); if (r1[0] != "a") throw new Exception("first"); if (r1[1] != "(b, c)") throw...
var ha = SplitTopLevel(""); if (ha.Count != 1 || ha[0] != "") throw new Exception("empty"); var hb = SplitTopLevel("x"); if (hb.Count != 1 || hb[0] != "x") throw new Exception("single"); var hc = SplitTopLevel("a, b, c"); if (hc.Count != 3) throw new Exception("simple split"); var hd = SplitTopLevel("f(a, b), g(c, (d, ...
pattern_matching
28
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { static string StripRC(string s) { bool q = false; for (int i = 0; i < s.Length; i++) { if (s[i] == '"') q = !q; if (s[i] == '#' && !q) return s.Substring(0, i); } return s; } ...
int arrow = logical.IndexOf("->"); if (arrow < 0) continue; string key = logical.Substring(0, arrow).Trim(); string handler = logical.Substring(arrow + 2).Trim(); if (handler.Length >= 2 && handler[0] == '"' && handler[handler.Length - 1] == '"') ...
} return routes; } static void Main(string[] args) { string table = "GET /users -> \\\n" + " userIndex # visible route\n" + "POST /msg -> \"save#draft\" # comment"; var r = ParseRoutes(table); if (r["GET /users"] != "use...
var ha = ParseRoutes(""); if (ha.Count != 0) throw new Exception("empty"); var hb = ParseRoutes("GET / -> root\n# skip\nBAD LINE"); if (hb["GET /"] != "root") throw new Exception("basic route"); if (hb.Count != 1) throw new Exception("skip bad lines"); var hc = ParseRoutes("PUT /a -> one \\\n two \\\n three"); if (hc["...
pattern_matching
29
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; using System.Text; class Program { // Tokenizer: IDENT, NUM, STRING, OP. Skip // and /* */ comments. // Strings: "..." with \\ and \" escapes. // Operators: +-*/=(){};, static List<string> Tokenize(string code) { var tokens = new List<string>(...
if (char.IsDigit(code[i])) { int s = i; while (i < code.Length && char.IsDigit(code[i])) i++; tokens.Add("NUM:" + code.Substring(s, i - s)); continue; } if (char.IsLetter(code[i]) || code[i] == '_') { int s = i; while (i < code.Length && (char.IsLetterOrDigit(code[i]) || ...
} return tokens; } static void Main(string[] args) { var t1 = Tokenize("x = 42;"); if (t1[0] != "IDENT:x") throw new Exception("ident"); if (t1[1] != "OP:=") throw new Exception("op"); if (t1[2] != "NUM:42") throw new Exception("num"); if (t1[3] != "O...
var ha = Tokenize(""); if (ha.Count != 0) throw new Exception("empty"); var hb = Tokenize(" \n\t "); if (hb.Count != 0) throw new Exception("whitespace only"); var hc = Tokenize("\"hello\""); if (hc.Count != 1 || hc[0] != "STRING:hello") throw new Exception("string"); var hd = Tokenize("\"a\\\\b\""); if (hd[0] != "ST...
pattern_matching
30
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { static string StripTC(string s) { bool q = false; for (int i = 0; i < s.Length; i++) { if (s[i] == '"') q = !q; if (!q && s[i] == '#') return s.Substring(0, i); } return s; } ...
if (valStr.Length >= 2 && valStr[0] == '"' && valStr[valStr.Length - 1] == '"') result[fk] = valStr.Substring(1, valStr.Length - 2); else if (valStr == "true" || valStr == "false") result[fk] = valStr == "true"; else if (int.TryParse(valStr, out int iv...
} return result; } static void Main(string[] args) { string cfg = "count = 42\nenabled = true\n[db]\nhost = \"localhost\"\nport = 5432\nssl = false"; var m = ParseTypedConfig(cfg); if ((int)m["count"] != 42) throw new Exception("int type"); if ((bool)m["enabl...
var ha = ParseTypedConfig(""); if (ha.Count != 0) throw new Exception("empty"); var hb = ParseTypedConfig("x = 0\ny = true\nz = false\nw = \"hello\""); if ((int)hb["x"] != 0) throw new Exception("zero int"); if ((bool)hb["y"] != true) throw new Exception("true"); if ((bool)hb["z"] != false) throw new Exception("false")...
pattern_matching
31
devbench-pattern-matching
c_sharp
using System; using System.Text; class Program { static readonly string STANDARD_B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; static readonly string REVERSED_B32 = new string( System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Reverse(STANDARD_B32))); // Base32 encoder with configurable alphabet a...
StringBuilder sb = new StringBuilder(); int buffer = 0, bitsLeft = 0; foreach (byte b in data) { buffer = (buffer << 8) | b; bitsLeft += 8; while (bitsLeft >= 5) { bitsLeft -= 5; sb.Append(alphabet[(buffer >>...
} static void Main() { // Reversed alphabet: STANDARD_B32[0]='A' maps to REVERSED_B32[0]='7' // Standard base32("f") = "MY======"; reversed must differ string r1 = Base32Encode(new byte[]{0x66}); if (r1 == "MY======") throw new Exception("Must not be standard base32"); ...
string e1 = Base32Encode(new byte[0]); if (e1 != "") throw new Exception($"Empty input should give empty, got {e1}"); string abc_std = Base32Encode(new byte[]{0x61,0x62,0x63}, STANDARD_B32, '='); if (abc_std != "MFRGG===") throw new Exception($"Expected MFRGG=== got {abc_std}"); ...
pattern_matching
32
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { // Parses INI-style config. Rules: // - Lines starting with # or ; are comments (but only if # or ; is the FIRST non-space char) // - [section] starts a new section // - key = value pairs; value is trimmed // - A line ending with \ con...
var result = new Dictionary<string, Dictionary<string, string>>(); string section = ""; result[section] = new Dictionary<string, string>(); string[] lines = text.Split('\n'); int i = 0; while (i < lines.Length) { string line = lines[i].TrimEnd(); ...
} static void Main() { string config = "[server]\nhost = localhost\nport = 8080\n# comment\n[db]\nconn = host=db;\\\n port=5432\nconn = user=admin"; var r = ParseIni(config); if (r["server"]["host"] != "localhost") throw new Exception("host wrong"); if (r["server"]["port"]...
string cfg2 = "key1 = hello\n; a comment\nkey1 = world"; var r2 = ParseIni(cfg2); if (r2[""]["key1"] != "hello,world") throw new Exception($"Global dup expected hello,world got {r2[""]["key1"]}"); string cfg3 = "[s1]\nval = a\\\n b\\\n c"; var r3 = ParseIni(cfg3); if (...
pattern_matching
33
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { // Parse .env-style file with profiles. // Rules: // - [profile_name] starts a new profile; default profile is "" // - Lines can optionally start with "export " which is stripped // - KEY=VALUE or KEY="quoted value" (strip quotes) ...
var result = new Dictionary<string, Dictionary<string, string>>(); string profile = ""; result[profile] = new Dictionary<string, string>(); string[] lines = text.Split('\n'); int i = 0; while (i < lines.Length) { string line = lines[i].TrimEnd(); ...
} static void Main() { string env = "# global\nexport DB_HOST=localhost\nDB_PORT=5432\n[production]\nDB_HOST=\"prod.db.com\"\nSECRET=abc\\\ndef"; var r = ParseEnv(env); if (r[""]["DB_HOST"] != "localhost") throw new Exception("global DB_HOST wrong"); if (r[""]["DB_PORT"] != ...
string env2 = "export KEY1=\"value with # hash\"\nKEY2=plain"; var r2 = ParseEnv(env2); if (r2[""]["KEY1"] != "value with # hash") throw new Exception($"Hash in quotes: got {r2[""]["KEY1"]}"); if (r2[""]["KEY2"] != "plain") throw new Exception("KEY2 wrong"); string env3 = "[dev]...
pattern_matching
34
devbench-pattern-matching
c_sharp
using System; class Program { // Edit distance with custom costs: // - Insert cost: 1 // - Delete cost: 1 // - Substitution cost: 2 (NOT the standard 1!) // - Transposition of adjacent chars cost: 0.5 // Returns minimum cost as double. static double EditDistance(string a, string b) {
int m = a.Length, n = b.Length; double[,] dp = new double[m + 1, n + 1]; for (int i = 0; i <= m; i++) dp[i, 0] = i; for (int j = 0; j <= n; j++) dp[0, j] = j; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) { double cost = a[i - 1...
} static void Main() { // "ab" -> "ba": transposition costs 0.5, NOT standard 2 double r1 = EditDistance("ab", "ba"); if (Math.Abs(r1 - 0.5) > 1e-9) throw new Exception($"ab->ba expected 0.5 got {r1}"); // "abc" -> "abc": identical = 0 if (Math.Abs(EditDistance("abc...
// "cat" -> "act": one transposition (ca->ac) + t stays = 0.5 // But also check "kitten" -> "sitting" double r3 = EditDistance("", "abc"); if (Math.Abs(r3 - 3.0) > 1e-9) throw new Exception($"empty->abc expected 3 got {r3}"); double r4 = EditDistance("abc", ""); if (Math...
pattern_matching
35
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; using System.Text; class Program { // Simple template engine. Supported syntax: // - {{key}} — replaced with vars[key], or "" if missing // - {%if key%}...{%endif%} — include block only if vars[key] is truthy (non-empty, non-"false", non-"0") // - {%if !k...
StringBuilder sb = new StringBuilder(); int i = 0; bool IsTruthy(string k) { if (!vars.ContainsKey(k)) return false; string v = vars[k]; return v != "" && v != "false" && v != "0"; } void Render(bool emit) { while (i...
} static void Main() { var vars = new Dictionary<string, string> { {"name", "Alice"}, {"show", "true"}, {"hide", "false"} }; string t1 = "Hello {{name}}!"; if (RenderTemplate(t1, vars) != "Hello Alice!") throw new Exception("Simple var failed"); string t2 = "{%if show%}Visi...
var v2 = new Dictionary<string, string> { {"a", "1"}, {"b", "0"} }; string t4 = "{%if a%}A{%if b%}B{%endif%}C{%endif%}"; string r4 = RenderTemplate(t4, v2); if (r4 != "AC") throw new Exception($"Nested if: expected 'AC' got '{r4}'"); string t5 = "{{missing}}x"; string r5...
pattern_matching
36
devbench-pattern-matching
c_sharp
using System; using System.Text; class Program { static readonly string STANDARD_HEX = "0123456789abcdef"; static readonly string REVERSED_HEX = "fedcba9876543210"; // Hex encoder with configurable digit alphabet. // Default uses REVERSED_HEX where '0' maps to 'f', '1' maps to 'e', etc. // separat...
StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.Length; i++) { int hi = (data[i] >> 4) & 0xF; int lo = data[i] & 0xF; if (i > 0) sb.Append(separator); sb.Append(alphabet[hi]); sb.Append(alphabet[lo]); } ...
} static void Main() { // Standard hex for 0xFF is "ff"; reversed maps 0xF->0, so "00" string r1 = HexEncode(new byte[]{0xFF}); if (r1 != "00") throw new Exception($"0xFF reversed: expected '00' got '{r1}'"); if (r1 == "ff") throw new Exception("Must not use standard hex"); ...
string e1 = HexEncode(new byte[0]); if (e1 != "") throw new Exception($"Empty expected '' got '{e1}'"); // 0x41='A' standard hex "41"; reversed: 4->b, 1->e => "be" string r4 = HexEncode(new byte[]{0x41}); if (r4 != "be") throw new Exception($"0x41 reversed expected 'be' got '{r4...
pattern_matching
37
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { // Custom CSV parser rules: // - Delimiter is '|' (pipe), NOT comma // - Quoting: fields wrapped in single quotes preserve pipes and newlines literally // - Escape: inside single quotes, '' (two single quotes) represents a literal ' //...
var rows = new List<List<string>>(); var current = new List<string>(); int i = 0; while (i <= text.Length) { var field = new System.Text.StringBuilder(); bool quoted = false; if (i < text.Length && text[i] == '\'') { ...
} static void Main() { string data = "a | b | c\n' d '|'e|f'|g"; var rows = ParseCsv(data); if (rows[0][0] != "a") throw new Exception($"Row0Col0: expected 'a' got '{rows[0][0]}'"); if (rows[0][1] != "b") throw new Exception($"Unquoted should be trimmed: got '{rows[0][1]}'")...
// Empty input var re = ParseCsv(""); if (re.Count != 1 || re[0].Count != 1 || re[0][0] != "") throw new Exception("Empty input handling wrong"); // Multi-row with quoted newline would not apply here since newlines end rows // Test all-quoted row string d3 = "'a'|'b'|'c'...
pattern_matching
38
devbench-pattern-matching
c_sharp
using System; using System.Text; class Program { // Run-length encode a string. Custom format rules: // - Single chars are output as-is (NOT "1a" or "a1") // - Runs of 2+ are output as COUNT THEN CHAR (e.g., "aaa" -> "3a") // - Digits in input are escaped by prefixing with '\' (e.g., "3" -> "\3") /...
if (input.Length == 0) return ""; StringBuilder sb = new StringBuilder(); int i = 0; while (i < input.Length) { char c = input[i]; int count = 1; while (i + count < input.Length && input[i + count] == c) count++; string escaped; ...
} static void Main() { if (RunLengthEncode("aaa") != "3a") throw new Exception($"aaa: got {RunLengthEncode("aaa")}"); if (RunLengthEncode("a") != "a") throw new Exception("single char wrong"); if (RunLengthEncode("aabbb") != "2a3b") throw new Exception($"aabbb: got {RunLengthEncode(...
if (RunLengthEncode("") != "") throw new Exception("empty wrong"); if (RunLengthEncode("abcd") != "abcd") throw new Exception("no runs wrong"); // backslash escaping string bs = RunLengthEncode("\\"); if (bs != "\\\\") throw new Exception($"backslash: got '{bs}'"); strin...
pattern_matching
39
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { // Split a string by a delimiter, but ignore delimiters inside brackets. // Bracket pairs: (), [], {} // Also ignore delimiters inside double-quoted strings (handle \" escape) // Delimiter defaults to ',' // Trim each resulting segment...
var result = new List<string>(); int depth = 0; bool inString = false; bool escaped = false; int start = 0; for (int i = 0; i < input.Length; i++) { char c = input[i]; if (escaped) { escaped = false; continue; } if (c == '\\' &&...
} static void Main() { var r1 = BracketAwareSplit("a, b, c"); if (r1.Count != 3 || r1[0] != "a") throw new Exception("Simple split failed"); var r2 = BracketAwareSplit("f(1,2), g(3)"); if (r2.Count != 2) throw new Exception($"Bracket: expected 2 got {r2.Count}"); if...
// Nested brackets var r4 = BracketAwareSplit("f({a,b},[c,d]), x"); if (r4.Count != 2) throw new Exception($"Nested: expected 2 got {r4.Count}"); // Escaped quote in string var r5 = BracketAwareSplit("\"a\\\"b,c\", d"); if (r5.Count != 2) throw new Exception($"Escaped qu...
pattern_matching
40
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { // Parse markdown table into list of dictionaries. // Rules: // - First row is header // - Second row is separator (---) — skip it // - Remaining rows are data // - Cells are separated by | and trimmed // - L...
List<string> SplitRow(string row) { // Strip leading/trailing | row = row.Trim(); if (row.StartsWith("|")) row = row.Substring(1); if (row.EndsWith("|")) row = row.Substring(0, row.Length - 1); var cells = new List<string>(); bool i...
} static void Main() { string table = "| Name | Value |\n| --- | --- |\n| foo | 42 |\n| bar | 99 |"; var rows = ParseMarkdownTable(table); if (rows.Count != 2) throw new Exception($"Expected 2 rows got {rows.Count}"); if (rows[0]["Name"] != "foo") throw new Exception($"Name:...
// Empty table var re = ParseMarkdownTable("| H |\n|---|\n"); if (re.Count != 0) throw new Exception($"Empty data: expected 0 rows got {re.Count}"); // Missing cells string t3 = "| A | B | C |\n|---|---|---|\n| 1 | 2 |"; var r3 = ParseMarkdownTable(t3); if (r3[0]...
pattern_matching
41
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { // Split identifier into words. Custom rules: // - Split before uppercase letter that follows a lowercase letter: "fooBar" -> ["foo","Bar"] // - Split before uppercase letter that is followed by lowercase (in an acronym run): "XMLParser" -> ["...
var words = new List<string>(); int start = 0; for (int i = 0; i < input.Length; i++) { if (input[i] == '_') { if (i > start) words.Add(input.Substring(start, i - start)); start = i + 1; continue; } ...
} static void Main() { var r1 = SplitIdentifier("fooBar"); if (r1.Count != 2 || r1[0] != "foo" || r1[1] != "Bar") throw new Exception($"fooBar: {string.Join(",", r1)}"); var r2 = SplitIdentifier("XMLParser"); if (r2.Count != 2 || r2[0] != "XML" || r2[1] != "Parser") throw n...
var r4 = SplitIdentifier("abc_def"); if (r4.Count != 2 || r4[0] != "abc" || r4[1] != "def") throw new Exception($"underscore: {string.Join(",", r4)}"); var r5 = SplitIdentifier("HTTPSConnection"); if (r5.Count != 2 || r5[0] != "HTTPS" || r5[1] != "Connection") throw new Exception($"HTTP...
pattern_matching
42
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { // Split a command line string into arguments, shell-style: // - Spaces delimit arguments // - Double-quoted strings: spaces preserved, \" for literal quote, \\ for literal backslash // - Single-quoted strings: everything literal (no escap...
var args = new List<string>(); var current = new System.Text.StringBuilder(); bool hasArg = false; int i = 0; while (i < input.Length) { char c = input[i]; if (c == '"') { hasArg = true; i++; while (i < i...
} static void Main() { var r1 = ShellSplit("echo hello world"); if (r1.Count != 3 || r1[0] != "echo") throw new Exception($"Simple: {string.Join("|", r1)}"); var r2 = ShellSplit("echo \"hello world\""); if (r2.Count != 2 || r2[1] != "hello world") throw new Exception($"Dquo...
// Escaped quote in double quotes var r5 = ShellSplit("echo \"say \\\"hi\\\"\""); if (r5.Count != 2 || r5[1] != "say \"hi\"") throw new Exception($"Escaped dquote: {string.Join("|", r5)}"); // Single quotes: no escaping var r6 = ShellSplit("echo 'it\\''s'"); // 'it\\' ->...
pattern_matching
43
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { // Analyzes a method and returns a precise description string. // The description MUST contain ALL of the following keywords based on method properties: // - "mutates" if the method modifies a collection parameter (add/remove/set) // - "pu...
var keywords = new SortedSet<string>(); string lower = code.ToLower(); if (lower.Contains(".add(") || lower.Contains(".remove") || lower.Contains(".insert(") || lower.Contains("[") && lower.Contains("] =")) keywords.Add("mutates"); if (lower.Contains("throw ") || ...
} static void Main() { string code1 = "public int Sum(List<int> items) { int s = 0; foreach(var x in items) s += x; return s; }"; string d1 = DescribeMethod("Sum", code1); if (!d1.Contains("pure")) throw new Exception($"Sum should be pure: {d1}"); if (!d1.Contains("O(n)")) t...
string code3 = "public string Find(Dictionary<string,string> d, string k) { if (!d.ContainsKey(k)) return null; return d[k]; }"; string d3 = DescribeMethod("Find", code3); if (!d3.Contains("nullable")) throw new Exception($"Find should be nullable: {d3}"); if (!d3.Contains("O(1)")) throw...
pattern_matching
44
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { // Match a URL path against a route pattern and extract parameters. // Pattern syntax: // /literal — exact match // /{name} — captures any non-slash segment into params["name"] // /{name:int} — captures only if segment is all dig...
var result = new Dictionary<string, string>(); string[] patParts = pattern.Split(new[]{'/'}, StringSplitOptions.RemoveEmptyEntries); string[] pathParts = path.Split(new[]{'/'}, StringSplitOptions.RemoveEmptyEntries); int pi = 0; for (int i = 0; i < patParts.Length; i++) ...
} static void Main() { var r1 = MatchRoute("/users/{id}", "/users/42"); if (r1 == null || r1["id"] != "42") throw new Exception("Simple param failed"); var r2 = MatchRoute("/users/{id:int}", "/users/abc"); if (r2 != null) throw new Exception("Int constraint should reject ab...
// Extra path segments should fail var r5 = MatchRoute("/users/{id}", "/users/42/extra"); if (r5 != null) throw new Exception("Extra segments should fail"); // Int constraint passes with digits var r6 = MatchRoute("/items/{id:int}", "/items/999"); if (r6 == null || r6["i...
pattern_matching
45
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { // Parse TOML-style config into nested dictionaries. // Rules: // - [table] defines a table; dotted: [a.b] means a -> b -> {} // - key = "string_value" or key = 123 (integer) or key = true/false // - Dotted keys: a.b.c = "x" means a ->...
var root = new Dictionary<string, object>(); var current = root; foreach (string rawLine in text.Split('\n')) { string line = rawLine.Trim(); if (line.Length == 0 || line[0] == '#') continue; if (line.StartsWith("[") && !line.StartsWith("[[")) ...
} static void Main() { string toml = "# config\n[server]\nhost = \"localhost\"\nport = 8080\nenabled = true\n\n[db.primary]\nconn = \"pg://localhost\""; var r = ParseToml(toml); var server = (Dictionary<string, object>)r["server"]; if ((string)server["host"] != "localhost")...
// Dotted key string toml2 = "a.b.c = \"deep\""; var r2 = ParseToml(toml2); var a2 = (Dictionary<string, object>)r2["a"]; var b2 = (Dictionary<string, object>)a2["b"]; if ((string)b2["c"] != "deep") throw new Exception("Dotted key failed"); // Boolean false ...
pattern_matching
46
devbench-pattern-matching
c_sharp
using System; using System.Text; using System.Numerics; class Program { static readonly string BITCOIN_B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; static readonly string REVERSED_B58 = new string( System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Reverse(BITCOIN_B58))); ...
// Count leading zeros int leadingZeros = 0; foreach (byte b in data) { if (b == 0) leadingZeros++; else break; } BigInteger num = new BigInteger(new ReadOnlySpan<byte>(data), true, true); StringBuilder sb = new StringBuilder(); while (num > 0) { num ...
} static void Main() { // Single byte 0x01 with reversed alphabet string r1 = Base58Encode(new byte[]{0x01}); string s1 = Base58Encode(new byte[]{0x01}, BITCOIN_B58); if (r1 == s1) throw new Exception("Reversed must differ from standard"); if (s1 != "2") throw new Ex...
// Empty input string e = Base58Encode(new byte[0]); if (e != "") throw new Exception($"Empty: expected '' got '{e}'"); // All zeros string z3 = Base58Encode(new byte[]{0x00, 0x00, 0x00}); if (z3.Length != 3) throw new Exception($"3 zeros: expected length 3 got {z3.Lengt...
pattern_matching
47
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { // Evaluate simple math expressions with variables. // Supports: +, -, *, / (integer division), parentheses // Operator precedence: * and / bind tighter than + and - // Variables are looked up in the vars dictionary. // Throws Exceptio...
int pos = 0; int ParseExpr() { int result = ParseTerm(); while (pos < expr.Length && (expr[pos] == '+' || expr[pos] == '-')) { char op = expr[pos++]; int right = ParseTerm(); result = op == '+' ? result + right :...
} static void Main() { var v = new Dictionary<string, int> { {"x", 10}, {"y", 3} }; if (EvalExpr("x+y", v) != 13) throw new Exception("x+y failed"); if (EvalExpr("x*y+1", v) != 31) throw new Exception("precedence failed"); if (EvalExpr("(x+y)*2", v) != 26) throw new Exceptio...
var v2 = new Dictionary<string, int> { {"a", 5} }; if (EvalExpr("a*a+a", v2) != 30) throw new Exception("a*a+a failed"); if (EvalExpr("(a+1)*(a-1)", v2) != 24) throw new Exception("nested parens failed"); if (EvalExpr("100", v2) != 100) throw new Exception("literal failed"); boo...
pattern_matching
48
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { // Simple JSON-path query on nested dictionaries/lists. // Path syntax: // .key — access dictionary key // [n] — access list index (0-based) // [*] — wildcard: return all elements of a list as flat list // Input is an object ...
object current = root; int i = 0; while (i < path.Length) { if (path[i] == '.') { i++; int start = i; while (i < path.Length && path[i] != '.' && path[i] != '[') i++; string key = path.Substring(start...
} static void Main() { var data = new Dictionary<string, object> { {"name", "Alice"}, {"scores", new List<object>{90, 85, 95}}, {"address", new Dictionary<string, object>{{"city", "NYC"}}} }; if ((string)JsonPathQuery(data, ".name") != "A...
// Nested wildcard var data2 = new Dictionary<string, object> { {"items", new List<object>{ new Dictionary<string, object>{{"v", 1}}, new Dictionary<string, object>{{"v", 2}} }} }; var vals = (List<object>)JsonPathQuery(data...
pattern_matching
49
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { // Sort strings using custom rules (NOT standard lexicographic!): // 1. Shorter strings come first // 2. Same length: sort by vowel count (more vowels first) // 3. Same length and vowel count: sort lexicographically (cas...
int CountVowels(string s) { int count = 0; foreach (char c in s.ToLower()) if ("aeiou".Contains(c)) count++; return count; } return items.OrderBy(s => s.Length) .ThenByDescending(s => CountVowels(s)) ...
} static void Main() { var input = new List<string> {"cat", "hi", "bee", "a", "dog", "eye"}; var result = CustomSort(input); // "a" (len 1), "hi" (len 2), then len 3: "eye"(2 vowels), "bee"(2 vowels), "cat"(1), "dog"(1) if (result[0] != "a") throw new Exception($"First: exp...
// Same length, same vowels => lexicographic var input2 = new List<string> {"bat", "cat", "ant"}; var r2 = CustomSort(input2); // All length 3, all 1 vowel => lex: ant, bat, cat if (r2[0] != "ant" || r2[1] != "bat" || r2[2] != "cat") throw new Exception($"Lex: {string.Join(",", r...
pattern_matching
50
devbench-pattern-matching
c_sharp
using System; using System.Collections.Generic; class Program { // Describe a C# type definition string with precise keywords. // Input is a simplified type declaration string. Output format: sorted comma-separated keywords. // Rules: // - Contains "class" -> "reference-type" // - Contains "struct"...
var keywords = new SortedSet<string>(); if (typeDecl.Contains("class")) keywords.Add("reference-type"); if (typeDecl.Contains("struct")) keywords.Add("value-type"); if (typeDecl.Contains("interface")) keywords.Add("contract"); if (typeDecl.Contains("sealed")) keywords.Add("non-in...
} static void Main() { string t1 = "public sealed class MyService : IDisposable"; string d1 = DescribeType(t1); if (!d1.Contains("non-inheritable")) throw new Exception($"Sealed: {d1}"); if (!d1.Contains("disposable")) throw new Exception($"Disposable: {d1}"); if (!d...
string t3 = "public struct Point"; string d3 = DescribeType(t3); if (!d3.Contains("value-type")) throw new Exception($"Struct: {d3}"); if (d3.Contains("reference-type")) throw new Exception("Struct should not be reference-type"); string t4 = "public interface IRepository<T> : IE...
pattern_matching
1
devbench-syntax-completion
c_sharp
using System; class Program { abstract record Shape; record Circle(double Radius) : Shape; record Rect(double W, double H) : Shape; record Triangle(double Base, double Height) : Shape; static string Classify(Shape s) => s switch {
Circle { Radius: > 10 } => "big-circle", Circle c => $"circle-{c.Radius}", Rect { W: var w, H: var h } when w == h => $"square-{w}", Rect r => $"rect-{r.W}x{r.H}", Triangle { Base: var b, Height: var h } when b * h / 2 > 50 => "big-tri", Triangle t => $"tri-{t.Base}", ...
}; static void Main() { if (!(Classify(new Circle(15)) == "big-circle")) throw new Exception(); if (!(Classify(new Circle(5)) == "circle-5")) throw new Exception(); if (!(Classify(new Rect(4, 4)) == "square-4")) throw new Exception(); if (!(Classify(new Rect(3, 5)) == "rect-...
if (!(Classify(new Circle(10)) == "circle-10")) throw new Exception(); if (!(Classify(new Circle(10.1)) == "big-circle")) throw new Exception(); if (!(Classify(new Rect(1, 1)) == "square-1")) throw new Exception(); if (!(Classify(new Triangle(10, 10)) == "tri-10")) throw new Exception(); if (!(Classify(new Triangle(100...
syntax_completion
2
devbench-syntax-completion
c_sharp
using System; using System.Linq; using System.Collections.Generic; class Program { record Sale(string Product, string Region, double Amount); static Dictionary<string, (int Count, double Total)> Summarize(List<Sale> sales) { var query = from s in sales let rounded = Math.Round(...
orderby g.Count() descending select new { Region = g.Key, Count = g.Count(), Total = g.Sum(x => x.Amount) }; return query.ToDictionary(x => x.Region, x => (x.Count, x.Total));
} static void Main() { var sales = new List<Sale> { new("Widget", "East", 50.5), new("Gadget", "East", 30.0), new("Widget", "West", 5.0), new("Gadget", "West", 20.0), new("Widget", "East", 8.0), }; var result = Summ...
var sales2 = new List<Sale> { new("A", "North", 100), new("B", "North", 200), new("C", "South", 5), }; var r2 = Summarize(sales2); if (!(r2.ContainsKey("North") && r2["North"].Count == 2)) throw new Exception(); if (!(r2["North"].Total == 300)) throw new Exception(); if (r2.ContainsKey("South")) throw new Exception...
syntax_completion
3
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; class Program { static List<T> MergeSorted<T>(List<T> a, List<T> b) where T : IComparable<T> { var result = new List<T>(a.Count + b.Count); int i = 0, j = 0;
while (i < a.Count && j < b.Count) { if (a[i].CompareTo(b[j]) <= 0) result.Add(a[i++]); else result.Add(b[j++]); } while (i < a.Count) result.Add(a[i++]); while (j < b.Count) result.Add(b[j++]);
return result; } static void Main() { var a = new List<int> { 1, 3, 5, 7 }; var b = new List<int> { 2, 4, 6, 8 }; var merged = MergeSorted(a, b); if (!(string.Join(",", merged) == "1,2,3,4,5,6,7,8")) throw new Exception(); } }
var empty = MergeSorted(new List<int>(), new List<int> { 1, 2 }); if (!(string.Join(",", empty) == "1,2")) throw new Exception(); var same = MergeSorted(new List<int> { 1, 1 }, new List<int> { 1, 1 }); if (!(string.Join(",", same) == "1,1,1,1")) throw new Exception(); var strs = MergeSorted(new List<string> { "a", "c" ...
syntax_completion
4
devbench-syntax-completion
c_sharp
using System; class Program { enum Season { Spring, Summer, Autumn, Winter } enum Temp { Cold, Mild, Hot } static string Advisory(Season s, Temp t, bool raining) => (s, t, raining) switch { (Season.Winter, Temp.Cold, true) => "blizzard-warning", (Season.Winter, Temp.Cold, false) => "fr...
(Season.Summer, Temp.Hot, true) => "thunderstorm", (Season.Summer, Temp.Hot, false) => "heat-wave", (Season.Summer, _, true) => "summer-rain", (Season.Summer, _, _) => "pleasant", (_, _, true) => "bring-umbrella", (_, Temp.Cold, _) => "bundle-up", _ => "normal"
}; static void Main() { if (!(Advisory(Season.Winter, Temp.Cold, true) == "blizzard-warning")) throw new Exception(); if (!(Advisory(Season.Summer, Temp.Hot, false) == "heat-wave")) throw new Exception(); if (!(Advisory(Season.Summer, Temp.Mild, true) == "summer-rain")) throw new Ex...
if (!(Advisory(Season.Winter, Temp.Mild, true) == "winter-mild")) throw new Exception(); if (!(Advisory(Season.Winter, Temp.Hot, false) == "winter-mild")) throw new Exception(); if (!(Advisory(Season.Summer, Temp.Hot, true) == "thunderstorm")) throw new Exception(); if (!(Advisory(Season.Summer, Temp.Cold, true) == "su...
syntax_completion
5
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { static IEnumerable<int> FibUpTo(int max) { int a = 0, b = 1;
while (a <= max) { yield return a; int next = a + b; a = b; b = next; }
} static void Main() { var fibs = FibUpTo(20).ToList(); if (!(string.Join(",", fibs) == "0,1,1,2,3,5,8,13")) throw new Exception(); if (!(FibUpTo(0).Count() == 1)) throw new Exception(); } }
if (!(FibUpTo(1).ToList().Count == 3)) throw new Exception("0,1,1"); if (!(FibUpTo(100).Last() == 89)) throw new Exception(); if (!(FibUpTo(100).Count() == 12)) throw new Exception(); var big = FibUpTo(1000).ToList(); if (!(big.Last() == 987)) throw new Exception();
syntax_completion
6
devbench-syntax-completion
c_sharp
using System; using System.Linq; using System.Collections.Generic; class Program { record Student(int Id, string Name, int DeptId); record Dept(int Id, string Name); record Grade(int StudentId, string Course, int Score); static List<string> TopStudents(List<Student> students, List<Dept> depts, List<Gr...
where avg >= 80 orderby avg descending, s.Name select $"{s.Name} ({d.Name}): {avg:F1}"; return query.ToList();
} static void Main() { var students = new List<Student> { new(1, "Alice", 1), new(2, "Bob", 1), new(3, "Carol", 2) }; var depts = new List<Dept> { new(1, "CS"), new(2, "Math") }; var grades = new List<Grade> { new(1, "Algo", 90), new(1, "DB", 85), new...
var s2 = new List<Student> { new(1, "Zara", 1), new(2, "Amy", 1) }; var d2 = new List<Dept> { new(1, "Bio") }; var g2 = new List<Grade> { new(1, "X", 80), new(2, "Y", 80) }; var r2 = TopStudents(s2, d2, g2); if (!(r2.Count == 2)) throw new Exception(); if (!(r2[0] == "Amy (Bio): 80.0")) throw new Exception("orderby nam...
syntax_completion
7
devbench-syntax-completion
c_sharp
using System; class Program { abstract record Expr; record Num(double Val) : Expr; record BinOp(string Op, Expr Left, Expr Right) : Expr; record UnaryOp(string Op, Expr Inner) : Expr; static double Eval(Expr e) => e switch { Num(var v) => v, BinOp("+", var l, var r) => Eval(l) ...
BinOp("/", var l, var r) when Eval(r) != 0 => Eval(l) / Eval(r), BinOp("/", _, _) => double.NaN, BinOp("**", var l, var r) => Math.Pow(Eval(l), Eval(r)), UnaryOp("-", var inner) => -Eval(inner), UnaryOp("abs", var inner) => Math.Abs(Eval(inner)), _ => throw new ArgumentEx...
}; static void Main() { var expr = new BinOp("+", new Num(3), new BinOp("*", new Num(2), new Num(4))); if (!(Math.Abs(Eval(expr) - 11.0) < 0.001)) throw new Exception(); if (!(double.IsNaN(Eval(new BinOp("/", new Num(1), new Num(0)))))) throw new Exception(); if (!(Math.Abs(...
if (!(Math.Abs(Eval(new BinOp("**", new Num(2), new Num(10))) - 1024) < 0.001)) throw new Exception(); if (!(Math.Abs(Eval(new UnaryOp("abs", new Num(-7))) - 7) < 0.001)) throw new Exception(); if (!(Math.Abs(Eval(new BinOp("/", new Num(10), new Num(3))) - 3.3333) < 0.01)) throw new Exception(); var nested = new UnaryO...
syntax_completion
8
devbench-syntax-completion
c_sharp
using System; using System.Threading.Tasks; using System.Collections.Generic; using System.Linq; class Program { static async Task<int> ComputeAsync(int x) { await Task.Delay(1); return x * x; } static async Task<List<int>> BatchCompute(int[] inputs) { var tasks = inputs.Se...
var results = await Task.WhenAll(tasks); return results.OrderByDescending(x => x).ToList();
} static async Task Main() { var result = await BatchCompute(new[] { 3, 1, 4, 1, 5 }); if (!(result[0] == 25)) throw new Exception($"Expected 25, got {result[0]}"); if (!(result[1] == 16)) throw new Exception(); if (!(result.Count == 5)) throw new Exception(); } }
var r2 = await BatchCompute(new[] { 0, 2 }); if (!(r2[0] == 4)) throw new Exception(); if (!(r2[1] == 0)) throw new Exception(); var r3 = await BatchCompute(new int[] { }); if (!(r3.Count == 0)) throw new Exception(); var r4 = await BatchCompute(new[] { 10 }); if (!(r4[0] == 100)) throw new Exception();
syntax_completion
9
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { abstract record Animal(string Name, int Age); record Dog(string Name, int Age, string Breed) : Animal(Name, Age); record Cat(string Name, int Age, bool Indoor) : Animal(Name, Age); record Bird(string Name, int Age, doubl...
Dog(var n, _, var breed) => $"{n}: {breed}", Cat(var n, _, true) => $"{n}: indoor cat", Cat(var n, var age, false) when age < 2 => $"{n}: outdoor kitten", Cat(var n, _, _) => $"{n}: outdoor cat", Bird(var n, _, var ws) when ws > 1.5 => $"{n}: large bird", Bird(var n, _, _...
}; static void Main() { if (!(Describe(new Dog("Rex", 12, "Lab")) == "Rex: senior Lab")) throw new Exception(); if (!(Describe(new Dog("Max", 3, "Pug")) == "Max: Pug")) throw new Exception(); if (!(Describe(new Cat("Mia", 5, true)) == "Mia: indoor cat")) throw new Exception(); ...
if (!(Describe(new Dog("A", 10, "X")) == "A: X")) throw new Exception("10 is not > 10"); if (!(Describe(new Dog("B", 11, "Y")) == "B: senior Y")) throw new Exception(); if (!(Describe(new Cat("C", 2, false)) == "C: outdoor cat")) throw new Exception("2 is not < 2"); if (!(Describe(new Bird("D", 1, 1.5)) == "D: small bi...
syntax_completion
10
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { class PriorityBag<TKey, TVal> where TKey : IComparable<TKey> where TVal : class, new() { private readonly SortedDictionary<TKey, List<TVal>> _data = new(); public void Add(TKey key, TVal val) ...
if (!_data.ContainsKey(key)) _data[key] = new List<TVal>(); _data[key].Add(val); } public TVal? PopHighest() { if (_data.Count == 0) return null; var last = _data.Last(); var val = last.Value[^1]; last.Value...
} public int Count => _data.Values.Sum(v => v.Count); } class Item { public string Tag { get; set; } = ""; public override string ToString() => Tag; } static void Main() { var bag = new PriorityBag<int, Item>(); bag.Add(1, new Item { Tag = "low"...
if (!(bag.PopHighest()!.Tag == "low")) throw new Exception(); if (!(bag.PopHighest() == null)) throw new Exception(); if (!(bag.Count == 0)) throw new Exception(); bag.Add(5, new Item { Tag = "x" }); if (!(bag.Count == 1)) throw new Exception(); if (!(bag.PopHighest()!.Tag == "x")) throw new Exception();
syntax_completion
11
devbench-syntax-completion
c_sharp
using System; using System.Linq; using System.Collections.Generic; class Program { record Order(int Id, int CustomerId, double Total); record Customer(int Id, string Name); static List<(string Name, double Sum, int Count)> SummaryByCustomer( List<Customer> customers, List<Order> orders) { ...
(c, ords) => new { c.Name, Sum = ords.Sum(o => o.Total), Count = ords.Count() }) .Where(x => x.Count > 0) .OrderBy(x => x.Name) .Select(x => (x.Name, x.Sum, x.Count)) .ToList();
} static void Main() { var customers = new List<Customer> { new(1, "Alice"), new(2, "Bob"), new(3, "Carol") }; var orders = new List<Order> { new(1, 1, 50), new(2, 1, 30), new(3, 2, 100), }; var result = SummaryByCustomer(customers, orders); if (!...
var cs = new List<Customer> { new(1, "Zoe") }; var os = new List<Order>(); var r = SummaryByCustomer(cs, os); if (!(r.Count == 0)) throw new Exception("no orders means filtered out"); var cs2 = new List<Customer> { new(1, "A"), new(2, "B") }; var os2 = new List<Order> { new(1, 1, 10), new(2, 2, 20), new(3, 2, 30) }; va...
syntax_completion
12
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { record Address(string City, string Country); record Person(string Name, int Age, Address? Addr); static List<string> FindAdults(List<Person> people, string country) { var result = new List<string>(); for...
if (p is { Age: >= 18, Addr: { Country: var c } } && c == country) { result.Add(p.Name); }
} return result.OrderBy(x => x).ToList(); } static void Main() { var people = new List<Person> { new("Alice", 25, new("NYC", "US")), new("Bob", 17, new("LA", "US")), new("Carol", 30, new("London", "UK")), new("Dave", 20, null),...
var p2 = new List<Person> { new("X", 18, new("A", "DE")), new("Y", 18, null) }; var de = FindAdults(p2, "DE"); if (!(de.Count == 1 && de[0] == "X")) throw new Exception(); var none = FindAdults(p2, "US"); if (!(none.Count == 0)) throw new Exception();
syntax_completion
13
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; class Program { class TrackedResource : IDisposable { static List<string> _log = new(); public static List<string> Log => _log; public static void Reset() => _log = new(); string _name; public TrackedResource(string name) {...
inner.Use(); if (failInner) throw new InvalidOperationException("inner-fail"); } catch (InvalidOperationException ex) { TrackedResource.Log.Add($"caught:{ex.Message}"); } finally { Tra...
} catch (ArgumentException ex) { TrackedResource.Log.Add($"caught:{ex.Message}"); } finally { TrackedResource.Log.Add("outer-finally"); } return string.Join("|", TrackedResource.Log); } static void Main() { var ...
var r3 = Process(false, true); if (!(r3 == "open:outer|use:outer|open:inner|use:inner|close:inner|inner-finally|close:outer|caught:outer-fail|outer-finally")) throw new Exception(r3); var r4 = Process(true, true); if (!(r4 == "open:outer|use:outer|open:inner|use:inner|close:inner|caught:inner-fail|inner-finally|clo...
syntax_completion
14
devbench-syntax-completion
c_sharp
using System; using System.Linq; class Program { static Func<int, int> MakeAccumulator(int initial) { int state = initial;
int Accumulate(int x) { state += x; return state; } return Accumulate;
} static void Main() { var acc = MakeAccumulator(10); if (!(acc(5) == 15)) throw new Exception(); if (!(acc(3) == 18)) throw new Exception(); if (!(acc(-8) == 10)) throw new Exception(); var acc2 = MakeAccumulator(0); if (!(acc2(1) == 1)) throw new Exception...
var acc3 = MakeAccumulator(100); if (!(acc3(0) == 100)) throw new Exception(); if (!(acc3(-100) == 0)) throw new Exception(); if (!(acc3(1) == 1)) throw new Exception(); var a = MakeAccumulator(0); var b = MakeAccumulator(0); a(10); b(20); if (!(a(0) == 10)) throw new Exception("separate state"); if (!(b(0) == 20)) thr...
syntax_completion
15
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { static (int Min, int Max, double Avg) Stats(IEnumerable<int> nums) { var list = nums.ToList(); if (list.Count == 0) return (0, 0, 0);
int min = list[0], max = list[0]; long sum = 0; foreach (var n in list) { if (n < min) min = n; if (n > max) max = n; sum += n; } return (min, max, (double)sum / list.Count);
} static void Main() { var (lo, hi, avg) = Stats(new[] { 3, 1, 4, 1, 5, 9 }); if (!(lo == 1)) throw new Exception(); if (!(hi == 9)) throw new Exception(); if (!(Math.Abs(avg - 3.833) < 0.01)) throw new Exception(); var (a, b, c) = Stats(new int[] { }); if (!...
var (lo2, hi2, avg2) = Stats(new[] { 42 }); if (!(lo2 == 42 && hi2 == 42 && Math.Abs(avg2 - 42) < 0.01)) throw new Exception(); var (lo3, hi3, avg3) = Stats(new[] { -5, -1, -10 }); if (!(lo3 == -10 && hi3 == -1)) throw new Exception(); if (!(Math.Abs(avg3 - (-16.0/3)) < 0.01)) throw new Exception();
syntax_completion
16
devbench-syntax-completion
c_sharp
using System; using System.Linq; using System.Collections.Generic; class Program { record Team(string Name, List<int> Scores); static List<(string Team, int Game, int Score)> TopScores(List<Team> teams, int threshold) { return teams .SelectMany(t => t.Scores.Select((s, idx) => (Team: t...
.Where(x => x.Score >= threshold) .OrderByDescending(x => x.Score) .ThenBy(x => x.Team) .ThenBy(x => x.Game) .ToList();
} static void Main() { var teams = new List<Team> { new("Alpha", new() { 80, 95, 70 }), new("Beta", new() { 90, 60, 85 }), }; var top = TopScores(teams, 85); if (!(top.Count == 3)) throw new Exception($"count={top.Count}"); if (!(top[0...
var empty = TopScores(new List<Team>(), 0); if (!(empty.Count == 0)) throw new Exception(); var t2 = new List<Team> { new("X", new() { 50, 50 }) }; if (!(TopScores(t2, 51).Count == 0)) throw new Exception(); if (!(TopScores(t2, 50).Count == 2)) throw new Exception(); var t3 = new List<Team> { new("A", new() { 100 }), n...
syntax_completion
17
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { static IEnumerable<(int Start, int End, int Sum)> ConsecutiveRuns(int[] arr, int minLen) { int start = 0; while (start < arr.Length) { int end = start + 1; while (end < arr.Length ...
if (len >= minLen) { int sum = 0; for (int i = start; i < end; i++) sum += arr[i]; yield return (arr[start], arr[end - 1], sum); } start = end;
} } static void Main() { var runs = ConsecutiveRuns(new[] { 1, 2, 3, 7, 8, 10, 11, 12, 13 }, 3).ToList(); if (!(runs.Count == 2)) throw new Exception($"count={runs.Count}"); if (!(runs[0] == (1, 3, 6))) throw new Exception(runs[0].ToString()); if (!(runs[1] == (10, 1...
var r2 = ConsecutiveRuns(new[] { 5 }, 1).ToList(); if (!(r2.Count == 1 && r2[0] == (5, 5, 5))) throw new Exception(); var r3 = ConsecutiveRuns(new[] { 1, 3, 5 }, 2).ToList(); if (!(r3.Count == 0)) throw new Exception("no consecutive runs of len 2"); var r4 = ConsecutiveRuns(new int[] { }, 1).ToList(); if (!(r4.Count ==...
syntax_completion
18
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { static Func<T, TResult> Compose<T, TMid, TResult>(Func<T, TMid> f, Func<TMid, TResult> g) => x => g(f(x)); static Func<IEnumerable<T>, IEnumerable<T>> BuildPipeline<T>( params Func<IEnumerable<T>, IEnumerable<T>...
Func<IEnumerable<T>, IEnumerable<T>> pipeline = x => x; foreach (var stage in stages) pipeline = Compose(pipeline, stage); return pipeline;
} static void Main() { var pipe = BuildPipeline<int>( xs => xs.Where(x => x > 0), xs => xs.Select(x => x * 2), xs => xs.OrderBy(x => x) ); var result = pipe(new[] { -1, 3, 1, -2, 4, 2 }).ToList(); if (!(result.Count == 4)) throw new Except...
var identity = BuildPipeline<int>(); var r = identity(new[] { 3, 1, 2 }).ToList(); if (!(r.Count == 3 && r[0] == 3)) throw new Exception("identity preserves order"); var pipe2 = BuildPipeline<string>( xs => xs.Where(x => x.Length > 1), xs => xs.Select(x => x.ToUpper()) ); var r2 = pipe2(new[] { "a", "bb", "ccc"...
syntax_completion
19
devbench-syntax-completion
c_sharp
using System; class Program { static string Grade(int score) => score switch {
>= 90 and <= 100 => "A", >= 80 and < 90 => "B", >= 70 and < 80 => "C", >= 60 and < 70 => "D", >= 0 and < 60 => "F", _ => throw new ArgumentOutOfRangeException()
}; static void Main() { if (!(Grade(95) == "A")) throw new Exception(); if (!(Grade(85) == "B")) throw new Exception(); if (!(Grade(75) == "C")) throw new Exception(); if (!(Grade(65) == "D")) throw new Exception(); if (!(Grade(50) == "F")) throw new Exception(); ...
if (!(Grade(90) == "A")) throw new Exception(); if (!(Grade(89) == "B")) throw new Exception(); if (!(Grade(80) == "B")) throw new Exception(); if (!(Grade(79) == "C")) throw new Exception(); if (!(Grade(70) == "C")) throw new Exception(); if (!(Grade(69) == "D")) throw new Exception(); if (!(Grade(60) == "D")) throw n...
syntax_completion
20
devbench-syntax-completion
c_sharp
using System; using System.Linq; using System.Collections.Generic; class Program { static (int Words, int Chars, string Longest) TextStats(string[] lines) { return lines.Aggregate( (Words: 0, Chars: 0, Longest: ""),
(acc, line) => { var words = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); var longest = words.Length > 0 ? words.OrderByDescending(w => w.Length).First() : acc.Longest; return ( ...
); } static void Main() { var result = TextStats(new[] { "hello world", "this is a test", "extraordinary" }); if (!(result.Words == 7)) throw new Exception($"words={result.Words}"); if (!(result.Chars == 38)) throw new Exception($"chars={result.Chars}"); if (!(result...
var r2 = TextStats(new[] { "a bb ccc" }); if (!(r2.Words == 3 && r2.Longest == "ccc")) throw new Exception(); var r3 = TextStats(new string[] { }); if (!(r3.Words == 0 && r3.Chars == 0 && r3.Longest == "")) throw new Exception(); var r4 = TextStats(new[] { "", "" }); if (!(r4.Words == 0 && r4.Chars == 0)) throw new Exc...
syntax_completion
21
devbench-syntax-completion
c_sharp
using System; using System.Linq; class Program { static string Describe(int[] arr) => arr switch { [] => "empty", [var x] => $"single:{x}", [var a, var b] when a > b => $"desc-pair:{a},{b}", [var a, var b] => $"pair:{a},{b}",
[var first, .. var middle, var last] when first == last => $"bookend:{first},mid={middle.Length}", [>= 0, .., >= 0] => $"non-neg:{arr.Length}", [var h, ..] when h < 0 => $"neg-start:{h}", _ => $"other:{arr.Length}"
}; static void Main() { if (!(Describe(Array.Empty<int>()) == "empty")) throw new Exception(); if (!(Describe(new[] { 42 }) == "single:42")) throw new Exception(); if (!(Describe(new[] { 5, 3 }) == "desc-pair:5,3")) throw new Exception(); if (!(Describe(new[] { 3, 5 }) == "p...
if (!(Describe(new[] { 0, 99, 0 }) == "bookend:0,mid=1")) throw new Exception(); if (!(Describe(new[] { 5, 5 }) == "pair:5,5")) throw new Exception("pair not desc, not bookend for len 2 with same"); if (!(Describe(new[] { 3, 0, 0, 3 }) == "bookend:3,mid=2")) throw new Exception(); if (!(Describe(new[] { 0, 1, 2, 3, 4 }...
syntax_completion
22
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { static async IAsyncEnumerable<int> RangeAsync(int start, int count) {
for (int i = 0; i < count; i++) { await Task.Delay(1); yield return start + i; }
} static async Task Main() { var items = new List<int>(); await foreach (var item in RangeAsync(5, 4)) { items.Add(item); } if (!(items.Count == 4)) throw new Exception($"count={items.Count}"); if (!(items[0] == 5 && items[1] == 6 && items[2] == 7...
var empty = new List<int>(); await foreach (var x in RangeAsync(0, 0)) empty.Add(x); if (!(empty.Count == 0)) throw new Exception(); var one = new List<int>(); await foreach (var x in RangeAsync(100, 1)) one.Add(x); if (!(one.Count == 1 && one[0] == 100)) throw new Exception();
syntax_completion
23
devbench-syntax-completion
c_sharp
using System; class Program { record HttpResponse(int StatusCode, string? Body, string ContentType); static string Categorize(HttpResponse r) => r switch { { StatusCode: 200 or 201, Body: not null, ContentType: "application/json" } => $"json-ok:{r.Body.Length}", { StatusCode: 2...
{ StatusCode: >= 300 and < 400 } => $"redirect:{r.StatusCode}", { StatusCode: >= 400 and < 500 } => $"client-error:{r.StatusCode}", { StatusCode: >= 500 } => $"server-error:{r.StatusCode}", { StatusCode: 204 } => "no-content", _ => ...
}; static void Main() { if (!(Categorize(new(200, "{}", "application/json")) == "json-ok:2")) throw new Exception(); if (!(Categorize(new(201, "hi", "text/plain")) == "ok:text/plain")) throw new Exception(); if (!(Categorize(new(200, null, "")) == "empty-ok")) throw new Exception();...
if (!(Categorize(new(302, "moved", "text/html")) == "redirect:302")) throw new Exception(); if (!(Categorize(new(399, null, "")) == "redirect:399")) throw new Exception(); if (!(Categorize(new(400, null, "")) == "client-error:400")) throw new Exception(); if (!(Categorize(new(499, null, "")) == "client-error:499")) thr...
syntax_completion
24
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; static class Extensions { public static IEnumerable<IGrouping<TKey, T>> ChunkBy<T, TKey>( this IEnumerable<T> source, Func<T, TKey> keySelector) where TKey : notnull { using var enumerator = source.GetEnumerator(); ...
var group = new List<T> { enumerator.Current }; while (enumerator.MoveNext()) { var key = keySelector(enumerator.Current); if (EqualityComparer<TKey>.Default.Equals(key, currentKey)) { group.Add(enumerator.Current); } el...
} } class Grouping<TKey, T> : IGrouping<TKey, T> { private readonly List<T> _items; public TKey Key { get; } public Grouping(TKey key, List<T> items) { Key = key; _items = items; } public IEnumerator<T> GetEnumerator() => _items.GetEnumerator(); System.Collections.IEnumerator System.Collections...
var empty = Array.Empty<int>().ChunkBy(x => x).ToList(); if (!(empty.Count == 0)) throw new Exception(); var single = new[] { 5 }.ChunkBy(x => x).ToList(); if (!(single.Count == 1 && single[0].Key == 5)) throw new Exception(); var strs = new[] { "aa", "ab", "ba", "bb" }.ChunkBy(x => x[0]).ToList(); if (!(strs.Count == ...
syntax_completion
25
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { record Config(Dictionary<string, Dictionary<string, string>>? Sections); static string GetValue(Config? config, string section, string key, string fallback) {
return config?.Sections?.GetValueOrDefault(section)?.GetValueOrDefault(key) ?? fallback;
} static void Main() { var cfg = new Config(new() { ["db"] = new() { ["host"] = "localhost", ["port"] = "5432" } }); if (!(GetValue(cfg, "db", "host", "none") == "localhost")) throw new Exception(); if (!(GetValue(cfg, "db", "timeout", "30") == "30")) throw new Exception(); ...
var cfg2 = new Config(new() { ["a"] = new() { ["b"] = "" } }); if (!(GetValue(cfg2, "a", "b", "x") == "")) throw new Exception("empty string is not null"); if (!(GetValue(cfg2, "a", "c", "y") == "y")) throw new Exception(); if (!(GetValue(cfg2, "z", "b", "y") == "y")) throw new Exception();
syntax_completion
26
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Probe : IDisposable { private readonly List<string> _log; public string Name { get; } public Probe(string name, List<string> log) { Name = name; _log = log; _log.Add($"open:{name}"); } public void Dispose() { _log.Add($"close:{Nam...
try { using (var middle = new Probe("middle", log)) { log.Add("body:middle"); using var inner = new Probe("inner", log); log.Add("body:inner"); if (fail) throw new InvalidOperationExce...
log.Add("after:try"); } return log; } static void Main() { var normal = Trace(false); if (!normal.Contains("body:cleanup")) throw new Exception("normal cleanup missing"); if (!normal.Contains("after:try")) throw new Exception("normal after missing"); ...
var normalOrder = string.Join("|", Trace(false)); if (normalOrder != "open:outer|body:outer|open:middle|body:middle|open:inner|body:inner|close:inner|close:middle|open:cleanup|body:cleanup|close:cleanup|after:try|close:outer") throw new Exception("normal order: " + normalOrder); var failedOrder = string.Join("|", Trace...
syntax_completion
27
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Token : IDisposable { private readonly List<string> _log; public string Name { get; } public Token(string name, List<string> log) { Name = name; _log = log; _log.Add($"open:{name}"); } public void Dispose() { _log.Add($"close:{Nam...
{ using var branch = new Token(shortPath ? "short" : "long", log); log.Add($"branch:{branch.Name}"); if (shortPath) { using var leaf = new Token("leaf", log); log.Add("short-body"); } else { ...
log.Add("end"); return log; } static void Main() { var shortLog = Plan(true, false); if (!shortLog.Contains("branch:short")) throw new Exception("short branch missing"); if (!shortLog.Contains("short-body")) throw new Exception("short body missing"); if (!sho...
var shortOrder = string.Join("|", Plan(true, false)); if (!(shortOrder == "open:root|start|open:short|branch:short|open:leaf|short-body|close:leaf|close:short|end|close:root")) throw new Exception("short order: " + shortOrder); var longOrder = string.Join("|", Plan(false, false)); if (!(longOrder == "open:root|start|op...
syntax_completion
28
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class AsyncProbe : IAsyncDisposable { private readonly List<string> _log; public string Name { get; } public AsyncProbe(string name, List<string> log) { Name = name; _log = log; _log.Add($"open:{name}"); } ...
try { await using (var middle = new AsyncProbe("middle", log)) { log.Add("body:middle"); await using var inner = new AsyncProbe("inner", log); log.Add("body:inner"); if (fail) throw ne...
log.Add("after:try"); } return log; } static void Main() { var normal = TraceAsync(false).GetAwaiter().GetResult(); if (!normal.Contains("body:middle")) throw new Exception("normal middle missing"); if (!normal.Contains("closed:cleanup")) throw new Except...
var normalOrder = string.Join("|", TraceAsync(false).GetAwaiter().GetResult()); if (!(normalOrder == "open:outer|body:outer|open:middle|body:middle|open:inner|body:inner|closing:inner|closed:inner|closing:middle|closed:middle|open:cleanup|body:cleanup|closing:cleanup|closed:cleanup|after:try|closing:outer|closed:outer"...
syntax_completion
29
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Marker : IDisposable { private readonly List<string> _log; public string Name { get; } public Marker(string name, List<string> log) { Name = name; _log = log; _log.Add($"open:{name}"); } public void Dispose() { _log.Add($"close:{N...
yield return "first"; if (includeSecond) { using (var inner = new Marker("inner", log)) { log.Add("inner-ready"); yield return "second"; } } yield return "last";
log.Add("done"); } static void Main() { var fullLog = new List<string>(); var full = Walk(true, fullLog).ToList(); if (!full.SequenceEqual(new[] { "first", "second", "last" })) throw new Exception("full sequence"); if (!fullLog.Contains("close:inner")) throw new Exce...
var fullLog2 = new List<string>(); var full2 = Walk(true, fullLog2).ToList(); var fullOrder = string.Join("|", fullLog2); if (!(fullOrder == "open:outer|ready|open:inner|inner-ready|close:inner|done|close:outer")) throw new Exception("full order: " + fullOrder); var noSecondLog2 = new List<string>(); var noSecond2 = Wa...
syntax_completion
30
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { static IEnumerable<string> BuildPipeline(IEnumerable<int> source, List<string> log) { int seen = 0;
var query = source .Select(x => { log.Add($"select:{x}:{seen}"); seen++; return (Value: x, Seen: seen); }) .Where(p => { log.Add($"where:{p.Value}:{p.Seen}"); return p.Valu...
} static void Main() { var log = new List<string>(); var query = BuildPipeline(new[] { 1, 2, 3 }, log); if (!log.SequenceEqual(new[] { "built" })) throw new Exception("query should be deferred"); var first = query.Take(1).ToList(); if (!first.SequenceEqual(new[] { "1...
var log2 = new List<string>(); var nums = new List<int> { 1, 2, 3 }; var query2 = BuildPipeline(nums, log2); nums.Add(5); if (!(log2.SequenceEqual(new[] { "built" }))) throw new Exception("deferred build log: " + string.Join("|", log2)); var all = query2.ToList(); if (!(all.SequenceEqual(new[] { "1:1", "3:3", "5:4" }))...
syntax_completion
31
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Probe : IDisposable { private readonly List<string> _log; public string Name { get; } public Probe(string name, List<string> log) { Name = name; _log = log; _log.Add($"open:{name}"); } public void Dispose() { _log.Add($"close:{Nam...
{ using var zero = new Probe("zero", log); log.Add("case:0"); break; } case 1: { using var one = new Probe("one", log); using var tail = new Probe("one-tail", l...
case 2: log.Add("case:2"); break; default: log.Add("case:default"); break; } log.Add("after:switch"); return log; } static void Main() { var zero = Route(0); if (!zero.Contains("c...
var zeroOrder = string.Join("|", Route(0)); if (!(zeroOrder == "open:root|start|open:zero|case:0|close:zero|after:switch|close:root")) throw new Exception("zero order: " + zeroOrder); var oneOrder = string.Join("|", Route(1)); if (!(oneOrder == "open:root|start|open:one|open:one-tail|case:1|close:one-tail|close:one|aft...
syntax_completion
32
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Probe : IDisposable { private readonly List<string> _log; public string Name { get; } public Probe(string name, List<string> log) { Name = name; _log = log; _log.Add($"open:{name}"); } public void Dispose() { _log.Add($"close:{Nam...
using var item = new Probe($"item:{value}", log); if (value < 0) { log.Add($"skip:{value}"); continue; } log.Add($"visit:{value}"); if (value == stopAt) { log.Add($"stop:{value}"); ...
} log.Add("after:loop"); return log; } static void Main() { var log = Sweep(new[] { 1, -2, 3, 4 }, 3); if (!log.Contains("visit:1")) throw new Exception("visit 1 missing"); if (!log.Contains("skip:-2")) throw new Exception("skip missing"); if (!log.Co...
var order = string.Join("|", Sweep(new[] { 1, -2, 3, 4 }, 3)); if (!(order == "open:outer|open:item:1|visit:1|open:tail:1|tail:1|close:tail:1|close:item:1|open:item:-2|skip:-2|close:item:-2|open:item:3|visit:3|stop:3|close:item:3|after:loop|close:outer")) throw new Exception("mixed order: " + order); var noStop = strin...
syntax_completion
33
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Probe : IDisposable { private readonly List<string> _log; public string Name { get; } public Probe(string name, List<string> log) { Name = name; _log = log; _log.Add($"open:{name}"); } public void Dispose() { _log.Add($"close:{Nam...
using var first = new Probe("first", log); log.Add($"mode:{mode}"); if (mode == 1) { using var invalid = new Probe("invalid", log); log.Add("throw:invalid"); throw new InvalidOperationException("one"); } ...
} catch (InvalidOperationException ex) when (ex.Message == "one") { log.Add("catch:invalid"); } catch (Exception ex) { log.Add($"catch:{ex.GetType().Name}"); } log.Add("after:catch"); return log; } static void Main(...
var okOrder = string.Join("|", Handle(0)); if (!(okOrder == "open:outer|try:start|open:first|mode:0|try:ok|close:first|after:catch|close:outer")) throw new Exception("ok order: " + okOrder); var invalidOrder = string.Join("|", Handle(1)); if (!(invalidOrder == "open:outer|try:start|open:first|mode:1|open:invalid|throw:...
syntax_completion
34
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { var words = new[] { "hello", "world", "foo", "bar", "baz" }; var result = words.Aggregate( new { Count = 0, Longest = "", TotalLen = 0 }, (acc, word) => new ...
Longest = word.Length > acc.Longest.Length ? word : acc.Longest, TotalLen = acc.TotalLen + word.Length
}, acc => $"{acc.Count}:{acc.Longest}:{acc.TotalLen}"); if (!(result == "5:hello:19")) throw new Exception($"got: {result}"); } }
syntax_completion
35
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class AsyncMarker : IAsyncDisposable { private readonly List<string> _log; public string Name { get; } public AsyncMarker(string name, List<string> log) { Name = name; _log = log; _log.Add($"open:{name}"); } ...
for (int i = 0; i < limit; i++) { await using var item = new AsyncMarker($"item:{i}", log); log.Add($"yield:{i}"); await Task.Delay(1); yield return i; }
log.Add("done"); } static async Task<List<int>> TakeAsync(IAsyncEnumerable<int> source, int max) { var result = new List<int>(); await foreach (var item in source) { result.Add(item); if (result.Count == max) break; } return result; ...
var fullLog2 = new List<string>(); var all2 = TakeAsync(Stream(fullLog2, 2), 10).GetAwaiter().GetResult(); var fullOrder = string.Join("|", fullLog2); if (!(fullOrder == "open:outer|ready|open:item:0|yield:0|closing:item:0|closed:item:0|open:item:1|yield:1|closing:item:1|closed:item:1|done|closing:outer|closed:outer"))...
syntax_completion
36
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Marker : IDisposable { private readonly List<string> _log; public string Name { get; } public Marker(string name, List<string> log) { Name = name; _log = log; _log.Add($"open:{name}"); } public void Dispose() { _log.Add($"close:{N...
foreach (var value in values) { using var item = new Marker($"item:{value}", log); if (value < 0) { log.Add($"stop:{value}"); yield break; } log.Add($"yield:{value}"); yield return $"ok:{value}"; ...
log.Add("scan:done"); } static void Main() { var goodLog = new List<string>(); var good = Scan(new[] { 1, 2 }, goodLog).ToList(); if (!good.SequenceEqual(new[] { "ok:1", "ok:2" })) throw new Exception("good sequence"); if (!goodLog.Contains("scan:done")) throw new Ex...
var goodLog2 = new List<string>(); var good2 = Scan(new[] { 1, 2 }, goodLog2).ToList(); var goodOrder = string.Join("|", goodLog2); if (!(goodOrder == "open:outer|scan:start|open:item:1|yield:1|close:item:1|open:item:2|yield:2|close:item:2|scan:done|close:outer")) throw new Exception("good order: " + goodOrder); var st...
syntax_completion
37
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Marker : IDisposable { private readonly List<string> _log; public string Name { get; } public Marker(string name, List<string> log) { Name = name; _log = log; _log.Add($"open:{name}"); } public void Dispose() { _log.Add($"close:{N...
using var inner = new Marker("inner", log); log.Add("before:first"); yield return 1; if (failAfterFirst) { log.Add("throw:after-first"); throw new InvalidOperationException("after-first"); } log.Add("befo...
} finally { log.Add("finally:block"); } } static void Main() { var okLog = new List<string>(); var ok = Numbers(okLog, false).ToList(); if (!ok.SequenceEqual(new[] { 1, 2 })) throw new Exception("ok numbers"); if (!okLog.Contains("...
var okLog2 = new List<string>(); var ok2 = Numbers(okLog2, false).ToList(); var okOrder = string.Join("|", okLog2); if (!(okOrder == "open:outer|open:inner|before:first|before:second|close:inner|finally:block|close:outer")) throw new Exception("ok order: " + okOrder); var failLog2 = new List<string>(); try { Number...
syntax_completion
38
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { var students = new[] { new { Name = "Alice", Grade = 90 }, new { Name = "Bob", Grade = 75 }, new { Name = "Carol", Grade = 88 }, new { Name = "...
s => s.Grade >= 90 ? "A" : s.Grade >= 80 ? "B" : s.Grade >= 70 ? "C" : "D"
); if (!(letterGrades["Alice"] == "A")) throw new Exception($"alice={letterGrades["Alice"]}"); if (!(letterGrades["Bob"] == "C")) throw new Exception($"bob={letterGrades["Bob"]}"); if (!(letterGrades["Carol"] == "B")) throw new Exception($"carol={letterGrades["Carol"]}"); if (!...
syntax_completion
39
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class AsyncMarker : IAsyncDisposable { private readonly List<string> _log; public string Name { get; } public AsyncMarker(string name, List<string> log) { Name = name; _log = log; _log.Add($"open:{name}"); } ...
foreach (var value in values) { await using var item = new AsyncMarker($"item:{value}", log); if (value < 0) { log.Add($"stop:{value}"); yield break; } log.Add($"yield:{value}"); await Task.Delay(1); ...
log.Add("scan:done"); } static async Task<List<string>> CollectAsync(IAsyncEnumerable<string> source) { var result = new List<string>(); await foreach (var item in source) result.Add(item); return result; } static void Main() { var goodLog = ...
var goodLog2 = new List<string>(); var good2 = CollectAsync(ScanAsync(new[] { 1, 2 }, goodLog2)).GetAwaiter().GetResult(); var goodOrder = string.Join("|", goodLog2); if (!(goodOrder == "open:outer|scan:start|open:item:1|yield:1|closing:item:1|closed:item:1|open:item:2|yield:2|closing:item:2|closed:item:2|scan:done|clo...
syntax_completion
40
devbench-syntax-completion
c_sharp
using System; using System.Collections; using System.Collections.Generic; using System.Linq; class Marker : IDisposable { private readonly List<string> _log; public string Name { get; } public Marker(string name, List<string> log) { Name = name; _log = log; _log.Add($"open:{name}"); } public void Dispo...
while (enumerator.MoveNext()) { using var item = new Marker($"item:{enumerator.Current}", log); log.Add($"yield:{enumerator.Current}"); yield return enumerator.Current; }
log.Add("done"); } static void Main() { var fullLog = new List<string>(); var full = Replay(new[] { 4, 5 }, fullLog).ToList(); if (!full.SequenceEqual(new[] { 4, 5 })) throw new Exception("full sequence"); if (!fullLog.Contains("done")) throw new Exception("done miss...
var fullLog2 = new List<string>(); var full2 = Replay(new[] { 4, 5 }, fullLog2).ToList(); var fullOrder = string.Join("|", fullLog2); if (!(fullOrder == "open:enumerator|created|open:item:4|yield:4|close:item:4|open:item:5|yield:5|close:item:5|done|close:enumerator")) throw new Exception("full order: " + fullOrder); va...
syntax_completion
41
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { var people = new[] { new { First = "John", Last = "Doe", Age = 30 }, new { First = "Jane", Last = "Smith", Age = 25 }, new { First = "Bob", Last = "Jones",...
$"{i + 1}. {p.Last}, {p.First} ({p.Age})"
) .ToList(); if (!(labels[0] == "1. Smith, Jane (25)")) throw new Exception($"l0={labels[0]}"); if (!(labels[1] == "2. Doe, John (30)")) throw new Exception($"l1={labels[1]}"); if (!(labels[2] == "3. Jones, Bob (35)")) throw new Exception($"l2={labels[2]}"); } }
syntax_completion
42
devbench-syntax-completion
c_sharp
using System; using System.Linq; abstract record Shape; record Circle(double Radius) : Shape; record Rect(double W, double H) : Shape; record Group(Shape[] Items) : Shape; class Program { static double Area(Shape s) => s switch { Circle { Radius: var r } => Math.PI * r * r, Rect { W: var w, H:...
Group { Items: var items } => items.Sum(i => Area(i)),
_ => 0 }; static void Main() { var c = new Circle(1); var r = new Rect(3, 4); var sq = new Rect(5, 5); var g = new Group(new Shape[] { c, r, sq }); if (!(Math.Abs(Area(c) - Math.PI) < 0.001)) throw new Exception($"circle={Area(c)}"); if (!(Math.Abs(...
syntax_completion
43
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { static async Task<int> ComputeAsync(int x) { await Task.Delay(1); if (x < 0) throw new ArgumentException("negative"); return x * x; } static async Task Main() { var results...
var val = await ComputeAsync(n); results.Add($"ok:{val}");
} catch (ArgumentException ex) { results.Add($"err:{ex.Message}"); } } if (!(results.Count == 3)) throw new Exception($"count={results.Count}"); if (!(results[0] == "ok:9")) throw new Exception($"r0={results[0]}"); if (!(r...
syntax_completion
44
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; class Config { public Dictionary<string, string>? Settings { get; set; } } class Program { static string GetSetting(Config? cfg, string key, string fallback) {
return cfg?.Settings?.TryGetValue(key, out var val) == true ? val : fallback;
} static void Main() { var cfg1 = new Config { Settings = new() { ["theme"] = "dark" } }; Config? cfg2 = null; var cfg3 = new Config { Settings = null }; if (!(GetSetting(cfg1, "theme", "light") == "dark")) throw new Exception("t1"); if (!(GetSetting(cfg1, "missing...
syntax_completion
45
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; class Program { static string ClassifyPoint((int X, int Y) point) => point switch { (0, 0) => "origin", (var x, 0) when x > 0 => "positive-x-axis", (var x, 0) when x < 0 => "negative-x-axis", (0, var y) when y > 0 => "positive-y-ax...
(0, var y) when y < 0 => "negative-y-axis",
(var x, var y) when x > 0 && y > 0 => "Q1", (var x, var y) when x < 0 && y > 0 => "Q2", (var x, var y) when x < 0 && y < 0 => "Q3", _ => "Q4" }; static void Main() { if (!(ClassifyPoint((0, 0)) == "origin")) throw new Exception("t1"); if (!(ClassifyPoint((5,...
syntax_completion
46
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; class Program { static void Main() { var funcs = new List<Func<int, int>>(); for (int i = 0; i < 4; i++) { int captured = i; funcs.Add(x => { Func<int, int> inner = y => {...
return y * captured;
}; return inner(x) + captured; }); } if (!(funcs[0](10) == 0)) throw new Exception($"f0={funcs[0](10)}"); if (!(funcs[1](10) == 11)) throw new Exception($"f1={funcs[1](10)}"); if (!(funcs[2](10) == 22)) throw new Exception($"f2={funcs[2](10)}...
syntax_completion
47
devbench-syntax-completion
c_sharp
using System; using System.Collections.Generic; using System.Linq; class Department { public string Name { get; set; } = ""; public List<string> Members { get; set; } = new(); } class Program { static void Main() { var depts = new List<Department> { new() { Name = "Eng", Me...
new() { Name = "Sales", Members = { "Carol", "Dave" } }, new() { Name = "HR", Members = { "Eve" } }
}; var allMembers = depts.SelectMany(d => d.Members).OrderBy(m => m).ToList(); if (!(allMembers.Count == 5)) throw new Exception($"count={allMembers.Count}"); if (!(allMembers[0] == "Alice")) throw new Exception($"m0={allMembers[0]}"); if (!(allMembers[1] == "Bob")) throw new E...
syntax_completion
48
devbench-syntax-completion
c_sharp
using System; interface ITransform<in TIn, out TOut> { TOut Apply(TIn input); } class DoubleToString : ITransform<double, string> { public string Apply(double input) => input.ToString("F1"); } class IntToDouble : ITransform<int, double> { public double Apply(int input) => input * 2.5; } class Composed<A...
public C Apply(A input) => _second.Apply(_first.Apply(input));
} class Program { static void Main() { var intToStr = new Composed<int, double, string>(new IntToDouble(), new DoubleToString()); if (!(intToStr.Apply(4) == "10.0")) throw new Exception($"4->{intToStr.Apply(4)}"); if (!(intToStr.Apply(3) == "7.5")) throw new Exception($"3->{intToStr.Ap...
syntax_completion
49
devbench-syntax-completion
c_sharp
using System; using System.Linq; class Program { static void Main() { var xs = new[] { 1.0, 2.0, 3.0, 4.0, 5.0 }; var ys = new[] { 2.0, 4.0, 4.0, 4.0, 5.0 }; var stats = xs.Zip(ys, (x, y) => new { X = x, Y = y, Diff = y - x }) .Aggregate( new { SumDiff = 0.0...
(acc, pair) => new { SumDiff = acc.SumDiff + pair.Diff, SumSq = acc.SumSq + pair.Diff * pair.Diff, Count = acc.Count + 1 }
); double meanDiff = stats.SumDiff / stats.Count; double variance = stats.SumSq / stats.Count - meanDiff * meanDiff; if (!(stats.Count == 5)) throw new Exception($"count={stats.Count}"); if (!(Math.Abs(meanDiff - 0.8) < 0.001)) throw new Exception($"mean={meanDiff}"); ...
syntax_completion
50
devbench-syntax-completion
c_sharp
using System; class Program { static string Describe(int[] arr) => arr switch { [] => "empty", [var x] => $"single:{x}", [var f, .., var l] when f == l => $"bookend:{f}",
[var a, var b] => $"pair:{a},{b}",
_ => "other" }; static void Main() { if (!(Describe(Array.Empty<int>()) == "empty")) throw new Exception("t1"); if (!(Describe(new[] { 42 }) == "single:42")) throw new Exception("t2"); if (!(Describe(new[] { 5, 9, 5 }) == "bookend:5")) throw new Exception("t3"); if ...
syntax_completion